blade-code 0.10.144 → 0.10.146
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-m9srdfa1.js → chunk-0h3gj7rd.js} +1 -1
- package/dist/{chunk-ekjaa3h2.js → chunk-182ef3yh.js} +1 -1
- package/dist/{chunk-ehwn05np.js → chunk-1ekp201h.js} +1 -1
- package/dist/{chunk-p102vt6w.js → chunk-295aejt2.js} +1 -1
- package/dist/chunk-3a217980.js +353 -0
- package/dist/{chunk-x7gcmasv.js → chunk-5wvkcx8j.js} +1 -1
- package/dist/chunk-5y5smy9s.js +94 -0
- package/dist/{chunk-rrb49j43.js → chunk-6wa054ea.js} +1 -1
- package/dist/{chunk-8vd9y7ar.js → chunk-78w4nf32.js} +1 -1
- package/dist/{chunk-b7b1h83p.js → chunk-87xebr2g.js} +1 -1
- package/dist/chunk-9ybxmr9s.js +1 -0
- package/dist/{chunk-99t5b3qh.js → chunk-a4npzvvr.js} +1 -1
- package/dist/{chunk-qdxk9rcw.js → chunk-acdznbay.js} +1 -1
- package/dist/{chunk-ypfe8j02.js → chunk-b099f5sg.js} +2 -2
- package/dist/{chunk-4jqvrgpm.js → chunk-b63mpen4.js} +1 -1
- package/dist/{chunk-rqz0589c.js → chunk-ch29x278.js} +1 -1
- package/dist/{chunk-atcpkhxt.js → chunk-ehsyyg6w.js} +1 -1
- package/dist/{chunk-4bgsnpg0.js → chunk-ewbdz582.js} +1 -1
- package/dist/{chunk-10947adv.js → chunk-f3naz6qs.js} +2 -2
- package/dist/{chunk-96t1d492.js → chunk-grzwra4b.js} +1 -1
- package/dist/{chunk-s32yz7eq.js → chunk-gtyras9d.js} +1 -1
- package/dist/{chunk-pe6kcmvn.js → chunk-h217y9nr.js} +1 -1
- package/dist/{chunk-2n97dt2h.js → chunk-h5tkywm0.js} +1 -1
- package/dist/{chunk-sy59x1ts.js → chunk-kshztpba.js} +1 -1
- package/dist/{chunk-v67t8jmc.js → chunk-m7h23r1t.js} +1 -1
- package/dist/chunk-nbrywc86.js +1 -0
- package/dist/{chunk-6c972n1p.js → chunk-neqyry9c.js} +1 -1
- package/dist/{chunk-s6x7fme7.js → chunk-nrwvk6nj.js} +1 -1
- package/dist/{chunk-mw3e5scz.js → chunk-p5cbtf5b.js} +1 -1
- package/dist/{chunk-cd150xf2.js → chunk-pb4cx5ht.js} +1 -1
- package/dist/{chunk-qhr61n4y.js → chunk-qdsx35xh.js} +1 -1
- package/dist/{chunk-a9h3xfdj.js → chunk-qjtnbc6f.js} +1 -1
- package/dist/{chunk-vgxzpvyb.js → chunk-rj14y6h7.js} +1 -1
- package/dist/{chunk-9p0zyba2.js → chunk-whwkpq86.js} +1 -1
- package/dist/{chunk-ny2g84m0.js → chunk-wyma4wc7.js} +1 -1
- package/dist/{chunk-m7j6mq32.js → chunk-wz325egj.js} +1 -1
- package/dist/{chunk-c1qjdcf9.js → chunk-y11p2hkn.js} +1 -1
- package/dist/{chunk-1xa8z2h3.js → chunk-y4zg7d01.js} +3 -3
- package/dist/{chunk-65cxn7bb.js → chunk-yq5tpa0a.js} +1 -1
- package/dist/{chunk-srd0aqsm.js → chunk-zy5g7k16.js} +1 -1
- package/dist/web/assets/{ChatView-DuCQPnTY.js → ChatView-B6YVeOpl.js} +4 -4
- package/dist/web/assets/{CodeBlockHighlighter-QAgXsft7.js → CodeBlockHighlighter-p-CwwjLJ.js} +1 -1
- package/dist/web/assets/{FilePreview-4CWWDjOH.js → FilePreview-C0zjFfLF.js} +1 -1
- package/dist/web/assets/{KanbanBoard-Ck-cWvPd.js → KanbanBoard-BTjc3GTe.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-BT_XxFwe.js → MarkdownRenderer-BQUL4vI_.js} +3 -3
- package/dist/web/assets/{ScrollArea-pHWxoYad.js → ScrollArea-UfoiaWDB.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-ot9S7y0a.js → SessionHistorySurface-B0WHnLst.js} +1 -1
- package/dist/web/assets/{SettingsModal-CadB2Ewl.js → SettingsModal-CkF6k9qu.js} +1 -1
- package/dist/web/assets/{Sidebar-Ch8ljTll.js → Sidebar-DmVMsipF.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-DKMYqwyA.js → TaskSwitcher-DZELXs23.js} +1 -1
- package/dist/web/assets/{TerminalPanel-DiibeBVa.js → TerminalPanel-kmWnkCMc.js} +1 -1
- package/dist/web/assets/{archive-RtNeCZxZ.js → archive-WXotGSXW.js} +1 -1
- package/dist/web/assets/{arrow-left-ozhIfGE6.js → arrow-left-Cb-SEc-l.js} +1 -1
- package/dist/web/assets/{calendar-clock-HYACxDy_.js → calendar-clock-BRidlYhb.js} +1 -1
- package/dist/web/assets/{chevron-right-DzAXXFGA.js → chevron-right-CoRRZROd.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-DABp_klC.js → chevrons-up-down-Cv_JOz8A.js} +1 -1
- package/dist/web/assets/{clock-3-DTi7hWra.js → clock-3-CMvLtvtl.js} +1 -1
- package/dist/web/assets/{copy-DTdeEIqL.js → copy-DQqX0OQP.js} +1 -1
- package/dist/web/assets/{download-BmAUw5eK.js → download-FP4WtwG3.js} +1 -1
- package/dist/web/assets/{external-link-Bgh_DKjS.js → external-link-BTBZEQYA.js} +1 -1
- package/dist/web/assets/{folder-CcFAxEz0.js → folder-Dd0PwX-t.js} +1 -1
- package/dist/web/assets/{index-B0JUjEnb.js → index-CXHca5Sw.js} +11 -11
- package/dist/web/assets/{pause-Ch9b-6bD.js → pause-C4azsEtU.js} +1 -1
- package/dist/web/assets/{pencil-Dplt4XbT.js → pencil-BWrfxaIe.js} +1 -1
- package/dist/web/assets/{play-BfcPlDek.js → play-DgOFsd17.js} +1 -1
- package/dist/web/assets/{plus-99fbVJwp.js → plus-KK_f8iC4.js} +1 -1
- package/dist/web/assets/{settings-DNDRXm8y.js → settings-hrYiD_4G.js} +1 -1
- package/dist/web/assets/{team-Cw3NxMX6.js → team-Yr9DBygX.js} +1 -1
- package/dist/web/assets/{teamService-a7uKjSKx.js → teamService-CPSMTxV-.js} +1 -1
- package/dist/web/assets/{terminal-IkGhZXro.js → terminal-CHxuQT2f.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-b5qxype0.js +0 -1
- package/dist/chunk-bwm0jt16.js +0 -94
- package/dist/chunk-cr6d4zxs.js +0 -1
- package/dist/chunk-fd7ez529.js +0 -338
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{yf as W}from"./chunk-
|
|
2
|
+
import{yf as W}from"./chunk-pb4cx5ht.js";import{Bf as F,Cf as M}from"./chunk-wzqcea6x.js";import"./chunk-wyma4wc7.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-p5cbtf5b.js";import"./chunk-3y2x6fb6.js";import"./chunk-yq5tpa0a.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import{aj as N,bj as B}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Cj as T}from"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-h217y9nr.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import{Mk as J}from"./chunk-eg3ms291.js";import p from"node:path";var E=process.argv.slice(2),I=c(E),u=I!==null;if(I!==null)T.setGlobalDebug(I);function c(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function m(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function t(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function l(){if(m(E)){let{getVersion:K}=await import("./chunk-m7h23r1t.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=t(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-whwkpq86.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-66wk3exc.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-neqyry9c.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-295aejt2.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-rj14y6h7.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{browserCommands:S},{doctorCommands:k},{installCommands:O},{mcpCommands:y},{projectsCommands:V},{scheduleCommands:b},{serveCommand:P},{updateCommands:x},{webCommand:A}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-nbrywc86.js"),import("./chunk-b63mpen4.js"),import("./chunk-jq5bhnrd.js"),import("./chunk-b099f5sg.js"),import("./chunk-xmymx75h.js"),import("./chunk-a4npzvvr.js"),import("./chunk-0tzecdv3.js"),import("./chunk-6vcqajdc.js"),import("./chunk-ewbdz582.js"),import("./chunk-1ekp201h.js"),import("./chunk-78w4nf32.js")]),h=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(Z.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-9ybxmr9s.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-qdsx35xh.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:f};delete H._,delete H.$0,delete H.message,w(j(C,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await h.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)l().catch(console.error);export{l as main};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Xj as S}from"./chunk-
|
|
1
|
+
import{Xj as S}from"./chunk-h217y9nr.js";import{Mk as f}from"./chunk-eg3ms291.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
|
|
2
2
|
export{_ as k,u as l,g as m,C as n,V as o};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{wg as a,xg as b,yg as c,zg as d}from"./chunk-
|
|
1
|
+
import{wg as a,xg as b,yg as c,zg as d}from"./chunk-gtyras9d.js";import"./chunk-yq5tpa0a.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-h217y9nr.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,d as createProcessModelResources,a as cloneWorkspaceModelConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{k as o}from"./chunk-
|
|
1
|
+
import{k as o}from"./chunk-0h3gj7rd.js";import"./chunk-h217y9nr.js";import"./chunk-eg3ms291.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{p as c,q as v,r as d,s as m,t as l,u as a}from"./chunk-
|
|
1
|
+
import{p as c,q as v,r as d,s as m,t as l,u as a}from"./chunk-kshztpba.js";import{ca as O,ja as S}from"./chunk-y4zg7d01.js";import"./chunk-qm0j4szw.js";import"./chunk-ehsyyg6w.js";import"./chunk-e12xrg41.js";import{Yb as M,gc as E}from"./chunk-f3naz6qs.js";import"./chunk-wm896gnx.js";import{ge as f}from"./chunk-5y5smy9s.js";import"./chunk-9xbwtjac.js";import{Le as h}from"./chunk-3a217980.js";import"./chunk-mh9nqbwa.js";import{qf as I}from"./chunk-qjtnbc6f.js";import{sf as y,tf as R,uf as g}from"./chunk-h5tkywm0.js";import{vf as C}from"./chunk-6a16zba3.js";import"./chunk-wzqcea6x.js";import{Sf as w}from"./chunk-wyma4wc7.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-z2k08r1h.js";import"./chunk-w6qfbea8.js";import"./chunk-shb7g2vr.js";import"./chunk-7wcxjbyg.js";import"./chunk-gtyras9d.js";import"./chunk-nrwvk6nj.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-p5cbtf5b.js";import"./chunk-3y2x6fb6.js";import"./chunk-yq5tpa0a.js";import{Ti as A}from"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import{bj as P}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-h217y9nr.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
|
|
2
2
|
`);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
|
|
3
3
|
`);else j.io.stdout.write(`${j.response}
|
|
4
4
|
`)}function n(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await o(B);process.exit(q)})}async function o(j,B=process){let q;try{await c();let D=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await d({message:j.message,_:j._}):await v({message:j.message,_:j._,defaultMessage:"Hello"}),K=D===void 0,T=K?{mode:"agent",content:""}:await m(D);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
import{gf as h0,hf as mT}from"./chunk-mh9nqbwa.js";import{Dh as LT}from"./chunk-3y2x6fb6.js";import{Dj as PT}from"./chunk-2mk914vk.js";import{Ak as A,Ck as y0,Dk as r,Lk as hT,fk as V0,nk as D,pk as S,qk as d,sk as s,tk as q0,uk as RT,vk as bT,wk as yT}from"./chunk-4wx5sya5.js";import{Mk as g0}from"./chunk-eg3ms291.js";import{createHash as I_}from"node:crypto";import{readdir as D0,stat as w0}from"node:fs/promises";import U0 from"node:path";import{createHash as T$,randomBytes as n0}from"node:crypto";import{chmod as i0,link as $$,lstat as n,mkdir as _$,open as i,readdir as c0,realpath as l0,unlink as C0}from"node:fs/promises";import W from"node:path";function tT(){return typeof globalThis.Bun<"u"}function oT(T){return{exec:($)=>T.exec($),prepare:($)=>{let _=T.prepare($);return{run:(...G)=>{_.run(...G)},get:(...G)=>_.get(...G),all:(...G)=>_.all(...G)}},transaction:($)=>T.transaction($)(),pragma:($)=>T.pragma($,{simple:!0}),close:()=>T.close()}}function rT(T){return{exec:($)=>T.exec($),prepare:($)=>{let _=T.query($);return{run:(...G)=>{_.run(...G)},get:(...G)=>_.get(...G),all:(...G)=>_.all(...G)}},transaction:($)=>T.transaction($)(),pragma:($)=>{let _=T.query(`PRAGMA ${$}`).get();if(!_)return;let G=Object.values(_);return G.length===1?G[0]:_},close:()=>T.close()}}function eT(T){return[`PRAGMA busy_timeout=${T};`,"PRAGMA journal_mode=WAL;","PRAGMA synchronous=NORMAL;","PRAGMA foreign_keys=ON;"].join(`
|
|
2
|
+
`)}async function T0(T,$={}){let _=$.busyTimeoutMs??5000;if(!Number.isSafeInteger(_)||_<0)return null;let G=null;try{if(tT()){let{Database:Y}=await import("bun:sqlite");G=rT(new Y(T))}else{let Q=(await import("better-sqlite3")).default;G=oT(new Q(T))}return G.exec(eT(_)),G}catch{try{G?.close()}catch{}return null}}var G$="surface-workspaces-v1",d0=/^[a-f0-9]{64}$/,X$=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,Y$=1024,Q$=".surface-workspaces-v1.capacity.sqlite",s0=/^\.tmp-acp-remote-workspace-([1-9][0-9]*)-[a-f0-9]{32}\.pending$/;class H extends Error{name="AcpRemoteWorkspaceReferenceError";code;retryable;constructor(T){let $=T==="session_surface_not_found"?{message:"Session surface was not found",retryable:!1}:T==="session_surface_capacity"?{message:"Session surface capacity is exhausted",retryable:!0}:{message:"Session surface state is invalid",retryable:!1};super($.message);this.code=T,this.retryable=$.retryable,Object.setPrototypeOf(this,new.target.prototype)}}var v,$0=new Map;function a0(T){return W.join(String(T),G$)}async function t0(T,$){let _=S($);if(d(_.collisionIdentity)!==String(T))throw new H("session_surface_state_invalid");let G=r0(_.exactIdentity),X=a0(T);return await U$(T,X),Z$(X,()=>V$(X,async()=>{await H$(X);let Y=await o0(T,X,!0),Q=Y.recordsByDigest.get(G);if(Q)return Q.workspaceRef;if(Y.recordsByDigest.size>=Y$)throw new H("session_surface_capacity");let Z=W.join(X,`${G}.json`),U=new Set(Y.workspaceRefToDigest.keys());for(let V=0;V<32;V+=1){let g=L$();if(U.has(g))continue;return z$(T,X,Z,_,{version:1,exactIdentityDigest:G,workspaceRef:g})}throw new H("session_surface_state_invalid")}))}async function Z$(T,$){let _=$0.get(T)??Promise.resolve(),G=()=>{return},X=new Promise((Q)=>{G=Q}),Y=_.catch(()=>{return}).then(()=>X);$0.set(T,Y),await _.catch(()=>{return});try{return await $()}finally{if(G(),$0.get(T)===Y)$0.delete(T)}}async function U$(T,$){try{await H0($,String(T))}catch(_){if(q(_)!=="ENOENT"){if(_ instanceof H)throw _;throw new H("session_surface_state_invalid")}try{await _$($,{recursive:!1,mode:448})}catch(G){if(q(G)!=="EEXIST")throw new H("session_surface_state_invalid")}await H0($,String(T)),await m(String(T))}}async function V$(T,$){await v?.beforeCapacityLockAttempt?.();let _=await B$(T),G=!1,X,Y,Q;try{_.database.exec("BEGIN IMMEDIATE;"),G=!0,await v?.afterCapacityLockAcquired?.(),Q={value:await $()}}catch(Z){X=Z}if(G)try{await g$(_),_.database.exec("ROLLBACK;")}catch(Z){Y=Z}try{_.database.close()}catch(Z){if(!G)Y=Z}if(await _.identityHandle.close().catch(()=>{return}),Y!==void 0)throw new H("session_surface_state_invalid");if(X instanceof H)throw X;if(X!==void 0||!Q)throw new H("session_surface_state_invalid");return Q.value}async function B$(T){let $=W.join(T,Q$),_=null,G;try{let X=!1;try{let Q=await i($,"wx",384);X=!0,await Q.sync(),await Q.close()}catch(Q){if(q(Q)!=="EEXIST")throw Q}if(await u($,T),X)await m(T);G=await i($,"r"),await c(G,$,T);let Y=await G.stat({bigint:!0});if(_=await T0($,{busyTimeoutMs:30000}),!_)throw new H("session_surface_state_invalid");if(_.exec("PRAGMA locking_mode=NORMAL;"),_.exec("PRAGMA synchronous=FULL;"),_.exec("PRAGMA busy_timeout=30000;"),process.platform!=="win32")await i0($,384);return await c(G,$,T),await C$($,T),{database:_,identity:Y,identityHandle:G,path:$}}catch(X){await G?.close().catch(()=>{return});try{_?.close()}catch{}if(X instanceof H)throw X;throw new H("session_surface_state_invalid")}}async function g$(T){await c(T.identityHandle,T.path,W.dirname(T.path));let $=await T.identityHandle.stat({bigint:!0});if(!O0(T.identity,$))throw new H("session_surface_state_invalid")}async function C$(T,$){for(let _ of["-journal","-shm","-wal"]){let G=`${T}${_}`;try{if(process.platform!=="win32")await i0(G,384);await u(G,$)}catch(X){if(q(X)!=="ENOENT"){if(X instanceof H)throw X;throw new H("session_surface_state_invalid")}}}}async function H$(T){let $=await c0(T,{withFileTypes:!0}),_=!1;for(let G of $){if(!s0.test(G.name))continue;let X=W.join(T,G.name);await u(X,T),await C0(X),_=!0}if(_)await m(T)}async function o0(T,$,_){try{await H0($,String(T))}catch(Q){if(!_&&q(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};if(Q instanceof H)throw Q;throw new H("session_surface_state_invalid")}let G;try{G=await c0($,{withFileTypes:!0})}catch(Q){if(!_&&q(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};throw new H("session_surface_state_invalid")}let X=new Map,Y=new Map;for(let Q of G){if(s0.test(Q.name)){await u(W.join($,Q.name),$);continue}if(!Q.name.endsWith(".json"))continue;let Z=W.basename(Q.name,".json");if(!d0.test(Z))throw new H("session_surface_state_invalid");let U=W.join($,Q.name),V=await O$(U,$);if(V.exactIdentityDigest!==Z)throw new H("session_surface_state_invalid");if(X.has(Z))throw new H("session_surface_state_invalid");let g=Y.get(V.workspaceRef);if(g&&g!==Z)throw new H("session_surface_state_invalid");X.set(Z,V),Y.set(V.workspaceRef,Z)}return{recordsByDigest:X,workspaceRefToDigest:Y}}async function O$(T,$){let _;try{await u(T,$),_=await i(T,"r"),await c(_,T,$);let G=await _.readFile({encoding:"utf8"});return M$(G)}catch(G){if(G instanceof H&&G.code==="session_surface_not_found")throw G;if(q(G)==="ENOENT")throw new H("session_surface_not_found");throw new H("session_surface_state_invalid")}finally{await _?.close()}}function M$(T){let $;try{$=JSON.parse(T)}catch{throw new H("session_surface_state_invalid")}if(!F$($))throw new H("session_surface_state_invalid");return $}function F$(T){if(!T||typeof T!=="object"||Array.isArray(T))return!1;let $=T,_=Object.keys($).sort();if(_.length!==3||_[0]!=="exactIdentityDigest"||_[1]!=="version"||_[2]!=="workspaceRef")return!1;return $.version===1&&typeof $.exactIdentityDigest==="string"&&d0.test($.exactIdentityDigest)&&typeof $.workspaceRef==="string"&&X$.test($.workspaceRef)}function r0(T){return T$("sha256").update(`acp-remote-workspace-exact-identity\x00${T}`).digest("hex")}function L$(){return`acp-remote-workspace:${n0(32).toString("base64url")}`}function J$(){return`.tmp-acp-remote-workspace-${process.pid}-${n0(16).toString("hex")}.pending`}async function H0(T,$){if(W.dirname(T)!==$)throw new H("session_surface_state_invalid");let _=await n(T);if(_.isSymbolicLink()||!_.isDirectory())throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new H("session_surface_state_invalid");let G=e0(_.mode);if(process.platform!=="win32"&&G!==448)throw new H("session_surface_state_invalid");await M0(T,$,W.basename(T))}async function u(T,$){if(W.dirname(T)!==$)throw new H("session_surface_state_invalid");let _=await n(T);if(_.isSymbolicLink()||!_.isFile())throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new H("session_surface_state_invalid");let G=e0(_.mode);if(process.platform!=="win32"&&G!==384)throw new H("session_surface_state_invalid");await M0(T,$,W.basename(T))}async function c(T,$,_){let[G,X]=await Promise.all([T.stat({bigint:!0}),n($,{bigint:!0})]);if(W.dirname($)!==_||X.isSymbolicLink()||!X.isFile()||!G.isFile()||X.dev!==G.dev||X.ino!==G.ino)throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&(Number(X.uid)!==process.getuid()||Number(G.uid)!==process.getuid()))throw new H("session_surface_state_invalid");let Y=Number(X.mode&BigInt(511)),Q=Number(G.mode&BigInt(511));if(process.platform!=="win32"&&(Y!==384||Q!==384))throw new H("session_surface_state_invalid");await M0($,_,W.basename($))}async function M0(T,$,_){let G=await l0(T),X=await l0($);if(G!==W.join(X,_))throw new H("session_surface_state_invalid")}async function m(T){if(!I$(process.platform))return;try{if(v?.syncDirectory){await v.syncDirectory(T);return}await N$(T)}catch{throw new H("session_surface_state_invalid")}}function I$(T){return T!=="win32"}async function N$(T){let $=await i(T,"r");try{await $.sync()}finally{await $.close()}}async function z$(T,$,_,G,X){let Y=W.join($,J$()),Q,Z,U=!1,V=!1,g,O;try{Q=await i(Y,"wx",384),await Q.writeFile(JSON.stringify(X),"utf8"),await Q.sync(),await c(Q,Y,$),Z=await Q.stat({bigint:!0}),await Q.close(),Q=void 0,await v?.beforePublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y});try{await $$(Y,_),U=!0}catch(M){if(q(M)!=="EEXIST")throw M;g=await j$(T,G)}if(U){let M=await n(_,{bigint:!0});if(!Z||!O0(Z,M))throw new H("session_surface_state_invalid");await u(_,$),await m($),V=!0,g=X.workspaceRef;try{await v?.afterPublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y})}catch{}}}catch(M){O=M}finally{await Q?.close().catch(()=>{return})}if(O!==void 0&&U&&!V&&Z)try{let M=await n(_,{bigint:!0});if(O0(Z,M))await C0(_),await m($)}catch{}try{if(await C0(Y),!V)await m($)}catch(M){if(q(M)!=="ENOENT"&&O===void 0&&!V)O=M}if(O instanceof H)throw O;if(O!==void 0||g===void 0)throw new H("session_surface_state_invalid");return g}async function j$(T,$){let _=a0(T),G=await o0(T,_,!0),X=r0(S($).exactIdentity),Y=G.recordsByDigest.get(X);if(!Y)throw new H("session_surface_state_invalid");return Y.workspaceRef}function O0(T,$){return BigInt(T.dev)===BigInt($.dev)&&BigInt(T.ino)===BigInt($.ino)}function q(T){return T!==null&&typeof T==="object"&&"code"in T&&typeof T.code==="string"?T.code:void 0}function e0(T){return typeof T==="bigint"?Number(T&BigInt(511)):T&511}import*as b from"node:path";var XT=50,YT=100,W$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),K$=new Set(["high","medium","low"]),QT=/^[A-Za-z0-9_-]+$/,k$=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/,A$=/^acp-remote-exact-path:[a-f0-9]{64}$/;function ZT(T){return typeof T==="string"&&k$.test(T)&&Number.isFinite(Date.parse(T))}function TT(T){return typeof T==="string"&&b.isAbsolute(T)}function $T(T){return typeof T==="string"&&A$.test(T)}function x$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function E$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function q$(T){try{if(!QT.test(T))throw Error("invalid");let $=Buffer.from(T,"base64url").toString("utf8");if(Buffer.from($,"utf8").toString("base64url")!==T)throw Error("invalid");let _=JSON.parse($);if(_.version!==1||_.kind!==void 0&&_.kind!=="local"||typeof _.includeSubagents!=="boolean"||_.archived!==void 0&&typeof _.archived!=="boolean"||!(_.cwd===null||TT(_.cwd))||!ZT(_.lastMessageTime)||!TT(_.projectPath)||!A(_.sessionId))throw Error("invalid");return{version:1,kind:"local",cwd:_.cwd===null?null:b.resolve(_.cwd),includeSubagents:_.includeSubagents,archived:_.archived??!1,lastMessageTime:_.lastMessageTime,projectPath:b.resolve(_.projectPath),sessionId:_.sessionId}}catch{throw Error("Invalid session cursor")}}function D$(T){try{if(!QT.test(T))throw Error("invalid");let $=Buffer.from(T,"base64url").toString("utf8");if(Buffer.from($,"utf8").toString("base64url")!==T)throw Error("invalid");let _=JSON.parse($),G=Object.keys(_),X=new Set(["version","kind","exactIdentity","includeSubagents","archived","lastMessageTime","workspaceIdentity","sessionId"]);if(G.some((Y)=>!X.has(Y))||_.version!==1||_.kind!=="remote"||typeof _.includeSubagents!=="boolean"||typeof _.archived!=="boolean"||!(_.exactIdentity===null||$T(_.exactIdentity))||!ZT(_.lastMessageTime)||!$T(_.workspaceIdentity)||!A(_.sessionId))throw Error("invalid");return{version:1,kind:"remote",exactIdentity:_.exactIdentity??null,includeSubagents:_.includeSubagents,archived:_.archived,lastMessageTime:_.lastMessageTime,workspaceIdentity:_.workspaceIdentity,sessionId:_.sessionId}}catch{throw Error("Invalid remote session cursor")}}function p(T){let $="";for(let _=0;_<T.length;_+=1)$+=T.charCodeAt(_).toString(16).padStart(4,"0");return $}function w$(T){if(!T.cursor)return;let $=q$(T.cursor);if($.cwd!==T.cwd||$.includeSubagents!==T.includeSubagents||($.archived??!1)!==T.archived)throw Error("Session cursor scope does not match this query");return $}function S$(T){if(!T.cursor)return;let $=D$(T.cursor);if($.exactIdentity!==T.exactIdentity||T.exactIdentity!==null&&$.workspaceIdentity!==T.exactIdentity||$.includeSubagents!==T.includeSubagents||($.archived??!1)!==T.archived)throw Error("Remote session cursor scope does not match this query");return $}function i_(T={}){let{cwd:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T;if($!==void 0&&!b.isAbsolute($))throw Error("Session catalog cwd must be absolute");let Q=G===void 0?XT:G;if(!Number.isInteger(Q)||Q<1||Q>YT)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:$===void 0?null:b.resolve($),cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function c_(T={}){let{descriptor:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T,Q=G===void 0?XT:G;if(!Number.isInteger(Q)||Q<1||Q>YT)throw Error("Session catalog limit must be an integer from 1 to 100");return{descriptor:$,exactIdentity:$?.exactIdentity??null,cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function d_(T={}){let $=_T(T.taskStatus,W$,"task status"),_=_T(T.taskPriority,K$,"task priority"),G=GT(T.taskDueAfter,"taskDueAfter"),X=GT(T.taskDueBefore,"taskDueBefore");return f$(G,X),{...$?{taskStatuses:$}:{},..._?{taskPriorities:_}:{},...G?{taskDueAfter:G}:{},...X?{taskDueBefore:X}:{}}}function _T(T,$,_){if(T===void 0)return;let G=Array.isArray(T)?T:[T];if(G.length===0)return;let X=new Set;for(let Y of G){if(typeof Y!=="string"||!$.has(Y))throw Error(`Invalid session ${_} filter`);X.add(Y)}return[...X].sort()}function GT(T,$){if(T===void 0)return;if(typeof T!=="string"||!Number.isFinite(Date.parse(T)))throw Error(`Invalid session ${$} filter`);return new Date(T).toISOString()}function f$(T,$){if(T!==void 0&&$!==void 0&&T>$)throw Error("Session task due range is inverted")}function R$(T,$){if(T.lastMessageTime>$.lastMessageTime)return-1;if(T.lastMessageTime<$.lastMessageTime)return 1;if(T.projectPath<$.projectPath)return-1;if(T.projectPath>$.projectPath)return 1;if(T.sessionId<$.sessionId)return-1;if(T.sessionId>$.sessionId)return 1;return 0}function b$(T,$){if(T.lastMessageTime>$.lastMessageTime)return-1;if(T.lastMessageTime<$.lastMessageTime)return 1;if(T.workspaceIdentity<$.workspaceIdentity)return-1;if(T.workspaceIdentity>$.workspaceIdentity)return 1;if(T.sessionId<$.sessionId)return-1;if(T.sessionId>$.sessionId)return 1;return 0}function s_(T,$){let _=[...T],G=w$($);if(G)_=_.filter((Q)=>R$(Q,{sessionId:G.sessionId,projectPath:G.projectPath,lastMessageTime:G.lastMessageTime})>0);let X=_.slice(0,$.limit);if(X.length===0||_.length<=X.length)return{sessions:X};let Y=X[X.length-1];return{sessions:X,nextCursor:x$({version:1,kind:"local",cwd:$.cwd,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,projectPath:Y.projectPath,sessionId:Y.sessionId})}}function a_(T,$){let _=[...T],G=S$($);if(G)_=_.filter((Q)=>b$(Q,{sessionId:G.sessionId,projectPath:Q.projectPath,lastMessageTime:G.lastMessageTime,workspaceIdentity:G.workspaceIdentity})>0);let X=_.slice(0,$.limit);if(X.length===0||_.length<=X.length)return{sessions:X};let Y=X[X.length-1];return{sessions:X,nextCursor:E$({version:1,kind:"remote",exactIdentity:$.exactIdentity,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,workspaceIdentity:Y.workspaceIdentity,sessionId:Y.sessionId})}}function y$(T){return T.type==="message_created"||T.type==="token_budget_handoff_recorded"||T.type==="part_created"||T.type==="part_updated"||T.type==="turn_started"||T.type==="turn_completed"||T.type==="turn_aborted"||T.type==="turn_recovery_acknowledged"||T.type==="interaction_requested"||T.type==="interaction_responded"||T.type==="interaction_recovered"||T.type==="review_started"||T.type==="review_completed"}function F0(T){return T.type==="message_created"&&T.data.role==="user"&&(T.data.inboxMessageId!==void 0||T.data.parentMessageId===void 0)}function L0(T,$){let _=T.find((G)=>F0(G)&&G.data.messageId===$);if(!_)throw Error(`Rewind checkpoint not found: ${$}`);return{messageId:$,preview:UT(T,$),createdAt:_.data.createdAt}}function UT(T,$){let _=T.flatMap((G)=>{if(G.type!=="part_created"||G.data.messageId!==$)return[];if(G.data.partType==="text"){let X=G.data.payload;return typeof X.text==="string"?[X.text]:[]}if(G.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(_.length<=160)return _;return`${_.slice(0,160)}...`}function VT(T,$){L0(T,$);let _=T.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),G=T[_],X=G?.type==="message_created"?G.data.inboxMessageId:void 0,Y=new Set(T.flatMap((Q)=>Q.type==="turn_started"&&X&&Q.data.inputMessageIds?.includes(X)?[Q.data.turnId]:[]));return T.filter((Q,Z)=>{if((Q.type==="turn_started"||Q.type==="turn_completed"||Q.type==="turn_aborted"||Q.type==="turn_recovery_acknowledged")&&Y.has(Q.data.turnId))return!1;return Z<_||!y$(Q)})}function l(T){let $=[];for(let _ of T){if(_.type!=="session_rewound"){$.push(_);continue}if(L0($,_.data.targetMessageId),_.data.mode!=="code")$=VT($,_.data.targetMessageId)}return $}function o_(T){let $=l(T);return $.filter(F0).map((_)=>({messageId:_.data.messageId,preview:UT($,_.data.messageId),createdAt:_.data.createdAt})).reverse()}function r_(T,$){let _=l(T),G=L0(_,$),X=_.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),Y=_.slice(X);return{checkpoint:G,projectedEntries:VT(_,$),removedTurns:Y.filter(F0).length,snapshotMessageIds:Y.flatMap((Q)=>Q.type==="part_created"&&Q.data.partType==="tool_call"?[Q.data.partId]:[])}}import{createHash as s$}from"node:crypto";var T1={clientVisible:!1};function BT(T){if(T.metadata&&typeof T.metadata==="object"&&!Array.isArray(T.metadata)&&T.metadata.clientVisible===!1)return!1;return!(T.role==="user"&&typeof T.content==="string"&&T.content.startsWith("This turn made a non-trivial implementation. Before finishing, call Task ")&&T.content.endsWith("Only a fresh structured PASS verdict allows completion."))}import{StringDecoder as m$}from"node:string_decoder";var _1=1048576;function J0(T,$){let _=$;while(_<T.length&&(T[_]&192)===128)_+=1;return _}class I0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;totalBytes=0;constructor(T=1048576){this.maxBytes=T;if(!Number.isSafeInteger(T)||T<=0)throw Error("maxBytes must be a positive safe integer")}append(T){let $=Buffer.isBuffer(T)?T:Buffer.from(T);if($.length===0)return;if(this.totalBytes+=$.length,$.length>this.maxBytes){this.retainOversizedChunkTail($);return}this.chunks.push($),this.retainedBytes+=$.length,this.trimToLimit(),this.compactChunks()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),retainedBytes:this.retainedBytes,omittedBytes:this.omittedBytes,totalBytes:this.totalBytes}}consume(){let T=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,T}retainedChunkCountForTests(){return this.chunks.length}retainOversizedChunkTail(T){this.omittedBytes+=this.retainedBytes,this.chunks.length=0,this.retainedBytes=0;let $=J0(T,T.length-this.maxBytes);if(this.omittedBytes+=$,$===T.length)return;let _=Buffer.from(T.subarray($));this.chunks.push(_),this.retainedBytes=_.length}trimToLimit(){let T=!1;while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let _=this.retainedBytes-this.maxBytes;if($.length<=_){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length,T=!0;continue}let G=J0($,_);this.chunks[0]=$.subarray(G),this.retainedBytes-=G,this.omittedBytes+=G,T=!0}if(T)this.realignRetainedStart()}realignRetainedStart(){while(this.chunks.length>0){let T=this.chunks[0];if(T.length===0){this.chunks.shift();continue}let $=J0(T,0);if($===0)return;if(this.retainedBytes-=$,this.omittedBytes+=$,$===T.length)this.chunks.shift();else{this.chunks[0]=T.subarray($);return}}}compactChunks(){if(this.chunks.length<=32)return;let T=Buffer.concat(this.chunks,this.retainedBytes);if(this.chunks.length=0,T.length>0)this.chunks.push(T)}}var _0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},y={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},gT={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},h$={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},P$=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:_0,summaryTemplate:(T)=>`Successfully processed ${T} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:_0,summaryTemplate:(T)=>`Package operation completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:y,summaryTemplate:(T)=>`Build completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:gT},{pattern:/^git\s+(status|branch|remote)/i,config:y},{pattern:/^git\s+(log|diff|show)/i,config:gT},{pattern:/^(ls|dir|tree)\s+/i,config:y,summaryTemplate:(T)=>`Listed ${T} items`},{pattern:/^find\s+/i,config:y,summaryTemplate:(T)=>`Found ${T} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:y,summaryTemplate:(T)=>`Found ${T} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:_0,summaryTemplate:(T)=>`Docker operation completed (${T} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:_0,summaryTemplate:(T)=>`Python package operation completed (${T} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:y,summaryTemplate:(T)=>`Rust operation completed (${T} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:y,summaryTemplate:(T)=>`Go operation completed (${T} lines)`}];function CT(T,$,_){let G=$,X=_??T.length;if(G>0){let Y=T.charCodeAt(G);if(Y>=56320&&Y<=57343)G+=1}if(X<T.length){let Y=T.charCodeAt(X-1);if(Y>=55296&&Y<=56319)X-=1}return T.slice(G,X)}class N0{static getConfigForCommand(T){for(let{pattern:$,config:_,summaryTemplate:G}of P$)if($.test(T))return{config:_,summaryTemplate:G};return{config:h$}}static truncate(T,$){let{config:_,summaryTemplate:G}=this.getConfigForCommand($);return this.truncateWithConfig(T,_,G)}static truncateWithConfig(T,$,_){let G=T.length,X=T.split(`
|
|
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=CT(V,0,O),I=CT(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 HT=32768,v$=1048576,u$=65536,p$=3600000,OT=4096,l$=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;function V1(){return{async execute(){return{exitCode:null,stdout:"",stderr:"",error:"ACP terminal capability is unavailable"}}}}class z0{stream;executionId;onEvent;output=new I0(v$/2);decoder=new m$("utf8");sniffChunks=[];sniffBytes=0;binary=!1;totalBytes=0;streamedBytes=0;streamTruncated=!1;pendingEvents=[];constructor(T,$,_){this.stream=T;this.executionId=$;this.onEvent=_}append(T){let $=Buffer.isBuffer(T)?T:Buffer.from(T);if($.length===0)return;if(this.totalBytes+=$.length,this.sniffBytes<OT){let G=$.subarray(0,Math.min($.length,OT-this.sniffBytes));this.sniffChunks.push(G),this.sniffBytes+=G.length,this.binary=this.binary||Buffer.concat(this.sniffChunks).includes(0)}if(this.binary)return;let _=MT(this.decoder.write($));this.output.append(_),this.emit(_)}finish(){if(this.binary)return;let T=MT(this.decoder.end());this.output.append(T),this.emit(T)}snapshot(){let T=this.output.peek();if(this.binary)return{content:`[binary ${this.stream} omitted: ${this.totalBytes} bytes]`,omittedBytes:this.totalBytes,binary:!0};return{content:T.content,omittedBytes:T.omittedBytes,binary:!1}}async flushEvents(){await Promise.all(this.pendingEvents),this.pendingEvents.length=0}emit(T){if(!T||!this.onEvent||this.streamTruncated)return;let $=u$-this.streamedBytes;if($<=0){this.streamTruncated=!0;return}let _=n$(T,$);if(this.streamedBytes+=Buffer.byteLength(_),_.length<T.length)this.streamTruncated=!0;this.pendingEvents.push(Promise.resolve(this.onEvent({type:"output",executionId:this.executionId,stream:this.stream,chunk:_,streamedBytes:this.streamedBytes,streamTruncated:this.streamTruncated})).then(()=>{return}))}}function MT(T){return T.replace(l$,"")}function n$(T,$){let _=Buffer.from(T);if(_.length<=$)return T;let G=$;while(G>0&&(_[G]&192)===128)G-=1;return _.subarray(0,G).toString("utf8")}function FT(T){return T.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function i$(T){let $=T.trim();if(!$)throw Error("User shell command cannot be empty");if($.length>HT)throw Error(`User shell command exceeds ${HT} characters`);if($.includes("\x00"))throw Error("User shell command contains a null byte");return $}function c$(){return{execute(T,$){return new Promise((_)=>{let G=process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash",X=process.platform==="win32"?["/d","/s","/c",T]:["-l","-c",T],{child:Y,processTree:Q}=LT(G,X,{cwd:$.cwd,env:$.env,stdio:["ignore","pipe","pipe"]}),Z="",U="",V=!1,g=!1,O=!1,M,I=()=>{return M??=Q.terminate(),M},z=setTimeout(()=>{V=!0,I()},$.timeoutMs),j=()=>{g=!0,I()};if($.signal.addEventListener("abort",j,{once:!0}),$.signal.aborted)j();Y.stdout?.on("data",(C)=>{$.onOutput?.("stdout",C)}),Y.stderr?.on("data",(C)=>{$.onOutput?.("stderr",C)});let B=async(C)=>{if(O)return;if(O=!0,clearTimeout(z),$.signal.removeEventListener("abort",j),V||g)await I();_({...C,stdout:"",stderr:"",timedOut:V,aborted:g})};Y.once("error",(C)=>{B({exitCode:null,error:C.message})}),Y.once("close",(C)=>{B({exitCode:C})})})}}}async function B1(T,$){let _=i$(T),G=$.timeoutMs??p$,X=new z0("stdout",$.executionId,$.onEvent),Y=new z0("stderr",$.executionId,$.onEvent),Q=Date.now();await $.onEvent?.({type:"started",executionId:$.executionId,command:_});let Z,U=!1,V=!1;try{Z=await($.executor??c$()).execute(_,{cwd:$.cwd,env:$.env,timeoutMs:G,signal:$.signal,onOutput:(j,B)=>{if(j==="stdout")U=!0;else V=!0;(j==="stdout"?X:Y).append(B)}})}catch(j){Z={exitCode:null,stdout:"",stderr:"",error:j instanceof Error?j.message:String(j)}}if(!U)X.append(Z.stdout);if(!V)Y.append(Z.stderr);X.finish(),Y.finish(),await Promise.all([X.flushEvents(),Y.flushEvents()]);let g=X.snapshot(),O=Y.snapshot(),M=N0.truncateForLLM(g.content.trim(),O.content.trim(),_),I=Z.aborted||$.signal.aborted?"aborted":Z.timedOut?"timed_out":Z.error?"spawn_error":Z.exitCode===0?"completed":"failed",z={version:1,command:_,status:I,exitCode:Z.exitCode,durationMs:Math.max(0,Date.now()-Q),stdout:M.stdout,stderr:Z.error?[M.stderr,Z.error].filter(Boolean).join(`
|
|
20
|
+
`):M.stderr,stdoutOmittedBytes:g.omittedBytes,stderrOmittedBytes:O.omittedBytes,binaryOutput:g.binary||O.binary,truncated:Boolean(M.truncationInfo)||g.omittedBytes>0||O.omittedBytes>0};return await $.onEvent?.({type:"completed",executionId:$.executionId,record:z}),z}function g1(T){let $=[T.stdout?`stdout:
|
|
21
|
+
${T.stdout}`:"",T.stderr?`stderr:
|
|
22
|
+
${T.stderr}`:""].filter(Boolean).join(`
|
|
23
|
+
`);return["<user_shell_command>",`<command>${FT(T.command)}</command>`,"<result>",`Status: ${T.status}`,`Exit code: ${T.exitCode??"null"}`,`Duration: ${(T.durationMs/1000).toFixed(3)} seconds`,`Output:
|
|
24
|
+
${FT($||"(no output)")}`,"</result>","</user_shell_command>"].join(`
|
|
25
|
+
`)}function JT(T){let $=[T.stdout,T.stderr?`stderr:
|
|
26
|
+
${T.stderr}`:""].filter(Boolean).join(`
|
|
27
|
+
`);return[`! ${T.command}`,$||"(no output)"].join(`
|
|
28
|
+
`)}function d$(T){if(!T||typeof T!=="object"||Array.isArray(T))return;let $=T;if($.version!==1||typeof $.command!=="string"||!["completed","failed","aborted","timed_out","spawn_error"].includes(String($.status))||$.exitCode!==null&&typeof $.exitCode!=="number"||typeof $.durationMs!=="number"||typeof $.stdout!=="string"||typeof $.stderr!=="string"||typeof $.stdoutOmittedBytes!=="number"||typeof $.stderrOmittedBytes!=="number"||typeof $.binaryOutput!=="boolean"||typeof $.truncated!=="boolean")return;return $}function IT(T){if(!T||typeof T!=="object"||Array.isArray(T))return;return d$(T.userShellCommand)}var a$=262144,t$="session-surface-message\x00",KT="[private state path]",G0="[content truncated]",NT=`
|
|
29
|
+
${G0}`,X0=String.fromCharCode(27),o$=String.fromCharCode(7),r$=String.fromCharCode(157),e$=String.fromCharCode(156),T_=String.fromCharCode(155),$_=new RegExp(`(?:${f(X0)}\\]|${f(r$)})[\\s\\S]*?(?:${f(o$)}|${f(X0)}\\\\|${f(e$)})`,"g"),__=new RegExp(`(?:${f(X0)}\\[|${f(T_)})[0-?]*[ -/]*[@-~]`,"g");function j0(T,$){let _={privateRoots:[T],privateValues:[$.exactIdentity,$.collisionIdentity]};if($.style==="win32")_.caseInsensitivePrivateRoots=[$.wirePath];else _.privateRoots=[T,$.wirePath];return _}class L extends Error{code="session_surface_state_invalid";constructor(){super("session surface projection state is invalid");this.name="SessionSurfaceProjectionError"}}function kT(T,$){let _=M_($.maxContentBytes),{privateRoots:G,caseInsensitivePrivateRoots:X}=AT($),Y=xT($.privateValues??[]),Q=l(T),Z=new Map;for(let V of Q){if(k0(V.seq),V.type==="message_created"){Z.set(V.data.messageId,{event:V,orderedPartIds:[],partsById:new Map});continue}if(V.type!=="part_created"&&V.type!=="part_updated")continue;let g=Z.get(V.data.messageId);if(!g)continue;Q_(g,V)}let U=[];for(let V of Z.values()){let g=X_(V,G,X,Y,_);if(g)U.push(g)}return U}function G_(T){return typeof T==="object"&&T!==null&&!Array.isArray(T)}function f(T){return T.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function X_(T,$,_,G,X){let Y=T.event.data.role;if(Y!=="user"&&Y!=="assistant")return;let Q=Y_(T),Z=qT(Q),U={role:Y,content:Z,...T.event.data.metadata!==void 0?{metadata:T.event.data.metadata}:{}};if(!BT(U))return;let V=V_(T.event.data.createdAt),O=ET(Y0(Y0(Z,_,!0),$),G).trim();if(!O)return;let M=H_(O,X),I=U_(T.event);if(M.truncated)return{id:I,role:Y,content:M.content,timestamp:V,truncated:!0};return{id:I,role:Y,content:M.content,timestamp:V}}function W0(T,$){let{privateRoots:_,caseInsensitivePrivateRoots:G}=AT($);return ET(Y0(Y0(qT(T),G,!0),_),xT($.privateValues??[]))}function Y_(T){let $=IT(T.event.data.metadata);if($)return JT($);return T.orderedPartIds.map((_)=>T.partsById.get(_)).flatMap((_)=>_?[_.content]:[]).join("")}function Q_(T,$){if($.data.partType!=="text"&&$.data.partType!=="image")return;let _=$.data.partType==="text"?{partId:$.data.partId,type:"text",content:Z_($.data.payload)}:{partId:$.data.partId,type:"image",content:"[Image]"};if(!T.partsById.has($.data.partId))T.orderedPartIds.push($.data.partId);T.partsById.set($.data.partId,_)}function Z_(T){if(!G_(T))return"";let $=T.text;return typeof $==="string"?$:""}function U_(T){let $=k0(T.seq);return K0($,T.data.messageId)}function K0(T,$){let _=k0(T),G=s$("sha256").update(t$).update($).digest("hex").slice(0,16);return`surface-message:${_}:${G}`}function V_(T){let $=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/.exec(T);if(!$)throw new L;let _=Number($[1]),G=Number($[2]),X=Number($[3]),Y=Number($[4]),Q=Number($[5]),Z=Number($[6]),U=$[8],V=new Date(Date.UTC(_,G,0)).getUTCDate(),g=U==="Z"||U!==void 0&&Number(U.slice(1,3))<=23&&Number(U.slice(4,6))<=59;if(G<1||G>12||X<1||X>V||Y>23||Q>59||Z>59||!g||!Number.isFinite(Date.parse(T)))throw new L;return T}function zT(T,$){return[...new Set([...T,...$].filter(Boolean))].sort((_,G)=>G.length-_.length)}function jT(T){return/^[A-Za-z]:[\\/]/.test(T)||/^\\\\/.test(T)}function AT(T){let $=zT(T.privateRoots,T.bladeStorageRoots??[]);return{privateRoots:$.filter((_)=>!jT(_)),caseInsensitivePrivateRoots:zT([...T.caseInsensitivePrivateRoots??[],...$.filter(jT)],[])}}function xT(T){return[...new Set(T.filter(Boolean))].sort(($,_)=>_.length-$.length)}function ET(T,$){let _=T;for(let G of $)_=_.split(G).join(KT);return _}function Y0(T,$,_=!1){let G=T;for(let X of $)G=B_(G,X,_);return G}function B_(T,$,_){if(!$)return T;let G=0,X="",Y=_?new RegExp($.split(/[\\/]+/).map((Q)=>f(Q)).join("[\\\\/]+"),"i"):void 0;while(G<T.length){let Q=Y?.exec(T.slice(G)),Z=Y?Q?G+Q.index:-1:T.indexOf($,G);if(Z<0){X+=T.slice(G);break}X+=T.slice(G,Z);let U=Q?.[0].length??$.length,V=g_(T,Z,U);if(V===Z){X+=T[Z],G=Z+1;continue}X+=KT,G=V}return X}function g_(T,$,_){let G=$+_;if(G>=T.length)return G;let X=T[G];if(X===void 0)return G;if(!C_(X)&&!WT(X))return $;let Y=G;while(Y<T.length){let Q=T[Y];if(Q===void 0||WT(Q))break;Y+=1}return Y}function C_(T){return T==="/"||T==="\\"}function WT(T){return T===" "||T==="\t"||T===`
|
|
30
|
+
`||T==="\r"||T==='"'||T==="'"||T==="`"||T==="<"||T===">"||T==="("||T===")"||T==="["||T==="]"||T==="{"||T==="}"||T===","||T===";"||T===":"||T==="!"||T==="?"}function qT(T){return[...T.replace(/\r\n?/g,`
|
|
31
|
+
`).replace($_,"").replace(__,"").split(`${X0}\\`).join("")].filter((G)=>{let X=G.charCodeAt(0);return!(X===0||X>=1&&X<=8||X===11||X===12||X>=14&&X<=31||X>=127&&X<=159)}).join("")}function H_(T,$){if(Buffer.byteLength(T,"utf8")<=$)return{content:T,truncated:!1};let _=O_($),G=Buffer.byteLength(_,"utf8"),X=Math.max(0,$-G);return{content:`${DT(T,X)}${_}`,truncated:!0}}function DT(T,$){if($<=0)return"";let _=Buffer.from(T,"utf8");if(_.length<=$)return T;let G=_.subarray(0,$).toString("utf8");while(Buffer.byteLength(G,"utf8")>$)G=G.slice(0,-1);return G.replace(/\uFFFD$/,"")}function O_(T){let $=Buffer.byteLength(NT,"utf8");if(T>=$)return NT;let _=Buffer.byteLength(G0,"utf8");if(T>=_)return G0;return DT(G0,T)}function M_(T){let $=T??a$;if(!Number.isSafeInteger($)||$<=0)throw new L;return $}function k0(T){let $=T;if($===void 0||!Number.isSafeInteger($)||$<=0)throw new L;return $}import*as x from"node:fs";import{createReadStream as F_}from"node:fs";import*as J from"node:fs/promises";import*as A0 from"node:path";import{createInterface as L_}from"node:readline";var wT=65536;function Q0(T){let $=T.data;if($===null||typeof $!=="object"||Array.isArray($))throw Error("Session event data must be a JSON object");return JSON.stringify(T)}function J_(T,$,_){let G=T.trim();if(!G)return;try{return JSON.parse(G)}catch(X){throw Error(`Invalid session JSONL in ${_} at line ${$}`,{cause:X})}}function a(T,$="session transcript"){let _=T.split(`
|
|
32
|
+
`),G=!T.endsWith(`
|
|
33
|
+
`),X=[];for(let[Y,Q]of _.entries())try{let Z=J_(Q,Y+1,$);if(Z){if(typeof Z.seq!=="number")Z.seq=X.length+1;X.push(Z)}}catch(Z){if(G&&Y===_.length-1)break;throw Z}return X}class K{static appendQueues=new Map;filePath;constructor(T){this.filePath=T}static maxSeq(T){let $=0;for(let _ of T)if(typeof _.seq==="number"&&_.seq>$)$=_.seq;return $}static stampSeqFrom(T,$){let _=$;return T.map((G)=>{if(typeof G.seq==="number"){if(G.seq>_)_=G.seq;return G}return _+=1,{...G,seq:_}})}static stampSeq(T,$){return K.stampSeqFrom(T,K.maxSeq($))}async append(T){try{let[$]=await this.appendEntries([T]);return $}catch($){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,$),$}}async appendBatch(T){try{return await this.appendEntries(T)}catch($){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,$),$}}async appendEntries(T){if(T.length===0)return[];return this.enqueue(async()=>{await J.mkdir(A0.dirname(this.filePath),{recursive:!0,mode:493});let $=await J.open(this.filePath,"a+",384);try{let _=await this.repairIncompleteTail($),G=await this.readTailSeq($),X=K.stampSeqFrom(T,G),Y=`${X.map(Q0).join(`
|
|
34
|
+
`)}
|
|
35
|
+
`;return await $.appendFile(_+Y,"utf8"),await $.sync(),X}finally{await $.close()}})}async createExclusive(T){if(T.length===0)throw Error("Cannot create an empty session transcript");await J.mkdir(A0.dirname(this.filePath),{recursive:!0,mode:493});let $;try{$=await J.open(this.filePath,"wx",384);let G=`${K.stampSeq(T,[]).map(Q0).join(`
|
|
36
|
+
`)}
|
|
37
|
+
`;await $.writeFile(G,"utf-8"),await $.sync()}catch(_){if($)await $.close(),$=void 0,await J.unlink(this.filePath).catch(()=>{return});throw _}finally{await $?.close()}}async readAll(T={}){if(T.signal?.throwIfAborted(),!x.existsSync(this.filePath))return[];let $=await J.readFile(this.filePath,{encoding:"utf-8",signal:T.signal});return a($,this.filePath)}async readStream(T){return new Promise(($,_)=>{if(!x.existsSync(this.filePath)){$();return}let G=F_(this.filePath,"utf-8"),X=L_({input:G,crlfDelay:Number.POSITIVE_INFINITY}),Y=0;X.on("line",async(Q)=>{let Z=Q.trim();if(Z.length===0)return;try{let U=JSON.parse(Z);if(Y+=1,typeof U.seq!=="number")U.seq=Y;await T(U)}catch(U){console.warn(`[JSONLStore] 解析 JSON 行失败: ${Z}`,U)}}),X.on("close",()=>$()),X.on("error",_),G.on("error",_)})}async filter(T){let $=[];return await this.readStream((_)=>{if(T(_))$.push(_)}),$}async readLast(T){return(await this.readAll()).slice(-T)}async readFromSeq(T){return(await this.readAll()).filter((_)=>(_.seq??0)>=T)}async getStats(){try{if(!x.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let T=await J.stat(this.filePath),_=(await J.readFile(this.filePath,"utf-8")).split(`
|
|
38
|
+
`).filter((G)=>G.trim().length>0).length;return{exists:!0,size:T.size,lineCount:_}}catch(T){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,T),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await J.access(this.filePath),!0}catch{return!1}}async delete(){try{return await this.enqueue(async()=>{try{return await J.unlink(this.filePath),!0}catch(T){if(T.code==="ENOENT")return!1;throw T}})}catch(T){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,T),T}}async deleteValidated(T){return this.enqueue(async()=>{let $;try{$=await J.open(this.filePath,"r")}catch(G){if(G.code==="ENOENT")return!1;throw G}let _;try{_=a(await $.readFile("utf8"),"session transcript")}finally{await $.close()}if(!T(_))return!1;try{return await J.unlink(this.filePath),!0}catch(G){if(G.code==="ENOENT")return!1;throw G}})}async appendValidated(T,$={}){return this.appendValidatedAsync(async(_)=>T(_),$)}async appendValidatedBatch(T,$={}){return this.appendValidatedBatchAsync(async(_)=>T(_),$)}async appendValidatedBatchAsync(T,$={}){return this.enqueue(async()=>{let _=$.noFollow?x.constants.O_RDWR|(x.constants.O_NOFOLLOW??0):"r+",G=await J.open(this.filePath,_);try{await $.validateHandle?.(G);let{entries:X,separator:Y,size:Q}=await this.readCommittedState(G,"session transcript"),Z=await T(X);if(Z.length===0)return[];let U=K.stampSeq(Z,X),V=`${U.map(Q0).join(`
|
|
39
|
+
`)}
|
|
40
|
+
`;return await G.write(Y+V,Q,"utf8"),await G.sync(),await $.validateHandle?.(G),U}finally{await G.close()}})}async appendValidatedAsync(T,$={}){return this.enqueue(async()=>{let _=$.noFollow?x.constants.O_RDWR|(x.constants.O_NOFOLLOW??0):"r+",G=await J.open(this.filePath,_);try{await $.validateHandle?.(G);let{entries:X,separator:Y,size:Q}=await this.readCommittedState(G,"session transcript"),Z=await T(X),[U]=K.stampSeq([Z],X),V=`${Y}${Q0(U)}
|
|
41
|
+
`;return await G.write(V,Q,"utf8"),await G.sync(),await $.validateHandle?.(G),U}finally{await G.close()}})}async readAllValidated(T={}){T.signal?.throwIfAborted();let $=T.noFollow?x.constants.O_RDONLY|(x.constants.O_NOFOLLOW??0):"r",_;try{_=await J.open(this.filePath,$)}catch(G){if(T.signal?.throwIfAborted(),G.code==="ENOENT")return[];throw G}try{await T.validateHandle?.(_),T.signal?.throwIfAborted();let G=a(await _.readFile({encoding:"utf8",signal:T.signal}),"session transcript");return T.signal?.throwIfAborted(),await T.validateHandle?.(_),T.signal?.throwIfAborted(),G}finally{await _.close()}}getFilePath(){return this.filePath}async enqueue(T){let _=(K.appendQueues.get(this.filePath)??Promise.resolve()).catch(()=>{return}).then(T),G=_.then(()=>{return},()=>{return});K.appendQueues.set(this.filePath,G);try{return await _}finally{if(K.appendQueues.get(this.filePath)===G)K.appendQueues.delete(this.filePath)}}async readCommittedState(T,$=this.filePath){let _=await this.repairIncompleteTail(T),G=await T.readFile("utf8"),X=a(G,$),{size:Y}=await T.stat();return{entries:X,separator:_,size:Y}}async readTailSeq(T){let{size:$}=await T.stat();if($===0)return 0;let _=Math.max(0,$-wT),G=Buffer.allocUnsafe($-_);await T.read(G,0,G.length,_);let X=G.toString("utf8").split(`
|
|
42
|
+
`);for(let Q=X.length-1;Q>=0;Q--){let Z=X[Q].trim();if(!Z)continue;if(Q===0&&_>0)break;try{let U=JSON.parse(Z).seq;if(typeof U==="number")return U}catch{}break}let Y=await T.readFile("utf8");return K.maxSeq(a(Y,this.filePath))}async repairIncompleteTail(T){let{size:$}=await T.stat();if($===0)return"";let _=Buffer.allocUnsafe(1);if(await T.read(_,0,1,$-1),_[0]===10)return"";let G=await this.findTailStart(T,$),X=Buffer.allocUnsafe($-G);await T.read(X,0,X.length,G);try{return JSON.parse(X.toString("utf8").trim()),`
|
|
43
|
+
`}catch{return await T.truncate(G),""}}async findTailStart(T,$){let _=$;while(_>0){let G=Math.max(0,_-wT),X=Buffer.allocUnsafe(_-G);await T.read(X,0,X.length,G);let Y=X.lastIndexOf(10);if(Y>=0)return G+Y+1;_=G}return 0}}function ST(T){let $=Number(T.pragma("user_version")??0);if($===8)return;if($>0&&$!==8)T.exec(`
|
|
44
|
+
DROP TABLE IF EXISTS parts_fts;
|
|
45
|
+
DROP TABLE IF EXISTS surface_messages;
|
|
46
|
+
DROP TABLE IF EXISTS parts;
|
|
47
|
+
DROP TABLE IF EXISTS sessions;
|
|
48
|
+
DROP TABLE IF EXISTS projection_state;
|
|
49
|
+
DROP TABLE IF EXISTS surface_projection_meta;
|
|
50
|
+
`);T.exec(`
|
|
51
|
+
CREATE TABLE IF NOT EXISTS surface_projection_meta (
|
|
52
|
+
singleton INTEGER PRIMARY KEY CHECK(singleton = 1),
|
|
53
|
+
catalog_revision INTEGER NOT NULL DEFAULT 0 CHECK(catalog_revision >= 0)
|
|
54
|
+
);
|
|
55
|
+
INSERT OR IGNORE INTO surface_projection_meta (singleton, catalog_revision)
|
|
56
|
+
VALUES (1, 0);
|
|
57
|
+
|
|
58
|
+
CREATE TABLE IF NOT EXISTS projection_state (
|
|
59
|
+
source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
|
|
60
|
+
source_file_path TEXT NOT NULL,
|
|
61
|
+
project_path TEXT,
|
|
62
|
+
session_id TEXT NOT NULL,
|
|
63
|
+
last_seq INTEGER NOT NULL DEFAULT 0,
|
|
64
|
+
file_size INTEGER NOT NULL DEFAULT 0,
|
|
65
|
+
mtime_ms INTEGER NOT NULL DEFAULT 0,
|
|
66
|
+
stat_fingerprint TEXT NOT NULL DEFAULT '',
|
|
67
|
+
PRIMARY KEY (source_kind, source_file_path)
|
|
68
|
+
);
|
|
69
|
+
CREATE INDEX IF NOT EXISTS idx_projection_state_session ON projection_state(
|
|
70
|
+
source_kind, project_path, session_id
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
74
|
+
source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
|
|
75
|
+
source_file_path TEXT NOT NULL,
|
|
76
|
+
project_path TEXT NOT NULL,
|
|
77
|
+
session_id TEXT NOT NULL,
|
|
78
|
+
root_id TEXT,
|
|
79
|
+
parent_id TEXT,
|
|
80
|
+
relation_type TEXT,
|
|
81
|
+
title TEXT,
|
|
82
|
+
agent_type TEXT,
|
|
83
|
+
model TEXT,
|
|
84
|
+
task_status TEXT,
|
|
85
|
+
task_priority TEXT,
|
|
86
|
+
task_kind TEXT,
|
|
87
|
+
task_due_at TEXT,
|
|
88
|
+
archived_at TEXT,
|
|
89
|
+
last_message_time TEXT,
|
|
90
|
+
project_sort_key TEXT NOT NULL,
|
|
91
|
+
public_workspace_ref TEXT,
|
|
92
|
+
public_workspace_sort_key TEXT NOT NULL,
|
|
93
|
+
session_sort_key TEXT NOT NULL,
|
|
94
|
+
first_message_time TEXT,
|
|
95
|
+
message_count INTEGER NOT NULL DEFAULT 0,
|
|
96
|
+
has_errors INTEGER NOT NULL DEFAULT 0,
|
|
97
|
+
is_subagent INTEGER NOT NULL DEFAULT 0,
|
|
98
|
+
-- 完整 StoredSessionMetadata JSON,读回时直接反序列化,保证与 JSONL 路径一致。
|
|
99
|
+
metadata_json TEXT NOT NULL,
|
|
100
|
+
surface_digest TEXT NOT NULL,
|
|
101
|
+
PRIMARY KEY (source_kind, project_path, session_id)
|
|
102
|
+
);
|
|
103
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_source_file ON sessions(
|
|
104
|
+
source_kind, source_file_path
|
|
105
|
+
);
|
|
106
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_catalog ON sessions(
|
|
107
|
+
last_message_time DESC,
|
|
108
|
+
source_kind DESC,
|
|
109
|
+
public_workspace_sort_key ASC,
|
|
110
|
+
session_sort_key ASC
|
|
111
|
+
);
|
|
112
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_archived ON sessions(
|
|
113
|
+
source_kind,
|
|
114
|
+
archived_at,
|
|
115
|
+
project_path,
|
|
116
|
+
parent_id
|
|
117
|
+
);
|
|
118
|
+
-- 任务看板过滤/排序:按项目锁定后再按状态、优先级、截止时间收敛。
|
|
119
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_task_board ON sessions(
|
|
120
|
+
project_path,
|
|
121
|
+
task_status,
|
|
122
|
+
task_priority,
|
|
123
|
+
task_due_at,
|
|
124
|
+
source_kind
|
|
125
|
+
);
|
|
126
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_task_status ON sessions(
|
|
127
|
+
task_status,
|
|
128
|
+
project_path,
|
|
129
|
+
source_kind
|
|
130
|
+
);
|
|
131
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_task_priority ON sessions(
|
|
132
|
+
task_priority,
|
|
133
|
+
task_due_at,
|
|
134
|
+
source_kind
|
|
135
|
+
) WHERE task_priority IS NOT NULL;
|
|
136
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_task_due_at ON sessions(
|
|
137
|
+
task_due_at,
|
|
138
|
+
source_kind
|
|
139
|
+
) WHERE task_due_at IS NOT NULL;
|
|
140
|
+
|
|
141
|
+
CREATE TABLE IF NOT EXISTS parts (
|
|
142
|
+
source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
|
|
143
|
+
project_path TEXT NOT NULL,
|
|
144
|
+
session_id TEXT NOT NULL,
|
|
145
|
+
part_id TEXT NOT NULL,
|
|
146
|
+
message_id TEXT,
|
|
147
|
+
part_type TEXT,
|
|
148
|
+
role TEXT,
|
|
149
|
+
seq INTEGER,
|
|
150
|
+
timestamp TEXT,
|
|
151
|
+
text TEXT,
|
|
152
|
+
PRIMARY KEY (source_kind, project_path, session_id, part_id)
|
|
153
|
+
);
|
|
154
|
+
CREATE INDEX IF NOT EXISTS idx_parts_session ON parts(
|
|
155
|
+
source_kind, project_path, session_id
|
|
156
|
+
);
|
|
157
|
+
|
|
158
|
+
CREATE TABLE IF NOT EXISTS surface_messages (
|
|
159
|
+
source_kind TEXT NOT NULL CHECK(source_kind IN ('local', 'acp-remote')),
|
|
160
|
+
project_path TEXT NOT NULL,
|
|
161
|
+
session_id TEXT NOT NULL,
|
|
162
|
+
message_seq INTEGER NOT NULL CHECK(message_seq >= 0),
|
|
163
|
+
message_id TEXT NOT NULL,
|
|
164
|
+
message_json TEXT NOT NULL,
|
|
165
|
+
byte_count INTEGER NOT NULL CHECK(byte_count >= 0),
|
|
166
|
+
PRIMARY KEY (
|
|
167
|
+
source_kind, project_path, session_id, message_seq, message_id
|
|
168
|
+
)
|
|
169
|
+
);
|
|
170
|
+
CREATE INDEX IF NOT EXISTS idx_surface_messages_history ON surface_messages(
|
|
171
|
+
source_kind, project_path, session_id, message_seq DESC, message_id DESC
|
|
172
|
+
);
|
|
173
|
+
|
|
174
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
|
|
175
|
+
text,
|
|
176
|
+
source_kind UNINDEXED,
|
|
177
|
+
project_path UNINDEXED,
|
|
178
|
+
session_id UNINDEXED,
|
|
179
|
+
part_id UNINDEXED,
|
|
180
|
+
role UNINDEXED,
|
|
181
|
+
timestamp UNINDEXED,
|
|
182
|
+
seq UNINDEXED,
|
|
183
|
+
tokenize = 'unicode61'
|
|
184
|
+
);
|
|
185
|
+
`),T.exec("PRAGMA user_version=8;")}var N_=PT("Service"),z_="session-surface-projection-v1\x00",S0=524288,j_=3,W_=new AbortController().signal,K_=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,vT=`WITH RECURSIVE archive_members(
|
|
186
|
+
source_kind, project_path, public_workspace_ref, session_id, archive_root_id,
|
|
187
|
+
effective_archived_at, depth
|
|
188
|
+
) AS (
|
|
189
|
+
SELECT source_kind, project_path, public_workspace_ref, session_id, session_id,
|
|
190
|
+
archived_at, 0
|
|
191
|
+
FROM sessions
|
|
192
|
+
WHERE archived_at IS NOT NULL
|
|
193
|
+
UNION ALL
|
|
194
|
+
SELECT child.source_kind, child.project_path, child.public_workspace_ref,
|
|
195
|
+
child.session_id, parent.archive_root_id, parent.effective_archived_at,
|
|
196
|
+
parent.depth + 1
|
|
197
|
+
FROM sessions child
|
|
198
|
+
JOIN archive_members parent
|
|
199
|
+
ON child.source_kind = parent.source_kind
|
|
200
|
+
AND child.project_path = parent.project_path
|
|
201
|
+
AND child.public_workspace_ref IS parent.public_workspace_ref
|
|
202
|
+
AND child.parent_id = parent.session_id
|
|
203
|
+
WHERE parent.depth < 128
|
|
204
|
+
),
|
|
205
|
+
ranked_archive AS (
|
|
206
|
+
SELECT source_kind, project_path, public_workspace_ref, session_id,
|
|
207
|
+
archive_root_id, effective_archived_at,
|
|
208
|
+
ROW_NUMBER() OVER (
|
|
209
|
+
PARTITION BY source_kind, project_path, public_workspace_ref, session_id
|
|
210
|
+
ORDER BY depth ASC, archive_root_id ASC
|
|
211
|
+
) AS rank
|
|
212
|
+
FROM archive_members
|
|
213
|
+
)`,uT={readSession(T,$,_){return $?T.readAllValidated({noFollow:!0,signal:_,validateHandle:(G)=>RT($,T.getFilePath(),G)}):T.readAll({signal:_})}},P0=uT;function h1(T){P0=T}function P1(){P0=uT}function m1(){return S0}var t;function pT(){return U0.join(V0(),"index.db")}async function k_(){let T=pT();if(t&&t.path===T)return t.db;let $=(async()=>{let _=await T0(T);if(!_)return null;try{return ST(_),_}catch{return null}})();return t={path:T,db:$},$}function A_(){t=void 0}function x_(T){if(T&&typeof T==="object"){let $=T.text;if(typeof $==="string")return $}return null}function E_(T,$,_,G,X){T.prepare("DELETE FROM parts WHERE source_kind=? AND project_path=? AND session_id=?").run($,_,G),T.prepare("DELETE FROM parts_fts WHERE source_kind=? AND project_path=? AND session_id=?").run($,_,G);let Y=new Map;for(let U of X)if(U.type==="message_created")Y.set(U.data.messageId,U.data.role);let Q=T.prepare(`INSERT OR REPLACE INTO parts
|
|
214
|
+
(source_kind, project_path, session_id, part_id, message_id, part_type, role,
|
|
215
|
+
seq, timestamp, text)
|
|
216
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),Z=T.prepare(`INSERT INTO parts_fts
|
|
217
|
+
(text, source_kind, project_path, session_id, part_id, role, timestamp, seq)
|
|
218
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);for(let U of X){if(U.type!=="part_created"&&U.type!=="part_updated")continue;if(U.data.partType!=="text")continue;let V=x_(U.data.payload);if(V===null)continue;let g=Y.get(U.data.messageId)??"assistant",O=U.seq??0;if(Q.run($,_,G,U.data.partId,U.data.messageId,U.data.partType,g,O,U.timestamp,V),g==="user"||g==="assistant")Z.run(V,$,_,G,U.data.partId,g,U.timestamp,O)}}function q_(T,$,_,G,X){let{metadata:Y,publicWorkspaceRef:Q}=_,Z=p(Q??Y.projectPath);T.prepare(`INSERT INTO sessions
|
|
219
|
+
(source_kind, project_path, session_id, root_id, parent_id, relation_type, title,
|
|
220
|
+
agent_type, model, task_status, task_priority, task_kind, task_due_at,
|
|
221
|
+
archived_at, last_message_time, project_sort_key,
|
|
222
|
+
public_workspace_ref, public_workspace_sort_key, session_sort_key,
|
|
223
|
+
first_message_time, message_count, has_errors, is_subagent, metadata_json,
|
|
224
|
+
surface_digest, source_file_path)
|
|
225
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
226
|
+
ON CONFLICT(source_kind, project_path, session_id) DO UPDATE SET
|
|
227
|
+
source_file_path=excluded.source_file_path,
|
|
228
|
+
root_id=excluded.root_id, parent_id=excluded.parent_id,
|
|
229
|
+
relation_type=excluded.relation_type, title=excluded.title,
|
|
230
|
+
agent_type=excluded.agent_type, model=excluded.model,
|
|
231
|
+
task_status=excluded.task_status, task_priority=excluded.task_priority,
|
|
232
|
+
task_kind=excluded.task_kind, task_due_at=excluded.task_due_at,
|
|
233
|
+
archived_at=excluded.archived_at,
|
|
234
|
+
last_message_time=excluded.last_message_time,
|
|
235
|
+
project_sort_key=excluded.project_sort_key,
|
|
236
|
+
public_workspace_ref=excluded.public_workspace_ref,
|
|
237
|
+
public_workspace_sort_key=excluded.public_workspace_sort_key,
|
|
238
|
+
session_sort_key=excluded.session_sort_key,
|
|
239
|
+
first_message_time=excluded.first_message_time, message_count=excluded.message_count,
|
|
240
|
+
has_errors=excluded.has_errors, is_subagent=excluded.is_subagent,
|
|
241
|
+
metadata_json=excluded.metadata_json, surface_digest=excluded.surface_digest`).run($,Y.projectPath,Y.sessionId,Y.rootId,Y.parentId??null,Y.relationType??null,Y.title??null,Y.agentType??null,Y.model??null,Y.taskStatus,Y.taskPriority??null,Y.taskKind??null,Y.taskDueAt??null,Y.archivedAt??null,Y.lastMessageTime,p(Y.projectPath),Q??null,Z,p(Y.sessionId),Y.firstMessageTime,Y.messageCount,Y.hasErrors?1:0,Y.relationType==="subagent"?1:0,JSON.stringify(Y),G,X)}function E(T){T.prepare(`UPDATE surface_projection_meta
|
|
242
|
+
SET catalog_revision=catalog_revision + 1 WHERE singleton=1`).run()}function D_(T,$,_,G,X,Y){T.prepare(`DELETE FROM surface_messages
|
|
243
|
+
WHERE source_kind=? AND project_path=? AND session_id=?`).run($,_,G);let Q=new Map;for(let U of X)if(U.type==="message_created"&&typeof U.seq==="number")Q.set(U.seq,U.data.messageId);let Z=T.prepare(`INSERT INTO surface_messages
|
|
244
|
+
(source_kind, project_path, session_id, message_seq, message_id,
|
|
245
|
+
message_json, byte_count)
|
|
246
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`);for(let U of Y){let V=h0.parse(U),g=lT(V.id),O=Q.get(g);if(!O)throw new L;let M=JSON.stringify(V);Z.run($,_,G,g,O,M,Buffer.byteLength(M))}}function lT(T){let $=/^surface-message:([0-9]+):/.exec(T),_=$?Number($[1]):Number.NaN;if(!Number.isSafeInteger(_)||_<0)throw new L;return _}function w_(T){let{metadata:$}=T,_={locator:T.publicWorkspaceRef===void 0?{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}}:{version:2,sessionId:$.sessionId,workspace:{kind:"acp-remote",workspaceRef:T.publicWorkspaceRef}},...nT($,T.publicWorkspaceRef)};return I_("sha256").update(z_).update(JSON.stringify({catalogSummary:_,messages:T.surfaceMessages})).digest("hex")}function nT(T,$){let _=T.remoteWorkspace===void 0?void 0:S(T.remoteWorkspace);if(_===void 0!==($===void 0)||_&&d(_.collisionIdentity)!==T.projectPath||!A(T.sessionId)||!A(T.rootId)||T.parentId!==void 0&&!A(T.parentId)||T.relationType!==void 0&&T.relationType!=="subagent"&&T.relationType!=="fork"||!["queued","running","completed","failed","cancelled","interrupted"].includes(T.taskStatus)||!Number.isSafeInteger(T.messageCount)||T.messageCount<0||!T.firstMessageTime||!T.lastMessageTime||T.archivedAt!==void 0&&!T.archivedAt||T.selectedModelId!==void 0&&!T.selectedModelId)throw new L;let G={..._?j0(T.projectPath,_):{privateRoots:[]},bladeStorageRoots:[V0()]},X=T.relationType,Y=T.taskStatus,Q=mT(T.taskCompletedAt);return{displayCwd:_?.wirePath??T.projectPath,..._?{pathStyle:_.style}:{},...T.title!==void 0?{title:W0(T.title,G)}:{},rootId:T.rootId,...T.parentId!==void 0?{parentId:T.parentId}:{},...X!==void 0?{relationType:X}:{},taskStatus:Y,...Q!==void 0?{taskCompletedAt:Q}:{},messageCount:T.messageCount,firstMessageTime:T.firstMessageTime,lastMessageTime:T.lastMessageTime,hasErrors:T.hasErrors,...T.archivedAt!==void 0?{archivedAt:T.archivedAt}:{},...T.selectedModelId!==void 0?{selectedModelId:W0(T.selectedModelId,G)}:{}}}function m0(T,$,_,G){return T.prepare(`SELECT EXISTS(
|
|
247
|
+
SELECT 1 FROM sessions
|
|
248
|
+
WHERE source_kind=? AND project_path=? AND session_id=?
|
|
249
|
+
UNION ALL
|
|
250
|
+
SELECT 1 FROM surface_messages
|
|
251
|
+
WHERE source_kind=? AND project_path=? AND session_id=?
|
|
252
|
+
) AS present`).get($,_,G,$,_,G)?.present===1}function iT(T,$,_,G){let X=m0(T,$,_,G);if(X)T.prepare(`UPDATE projection_state SET stat_fingerprint=''
|
|
253
|
+
WHERE source_kind=? AND project_path=? AND session_id=?`).run($,_,G);for(let Y of["surface_messages","sessions","parts","parts_fts"])T.prepare(`DELETE FROM ${Y} WHERE source_kind=? AND project_path=? AND session_id=?`).run($,_,G);return X}function o(T,$,_,G){let X=iT(T,$,_,G);return T.prepare("DELETE FROM projection_state WHERE source_kind=? AND project_path=? AND session_id=?").run($,_,G),X}function Z0(T,$,_,G){let X=T.prepare(`SELECT project_path, session_id FROM sessions
|
|
254
|
+
WHERE source_kind=? AND source_file_path=?`).all($,_),Y=!1;for(let Q of X){if(Q.project_path===G?.projectPath&&Q.session_id===G.sessionId)continue;Y=iT(T,$,Q.project_path,Q.session_id)||Y}return Y}function f0(T,$,_){let G=Z0(T,$,_);return T.prepare("DELETE FROM projection_state WHERE source_kind=? AND source_file_path=?").run($,_),G}function x0(T,$,_,G,X,Y,Q,Z,U){T.prepare(`INSERT INTO projection_state
|
|
255
|
+
(source_kind, source_file_path, project_path, session_id, last_seq, file_size,
|
|
256
|
+
mtime_ms, stat_fingerprint)
|
|
257
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
258
|
+
ON CONFLICT(source_kind, source_file_path) DO UPDATE SET
|
|
259
|
+
project_path=excluded.project_path, session_id=excluded.session_id,
|
|
260
|
+
last_seq=excluded.last_seq, file_size=excluded.file_size,
|
|
261
|
+
mtime_ms=excluded.mtime_ms, stat_fingerprint=excluded.stat_fingerprint`).run($,U,_,G,X,Y,Q,Z)}function h(T){return[T.dev,T.ino,T.size,T.mtimeNs,T.ctimeNs].join(":")}async function E0(T,$,_,G,X,Y="local",Q){if(Q?.throwIfAborted(),Y==="acp-remote")return s(_,async(Z)=>{let U=r(Z,$),V=X??U;if(V!==U)throw new D("remote-session-file-path");return R0(T,$,_,G,V,Y,Z,Q)});return R0(T,$,_,G,X??y0(_,$),Y,void 0,Q)}async function R0(T,$,_,G,X,Y,Q,Z){if(Z?.throwIfAborted(),Y==="acp-remote"){if(!Q)throw new D("remote-session-scope");try{await q0(Q,X),Z?.throwIfAborted()}catch(F){if(Z?.aborted)throw F;if(F.code!=="ENOENT")throw F;return Z?.throwIfAborted(),T.transaction(()=>{if(o(T,Y,_,$))E(T)}),!0}}let U;try{U=await w0(X,{bigint:!0}),Z?.throwIfAborted()}catch(F){if(Z?.aborted)throw F;if(F.code!=="ENOENT")throw F;return T.transaction(()=>{if(f0(T,Y,X))E(T)}),!0}let V=T.prepare(`SELECT project_path, session_id, last_seq, file_size, mtime_ms, stat_fingerprint
|
|
262
|
+
FROM projection_state WHERE source_kind=? AND source_file_path=?`).get(Y,X);if(Y==="local"&&V&&V.stat_fingerprint===h(U)&&(V.project_path===null||m0(T,Y,V.project_path,V.session_id)))return!1;let g=new K(X),O;try{let F=U,k;for(let e=0;e<j_;e+=1){Z?.throwIfAborted();let p0=await P0.readSession(g,Q,Z??W_);Z?.throwIfAborted();let B0=await w0(X,{bigint:!0});if(Z?.throwIfAborted(),h(F)===h(B0)){O=p0,U=B0,k=p0;break}F=B0}if(!k)throw new L;O=k}catch(F){if(Z?.aborted)throw F;let k=F.code;if(k!=="ENOENT"){if(Y==="acp-remote"){if(F instanceof D)throw F;if(k!==void 0)throw new D("remote-session-read")}throw F}return T.transaction(()=>{if(f0(T,Y,X))E(T)}),!0}if(Y==="acp-remote"&&O.length===0){try{await q0(Q,X)}catch(F){if(Z?.aborted)throw F;if(F.code==="ENOENT")return T.transaction(()=>{if(o(T,Y,_,$))E(T)}),!0;throw F}throw new D("remote-session-empty")}Z?.throwIfAborted();let M=Y==="local"?O.find((F)=>F.type==="session_created"):void 0,I=Y==="local"&&M!==void 0&&Object.hasOwn(M.data,"remoteWorkspace"),z=null;if(Y==="acp-remote"){let F=bT(O,$,_);z=S(F.data.remoteWorkspace)}else if(I)S(M.data.remoteWorkspace);let j=O.reduce((F,k)=>typeof k.seq==="number"&&k.seq>F?k.seq:F,0),B=l(O),C=I?null:G(O,$,_,Y,X),N=C?.remoteWorkspace;if(Y==="acp-remote"){if(!C||C.sessionId!==$||C.projectPath!==_||N===void 0)throw new D("remote-session-metadata");let F=S(N);if(!z||F.style!==z.style||F.wirePath!==z.wirePath||F.exactIdentity!==z.exactIdentity||F.collisionIdentity!==z.collisionIdentity)throw new D("remote-session-descriptor");if(d(F.collisionIdentity)!==_)throw new D("remote-session-project-path")}if(O.length===0||!C||Y==="local"&&N!==void 0)return Z?.throwIfAborted(),T.transaction(()=>{let F=Z0(T,Y,X);if(x0(T,Y,null,$,j,Number(U.size),Number(U.mtimeMs),h(U),X),F)E(T)}),!0;let w=z&&Q?await t0(Q,z):void 0;Z?.throwIfAborted();let P=kT(O,{...z?j0(_,z):{privateRoots:[]},bladeStorageRoots:[V0()]}),v0={metadata:C,...w!==void 0?{publicWorkspaceRef:w}:{},surfaceMessages:P},u0=w_(v0),R=T.prepare(`SELECT last_message_time, source_file_path FROM sessions
|
|
263
|
+
WHERE source_kind=? AND project_path=? AND session_id=?`).get(Y,C.projectPath,C.sessionId),sT=Y==="acp-remote"&&Q?r(Q,C.sessionId):y0(C.projectPath,C.sessionId),aT=U0.resolve(X)===U0.resolve(sT);if(R&&R.source_file_path!==X&&!aT&&typeof R.last_message_time==="string"&&R.last_message_time>C.lastMessageTime)return Z?.throwIfAborted(),T.transaction(()=>{let F=Z0(T,Y,X,C);if(x0(T,Y,C.projectPath,C.sessionId,j,Number(U.size),Number(U.mtimeMs),h(U),X),F)E(T)}),!0;return Z?.throwIfAborted(),T.transaction(()=>{let F=T.prepare(`SELECT surface_digest FROM sessions
|
|
264
|
+
WHERE source_kind=? AND project_path=? AND session_id=?`).get(Y,C.projectPath,C.sessionId),e=Z0(T,Y,X,C)||F?.surface_digest!==u0;if(R?.source_file_path===X&&typeof R.last_message_time==="string"&&R.last_message_time>C.lastMessageTime)T.prepare(`UPDATE projection_state SET stat_fingerprint=''
|
|
265
|
+
WHERE source_kind=? AND project_path=? AND session_id=?`).run(Y,C.projectPath,C.sessionId);if(q_(T,Y,v0,u0,X),E_(T,Y,C.projectPath,C.sessionId,B),D_(T,Y,C.projectPath,C.sessionId,B,P),x0(T,Y,C.projectPath,C.sessionId,j,Number(U.size),Number(U.mtimeMs),h(U),X),e)E(T)}),!0}var fT=new WeakMap;function b0(T,$,_,G){let X=T.prepare(`SELECT session_id FROM projection_state
|
|
266
|
+
WHERE source_kind=? AND project_path=?
|
|
267
|
+
UNION
|
|
268
|
+
SELECT session_id FROM sessions
|
|
269
|
+
WHERE source_kind=? AND project_path=?
|
|
270
|
+
UNION
|
|
271
|
+
SELECT session_id FROM parts
|
|
272
|
+
WHERE source_kind=? AND project_path=?
|
|
273
|
+
UNION
|
|
274
|
+
SELECT session_id FROM parts_fts
|
|
275
|
+
WHERE source_kind=? AND project_path=?
|
|
276
|
+
UNION
|
|
277
|
+
SELECT session_id FROM surface_messages
|
|
278
|
+
WHERE source_kind=? AND project_path=?`).all($,_,$,_,$,_,$,_,$,_);for(let Y of X)if(!G.has(Y.session_id)){if(o(T,$,_,Y.session_id))E(T)}}async function S_(T,$,_,G){G?.throwIfAborted();try{await s(_,async(X)=>{let Y=(await D0(String(X))).flatMap((V)=>{if(!V.endsWith(".jsonl"))return[];let g=V.slice(0,-6);if(!A(g))return[];return[{filePath:r(X,g),sessionId:g}]});G?.throwIfAborted();let Q=new Set(Y.map((V)=>V.sessionId)),Z=Math.min(32,Y.length),U=0;await Promise.all(Array.from({length:Z},async()=>{while(U<Y.length){G?.throwIfAborted();let V=Y[U++];if(!V)continue;await R0(T,V.sessionId,_,$,V.filePath,"acp-remote",X,G)}})),G?.throwIfAborted(),T.transaction(()=>{b0(T,"acp-remote",_,Q)})})}catch(X){if(G?.aborted)throw X;if(X.code!=="ENOENT")throw X;T.transaction(()=>{b0(T,"acp-remote",_,new Set)})}}async function v1(T,$,_){_?.throwIfAborted();let G=await yT();_?.throwIfAborted();for(let Q of G)_?.throwIfAborted(),await S_(T,$,String(Q),_);let X=new Set(G.map(String)),Y=T.prepare(`SELECT project_path FROM projection_state WHERE source_kind='acp-remote'
|
|
279
|
+
UNION
|
|
280
|
+
SELECT project_path FROM sessions WHERE source_kind='acp-remote'
|
|
281
|
+
UNION
|
|
282
|
+
SELECT project_path FROM parts WHERE source_kind='acp-remote'
|
|
283
|
+
UNION
|
|
284
|
+
SELECT project_path FROM parts_fts WHERE source_kind='acp-remote'
|
|
285
|
+
UNION
|
|
286
|
+
SELECT project_path FROM surface_messages WHERE source_kind='acp-remote'`).all();for(let Q of Y)if(_?.throwIfAborted(),!X.has(Q.project_path))T.transaction(()=>{b0(T,"acp-remote",Q.project_path,new Set)})}async function f_(T,$,_=0){let G=fT.get(T)??{};if(fT.set(T,G),G.inFlight)return G.inFlight;if(_>0&&G.lastCompletedAt!==void 0&&Date.now()-G.lastCompletedAt<=_)return;let X=R_(T,$);G.inFlight=X;try{await X,G.lastCompletedAt=Date.now()}finally{if(G.inFlight===X)G.inFlight=void 0}}async function R_(T,$){let _=new Set,G=await hT(),Y=(await Promise.all(G.map(async(B)=>{if(B.kind==="local")try{return(await D0(B.storagePath)).flatMap((N)=>{if(!N.endsWith(".jsonl"))return[];let w=N.slice(0,-6);if(!A(w))return[];return[{kind:"local",filePath:U0.join(B.storagePath,N),projectPath:B.projectPath,sessionId:w}]})}catch{return[]}return s(B.storagePath,async(C)=>{return(await D0(String(C))).flatMap((w)=>{if(!w.endsWith(".jsonl"))return[];let P=w.slice(0,-6);if(!A(P))return[];return[{kind:"acp-remote",filePath:r(C,P),projectPath:B.projectPath,sessionId:P}]})})}))).flat();for(let B of Y)_.add(`${B.kind}\x00${B.filePath}`);let Q=T.prepare(`SELECT source_kind, source_file_path, project_path, session_id, last_seq,
|
|
287
|
+
file_size, mtime_ms, stat_fingerprint FROM projection_state`).all();T.transaction(()=>{for(let B of Q)if(!_.has(`${B.source_kind}\x00${B.source_file_path}`)){if(f0(T,B.source_kind,B.source_file_path))E(T)}});let Z=new Map(Q.map((B)=>[`${B.source_kind}\x00${B.source_file_path}`,B])),U=[],V=Math.min(128,Y.length),g=0;await Promise.all(Array.from({length:V},async()=>{while(g<Y.length){let B=Y[g++];if(!B)continue;if(B.kind==="acp-remote"){U.push(B);continue}try{let C=await w0(B.filePath,{bigint:!0}),N=Z.get(`${B.kind}\x00${B.filePath}`);if(N&&N.stat_fingerprint===h(C)&&(N.project_path===null||m0(T,B.kind,N.project_path,N.session_id)))continue}catch(C){if(C.code!=="ENOENT")throw C}U.push(B)}}));let O=Math.min(32,U.length),M=0;await Promise.all(Array.from({length:O},async()=>{while(M<U.length){let B=U[M++];if(!B)continue;try{if(B.kind==="acp-remote")await E0(T,B.sessionId,B.projectPath,$,B.filePath,"acp-remote");else await E0(T,B.sessionId,B.projectPath,$,B.filePath,"local")}catch(C){let N=C.code;if(B.kind==="acp-remote"){if(N==="ENOENT")continue;throw C}if(N==="acp_remote_workspace_state_invalid")throw C;if(N!=="ENOENT")N_.warn(`[SessionService] Skipping invalid session transcript: ${B.sessionId}`)}}}));let I=T.prepare(`SELECT p.source_file_path, p.project_path, p.session_id
|
|
288
|
+
FROM projection_state p
|
|
289
|
+
WHERE p.source_kind='local' AND p.project_path IS NOT NULL
|
|
290
|
+
AND (p.stat_fingerprint='' OR NOT EXISTS (
|
|
291
|
+
SELECT 1 FROM sessions s WHERE s.source_kind=p.source_kind
|
|
292
|
+
AND s.project_path=p.project_path AND s.session_id=p.session_id
|
|
293
|
+
))`).all();T.transaction(()=>{for(let B of I)T.prepare(`UPDATE projection_state SET stat_fingerprint=''
|
|
294
|
+
WHERE source_kind='local' AND source_file_path=?`).run(B.source_file_path)});for(let B of I)await E0(T,B.session_id,B.project_path,$,B.source_file_path);let z=T.prepare(`SELECT source_kind, project_path, session_id FROM sessions WHERE source_kind='acp-remote'
|
|
295
|
+
UNION SELECT source_kind, project_path, session_id FROM parts WHERE source_kind='acp-remote'
|
|
296
|
+
UNION SELECT source_kind, project_path, session_id FROM parts_fts WHERE source_kind='acp-remote'
|
|
297
|
+
UNION SELECT source_kind, project_path, session_id FROM surface_messages WHERE source_kind='acp-remote'`).all(),j=new Set(Y.filter((B)=>B.kind==="acp-remote").map((B)=>`${B.projectPath}\x00${B.sessionId}`));for(let B of z)if(!j.has(`${B.project_path}\x00${B.session_id}`))T.transaction(()=>{if(o(T,"acp-remote",B.project_path,B.session_id))E(T)})}function u1(T,$,_,G="local"){T.transaction(()=>{if(o(T,G,_,$))E(T)})}async function p1(T){let{rm:$}=await import("node:fs/promises");A_();let _=pT();for(let Y of["","-wal","-shm"])await $(`${_}${Y}`,{force:!0}).catch(()=>{return});let G=await k_();if(!G)return null;return await f_(G,T),G.prepare("SELECT COUNT(*) c FROM sessions").get()?.c??0}function cT(T){try{let $=JSON.parse(T.metadata_json);if(!$||typeof $!=="object"||Array.isArray($))throw new L;let _=$,G=p(T.public_workspace_ref??T.project_path);if(_.sessionId!==T.session_id||_.projectPath!==T.project_path||_.rootId!==T.root_id||(_.parentId??null)!==T.parent_id||(_.relationType??null)!==T.relation_type||_.taskStatus!==T.task_status||T.relation_type!==null&&T.relation_type!=="subagent"&&T.relation_type!=="fork"||!Number.isSafeInteger(T.message_count)||T.message_count<0||T.has_errors!==0&&T.has_errors!==1||T.is_subagent!==0&&T.is_subagent!==1||_.firstMessageTime!==T.first_message_time||_.lastMessageTime!==T.last_message_time||(_.title??null)!==T.title||(_.archivedAt??null)!==T.archived_at||_.messageCount!==T.message_count||Number(_.hasErrors)!==T.has_errors||Number(_.relationType==="subagent")!==T.is_subagent||T.public_workspace_sort_key!==G||T.session_sort_key!==p(T.session_id)||!/^[a-f0-9]{64}$/.test(T.surface_digest)||!T.stat_fingerprint||T.source_kind==="local"&&(T.public_workspace_ref!==null||_.remoteWorkspace!==void 0)||T.source_kind==="acp-remote"&&(T.public_workspace_ref===null||!K_.test(T.public_workspace_ref)||_.remoteWorkspace===void 0))throw new L;let X=T.effective_archived_at?{..._,archivedAt:T.effective_archived_at,archivedBySessionId:T.archive_root_id}:_,Y=nT(X,T.public_workspace_ref??void 0);return{sourceKind:T.source_kind,projectPath:T.project_path,sessionId:T.session_id,...T.public_workspace_ref===null?{}:{publicWorkspaceRef:T.public_workspace_ref},publicWorkspaceSortKey:T.public_workspace_sort_key,surfaceDigest:T.surface_digest,transcriptFingerprint:T.stat_fingerprint,lastMessageTime:T.last_message_time,sessionSortKey:T.session_sort_key,summary:Y}}catch{throw new L}}function l1(T,$){if(!A($))throw new L;try{return T.prepare(`${vT}
|
|
298
|
+
SELECT s.source_kind, s.project_path, s.session_id, s.root_id, s.parent_id,
|
|
299
|
+
s.relation_type, s.task_status, s.first_message_time,
|
|
300
|
+
s.last_message_time, s.title, s.archived_at, s.message_count,
|
|
301
|
+
s.has_errors,
|
|
302
|
+
s.is_subagent, a.archive_root_id, a.effective_archived_at,
|
|
303
|
+
s.public_workspace_ref, s.public_workspace_sort_key,
|
|
304
|
+
s.session_sort_key, s.surface_digest, p.stat_fingerprint,
|
|
305
|
+
s.metadata_json
|
|
306
|
+
FROM sessions s
|
|
307
|
+
JOIN projection_state p
|
|
308
|
+
ON p.source_kind=s.source_kind AND p.source_file_path=s.source_file_path
|
|
309
|
+
AND p.project_path=s.project_path AND p.session_id=s.session_id
|
|
310
|
+
LEFT JOIN ranked_archive a
|
|
311
|
+
ON a.source_kind=s.source_kind AND a.project_path=s.project_path
|
|
312
|
+
AND a.public_workspace_ref IS s.public_workspace_ref
|
|
313
|
+
AND a.session_id=s.session_id AND a.rank=1
|
|
314
|
+
WHERE s.session_id=?
|
|
315
|
+
ORDER BY s.source_kind DESC, s.public_workspace_sort_key ASC,
|
|
316
|
+
s.session_sort_key ASC`).all($).map(cT)}catch{throw new L}}function b_(T){let $=T.prepare("SELECT catalog_revision FROM surface_projection_meta WHERE singleton=1").get()?.catalog_revision;if(!Number.isSafeInteger($)||$===void 0||$<0)throw new L;return $}function n1(T,$){return dT($.limit),T.transaction(()=>{let _=[],G=["s.is_subagent=0",$.archived?"a.session_id IS NOT NULL":"a.session_id IS NULL"];if($.workspaceKind!==void 0)G.push("s.source_kind=?"),_.push($.workspaceKind);if($.boundary!==void 0)G.push(`(s.last_message_time < ?
|
|
317
|
+
OR (s.last_message_time = ? AND s.source_kind < ?)
|
|
318
|
+
OR (s.last_message_time = ? AND s.source_kind = ?
|
|
319
|
+
AND s.public_workspace_sort_key > ?)
|
|
320
|
+
OR (s.last_message_time = ? AND s.source_kind = ?
|
|
321
|
+
AND s.public_workspace_sort_key = ? AND s.session_sort_key > ?))`),_.push($.boundary.lastMessageTime,$.boundary.lastMessageTime,$.boundary.sourceKind,$.boundary.lastMessageTime,$.boundary.sourceKind,$.boundary.publicWorkspaceSortKey,$.boundary.lastMessageTime,$.boundary.sourceKind,$.boundary.publicWorkspaceSortKey,$.boundary.sessionSortKey);_.push($.limit+1);let X=b_(T),Y=T.prepare(`${vT}
|
|
322
|
+
SELECT s.source_kind, s.project_path, s.session_id, s.root_id, s.parent_id,
|
|
323
|
+
s.relation_type, s.task_status, s.first_message_time,
|
|
324
|
+
s.last_message_time, s.title, s.archived_at, s.message_count,
|
|
325
|
+
s.has_errors,
|
|
326
|
+
s.is_subagent, a.archive_root_id, a.effective_archived_at,
|
|
327
|
+
s.public_workspace_ref, s.public_workspace_sort_key,
|
|
328
|
+
s.session_sort_key, s.surface_digest, p.stat_fingerprint,
|
|
329
|
+
s.metadata_json
|
|
330
|
+
FROM sessions s
|
|
331
|
+
JOIN projection_state p
|
|
332
|
+
ON p.source_kind=s.source_kind AND p.source_file_path=s.source_file_path
|
|
333
|
+
AND p.project_path=s.project_path AND p.session_id=s.session_id
|
|
334
|
+
LEFT JOIN ranked_archive a
|
|
335
|
+
ON a.source_kind=s.source_kind AND a.project_path=s.project_path
|
|
336
|
+
AND a.public_workspace_ref IS s.public_workspace_ref
|
|
337
|
+
AND a.session_id=s.session_id AND a.rank=1
|
|
338
|
+
WHERE ${G.join(" AND ")}
|
|
339
|
+
ORDER BY s.last_message_time DESC, s.source_kind DESC,
|
|
340
|
+
s.public_workspace_sort_key ASC, s.session_sort_key ASC
|
|
341
|
+
LIMIT ?`).all(..._),Q=Y.slice(0,$.limit),Z=Q.map(cT),U=Y.length>$.limit?Q.at(-1):void 0;return{revision:X,sessions:Z,...U?{nextBoundary:{lastMessageTime:U.last_message_time,sourceKind:U.source_kind,publicWorkspaceSortKey:U.public_workspace_sort_key,sessionSortKey:U.session_sort_key}}:{}}})}function i1(T,$){if(dT($.limit),$.beforeSequence!==void 0&&(!Number.isSafeInteger($.beforeSequence)||$.beforeSequence<0))throw new L;let _=$.maxBytes??S0;if(!Number.isSafeInteger(_)||_<1)throw new L;let G=Math.min(_,S0);return T.transaction(()=>{let X=T.prepare(`SELECT s.surface_digest, p.stat_fingerprint FROM sessions s
|
|
342
|
+
JOIN projection_state p
|
|
343
|
+
ON p.source_kind=s.source_kind AND p.source_file_path=s.source_file_path
|
|
344
|
+
AND p.project_path=s.project_path AND p.session_id=s.session_id
|
|
345
|
+
WHERE s.source_kind=? AND s.project_path=? AND s.session_id=?`).get($.sourceKind,$.projectPath,$.sessionId);if(!X)throw new L;if(!/^[a-f0-9]{64}$/.test(X.surface_digest)||!X.stat_fingerprint)throw new L;let Y=$.beforeSequence===void 0?"":"AND message_seq < ?",Q=[$.sourceKind,$.projectPath,$.sessionId,...$.beforeSequence===void 0?[]:[$.beforeSequence],$.limit+1],Z=T.prepare(`SELECT message_seq, message_id, message_json, byte_count
|
|
346
|
+
FROM surface_messages
|
|
347
|
+
WHERE source_kind=? AND project_path=? AND session_id=? ${Y}
|
|
348
|
+
ORDER BY message_seq DESC, message_id DESC LIMIT ?`).all(...Q),U=[],V=2;for(let M of Z.slice(0,$.limit)){let I=U.length===0?0:1;if(U.length>0&&V+I+M.byte_count>G)break;U.push(M),V+=I+M.byte_count}let g=U.map((M)=>y_(M)).reverse(),O=Z.length>U.length;return{messages:g,hasOlder:O,...O&&U.length>0?{nextSequence:U.at(-1).message_seq}:{},transcriptFingerprint:X.stat_fingerprint,surfaceDigest:X.surface_digest}})}function y_(T){try{if(Buffer.byteLength(T.message_json)!==T.byte_count)throw new L;let $=h0.parse(JSON.parse(T.message_json));if($.id!==K0(T.message_seq,T.message_id)||lT($.id)!==T.message_seq)throw new L;return $}catch{throw new L}}function dT(T){if(!Number.isSafeInteger(T)||T<1||T>100)throw new L}function c1(T,$,_,G){let X=$.replace(/["*]/g," ").trim().split(/\s+/)[0];if(!X)return[];let Y=`"${X}"*`,Q=_?`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
349
|
+
WHERE parts_fts MATCH ? AND source_kind = 'local' AND project_path = ?
|
|
350
|
+
ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
351
|
+
WHERE parts_fts MATCH ? AND source_kind = 'local'
|
|
352
|
+
ORDER BY timestamp DESC LIMIT ?`,Z=T.prepare(Q);return _?Z.all(Y,_,G):Z.all(Y,G)}
|
|
353
|
+
export{t0 as ne,l as oe,o_ as pe,r_ as qe,a as re,K as se,p as te,w$ as ue,S$ as ve,i_ as we,c_ as xe,d_ as ye,R$ as ze,b$ as Ae,s_ as Be,a_ as Ce,T1 as De,BT as Ee,_1 as Fe,I0 as Ge,N0 as He,V1 as Ie,B1 as Je,g1 as Ke,JT as Le,IT as Me,j0 as Ne,kT as Oe,h1 as Pe,P1 as Qe,m1 as Re,pT as Se,k_ as Te,A_ as Ue,nT as Ve,E0 as We,S_ as Xe,v1 as Ye,f_ as Ze,u1 as _e,p1 as $e,l1 as af,b_ as bf,n1 as cf,i1 as df,c1 as ef};
|