blade-code 0.10.191 → 0.10.193

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-4cdk4mds.js → chunk-0eajnhrj.js} +1 -1
  3. package/dist/{chunk-3yxrw6x2.js → chunk-0h97pwtv.js} +2 -2
  4. package/dist/{chunk-9tj11gsc.js → chunk-0w1w2555.js} +1 -1
  5. package/dist/{chunk-xmymx75h.js → chunk-0xf70s5c.js} +1 -1
  6. package/dist/{chunk-vbjgcn49.js → chunk-1cy4ab77.js} +1 -1
  7. package/dist/chunk-1gwae1gr.js +1 -0
  8. package/dist/{chunk-ct8637yk.js → chunk-2qjsbxq5.js} +1 -1
  9. package/dist/{chunk-d420fs8m.js → chunk-2xpjy0ef.js} +1 -1
  10. package/dist/{chunk-0mr8nexh.js → chunk-3cas6rv5.js} +2 -2
  11. package/dist/chunk-42vt2eqq.js +1 -0
  12. package/dist/chunk-4bd6fe6g.js +1 -0
  13. package/dist/{chunk-kqvzmnja.js → chunk-4fbpydtn.js} +2 -2
  14. package/dist/{chunk-z31temfe.js → chunk-4g3qg8j7.js} +1 -1
  15. package/dist/{chunk-epe57k9k.js → chunk-4vcea99r.js} +247 -247
  16. package/dist/{chunk-t0gm0pn1.js → chunk-5yyp6njq.js} +1 -1
  17. package/dist/chunk-6ax5dpd3.js +1 -0
  18. package/dist/{chunk-arr9x580.js → chunk-6q0n03nz.js} +2 -2
  19. package/dist/chunk-6vaq3jf6.js +1 -0
  20. package/dist/{chunk-aewb2nz3.js → chunk-6wmjxmdg.js} +2 -2
  21. package/dist/{chunk-06hkf59s.js → chunk-7ajvrtb3.js} +1 -1
  22. package/dist/chunk-8sggrqep.js +1 -0
  23. package/dist/chunk-8sqpz0sz.js +1 -0
  24. package/dist/{chunk-dgbgj0kd.js → chunk-97rqk0ek.js} +1 -1
  25. package/dist/{chunk-xrkas5w5.js → chunk-9c7hesmj.js} +1 -1
  26. package/dist/{chunk-30x3mcsb.js → chunk-9fyjyk2f.js} +1 -1
  27. package/dist/chunk-ae0fafmv.js +1 -0
  28. package/dist/{chunk-kkrvvdf5.js → chunk-azd57pvw.js} +1 -1
  29. package/dist/{chunk-eg3ms291.js → chunk-cjfb4kjp.js} +1 -1
  30. package/dist/{chunk-ttpf4fc0.js → chunk-cycsbwm3.js} +2 -2
  31. package/dist/{chunk-acq26c7b.js → chunk-czrktgmy.js} +2 -2
  32. package/dist/{chunk-9e10833x.js → chunk-dkhn7mqt.js} +2 -2
  33. package/dist/{chunk-53fc0yrq.js → chunk-egss0m1x.js} +1 -1
  34. package/dist/chunk-ety33ry2.js +10 -0
  35. package/dist/{chunk-zzvs471p.js → chunk-fdr4fcrf.js} +1 -1
  36. package/dist/{chunk-5cznfhch.js → chunk-fnfay5y6.js} +2 -2
  37. package/dist/{chunk-a6wkam4s.js → chunk-g383afnv.js} +1 -1
  38. package/dist/{chunk-xw7bq6zq.js → chunk-gerzcz6q.js} +1 -1
  39. package/dist/{chunk-rvs364rz.js → chunk-ggdgk3gy.js} +2 -2
  40. package/dist/{chunk-wt3yt1yn.js → chunk-ghvfd7bx.js} +2 -2
  41. package/dist/{chunk-4ewsqbfn.js → chunk-gr9603ca.js} +1 -1
  42. package/dist/{chunk-zj1g4nbq.js → chunk-hnvvve5d.js} +1 -1
  43. package/dist/{chunk-j8hbddjp.js → chunk-j89qk7bp.js} +2 -2
  44. package/dist/{chunk-nheny8xp.js → chunk-je908ygr.js} +2 -2
  45. package/dist/chunk-jg7agxyv.js +1 -0
  46. package/dist/{chunk-3kszepm6.js → chunk-kehgewqh.js} +1 -1
  47. package/dist/{chunk-wcps5gjm.js → chunk-kkzznz4w.js} +1 -1
  48. package/dist/{chunk-ccevgmzy.js → chunk-ks48r1c6.js} +57 -57
  49. package/dist/{chunk-vw9paban.js → chunk-ky592ay9.js} +1 -1
  50. package/dist/{chunk-v0v07eef.js → chunk-m31pg7t5.js} +1 -1
  51. package/dist/{chunk-ptpjywje.js → chunk-m6bx0jv1.js} +2 -2
  52. package/dist/{chunk-qx6gb5k6.js → chunk-myvt7yjm.js} +2 -2
  53. package/dist/{chunk-4wx5sya5.js → chunk-n52n2w5v.js} +1 -1
  54. package/dist/{chunk-hpn1djam.js → chunk-nh9d0m2m.js} +2 -2
  55. package/dist/chunk-ntdw1nq1.js +1 -0
  56. package/dist/{chunk-jj4ggb04.js → chunk-p0wyhp5a.js} +2 -2
  57. package/dist/{chunk-w33zjw8m.js → chunk-p6586ftx.js} +2 -2
  58. package/dist/{chunk-f70awdz6.js → chunk-pk3ftt16.js} +1 -1
  59. package/dist/{chunk-2f8d0km4.js → chunk-qdbbke8f.js} +1 -1
  60. package/dist/{chunk-kv458q06.js → chunk-qpmvp4q2.js} +1 -1
  61. package/dist/{chunk-1amhckjs.js → chunk-qr80p5m0.js} +3 -3
  62. package/dist/{chunk-2mk914vk.js → chunk-rmfzym94.js} +2 -2
  63. package/dist/chunk-rmvfnmzv.js +1 -0
  64. package/dist/chunk-tm3789m3.js +2 -0
  65. package/dist/chunk-vsxv2sc6.js +1 -0
  66. package/dist/{chunk-g01mth5d.js → chunk-vzdsext4.js} +1 -1
  67. package/dist/{chunk-ddvdc2p0.js → chunk-wezr6wfq.js} +1 -1
  68. package/dist/{chunk-kvp523gt.js → chunk-wk869s65.js} +1 -1
  69. package/dist/chunk-wpg023nf.js +1 -0
  70. package/dist/{chunk-0tzecdv3.js → chunk-x49bw41v.js} +1 -1
  71. package/dist/{chunk-dk7ne5ns.js → chunk-xs15f82r.js} +1 -1
  72. package/dist/{chunk-g124q0rg.js → chunk-xvqbvpks.js} +1 -1
  73. package/dist/{chunk-3y2x6fb6.js → chunk-ys8gysg8.js} +1 -1
  74. package/dist/{chunk-a0j97370.js → chunk-z4cz1rce.js} +2 -2
  75. package/dist/{chunk-50vwafn5.js → chunk-zfxcef0z.js} +1 -1
  76. package/dist/{chunk-qcs8ce4s.js → chunk-zjjwxnmd.js} +1 -1
  77. package/dist/{chunk-y5wngtz0.js → chunk-ztreczac.js} +2 -2
  78. package/package.json +1 -1
  79. package/dist/chunk-57qaxtar.js +0 -1
  80. package/dist/chunk-5v0jcyea.js +0 -2
  81. package/dist/chunk-66wk3exc.js +0 -1
  82. package/dist/chunk-dvzyq3za.js +0 -1
  83. package/dist/chunk-efjy34de.js +0 -1
  84. package/dist/chunk-kdat33d5.js +0 -1
  85. package/dist/chunk-m5a288md.js +0 -10
  86. package/dist/chunk-mchg9trh.js +0 -1
  87. package/dist/chunk-pzqy0x7r.js +0 -1
  88. package/dist/chunk-qmfqy2qj.js +0 -1
  89. package/dist/chunk-tpkx9ztz.js +0 -1
  90. package/dist/chunk-v9pn46bz.js +0 -1
  91. package/dist/chunk-wqnq4kyn.js +0 -1
  92. package/dist/chunk-x0tavahs.js +0 -1
  93. package/dist/chunk-yp13ezhf.js +0 -1
@@ -0,0 +1 @@
1
+ import{sf as a,tf as b}from"./chunk-6wmjxmdg.js";import"./chunk-cycsbwm3.js";import"./chunk-cjfb4kjp.js";export{a as globalOptions,b as cliConfig};
@@ -0,0 +1,2 @@
1
+ var _=20,E=5242880,T=32768,A=1e6,S=4194304;
2
+ export{_ as Wi,E as Xi,T as Yi,A as Zi,S as _i};
@@ -0,0 +1 @@
1
+ import{ce as a,de as b,ee as c,fe as d,ge as e,he as f,ie as g}from"./chunk-czrktgmy.js";import"./chunk-egss0m1x.js";import"./chunk-ztreczac.js";import"./chunk-p6586ftx.js";import"./chunk-zfxcef0z.js";import"./chunk-1cy4ab77.js";import"./chunk-ys8gysg8.js";import"./chunk-tm3789m3.js";import"./chunk-qdbbke8f.js";import"./chunk-rmfzym94.js";import"./chunk-0eajnhrj.js";import"./chunk-cycsbwm3.js";import"./chunk-n52n2w5v.js";import"./chunk-cjfb4kjp.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
@@ -1,2 +1,2 @@
1
- import{Mk as K}from"./chunk-eg3ms291.js";import{spawn as Y}from"node:child_process";import{constants as j}from"node:fs";import{access as x,readFile as B}from"node:fs/promises";import{createRequire as L}from"node:module";import C from"node:path";var P="blade browser install";var D=["PATH","Path","PATHEXT","HOME","USERPROFILE","LOCALAPPDATA","PROGRAMDATA","TMPDIR","TMP","TEMP","LANG","LC_ALL","LC_CTYPE","TZ","SystemRoot","SYSTEMROOT","WINDIR","COMSPEC","XDG_RUNTIME_DIR","CHROME_DEVEL_SANDBOX"],A=[...D,"PLAYWRIGHT_BROWSERS_PATH","PLAYWRIGHT_DOWNLOAD_CONNECTION_TIMEOUT","PLAYWRIGHT_DOWNLOAD_HOST","PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","SSL_CERT_DIR"],J=32768,M=4096;function U(f,F){let $={};for(let Z of F){let q=f[Z];if(q!==void 0&&q.length<=J)$[Z]=q}return $}function V(f=process.env){return U(f,D)}function S(f=process.env){return U(f,A)}function W(){return L(import.meta.url).resolve("playwright/package.json")}function y(f=W){return C.join(C.dirname(f()),"cli.js")}async function T(){return await import("playwright")}async function m(f){let F=JSON.parse(await B(f,"utf8"));if(typeof F.version!=="string"||F.version.length===0)throw Error("Playwright package version is invalid");return F.version}function I(f){return(f instanceof Error?f.message:String(f)).replace(/[\r\n]+/g," ").slice(0,M)}async function R(f={}){let $=(f.resolvePackageJson??W)(),Z=await m($),q=await(f.loadPlaywright??T)(),G=q.chromium.executablePath(),H=f.access??x,z;try{await H(G,j.X_OK),z=await q.chromium.launch({executablePath:G,headless:!0,chromiumSandbox:!0,env:V(f.environment)});let Q=z.version();return await z.close(),z=void 0,{playwrightVersion:Z,executablePath:G,installed:!0,browserVersion:Q}}catch(Q){return{playwrightVersion:Z,executablePath:G,installed:!1,error:I(Q)}}finally{await z?.close().catch(()=>{return})}}async function N(f={}){let F=f.resolvePackageJson??W,$=y(F),Z=f.spawn??((q,G,H)=>Y(q,[...G],H));await new Promise((q,G)=>{let H=Z(f.execPath??process.execPath,[$,"install","chromium"],{env:S(f.environment),shell:!1,stdio:"inherit"}),z=!1;H.once("error",(Q)=>{if(z)return;z=!0,G(Q)}),H.once("close",(Q,X)=>{if(z)return;if(z=!0,Q===0){q();return}G(Error(X?`Playwright browser installer stopped by ${X}`:`Playwright browser installer exited with code ${Q??1}`))})})}
1
+ import{Nk as K}from"./chunk-cjfb4kjp.js";import{spawn as Y}from"node:child_process";import{constants as j}from"node:fs";import{access as x,readFile as B}from"node:fs/promises";import{createRequire as L}from"node:module";import C from"node:path";var P="blade browser install";var D=["PATH","Path","PATHEXT","HOME","USERPROFILE","LOCALAPPDATA","PROGRAMDATA","TMPDIR","TMP","TEMP","LANG","LC_ALL","LC_CTYPE","TZ","SystemRoot","SYSTEMROOT","WINDIR","COMSPEC","XDG_RUNTIME_DIR","CHROME_DEVEL_SANDBOX"],A=[...D,"PLAYWRIGHT_BROWSERS_PATH","PLAYWRIGHT_DOWNLOAD_CONNECTION_TIMEOUT","PLAYWRIGHT_DOWNLOAD_HOST","PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","SSL_CERT_DIR"],J=32768,M=4096;function U(f,F){let $={};for(let Z of F){let q=f[Z];if(q!==void 0&&q.length<=J)$[Z]=q}return $}function V(f=process.env){return U(f,D)}function S(f=process.env){return U(f,A)}function W(){return L(import.meta.url).resolve("playwright/package.json")}function y(f=W){return C.join(C.dirname(f()),"cli.js")}async function T(){return await import("playwright")}async function m(f){let F=JSON.parse(await B(f,"utf8"));if(typeof F.version!=="string"||F.version.length===0)throw Error("Playwright package version is invalid");return F.version}function I(f){return(f instanceof Error?f.message:String(f)).replace(/[\r\n]+/g," ").slice(0,M)}async function R(f={}){let $=(f.resolvePackageJson??W)(),Z=await m($),q=await(f.loadPlaywright??T)(),G=q.chromium.executablePath(),H=f.access??x,z;try{await H(G,j.X_OK),z=await q.chromium.launch({executablePath:G,headless:!0,chromiumSandbox:!0,env:V(f.environment)});let Q=z.version();return await z.close(),z=void 0,{playwrightVersion:Z,executablePath:G,installed:!0,browserVersion:Q}}catch(Q){return{playwrightVersion:Z,executablePath:G,installed:!1,error:I(Q)}}finally{await z?.close().catch(()=>{return})}}async function N(f={}){let F=f.resolvePackageJson??W,$=y(F),Z=f.spawn??((q,G,H)=>Y(q,[...G],H));await new Promise((q,G)=>{let H=Z(f.execPath??process.execPath,[$,"install","chromium"],{env:S(f.environment),shell:!1,stdio:"inherit"}),z=!1;H.once("error",(Q)=>{if(z)return;z=!0,G(Q)}),H.once("close",(Q,X)=>{if(z)return;if(z=!0,Q===0){q();return}G(Error(X?`Playwright browser installer stopped by ${X}`:`Playwright browser installer exited with code ${Q??1}`))})})}
2
2
  export{P as Fa,V as Ga,R as Ha,N as Ia};
@@ -1,2 +1,2 @@
1
1
  var I=600000,r=30000,t=3600000,o=12,O=15000,P=60000;function R(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=30000&&_<=3600000}var C=1e4,M=1000,p=300000;function E(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=300000}var T=1,s=16,n=Number.MAX_SAFE_INTEGER,D=180000,m=1000,x=600000,S=134217728,U=65536,V=134217728;function A(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=16}function w(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=n}function z(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=600000}function F(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=65536&&_<=134217728}
2
- export{I as cj,r as dj,t as ej,o as fj,O as gj,P as hj,R as ij,C as jj,M as kj,p as lj,E as mj,T as nj,s as oj,n as pj,D as qj,m as rj,x as sj,S as tj,U as uj,V as vj,A as wj,w as xj,z as yj,F as zj};
2
+ export{I as dj,r as ej,t as fj,o as gj,O as hj,P as ij,R as jj,C as kj,M as lj,p as mj,E as nj,T as oj,s as pj,n as qj,D as rj,m as sj,x as tj,S as uj,U as vj,V as wj,A as xj,w as yj,z as zj,F as Aj};
@@ -1 +1 @@
1
- import{Fa as h,Ha as f,Ia as k}from"./chunk-g01mth5d.js";import"./chunk-eg3ms291.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
1
+ import{Fa as h,Ha as f,Ia as k}from"./chunk-vzdsext4.js";import"./chunk-cjfb4kjp.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
@@ -0,0 +1 @@
1
+ import{$b as h,Qb as a,Rb as b,Tb as c,Xb as d,Yb as e,Zb as f,_b as g,ac as i,bc as j,cc as k,lc as l,mc as m,nc as n,oc as o,qc as p,rc as q,sc as r}from"./chunk-ks48r1c6.js";import"./chunk-fdr4fcrf.js";import"./chunk-czrktgmy.js";import"./chunk-egss0m1x.js";import"./chunk-ztreczac.js";import"./chunk-p6586ftx.js";import"./chunk-5yyp6njq.js";import"./chunk-myvt7yjm.js";import"./chunk-4fbpydtn.js";import"./chunk-zfxcef0z.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-qr80p5m0.js";import"./chunk-ys8gysg8.js";import"./chunk-qpmvp4q2.js";import"./chunk-tm3789m3.js";import"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import"./chunk-rmfzym94.js";import"./chunk-j89qk7bp.js";import"./chunk-0eajnhrj.js";import"./chunk-cycsbwm3.js";import"./chunk-ky592ay9.js";import"./chunk-n52n2w5v.js";import"./chunk-cjfb4kjp.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1,3 +1,3 @@
1
- import{j as i}from"./chunk-zj1g4nbq.js";import{bj as s}from"./chunk-2f8d0km4.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
1
+ import{j as i}from"./chunk-hnvvve5d.js";import{cj as s}from"./chunk-qdbbke8f.js";import"./chunk-n52n2w5v.js";import"./chunk-cjfb4kjp.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
2
2
  ${e.path}`}).join(`
3
3
  `)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
@@ -1,4 +1,4 @@
1
- import{e as U3,f as H3,g as R3,h as s0,i as q3}from"./chunk-qcs8ce4s.js";import{j as o1}from"./chunk-zj1g4nbq.js";import{v as a0,w as y2}from"./chunk-dgbgj0kd.js";import{A as m0,x as g2,y as p2,z as v2}from"./chunk-xw7bq6zq.js";import{B as C2,C as U$,D as H$,E as F$,F as z0,G as N$}from"./chunk-xrkas5w5.js";import{$ as I2,Ea as u3,J as B2,K as u1,L as v3,O as D2,P as e0,Q as d4,R as i1,S as g$,T as A4,U as j4,V as K0,W as L2,X as M2,Y as D$,Z as w1,aa as R2,ba as b4,ca as j0,da as H0,ga as q1,ha as E1,ia as O5,ja as q2,ka as E2,la as r2,ma as e2,na as O3,oa as $3,pa as Q3,qa as Z3,ra as J3,sa as Y3,ta as X3,wa as w3,za as W5}from"./chunk-epe57k9k.js";import{La as q$,Ra as uO}from"./chunk-f70awdz6.js";import{Ua as A2,Wa as j2,Xa as b2,Ya as T2,cb as V4,fb as c3,gb as c4,hb as S2,ib as f2,jb as i3,kb as l3,lb as i4,mb as a3,nb as g0,ob as N3,pb as B3,qb as D3,rb as P2,sb as k2,tb as m2,ub as h2,vb as W$,wb as r4}from"./chunk-30x3mcsb.js";import{Kb as dO,Lb as a,Nb as P,Ob as x2,Zb as M4,hc as y0}from"./chunk-ccevgmzy.js";import{sc as T4}from"./chunk-zzvs471p.js";import{$c as W2,$d as D4,Cd as w2,Ic as V2,Md as A1,Nd as h0,Sc as z2,Ud as I1,Vd as I4,Wd as R1,Yd as o0,Zc as G2,_c as B4,ad as D1,bd as K2,ed as U4,ee as N2,fe as x4,ge as L4,he as g,rd as _2}from"./chunk-acq26c7b.js";import{Fe as U2,Me as H2,Ne as F2}from"./chunk-y5wngtz0.js";import{gf as L3,kf as M3,lf as A3,mf as j3,nf as b3,of as y4,pf as T3,qf as I3}from"./chunk-w33zjw8m.js";import{Pf as r3,Tf as MO,Xf as f$,cg as nO}from"./chunk-arr9x580.js";import{dg as c1}from"./chunk-t0gm0pn1.js";import{wg as J2}from"./chunk-50vwafn5.js";import{yg as B1}from"./chunk-hpn1djam.js";import{Hg as e3,Lg as s2,Pg as H1,Qg as F1,Ug as B5,Xg as eO,Yg as N1,_g as X2,ah as s4}from"./chunk-9e10833x.js";import{th as P$,uh as Y2}from"./chunk-vbjgcn49.js";import{yh as b$,zh as l0}from"./chunk-1amhckjs.js";import{Mi as T$,Rh as R$,Ri as U1,fi as s$,ii as r$,ki as e$,li as O2,mi as h$,ni as y$,oi as K$,ui as $2,xi as Q2,zi as Z2}from"./chunk-wt3yt1yn.js";import{Ui as F4}from"./chunk-kv458q06.js";import{Wi as a1,Zi as N4}from"./chunk-5v0jcyea.js";import{bj as GO}from"./chunk-2f8d0km4.js";import{Dj as ZO,Fj as y,Hj as G,Ij as oO,Kj as zO}from"./chunk-2mk914vk.js";import{Pj as f0}from"./chunk-j8hbddjp.js";import{Rj as C$,Sj as o$,Uj as S$,Vj as t$}from"./chunk-4cdk4mds.js";import{Xj as i0}from"./chunk-ttpf4fc0.js";import{ck as t4}from"./chunk-rvs364rz.js";import{Bk as g1,Jk as L$,fk as l1,zk as wO}from"./chunk-4wx5sya5.js";import{Mk as a4}from"./chunk-eg3ms291.js";var H8={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function F8(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as e4,readFileSync as f1}from"node:fs";import{createServer as c6}from"node:http";import{networkInterfaces as i6}from"node:os";import{dirname as l6,extname as a6,join as E0}from"node:path";import{fileURLToPath as n6}from"node:url";import{brotliCompressSync as o6,gzipSync as t6,constants as s6}from"node:zlib";import{Hono as r6}from"hono";import{cors as e6}from"hono/cors";import{WebSocketServer as O8}from"ws";var c0=ZO("Service"),f5=30000,P5=new Set(["completed","failed","cancelled","interrupted"]);class z4{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??W$.getInstance(),this.tickMs=O.tickMs??f5}start(){if(this.timer)return;c0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=P.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!P5.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,c0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let Q of $)await this.evaluate(Q,O)}catch($){c0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),c0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,Q={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Z=$.toISOString();try{let J=await this.dispatch({prompt:O.prompt,title:O.title??k5(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),X=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastRunSessionId:J.session.sessionId,lastStatus:J.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),P.publish({sessionId:J.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Z,sessionId:J.session.sessionId,runId:J.runId,status:J.status}),c0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${J.session.sessionId} (${J.status})`)}catch(J){let X=J instanceof Error?J.message:String(J);c0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,J);let V=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastStatus:"error",lastError:X,nextRunAt:V?V.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,Q){let J=(await this.store.list()).find((X)=>X.lastRunSessionId===O);if(!J)return;await this.store.update(J.id,{lastStatus:$,...Q?{lastError:Q}:{lastError:void 0}})}}function k5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class _O extends Error{code;statusCode;details;constructor(O,$,Q=500,Z){super($);this.code=O;this.statusCode=Q;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class i extends _O{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class F extends _O{constructor(O){super("BAD_REQUEST",O,400)}}class v extends _O{constructor(O){super("CONFLICT",O,409)}}class rO extends _O{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class LO extends _O{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class A0 extends _O{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class vO extends _O{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class VO extends _O{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var j8=G.Object({error:G.Object({code:G.String(),message:G.String(),details:G.Optional(G.Record(G.String(),G.Unknown()))})});import{Hono as m5}from"hono";var G4=ZO("Service"),h5=G.Object({updates:G.Record(G.String(),G.Any()),options:G.Optional(G.Object({scope:G.Optional(zO(["local","project","global"])),immediate:G.Optional(G.Boolean())}))});function y5(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var _$=()=>{let O=new m5;return O.get("/",async($)=>{try{let Q=MO();return $.json(Q?y5(Q):{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get config:",Q),$.json({})}}),O.put("/",async($)=>{try{let Q=await $.req.json(),Z=y(h5,Q);if(!Z.success)throw new F("Invalid config update format");let{updates:J,options:X}=Z.data;return await nO().updateConfig(J,X),$.json({success:!0,updates:J})}catch(Q){if(Q instanceof K$)throw new F(Q.message);throw G4.error("[ConfigRoutes] Failed to update config:",Q),Q}}),O.get("/permissions",async($)=>{try{let Q=MO();return $.json(Q?.permissions||{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get permissions:",Q),$.json({})}}),O};import{Hono as g5}from"hono";import{streamSSE as p5}from"hono/streaming";function w$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
1
+ import{e as U3,f as H3,g as R3,h as s0,i as q3}from"./chunk-zjjwxnmd.js";import{j as o1}from"./chunk-hnvvve5d.js";import{v as a0,w as y2}from"./chunk-97rqk0ek.js";import{A as m0,x as g2,y as p2,z as v2}from"./chunk-gerzcz6q.js";import{B as C2,C as U$,D as H$,E as F$,F as z0,G as N$}from"./chunk-9c7hesmj.js";import{$ as I2,Ea as u3,J as B2,K as u1,L as v3,O as D2,P as e0,Q as d4,R as i1,S as g$,T as A4,U as j4,V as K0,W as L2,X as M2,Y as D$,Z as w1,aa as R2,ba as b4,ca as j0,da as H0,ga as q1,ha as E1,ia as O5,ja as q2,ka as E2,la as r2,ma as e2,na as O3,oa as $3,pa as Q3,qa as Z3,ra as J3,sa as Y3,ta as X3,wa as w3,za as W5}from"./chunk-4vcea99r.js";import{La as q$,Ra as uO}from"./chunk-pk3ftt16.js";import{Ua as A2,Wa as j2,Xa as b2,Ya as T2,cb as V4,fb as c3,gb as c4,hb as S2,ib as f2,jb as i3,kb as l3,lb as i4,mb as a3,nb as g0,ob as N3,pb as B3,qb as D3,rb as P2,sb as k2,tb as m2,ub as h2,vb as W$,wb as r4}from"./chunk-9fyjyk2f.js";import{Kb as dO,Lb as a,Nb as P,Ob as x2,Zb as M4,ic as y0}from"./chunk-ks48r1c6.js";import{tc as T4}from"./chunk-fdr4fcrf.js";import{$c as B4,Dd as w2,Jc as V2,Nd as A1,Od as h0,Tc as z2,Vd as I1,Wd as I4,Xd as R1,Zd as o0,_c as G2,ad as W2,ae as D4,bd as D1,cd as K2,fd as U4,fe as N2,ge as x4,he as L4,ie as g,sd as _2}from"./chunk-czrktgmy.js";import{Ge as U2,Ne as H2,Oe as F2}from"./chunk-ztreczac.js";import{hf as L3,lf as M3,mf as A3,nf as j3,of as b3,pf as y4,qf as T3,rf as I3}from"./chunk-p6586ftx.js";import{Qf as r3,Uf as MO,Yf as f$,dg as nO}from"./chunk-6q0n03nz.js";import{eg as c1}from"./chunk-5yyp6njq.js";import{xg as J2}from"./chunk-zfxcef0z.js";import{zg as B1}from"./chunk-nh9d0m2m.js";import{$g as X2,Ig as e3,Mg as s2,Qg as H1,Rg as F1,Vg as B5,Yg as eO,Zg as N1,bh as s4}from"./chunk-dkhn7mqt.js";import{uh as P$,vh as Y2}from"./chunk-1cy4ab77.js";import{Ah as l0,zh as b$}from"./chunk-qr80p5m0.js";import{Ai as Z2,Ni as T$,Sh as R$,Si as U1,gi as s$,ji as r$,li as e$,mi as O2,ni as h$,oi as y$,pi as K$,vi as $2,yi as Q2}from"./chunk-ghvfd7bx.js";import{Vi as F4}from"./chunk-qpmvp4q2.js";import{Xi as a1,_i as N4}from"./chunk-tm3789m3.js";import{cj as GO}from"./chunk-qdbbke8f.js";import{Ej as ZO,Gj as y,Ij as G,Jj as oO,Lj as zO}from"./chunk-rmfzym94.js";import{Qj as f0}from"./chunk-j89qk7bp.js";import{Sj as C$,Tj as o$,Vj as S$,Wj as t$}from"./chunk-0eajnhrj.js";import{Yj as i0}from"./chunk-cycsbwm3.js";import{dk as t4}from"./chunk-ggdgk3gy.js";import{Ak as wO,Ck as g1,Kk as L$,gk as l1}from"./chunk-n52n2w5v.js";import{Nk as a4}from"./chunk-cjfb4kjp.js";var H8={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function F8(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as e4,readFileSync as f1}from"node:fs";import{createServer as c6}from"node:http";import{networkInterfaces as i6}from"node:os";import{dirname as l6,extname as a6,join as E0}from"node:path";import{fileURLToPath as n6}from"node:url";import{brotliCompressSync as o6,gzipSync as t6,constants as s6}from"node:zlib";import{Hono as r6}from"hono";import{cors as e6}from"hono/cors";import{WebSocketServer as O8}from"ws";var c0=ZO("Service"),f5=30000,P5=new Set(["completed","failed","cancelled","interrupted"]);class z4{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??W$.getInstance(),this.tickMs=O.tickMs??f5}start(){if(this.timer)return;c0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=P.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!P5.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,c0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let Q of $)await this.evaluate(Q,O)}catch($){c0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),c0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,Q={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Z=$.toISOString();try{let J=await this.dispatch({prompt:O.prompt,title:O.title??k5(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),X=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastRunSessionId:J.session.sessionId,lastStatus:J.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),P.publish({sessionId:J.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Z,sessionId:J.session.sessionId,runId:J.runId,status:J.status}),c0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${J.session.sessionId} (${J.status})`)}catch(J){let X=J instanceof Error?J.message:String(J);c0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,J);let V=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastStatus:"error",lastError:X,nextRunAt:V?V.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,Q){let J=(await this.store.list()).find((X)=>X.lastRunSessionId===O);if(!J)return;await this.store.update(J.id,{lastStatus:$,...Q?{lastError:Q}:{lastError:void 0}})}}function k5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class _O extends Error{code;statusCode;details;constructor(O,$,Q=500,Z){super($);this.code=O;this.statusCode=Q;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class i extends _O{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class F extends _O{constructor(O){super("BAD_REQUEST",O,400)}}class v extends _O{constructor(O){super("CONFLICT",O,409)}}class rO extends _O{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class LO extends _O{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class A0 extends _O{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class vO extends _O{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class VO extends _O{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var j8=G.Object({error:G.Object({code:G.String(),message:G.String(),details:G.Optional(G.Record(G.String(),G.Unknown()))})});import{Hono as m5}from"hono";var G4=ZO("Service"),h5=G.Object({updates:G.Record(G.String(),G.Any()),options:G.Optional(G.Object({scope:G.Optional(zO(["local","project","global"])),immediate:G.Optional(G.Boolean())}))});function y5(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var _$=()=>{let O=new m5;return O.get("/",async($)=>{try{let Q=MO();return $.json(Q?y5(Q):{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get config:",Q),$.json({})}}),O.put("/",async($)=>{try{let Q=await $.req.json(),Z=y(h5,Q);if(!Z.success)throw new F("Invalid config update format");let{updates:J,options:X}=Z.data;return await nO().updateConfig(J,X),$.json({success:!0,updates:J})}catch(Q){if(Q instanceof K$)throw new F(Q.message);throw G4.error("[ConfigRoutes] Failed to update config:",Q),Q}}),O.get("/permissions",async($)=>{try{let Q=MO();return $.json(Q?.permissions||{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get permissions:",Q),$.json({})}}),O};import{Hono as g5}from"hono";import{streamSSE as p5}from"hono/streaming";function w$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
2
2
  `;if(O.event!==void 0)$+=`event: ${O.event}
3
3
  `;for(let Q of O.data.split(/\r\n|\r|\n/))$+=`data: ${Q}
4
4
  `;if(O.retry!==void 0)$+=`retry: ${O.retry}
@@ -1,2 +1,2 @@
1
- import{Xj as I}from"./chunk-ttpf4fc0.js";import{Mk as f}from"./chunk-eg3ms291.js";import*as j from"fs/promises";import*as S from"path";import X from"semver";import{ProxyAgent as R,fetch as k}from"undici";function x(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function L(){let z=x();if(z)try{return new R(z)}catch(q){console.warn(`[proxyFetch] Invalid proxy URL: ${z}`)}return}async function F(z,q,Z){let{timeout:W=30000,signal:J,...Q}=q;if(J?.aborted)throw new DOMException("The operation was aborted.","AbortError");let Y=L(),$=new AbortController,w=!1,y=setTimeout(()=>{w=!0,$.abort()},W),T=()=>$.abort();J?.addEventListener("abort",T);let D;try{let B={method:Q.method,headers:Q.headers,body:Q.body,signal:$.signal,dispatcher:Y};return D=await k(z.toString(),B),await Z(D)}catch(B){if(B instanceof Error&&B.name==="AbortError"){if(w)throw Error(`Request timeout after ${W}ms`);throw B}throw B}finally{if(clearTimeout(y),J?.removeEventListener("abort",T),$.abort(),D?.body&&!D.body.locked)await D.body.cancel().catch(()=>{return});await Y?.destroy?.().catch(()=>{return})}}var O="blade-code",G="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",H=S.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),N=S.join(H,"version-cache.json"),_=3600000,g=`https://registry.npmjs.org/${O}/latest`,M=null;async function P(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return I()}catch{return"unknown"}}async function b(){try{let z=await j.readFile(N,"utf-8"),q=JSON.parse(z);if(Date.now()-q.checkedAt<_)return q;return{...q,checkedAt:0}}catch{return null}}async function K(z){try{await j.mkdir(H,{recursive:!0,mode:493}),await j.writeFile(N,JSON.stringify(z,null,2))}catch{}}async function E(){try{return await F(g,{timeout:5000,headers:{Accept:"application/json"}},async(z)=>{if(!z.ok)return null;let q=await z.json();if(!q||typeof q!=="object"||!("version"in q))return null;return typeof q.version==="string"&&X.valid(q.version)?q.version:null})}catch{return null}}async function A(z=!1){let q=await P(),Z=G;if(q==="unknown")return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to determine current version"};let W=await b(),J=W?.skipUntilVersion,Q=null;if(!z&&W?.latestVersion&&W.checkedAt>0)Q=W.latestVersion;else if(Q=await E(),J=(await b())?.skipUntilVersion??J,Q)await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});else if(W?.latestVersion)await K({checkedAt:0,skipUntilVersion:J});if(!Q||!X.valid(Q))return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to check for updates"};if(X.lt(Q,q))Q=q,await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});let Y=X.gt(Q,q),$=Y;if(Y&&J)$=X.gt(Q,J);return{currentVersion:q,latestVersion:Q,hasUpdate:Y,shouldPrompt:$,releaseNotesUrl:Z}}async function V(z){let q=await b();await K({latestVersion:q?.latestVersion??z,checkedAt:q?.checkedAt||Date.now(),skipUntilVersion:z})}function v(){return`npm install -g ${O}@latest --registry https://registry.npmjs.org`}async function p(){let{spawn:z}=await import("child_process");return new Promise((q)=>{let Z=v(),W=z(Z,{stdio:"inherit",shell:!0});W.on("close",(J)=>{if(J===0)q({success:!0,message:"Upgrade successful! Please restart blade."});else q({success:!1,message:`Upgrade failed (exit code: ${J})`})}),W.on("error",(J)=>{q({success:!1,message:`Upgrade failed: ${J.message}`})})})}async function h(){try{let z=await b();if(!z?.latestVersion||!X.valid(z.latestVersion)||!z.checkedAt){if(!M)M=A(!0).then(()=>{return},()=>{return}).finally(()=>{M=null});return null}let q=await P();if(!X.valid(q)||!X.gt(z.latestVersion,q)||z.skipUntilVersion&&X.valid(z.skipUntilVersion)&&!X.gt(z.latestVersion,z.skipUntilVersion))return null;return{currentVersion:q,latestVersion:z.latestVersion,hasUpdate:!0,shouldPrompt:!0,releaseNotesUrl:G}}catch{return null}}
1
+ import{Yj as I}from"./chunk-cycsbwm3.js";import{Nk as f}from"./chunk-cjfb4kjp.js";import*as j from"fs/promises";import*as S from"path";import X from"semver";import{ProxyAgent as R,fetch as k}from"undici";function x(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function L(){let z=x();if(z)try{return new R(z)}catch(q){console.warn(`[proxyFetch] Invalid proxy URL: ${z}`)}return}async function F(z,q,Z){let{timeout:W=30000,signal:J,...Q}=q;if(J?.aborted)throw new DOMException("The operation was aborted.","AbortError");let Y=L(),$=new AbortController,w=!1,y=setTimeout(()=>{w=!0,$.abort()},W),T=()=>$.abort();J?.addEventListener("abort",T);let D;try{let B={method:Q.method,headers:Q.headers,body:Q.body,signal:$.signal,dispatcher:Y};return D=await k(z.toString(),B),await Z(D)}catch(B){if(B instanceof Error&&B.name==="AbortError"){if(w)throw Error(`Request timeout after ${W}ms`);throw B}throw B}finally{if(clearTimeout(y),J?.removeEventListener("abort",T),$.abort(),D?.body&&!D.body.locked)await D.body.cancel().catch(()=>{return});await Y?.destroy?.().catch(()=>{return})}}var O="blade-code",G="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",H=S.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),N=S.join(H,"version-cache.json"),_=3600000,g=`https://registry.npmjs.org/${O}/latest`,M=null;async function P(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return I()}catch{return"unknown"}}async function b(){try{let z=await j.readFile(N,"utf-8"),q=JSON.parse(z);if(Date.now()-q.checkedAt<_)return q;return{...q,checkedAt:0}}catch{return null}}async function K(z){try{await j.mkdir(H,{recursive:!0,mode:493}),await j.writeFile(N,JSON.stringify(z,null,2))}catch{}}async function E(){try{return await F(g,{timeout:5000,headers:{Accept:"application/json"}},async(z)=>{if(!z.ok)return null;let q=await z.json();if(!q||typeof q!=="object"||!("version"in q))return null;return typeof q.version==="string"&&X.valid(q.version)?q.version:null})}catch{return null}}async function A(z=!1){let q=await P(),Z=G;if(q==="unknown")return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to determine current version"};let W=await b(),J=W?.skipUntilVersion,Q=null;if(!z&&W?.latestVersion&&W.checkedAt>0)Q=W.latestVersion;else if(Q=await E(),J=(await b())?.skipUntilVersion??J,Q)await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});else if(W?.latestVersion)await K({checkedAt:0,skipUntilVersion:J});if(!Q||!X.valid(Q))return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to check for updates"};if(X.lt(Q,q))Q=q,await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});let Y=X.gt(Q,q),$=Y;if(Y&&J)$=X.gt(Q,J);return{currentVersion:q,latestVersion:Q,hasUpdate:Y,shouldPrompt:$,releaseNotesUrl:Z}}async function V(z){let q=await b();await K({latestVersion:q?.latestVersion??z,checkedAt:q?.checkedAt||Date.now(),skipUntilVersion:z})}function v(){return`npm install -g ${O}@latest --registry https://registry.npmjs.org`}async function p(){let{spawn:z}=await import("child_process");return new Promise((q)=>{let Z=v(),W=z(Z,{stdio:"inherit",shell:!0});W.on("close",(J)=>{if(J===0)q({success:!0,message:"Upgrade successful! Please restart blade."});else q({success:!1,message:`Upgrade failed (exit code: ${J})`})}),W.on("error",(J)=>{q({success:!1,message:`Upgrade failed: ${J.message}`})})})}async function h(){try{let z=await b();if(!z?.latestVersion||!X.valid(z.latestVersion)||!z.checkedAt){if(!M)M=A(!0).then(()=>{return},()=>{return}).finally(()=>{M=null});return null}let q=await P();if(!X.valid(q)||!X.gt(z.latestVersion,q)||z.skipUntilVersion&&X.valid(z.skipUntilVersion)&&!X.gt(z.latestVersion,z.skipUntilVersion))return null;return{currentVersion:q,latestVersion:z.latestVersion,hasUpdate:!0,shouldPrompt:!0,releaseNotesUrl:G}}catch{return null}}
2
2
  export{A as k,V as l,v as m,p as n,h as o};
@@ -1,2 +1,2 @@
1
1
  import{spawn as I}from"node:child_process";var X=500;function x(j){return new Promise((q)=>setTimeout(q,j))}function Z(j){return j&&typeof j==="object"&&"code"in j?String(j.code):void 0}function L(j){return j()||j()}function G(j,q=process.platform,y=process.kill.bind(process)){if(q==="win32"||!Number.isInteger(j)||j<=1||j===process.pid)return!1;try{return y(-j,0),!0}catch(z){let B=Z(z);if(B==="ESRCH")return!1;if(B==="EPERM")return!0;throw z}}function N(j,q){return new Promise((y)=>{let z=["/PID",String(j),"/T"];if(q)z.push("/F");let B=I("taskkill",z,{stdio:"ignore",windowsHide:!0}),K=!1,J=(H)=>{if(K)return;K=!0,y(H)};B.once("error",()=>J(!1)),B.once("close",(H)=>J(H===0))})}async function F(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};let y=q.platform??process.platform,z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.taskkill??N,J=q.wait??x,H=q.validatePidOwnership??(()=>!0);if(!L(H))return{success:!1,alreadyExited:!1,forced:!1};if(y==="win32"){let V=await K(j,!1);if(await J(z),!H())return{success:V,alreadyExited:!1,forced:!1};let Y=await K(j,!0);return{success:V||Y,alreadyExited:!V&&!Y,forced:Y}}let Q=(V,Y)=>{try{return B(V,Y)}catch(D){return Z(D)==="ESRCH"}},W=Q(-j,"SIGTERM")||Q(j,"SIGTERM");if(await J(z),!H())return{success:W,alreadyExited:!1,forced:!1};let $=Q(-j,"SIGKILL")||Q(j,"SIGKILL");return{success:W||$,alreadyExited:!1,forced:$}}async function R(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};if((q.platform??process.platform)==="win32")return{success:!1,alreadyExited:!1,forced:!1};let z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.wait??x,J=q.validatePidOwnership??(()=>!0);if(!J())return{success:!1,alreadyExited:!1,forced:!1};let H=($)=>{try{return B(-j,$),"sent"}catch(V){return Z(V)==="ESRCH"?"missing":"failed"}},Q=H("SIGTERM");if(Q==="missing")return{success:!0,alreadyExited:!0,forced:!1};if(Q==="failed")return{success:!1,alreadyExited:!1,forced:!1};if(await K(z),!J())return{success:!1,alreadyExited:!1,forced:!1};let W=H("SIGKILL");return{success:W!=="failed",alreadyExited:W==="missing",forced:W==="sent"}}class b{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(j,q={}){this.child=j;if(this.platform=q.platform??process.platform,this.gracePeriodMs=q.gracePeriodMs??X,this.killProcess=q.killProcess??process.kill.bind(process),this.taskkill=q.taskkill??N,this.wait=q.wait??x,q.releaseOnExit!==!1){let y=()=>{if(this.state==="owned")this.state="released"};j.once("close",y),j.once("error",y)}}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((j)=>{return this.state="released",this.terminationResult=j,j}),this.terminationPromise}async terminateOwnedTree(){let j=this.child.pid;if(!j)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let z=await this.taskkill(j,!1);await this.wait(this.gracePeriodMs);let B=await this.taskkill(j,!0);if(!z&&!B)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let q=this.signalPosixTree(j,"SIGTERM");await this.wait(this.gracePeriodMs);let y=this.signalPosixTree(j,"SIGKILL");return{success:q||y,alreadyExited:!1,forced:y}}signalPosixTree(j,q){if(j<=1||j===process.pid)return this.signalDirectChild(q);try{return this.killProcess(-j,q)}catch(y){if(Z(y)==="ESRCH")return!0;return this.signalDirectChild(q)}}signalDirectChild(j){try{return this.child.kill(j)}catch(q){return Z(q)==="ESRCH"}}}function v(j,q,y={},z={}){let B=I(j,q,{...y,detached:process.platform==="win32"?y.detached:!0,windowsHide:y.windowsHide??!0});return{child:B,processTree:new b(B,z)}}
2
- export{G as Ah,F as Bh,R as Ch,v as Dh};
2
+ export{G as Bh,F as Ch,R as Dh,v as Eh};
@@ -1,4 +1,4 @@
1
- import{e as JX,f as YX,h as S$,i as T4}from"./chunk-qcs8ce4s.js";import{l as YZ,m as XZ,n as ZZ}from"./chunk-g124q0rg.js";import{A as q4,y as MJ,z as TJ}from"./chunk-xw7bq6zq.js";import{Aa as QY,Ca as UY,Ea as lY,I as dY,M as LZ,O as m6,P as y6,Q as jY,W as AY,X as bY,_ as MY,da as i$,fa as SJ,ga as kJ,ia as TY,ka as q8,la as BX,ma as wX,pa as PX,qa as AX,ua as a9,va as w3,xa as F3,ya as L3,za as BZ}from"./chunk-epe57k9k.js";import"./chunk-g01mth5d.js";import{Ma as E5,Na as g5,Oa as m5,Ra as FZ}from"./chunk-f70awdz6.js";import{Ta as PY}from"./chunk-30x3mcsb.js";import{Mb as BY,Nb as F4,Zb as wY,hc as b6}from"./chunk-ccevgmzy.js";import{sc as H8}from"./chunk-zzvs471p.js";import{Cd as _Y,Md as bJ,Nd as m2,Rd as yJ,Wd as IJ,Yd as t8,ee as z8,he as a0}from"./chunk-acq26c7b.js";import"./chunk-53fc0yrq.js";import{Le as vJ,Me as A6,Ne as VJ}from"./chunk-y5wngtz0.js";import{if as JY,jf as U4}from"./chunk-w33zjw8m.js";import{wf as $Z}from"./chunk-nheny8xp.js";import{Af as Y1,xf as W8,yf as _4}from"./chunk-5cznfhch.js";import"./chunk-jj4ggb04.js";import{Ef as R2,Ff as L$,Gf as a1,Hf as z9,If as o8,Jf as CJ,Kf as s3,Lf as I9,Mf as a5,Nf as e3,Of as v2,Pf as m0,Qf as HZ,Rf as B$,Sf as eX,Tf as i4,Uf as O8,Xf as $Y,cg as z$}from"./chunk-arr9x580.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-qx6gb5k6.js";import"./chunk-kqvzmnja.js";import{ug as S9}from"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-hpn1djam.js";import{Hg as W4,Jg as pX,Og as LX,Xg as WZ}from"./chunk-9e10833x.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import{xh as O9,zh as h$}from"./chunk-1amhckjs.js";import"./chunk-3y2x6fb6.js";import{Mi as OZ,Ri as FX,Si as NZ}from"./chunk-wt3yt1yn.js";import{Ui as mJ}from"./chunk-kv458q06.js";import{Vi as p2,Wi as e8,Yi as N9}from"./chunk-5v0jcyea.js";import{bj as K$}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Aj as _Z,Dj as H1}from"./chunk-2mk914vk.js";import{Lj as s5,Mj as e5,Pj as R1}from"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import{$j as c5}from"./chunk-ttpf4fc0.js";import{ck as l9}from"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import{fk as K8,zk as eJ}from"./chunk-4wx5sya5.js";import{Mk as Y4}from"./chunk-eg3ms291.js";import{useMemoizedFn as G6}from"ahooks";import{useEffect as _z,useState as K6}from"react";import{useMemoizedFn as i0}from"ahooks";import tX from"ansi-escapes";import{Box as m1,useStdout as Zz}from"ink";import{useEffect as J1,useMemo as Qz,useRef as I2,useState as sX}from"react";import{useShallow as AZ}from"zustand/react/shallow";import{useStore as PZ}from"zustand";function z0($){return PZ(v2,$)}var bZ=[],V2=()=>z0(($)=>$.session.sessionId),O1=()=>z0(($)=>$.session.workspaceRoot),V8=()=>z0(($)=>$.session.messages),i9=()=>z0(($)=>$.session.clearCount),o9=()=>z0(($)=>$.session.isCompacting),n9=()=>z0(($)=>$.session.tokenUsage.estimatedCostUsd),t9=()=>z0(($)=>{let{totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}=$.session.tokenUsage;return a9({totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}).hitRate});var j8=()=>z0(($)=>$.session.providerRecovery),s9=()=>z0(($)=>$.session.turnActivity),e9=()=>z0(($)=>$.session.actionStationarity),d1=()=>z0(($)=>$.session.actions),$J=()=>z0(($)=>{let{totalTokens:J,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let Z=Math.max(0,100-J/Y*100);return Math.round(Z)}),JJ=()=>z0(($)=>$.app.initializationStatus),YJ=()=>z0(($)=>$.app.initializationError),j2=()=>z0(($)=>$.app.activeModal),XJ=()=>z0(($)=>$.app.tasks),ZJ=()=>z0(($)=>$.app.modelEditorTarget),QJ=()=>z0(($)=>$.app.sessionSelectorData),UJ=()=>z0(($)=>$.app.sessionHistoryViewerData),GJ=()=>z0(($)=>$.app.taskAttentionStatus),h8=()=>z0(($)=>$.app.taskAttentionUnreadKeys),KJ=()=>z0(($)=>$.app.awaitingSecondCtrlC),N1=()=>z0(($)=>$.app.actions),h2=()=>z0(($)=>$.app.sideConversation),zJ=()=>z0(($)=>$.app.teams),E8=()=>z0(($)=>$.app.initializationStatus==="ready"),qJ=()=>z0(($)=>$.app.tasks.length>0),E2=()=>z0(($)=>$.config.config?.permissionMode||"default"),_J=()=>z0(($)=>$.config.config?.models??bZ),g8=()=>z0(($)=>{let J=$.config.config;if(!J)return;let Y=J.currentModelId;return J.models.find((X)=>X.id===Y)??J.models[0]}),m8=()=>z0(($)=>$.config.config?.currentModelId),OJ=()=>z0(($)=>$.config.config?.agentTeamsEnabled===!0),D0=()=>z0(($)=>{return L$.getTheme()}),NJ=()=>z0(($)=>$.config.config?.codeTheme??"default"),s0=()=>z0(($)=>$.focus.currentFocus),HJ=()=>z0(($)=>$.focus.actions),g2=()=>z0(($)=>$.command.isProcessing),WJ=()=>z0(($)=>$.command.actions),p8=()=>z0(($)=>$.app.followUpQueue),FJ=()=>z0(($)=>$.app.followUpQueueMutation),LJ=()=>z0(($)=>$.command.recoveredSteeringCount),x8=()=>z0(($)=>$.app.reasoningEffort!=="off"),c8=()=>z0(($)=>$.app.reasoningEffort),u8=()=>z0(($)=>$.app.serviceTier),d8=()=>z0(($)=>$.app.responseVerbosity),l8=()=>z0(($)=>$.app.communicationStyle),r8=()=>z0(($)=>$.session.currentThinkingContent),BJ=()=>z0(($)=>$.session.thinkingExpanded),a8=()=>z0(($)=>$.session.currentStreamingMessageId),i8=()=>z0(AZ(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),wJ=()=>z0(($)=>$.session.finalizingStreamingMessageId),PJ=()=>z0(($)=>$.session.historyExpanded),AJ=()=>z0(($)=>$.session.expandedMessageCount);import{randomUUID as H7}from"node:crypto";import{useMemoizedFn as X1}from"ahooks";import{useEffect as l1,useMemo as FY,useRef as N4}from"react";function MZ($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class q6{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((Y)=>{this.handleUnexpectedFailure(Y,$)})})}catch(Y){this.handleUnexpectedFailure(Y,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},Y=new AbortController,Z=this.wakeEpoch,X=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=Y;let Q;try{Q=await this.options.run(Y.signal)}finally{if(this.activeAttemptToken===J){if(this.activeAttemptToken=null,this.activeRunController=null,!this.disposed&&$!==this.generation)this.scheduleIfRunnable()}}if(this.disposed||$!==this.generation)return;if(Q.status==="completed"){let U=this.wakeEpoch!==Z;if(this.clearEpisode(),U)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==X)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let Y=m2($.taskFailure),Z=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Z||!MZ($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,Y);return}let X=TJ({sessionIdentity:Z,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(X.phase!=="retry_scheduled"){this.terminate(X.phase,this.attempt,Y);return}this.requested=!0,this.waitingForIdle=!1;let Q={},U=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},X.delayMs);this.retryTimer={handle:U,token:Q},U.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),m2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},Y=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),bJ("timeout"),"pending-resume-recovery-deadline-exceeded")},MJ);this.deadlineTimer={handle:Y,token:J},Y.unref?.()}terminate($,J,Y,Z){let X=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Z)X?.abort(Z);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:Y})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class U8{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)o8(J,$.extraContent);CJ(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function TZ($){if(!($ instanceof Error))return"未知错误";let Z=$.lastError??$;if(Z.responseBody)try{let U=JSON.parse(Z.responseBody)?.error?.message;if(U){let G=Z.statusCode?` (HTTP ${Z.statusCode})`:"";return`${U}${G}`}}catch{}let X=$.message.match(/Last error:\s*(.+)$/);if(X)return X[1];return $.message}function CZ($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function RZ($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function n8($){let J=CZ($),Y=RZ($),Z;if(Y)Z="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Z=TZ($);return{displayMessage:Z,isAbort:J,isVisionNotSupported:Y}}import{appendFileSync as yZ,mkdirSync as IZ,writeFileSync as SZ}from"node:fs";import kZ from"node:os";import _6 from"node:path";var RJ=null;function DZ(){let $=process.env.BLADE_STORAGE_ROOT||_6.join(kZ.homedir(),".blade");return _6.join($,"logs","stream-debug.log")}function fZ($){if(RJ===$)return;let J=_6.dirname($);IZ(J,{recursive:!0,mode:493}),SZ($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
1
+ import{e as JX,f as YX,h as S$,i as T4}from"./chunk-zjjwxnmd.js";import{l as YZ,m as XZ,n as ZZ}from"./chunk-xvqbvpks.js";import{A as q4,y as MJ,z as TJ}from"./chunk-gerzcz6q.js";import{Aa as QY,Ca as UY,Ea as lY,I as dY,M as LZ,O as m6,P as y6,Q as jY,W as AY,X as bY,_ as MY,da as i$,fa as SJ,ga as kJ,ia as TY,ka as q8,la as BX,ma as wX,pa as PX,qa as AX,ua as a9,va as w3,xa as F3,ya as L3,za as BZ}from"./chunk-4vcea99r.js";import"./chunk-vzdsext4.js";import{Ma as E5,Na as g5,Oa as m5,Ra as FZ}from"./chunk-pk3ftt16.js";import{Ta as PY}from"./chunk-9fyjyk2f.js";import{Mb as BY,Nb as F4,Zb as wY,ic as b6}from"./chunk-ks48r1c6.js";import{tc as H8}from"./chunk-fdr4fcrf.js";import{Dd as _Y,Nd as bJ,Od as m2,Sd as yJ,Xd as IJ,Zd as t8,fe as z8,ie as a0}from"./chunk-czrktgmy.js";import"./chunk-egss0m1x.js";import{Me as vJ,Ne as A6,Oe as VJ}from"./chunk-ztreczac.js";import{jf as JY,kf as U4}from"./chunk-p6586ftx.js";import{xf as $Z}from"./chunk-je908ygr.js";import{Bf as Y1,yf as W8,zf as _4}from"./chunk-fnfay5y6.js";import"./chunk-p0wyhp5a.js";import{Ff as R2,Gf as L$,Hf as a1,If as z9,Jf as o8,Kf as CJ,Lf as s3,Mf as I9,Nf as a5,Of as e3,Pf as v2,Qf as m0,Rf as HZ,Sf as B$,Tf as eX,Uf as i4,Vf as O8,Yf as $Y,dg as z$}from"./chunk-6q0n03nz.js";import"./chunk-v508x7cg.js";import"./chunk-5yyp6njq.js";import"./chunk-myvt7yjm.js";import"./chunk-4fbpydtn.js";import{vg as S9}from"./chunk-3cas6rv5.js";import"./chunk-zfxcef0z.js";import"./chunk-nh9d0m2m.js";import{Ig as W4,Kg as pX,Pg as LX,Yg as WZ}from"./chunk-dkhn7mqt.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import{Ah as h$,yh as O9}from"./chunk-qr80p5m0.js";import"./chunk-ys8gysg8.js";import{Ni as OZ,Si as FX,Ti as NZ}from"./chunk-ghvfd7bx.js";import{Vi as mJ}from"./chunk-qpmvp4q2.js";import{Wi as p2,Xi as e8,Zi as N9}from"./chunk-tm3789m3.js";import{cj as K$}from"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import{Bj as _Z,Ej as H1}from"./chunk-rmfzym94.js";import{Mj as s5,Nj as e5,Qj as R1}from"./chunk-j89qk7bp.js";import"./chunk-0eajnhrj.js";import{ak as c5}from"./chunk-cycsbwm3.js";import{dk as l9}from"./chunk-ggdgk3gy.js";import"./chunk-ky592ay9.js";import{Ak as eJ,gk as K8}from"./chunk-n52n2w5v.js";import{Nk as Y4}from"./chunk-cjfb4kjp.js";import{useMemoizedFn as G6}from"ahooks";import{useEffect as _z,useState as K6}from"react";import{useMemoizedFn as i0}from"ahooks";import tX from"ansi-escapes";import{Box as m1,useStdout as Zz}from"ink";import{useEffect as J1,useMemo as Qz,useRef as I2,useState as sX}from"react";import{useShallow as AZ}from"zustand/react/shallow";import{useStore as PZ}from"zustand";function z0($){return PZ(v2,$)}var bZ=[],V2=()=>z0(($)=>$.session.sessionId),O1=()=>z0(($)=>$.session.workspaceRoot),V8=()=>z0(($)=>$.session.messages),i9=()=>z0(($)=>$.session.clearCount),o9=()=>z0(($)=>$.session.isCompacting),n9=()=>z0(($)=>$.session.tokenUsage.estimatedCostUsd),t9=()=>z0(($)=>{let{totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}=$.session.tokenUsage;return a9({totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}).hitRate});var j8=()=>z0(($)=>$.session.providerRecovery),s9=()=>z0(($)=>$.session.turnActivity),e9=()=>z0(($)=>$.session.actionStationarity),d1=()=>z0(($)=>$.session.actions),$J=()=>z0(($)=>{let{totalTokens:J,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let Z=Math.max(0,100-J/Y*100);return Math.round(Z)}),JJ=()=>z0(($)=>$.app.initializationStatus),YJ=()=>z0(($)=>$.app.initializationError),j2=()=>z0(($)=>$.app.activeModal),XJ=()=>z0(($)=>$.app.tasks),ZJ=()=>z0(($)=>$.app.modelEditorTarget),QJ=()=>z0(($)=>$.app.sessionSelectorData),UJ=()=>z0(($)=>$.app.sessionHistoryViewerData),GJ=()=>z0(($)=>$.app.taskAttentionStatus),h8=()=>z0(($)=>$.app.taskAttentionUnreadKeys),KJ=()=>z0(($)=>$.app.awaitingSecondCtrlC),N1=()=>z0(($)=>$.app.actions),h2=()=>z0(($)=>$.app.sideConversation),zJ=()=>z0(($)=>$.app.teams),E8=()=>z0(($)=>$.app.initializationStatus==="ready"),qJ=()=>z0(($)=>$.app.tasks.length>0),E2=()=>z0(($)=>$.config.config?.permissionMode||"default"),_J=()=>z0(($)=>$.config.config?.models??bZ),g8=()=>z0(($)=>{let J=$.config.config;if(!J)return;let Y=J.currentModelId;return J.models.find((X)=>X.id===Y)??J.models[0]}),m8=()=>z0(($)=>$.config.config?.currentModelId),OJ=()=>z0(($)=>$.config.config?.agentTeamsEnabled===!0),D0=()=>z0(($)=>{return L$.getTheme()}),NJ=()=>z0(($)=>$.config.config?.codeTheme??"default"),s0=()=>z0(($)=>$.focus.currentFocus),HJ=()=>z0(($)=>$.focus.actions),g2=()=>z0(($)=>$.command.isProcessing),WJ=()=>z0(($)=>$.command.actions),p8=()=>z0(($)=>$.app.followUpQueue),FJ=()=>z0(($)=>$.app.followUpQueueMutation),LJ=()=>z0(($)=>$.command.recoveredSteeringCount),x8=()=>z0(($)=>$.app.reasoningEffort!=="off"),c8=()=>z0(($)=>$.app.reasoningEffort),u8=()=>z0(($)=>$.app.serviceTier),d8=()=>z0(($)=>$.app.responseVerbosity),l8=()=>z0(($)=>$.app.communicationStyle),r8=()=>z0(($)=>$.session.currentThinkingContent),BJ=()=>z0(($)=>$.session.thinkingExpanded),a8=()=>z0(($)=>$.session.currentStreamingMessageId),i8=()=>z0(AZ(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),wJ=()=>z0(($)=>$.session.finalizingStreamingMessageId),PJ=()=>z0(($)=>$.session.historyExpanded),AJ=()=>z0(($)=>$.session.expandedMessageCount);import{randomUUID as H7}from"node:crypto";import{useMemoizedFn as X1}from"ahooks";import{useEffect as l1,useMemo as FY,useRef as N4}from"react";function MZ($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class q6{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((Y)=>{this.handleUnexpectedFailure(Y,$)})})}catch(Y){this.handleUnexpectedFailure(Y,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},Y=new AbortController,Z=this.wakeEpoch,X=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=Y;let Q;try{Q=await this.options.run(Y.signal)}finally{if(this.activeAttemptToken===J){if(this.activeAttemptToken=null,this.activeRunController=null,!this.disposed&&$!==this.generation)this.scheduleIfRunnable()}}if(this.disposed||$!==this.generation)return;if(Q.status==="completed"){let U=this.wakeEpoch!==Z;if(this.clearEpisode(),U)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==X)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let Y=m2($.taskFailure),Z=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Z||!MZ($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,Y);return}let X=TJ({sessionIdentity:Z,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(X.phase!=="retry_scheduled"){this.terminate(X.phase,this.attempt,Y);return}this.requested=!0,this.waitingForIdle=!1;let Q={},U=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},X.delayMs);this.retryTimer={handle:U,token:Q},U.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),m2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},Y=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),bJ("timeout"),"pending-resume-recovery-deadline-exceeded")},MJ);this.deadlineTimer={handle:Y,token:J},Y.unref?.()}terminate($,J,Y,Z){let X=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Z)X?.abort(Z);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:Y})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class U8{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)o8(J,$.extraContent);CJ(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function TZ($){if(!($ instanceof Error))return"未知错误";let Z=$.lastError??$;if(Z.responseBody)try{let U=JSON.parse(Z.responseBody)?.error?.message;if(U){let G=Z.statusCode?` (HTTP ${Z.statusCode})`:"";return`${U}${G}`}}catch{}let X=$.message.match(/Last error:\s*(.+)$/);if(X)return X[1];return $.message}function CZ($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function RZ($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function n8($){let J=CZ($),Y=RZ($),Z;if(Y)Z="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Z=TZ($);return{displayMessage:Z,isAbort:J,isVisionNotSupported:Y}}import{appendFileSync as yZ,mkdirSync as IZ,writeFileSync as SZ}from"node:fs";import kZ from"node:os";import _6 from"node:path";var RJ=null;function DZ(){let $=process.env.BLADE_STORAGE_ROOT||_6.join(kZ.homedir(),".blade");return _6.join($,"logs","stream-debug.log")}function fZ($){if(RJ===$)return;let J=_6.dirname($);IZ(J,{recursive:!0,mode:493}),SZ($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
2
2
  `),RJ=$}function O6($,J,Y){try{let Z=DZ();fZ(Z);let X=new Date().toISOString(),Q=Y?` | ${JSON.stringify(Y)}`:"",U=`[${X}] [${$}] ${J}${Q}
3
3
  `;yZ(Z,U)}catch{}}var G8=H1("UI");function N6($,J){if(J.state==="requires_attention"){let Y=J.reason==="interrupted_tool_call";$.addToolMessage("Turn recovery requires attention",{toolName:"Runtime Recovery",phase:"complete",summary:Y?"An interrupted tool may have partially completed":"A completed tool may already have changed external state",detail:`${J.turnId} · inspect workspace, processes, and external state before retrying`});return}$.addToolMessage(J.state==="completed"?"Recovered completed turn":"Resuming interrupted turn",{toolName:"Runtime Recovery",phase:"complete",summary:J.state==="completed"?"The durable final response was recovered":"No tool execution was recorded before interruption",detail:J.turnId})}function DJ($,J){let Y=$.streamSession??new U8({signal:$.signal,streamingBuffer:$.streamingBuffer,getStreamingMessageId:$.getStreamingMessageId,finalizeStreamingMessage:$.sessionActions.finalizeStreamingMessage,discardStreamingMessage:$.sessionActions.discardStreamingMessage,clearThinking:()=>$.sessionActions.setCurrentThinkingContent(null)}),Z=(X)=>{for(let Q of X){if((Q.origin??"user")!=="user")continue;let U=$.commandActions.takeFollowUpPresentation(Q.id);if(U){$.sessionActions.addUserMessage(U.displayText);continue}if(!Q.recovered||Q.persisted)continue;let G=typeof Q.content==="string"?Q.content:Q.content.map((z)=>z.type==="text"?z.text:"[Image]").join(`
4
4
  `);$.sessionActions.addUserMessage(G)}};return(X)=>{switch(X.kind){case"content_delta":if(X.delta.length>0)J.outputStarted=!0;if(!Y.acceptsDeltas())break;J.contentDeltaCount++,J.contentDeltaTotalLen+=X.delta.length,O6("loopEventHandler","onContentDelta",{callCount:J.contentDeltaCount,deltaLen:X.delta.length,totalLen:J.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(X.delta);break;case"thinking_delta":if(X.delta.length>0)J.outputStarted=!0;if(!Y.acceptsDeltas())break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(X.delta);break;case"stream_end":{$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),G8.debug("[loopEventHandler] stream_end",{contentDeltaCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Y.isFinalized,signalAborted:$.signal.aborted}),O6("loopEventHandler","onStreamEnd",{contentDeltaCallCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Y.isFinalized,signalAborted:$.signal.aborted}),Y.finalize();break}case"model_fallback":$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y.discard();break;case"provider_admission":{let{kind:Q,...U}=X;$.sessionActions.setProviderAdmission(X.phase==="queued"?U:null);break}case"provider_circuit":{let{kind:Q,...U}=X;$.sessionActions.setProviderCircuit(X.phase==="closed"?null:U);break}case"provider_retry":{let{kind:Q,...U}=X;$.sessionActions.setProviderRetry(X.phase==="recovered"?null:U);break}case"provider_stall":{let{kind:Q,...U}=X;$.sessionActions.setProviderStall(X.phase==="detected"?U:null);break}case"provider_recovery":$.sessionActions.setProviderRecovery(X.recovery);break;case"action_stationarity":{let{kind:Q,...U}=X;$.sessionActions.setActionStationarity(X.phase==="recovered"?null:U);break}case"turn_recovery":{N6($.sessionActions,X.assessment);break}case"tool_start":{J.toolExecutionStarted=!0;let Q=X.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;if(G8.debug("[loopEventHandler] tool_start",{toolName:Q.function.name,toolKind:X.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name))break;try{let U=JSON.parse(Q.function.arguments),G=SJ(Q.function.name,U);$.sessionActions.addToolMessage(G,{toolCallId:Q.id,toolName:Q.function.name,phase:"start",summary:G,params:U})}catch(U){G8.error("[loopEventHandler] onToolStart error:",U)}break}case"tool_progress":{J.toolExecutionStarted=!0;let Q=X.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;let U=X.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((X.update.progress??0)/X.update.total*100)))}%`:"",G=`${Q.function.name}${U}: ${X.update.message}`;$.sessionActions.addToolMessage(G,{toolCallId:Q.id,toolName:Q.function.name,phase:"progress",summary:G,...X.update.admission?{admission:X.update.admission}:{}});break}case"tool_result":{J.toolExecutionStarted=!0;let Q=X.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;G8.debug("[loopEventHandler] tool_result",{toolName:Q.function.name,success:X.result.success});let U=IJ(kJ(Q.function.name,X.result),yJ);$.sessionActions.addToolMessage(U.summary,{toolCallId:Q.id,toolName:Q.function.name,phase:"complete",summary:U.summary,detail:U.detail});break}case"structured_output":J.outputStarted=!0,$.sessionActions.replaceLastAssistantMessage(JSON.stringify(X.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(X.usage);break;case"compaction":if($.sessionActions.setCompacting(X.phase==="start"),X.phase==="end"){if($.sessionActions.resetContextUsage(),X.outcome!=="failed")J.compactionCount=(J.compactionCount??0)+1;if(X.memory?.outcome==="written"){let Q=`Saved ${X.memory.entries} project memories`;$.sessionActions.addToolMessage(Q,{toolName:"Project Memory",phase:"complete",summary:Q})}}break;case"turn_start":G8.debug("[loopEventHandler] turn_start",{turn:X.turn,maxTurns:X.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:X.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y.startTurn();break;case"task_update":$.appActions.setTasks(X.tasks);break;case"goal_frontier_updated":$.appActions.setTasks(X.tasks);break;case"mcp_catalog_changed":{let Q=`MCP catalog r${X.revision}: +${X.added.length} -${X.removed.length} ~${X.updated.length}`;$.sessionActions.addToolMessage(Q,{toolName:"MCP Catalog",phase:"complete",summary:Q,detail:[X.added.length>0?`Added: ${X.added.join(", ")}`:"",X.removed.length>0?`Removed: ${X.removed.join(", ")}`:"",X.updated.length>0?`Updated: ${X.updated.join(", ")}`:""].filter(Boolean).join(`
@@ -10,7 +10,7 @@ import{e as JX,f as YX,h as S$,i as T4}from"./chunk-qcs8ce4s.js";import{l as YZ,
10
10
  `)});break}case"project_rules_loaded":{let Q=`Project rules loaded: ${X.files.length}`+(X.blockedWrite?" (write retry required)":"");$.sessionActions.addToolMessage(Q,{toolName:"Project Rules",phase:"complete",summary:Q,detail:X.files.map((U)=>`${U.relativePath} ${U.source} sha256=${U.contentSha256}`).join(`
11
11
  `)});break}case"steering_applied":if(Z(X.messages),$.appActions.projectFollowUpQueue(X.queue,$.followUpQueueOwner),X.recovered>0)$.commandActions.setRecoveredSteeringCount(X.recovered);break;case"follow_up_started":if($.appActions.projectFollowUpQueue(X.queue,$.followUpQueueOwner),X.recovered>0)$.commandActions.setRecoveredSteeringCount(X.recovered);break;case"follow_up_queue_changed":$.appActions.projectFollowUpQueue(X.queue,$.followUpQueueOwner);break;case"goal_updated":case"goal_continuation_started":break;case"turn_activity":$.sessionActions.setTurnActivity(X.activity);break;case"subagent_spawned":case"subagent_completed":break;default:{let Q=X}}}}function H6($){let{text:J,parts:Y}=$,Z=Y.filter((U)=>U.type==="image");if(Z.length===0)return J;if(Z.length>p2)throw Error(`最多只能发送 ${p2} 张图片`);if(Z.reduce((U,G)=>U+`data:${G.mimeType};base64,`.length+G.base64.length,0)>e8)throw Error("图片编码后总大小不能超过 5 MiB");let Q=[];for(let U of Y)if(U.type==="text")Q.push({type:"text",text:U.text});else Q.push({type:"image_url",image_url:{url:`data:${U.mimeType};base64,${U.base64}`}});return Q}function fJ($){let J=VJ($.metadata);return{role:$.role,content:J?vJ(J):$.content,...$.metadata?{metadata:$.metadata}:{}}}function $4($){if(!$.restoredContextMessages||$.restoredVisibleMessageCount<=0)return $.messages.map(fJ);let J=$.messages.slice($.restoredVisibleMessageCount).map(fJ);return[...$.restoredContextMessages,...J]}import $7 from"node:path";import{basename as oZ}from"node:path";import{createHash as vZ}from"node:crypto";import*as U2 from"node:fs/promises";import*as X4 from"node:path";import VZ from"write-file-atomic";var W6=1,jZ="tui-task-attention-v1.json",hZ=/^[a-f0-9]{64}$/,EZ=4194304,gZ=20000,pJ=1024,jJ=256,mZ=/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d\.\d{3}Z$/,pZ={realpath:!1,retries:{retries:150,factor:1.2,minTimeout:10,maxTimeout:100,randomize:!0}},hJ;class Z4{static operations=new mJ;filePath;writeFile;openFile;lockFile;chmodFile;reportDiagnostic;entries=[];pending=[];journalOverflowed=!1;constructor($={}){this.filePath=$.filePath??X4.join(K8(),jZ),this.writeFile=$.writeFile??VZ,this.openFile=$.openFile??U2.open,this.lockFile=$.lockFile??iZ,this.chmodFile=$.chmodFile??U2.chmod,this.reportDiagnostic=$.reportDiagnostic??(()=>{return})}reconcile($,J){return this.mutate({kind:"reconcile",sessions:$,visibleLocator:J})}acknowledge($){return this.mutate({kind:"acknowledge",summary:$})}snapshot(){return J4(this.entries)}async mutate($){return Z4.operations.runExclusive(this.filePath,async()=>{if(this.journalOverflowed||this.pending.length>=jJ)return this.journalOverflowed=!0,this.entries=F6(this.entries,$),this.reportDiagnostic("TUI task attention persistence unavailable"),J4(this.entries);let J,Y,Z=!1,X=!1;try{await rZ(this.filePath),J=await this.lockFile(this.filePath,{...pZ,onCompromised:()=>{Z=!0}});let Q=await lZ(this.filePath,this.openFile);if(Y=xZ(Q,[...this.pending,$]),this.entries=Y,Z)throw Error("attention file lock compromised");let U=JSON.stringify({version:W6,entries:Y},null,2);if(await this.writeFile(this.filePath,U+`
12
12
  `,{mode:384}),Z)throw Error("attention file lock compromised");X=!0,this.pending=[],await this.chmodFile(this.filePath,384)}catch{if(X)return this.reportDiagnostic("TUI task attention persistence unavailable"),J4(this.entries);if(Y===void 0)Y=F6(this.entries,$),this.entries=Y;this.enqueue($),this.reportDiagnostic("TUI task attention persistence unavailable")}finally{if(J)try{await J()}catch{this.reportDiagnostic("TUI task attention persistence unavailable")}}return J4(this.entries)})}enqueue($){if(this.journalOverflowed)return;if(this.pending.length>=jJ){this.journalOverflowed=!0;return}this.pending.push($)}}function xZ($,J){return J.reduce((Y,Z)=>{return F6(Y,Z)},[...$])}function F6($,J){if(J.kind==="reconcile")return EJ(cZ($,J.sessions,J.visibleLocator));let Y=x2(J.summary.locator);return EJ(xJ($,{key:Y,signature:L6(J.summary),unread:!1}))}function cZ($,J,Y){let Z=new Map($.map((O)=>[O.key,O])),X=new Set,Q=Y?x2(Y):void 0,U,G=[],z=[];for(let O of J){let q=x2(O.locator);if(X.has(q))continue;X.add(q);let N=L6(O);if(Q===q){U=O;continue}let _=Z.get(q);if(!_){let W={key:q,signature:N,unread:!1};if(N===null)G.push(W);else z.push(W);continue}if(N===null){G.push({key:q,signature:null,unread:_.unread});continue}if(_.signature!==N){G.push({..._,unread:!0});continue}if(_.unread)G.push(_);else z.push(_)}let K=[...z.slice(0,pJ).reverse(),...G.reverse()];if(U)K=xJ(K,{key:x2(U.locator),signature:L6(U),unread:!1});return K}function EJ($){let J=$.map((Z,X)=>({entry:Z,index:X})).filter(({entry:Z})=>Z.signature!==null&&!Z.unread).map(({index:Z})=>Z),Y=new Set(J.slice(0,Math.max(0,J.length-pJ)));return $.filter((Z,X)=>!Y.has(X))}function xJ($,J){return[...$.filter((Y)=>Y.key!==J.key),J]}function J4($){return Object.freeze({unreadKeys:Object.freeze($.filter((J)=>J.unread).map((J)=>J.key))})}function x2($){let J=$.workspace.kind==="local"?[2,"local",$.workspace.projectPath,$.sessionId]:[2,"acp-remote",$.workspace.workspaceRef,$.sessionId];return vZ("sha256").update("blade-tui-task-attention-locator-v1\x00").update(JSON.stringify(J)).digest("hex")}function L6($){if($.taskStatus!=="completed"&&$.taskStatus!=="failed"&&$.taskStatus!=="interrupted")return null;return JSON.stringify([$.taskStatus,$.taskCompletedAt??null])}function uZ($){try{let J=JSON.parse($);if(!Array.isArray(J)||J.length!==2||J[0]!=="completed"&&J[0]!=="failed"&&J[0]!=="interrupted")return!1;if(J[1]!==null&&(typeof J[1]!=="string"||!mZ.test(J[1])||new Date(J[1]).toISOString()!==J[1]))return!1;return JSON.stringify(J)===$}catch{return!1}}function gJ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function dZ($){if(!gJ($)||Object.keys($).some((Z)=>Z!=="version"&&Z!=="entries")||$.version!==W6||!Array.isArray($.entries)||$.entries.length>gZ)return;let J=new Set,Y=[];for(let Z of $.entries){if(!gJ(Z)||Object.keys(Z).some((X)=>X!=="key"&&X!=="signature"&&X!=="unread")||typeof Z.key!=="string"||!hZ.test(Z.key)||J.has(Z.key)||Z.signature!==null&&(typeof Z.signature!=="string"||!uZ(Z.signature))||typeof Z.unread!=="boolean")return;J.add(Z.key),Y.push({key:Z.key,signature:Z.signature,unread:Z.unread})}return{version:W6,entries:Y}}async function lZ($,J){let Y;try{Y=await J($,"r");let Z=await Y.readFile();if(Z.byteLength>EZ)return[];let X=JSON.parse(Z.toString("utf8"));return dZ(X)?.entries??[]}catch(Z){if(Z instanceof SyntaxError||Z instanceof Error&&"code"in Z&&Z.code==="ENOENT")return[];throw Z}finally{await Y?.close()}}async function rZ($){let J=X4.dirname($);await U2.mkdir(J,{recursive:!0,mode:448}),await U2.chmod(J,448)}async function aZ(){return hJ??=await import("proper-lockfile"),hJ}async function iZ($,J){return(await aZ()).lock($,J)}function T1($){let{locator:J}=$;if(J.workspace.kind==="acp-remote")return[J.version,J.workspace.kind,J.workspace.workspaceRef,J.sessionId].join("\x00");return[J.version,J.workspace.kind,J.workspace.projectPath,J.sessionId].join("\x00")}function cJ($){return x2($.locator)}async function uJ($,J,Y){if(await $.start(),Y.continueSession||Y.resume!==void 0||Y.forkSession)return;if(Y.requestedSessionId!==void 0&&$.getState().status!=="ready")return;if(Y.requestedSessionId!==void 0&&$.getState().sessions.some((Z)=>nZ(Z.locator,Y.locator)))return;await J.proveLocal(Y.locator)}function nZ($,J){if($.sessionId!==J.sessionId||$.workspace.kind!==J.workspace.kind)return!1;return $.workspace.kind==="local"&&J.workspace.kind==="local"?$.workspace.projectPath===J.workspace.projectPath:$.workspace.kind==="acp-remote"&&J.workspace.kind==="acp-remote"&&$.workspace.workspaceRef===J.workspace.workspaceRef}async function tZ($,J,Y,Z){if($==="resume"){await Y.acknowledge(J),await Y.setVisibleLocator(J.locator);return}if(Z)await Y.setVisibleLocator(Z)}function dJ($,J,Y,Z){let X={version:2,sessionId:Y.sessionId,workspace:{kind:"local",projectPath:Y.projectPath}};return tZ($,J,{acknowledge:(Q)=>Z.acknowledge(Q),setVisibleLocator:(Q)=>Q?Z.proveLocal(Q):Promise.resolve()},X)}function lJ($,J){return $.proveLocal(J)}class B6{attention;remote;remoteEpoch=0;provenLocalLocator;remoteActive=!1;constructor($){this.attention=$;this.remote=new rJ((J)=>$.acknowledge(J))}acknowledge($){return this.attention.acknowledge($)}async proveLocal($){if(this.provenLocalLocator=$,this.remoteActive)return;this.remoteEpoch+=1,this.remote.reset(),await this.attention.setVisibleLocator($)}async beginRemote($,J){this.remoteActive=!0,this.remoteEpoch+=1,this.remote.begin($,J)}beginRemoteOpening(){this.remoteActive=!0;let $=++this.remoteEpoch;return this.remote.reset(),{epoch:$,cleared:this.attention.setVisibleLocator(void 0)}}isRemoteOpeningCurrent($){return this.remoteActive&&this.remoteEpoch===$}bindRemoteOpening($,J,Y){if(!this.isRemoteOpeningCurrent($))return!1;return this.remote.begin(J,Y),!0}async endRemote(){if(!this.remoteActive)return;this.remoteActive=!1,this.remoteEpoch+=1,this.remote.reset(),await this.attention.setVisibleLocator(this.provenLocalLocator)}async updateRemote($,J){let Y=this.remoteEpoch;if(!await this.remote.update($,J)||Y!==this.remoteEpoch)return;await this.attention.setVisibleLocator(J.session?.locator)}}class rJ{acknowledge;acknowledgedView;pendingView;expectedView;constructor($){this.acknowledge=$}begin($,J){this.expectedView=$.intent==="resume"?{key:T1($.session),generation:J}:void 0}reset(){this.expectedView=void 0}async update($,J){if($.intent!=="resume"||J.status!=="ready"||!J.session||!this.expectedView||J.viewGeneration!==this.expectedView.generation||T1($.session)!==this.expectedView.key||T1($.session)!==T1(J.session))return!1;let Y=`${J.viewGeneration}\x00${T1(J.session)}`;if(Y===this.acknowledgedView||Y===this.pendingView)return!1;this.pendingView=Y;try{if(await this.acknowledge(J.session),this.expectedView?.generation!==J.viewGeneration||this.expectedView.key!==T1(J.session))return!1;return this.acknowledgedView=Y,!0}finally{if(this.pendingView===Y)this.pendingView=void 0}}}function sZ($){return $.title?.trim()||`Session ${$.locator.sessionId.slice(0,8)}`}function Q4($,J){let Y=$.filter((Z)=>Z.relationType!=="subagent");if(J!=="fork")return Y;return Y.filter((Z)=>Z.archivedAt===void 0&&Z.capabilities.history.fork)}function aJ($){return $.find((J)=>J.relationType!=="subagent"&&J.locator.workspace.kind==="local")}function iJ($,J,Y=!1){let Z=sZ($),X=Y?"[NEW] ":"";if($.locator.workspace.kind==="acp-remote"){let G=$.archivedAt?" · archived":"";return`${X}[remote · ${$.capabilities.connection} · history${G}] ${Z}
13
- ${$.displayCwd} · ${$.messageCount} messages · ${J}${$.hasErrors?" [!]":""}`}let Q=eZ($.taskStatus),U=$.relationType==="subagent"?" ↳ subagent":$.relationType==="fork"?" ↳ fork":"";return`${X}[${Q}] ${Z} · ${J} | ${oZ($.displayCwd)} | ${$.messageCount} 条消息${$.hasErrors?" [!]":""}${U}`}function oJ($){return{title:$==="fork"?"选择要 fork 的会话:":"选择要恢复的会话:",instructions:"(Left/Right to page | Up/Down to select | Enter to confirm | Esc to cancel)"}}function eZ($){switch($){case"queued":return"QUEUED";case"running":return"RUNNING";case"failed":return"FAILED";case"cancelled":return"CANCELLED";case"interrupted":return"INTERRUPTED";case"completed":return"DONE"}}async function YY($,J,Y,Z={}){if($.locator.workspace.kind==="acp-remote"){if(J==="fork"&&Z.newSessionId)throw Error("Custom Session IDs are unavailable for remote history forks");return await Y.openHistory($,J),"history-only"}let X=await w6($);return await Y.activateLocal(X,J),"interactive"}function G4($){if($.remoteWorkspace)throw Error("Remote history cannot enter the local compatibility path");let J=$.archivedAt!==void 0,Y=JY($.taskCompletedAt);return U4.parse({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}},displayCwd:$.projectPath,title:$.title,rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,taskStatus:$.taskStatus,...Y!==void 0?{taskCompletedAt:Y}:{},messageCount:$.messageCount,firstMessageTime:$.firstMessageTime,lastMessageTime:$.lastMessageTime,hasErrors:$.hasErrors,archivedAt:$.archivedAt,selectedModelId:$.selectedModelId,capabilities:{connection:"local",history:{read:!0,fork:!J},turn:J?{start:!1,reason:"archived"}:{start:!0},files:J?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:J?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}}})}async function w6($){if($.locator.workspace.kind!=="local")throw Error("Remote history cannot enter the local activation path");let J=eJ($.locator.workspace.projectPath),Y=await a0.findSessionMetadata($.locator.sessionId,J);if(!Y)throw Error("Session history is no longer available");if(Y.remoteWorkspace)throw Error("Remote history cannot enter the local activation path");return Y}function nJ($){if($.length<=8)return $;return`${$.slice(0,8)}…`}function J7($){return $7.resolve($)}function tJ($){if(!$||!$Y($))return;m0().config.actions.updateConfig({currentModelId:$})}function sJ($){if(!$)return;m0().config.actions.updateConfig({permissionMode:$})}async function K4($,J,Y){let Z=Y?await Y.listAll():(await a0.listSessions({includeSubagents:!1})).map(G4);return Q4(Z,$)}async function z4($,J,Y,Z){let{intent:X,session:Q,newSessionId:U,announceFork:G,permissionModeOverride:z}=$,K=J7(Q.projectPath);if(X==="fork"){let _=await a0.forkSession(Q.sessionId,{...U?{newSessionId:U}:{},sourceProjectPath:K,targetProjectPath:K}),W=await a0.loadSessionModelContext(_.sessionId,_.metadata.projectPath),H=[...a0.toUISafeMessages(_.messages)];if(G!==!1){let A=Date.parse(_.metadata.lastMessageTime);H.push({id:"fork-announcement-"+_.sessionId,role:"assistant",content:"Forked "+nJ(Q.sessionId)+" → "+nJ(_.sessionId),timestamp:Number.isNaN(A)?0:A})}return await Z(),sJ(z??_.metadata.permissionMode),tJ(_.metadata.selectedModelId),Y.restoreSession(_.sessionId,H,W,_.metadata.projectPath),{sessionId:_.sessionId,messages:W,projectPath:_.metadata.projectPath}}await a0.assertSessionWritable(Q.sessionId,Q.projectPath);let[O,q]=await Promise.all([a0.loadSession(Q.sessionId,Q.projectPath),a0.loadSessionModelContext(Q.sessionId,Q.projectPath)]),N=a0.toUISafeMessages(O);return await Z(),sJ(z??Q.permissionMode),tJ(Q.selectedModelId),Y.restoreSession(Q.sessionId,N,q,Q.projectPath),{sessionId:Q.sessionId,messages:q,projectPath:Q.projectPath}}var Y7=H1("UI");function GY($){return typeof $==="object"&&$!==null&&typeof $.sessionId==="string"&&typeof $.projectPath==="string"&&typeof $.rootId==="string"&&typeof $.messageCount==="number"&&typeof $.firstMessageTime==="string"&&typeof $.lastMessageTime==="string"&&typeof $.hasErrors==="boolean"}function KY($){return U4.safeParse($).success}function XY($){if(typeof $!=="object"||$===null)return!1;return Object.hasOwn($,"locator")?KY($):GY($)}function ZY($){return KY($)?$:G4($)}function X7($){return typeof $==="object"&&$!==null&&$.action==="invoke_skill"&&typeof $.skillName==="string"}function Z7($){return typeof $==="object"&&$!==null&&$.action==="invoke_custom_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function Q7($){return typeof $==="object"&&$!==null&&$.action==="invoke_plugin_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function U7($){return typeof $==="object"&&$!==null&&$.action==="invoke_once_model"&&typeof $.modelId==="string"&&typeof $.prompt==="string"}function G7($){return typeof $==="object"&&$!==null&&["start_goal","resume_goal"].includes(String($.action))&&typeof $.goal?.objective==="string"}function K7($){return typeof $==="object"&&$!==null&&$.action==="rewind_session"&&typeof $.sessionId==="string"&&Array.isArray($.messages)&&Array.isArray($.visibleMessages)}function z7($){if(typeof $!=="object"||$===null)return!1;let J=$.intent;if(J!=="resume"&&J!=="fork")return!1;let Y=$.action;if(Y==="select_session"){let Z=$.sessions;return Array.isArray(Z)&&Z.every(XY)}if(Y==="activate_session"){let Z=$.session;return XY(Z)}return!1}function q7($,J,Y,Z){switch($){case"show_theme_selector":return Y.setActiveModal("themeSelector"),!0;case"show_model_selector":return Y.setActiveModal("modelSelector"),!0;case"show_model_add_wizard":return Y.setActiveModal("modelAddWizard"),!0;case"show_permissions_manager":return Y.setActiveModal("permissionsManager"),!0;case"show_agents_manager":return Y.setActiveModal("agentsManager"),!0;case"show_skills_manager":return Y.setActiveModal("skillsManager"),!0;case"show_hooks_manager":return Y.setActiveModal("hooksManager"),!0;case"show_plugins_manager":return Y.setActiveModal("pluginsManager"),!0;case"show_follow_up_queue":return Y.setActiveModal("followUpQueue"),!0;case"show_agent_creation_wizard":return Y.setActiveModal("agentCreationWizard"),!0;case"show_session_selector":{let X=J?.sessions;return Y.showSessionSelector((X??[]).map(G4),"resume"),!0}case"session_forked":{let X=J;if(X?.action!=="restore_forked_session"||!X.sessionId||!Array.isArray(X.messages)||!Array.isArray(X.visibleMessages))return!1;return Z.restoreSession(X.sessionId,X.visibleMessages,X.messages),!0}case"session_archived":{let X=J?.session;return Z.addAssistantMessage(X?`会话 ${X.sessionId} 已归档。`:"当前会话已归档。"),Y1(0),!0}case"clear_screen":return Z.clearMessages(),Z.setError(null),Z.resetTokenUsage(),Y.setTasks([]),!0;case"compact_completed":case"compact_fallback":{let X=J,Q=X?.compactedMessages;if(Q)Z.setCompactedContext(Q);if(X?.usage)Z.updateTokenUsage({inputTokens:X.usage.promptTokens,outputTokens:X.usage.completionTokens,totalTokens:X.usage.totalTokens,maxContextTokens:X.maxContextTokens,cacheReadTokens:X.usage.cacheReadInputTokens??0,cacheWriteTokens:X.usage.cacheCreationInputTokens??0,costUsd:X.usage.costUsd});return Z.resetContextUsage(),!0}case"exit_application":return Y1(0),!0;default:return!1}}async function P6($,J,Y,Z,X,Q,U,G,z,K,O,q,N,_,W=K$(),H,A){let{text:b}=$;if(!QY(b))return{type:"not_slash"};let B=await UY(b,{cwd:W,surface:"tui",workspaceRoot:W,sessionId:Q,messages:U,rewind:G,lifecycle:Q===void 0?void 0:{archiveCurrent:async()=>{return await X(),a0.archiveSession(Q,W)}},subagents:z,mcp:K,reasoning:O,serviceTier:q,responseVerbosity:N,communicationStyle:_,codeReview:H,sessionSurfaces:A,signal:Z});if(B.success&&z7(B.data)){if(B.data.action==="select_session")return J.showSessionSelector(B.data.sessions.map(ZY),B.data.intent),{type:"handled",commandResult:{success:!0}};let F=ZY(B.data.session);if(F.locator.workspace.kind==="acp-remote")return J.showSessionHistoryViewer(F,B.data.intent),{type:"handled",commandResult:{success:!0}};let M=GY(B.data.session)?B.data.session:await w6(F),L=await z4({...B.data,session:M},W,Y,X);try{if(B.data.intent==="resume")await A?.acknowledge?.(F),await A?.setVisibleLocator?.(F.locator);else await A?.setVisibleLocator?.({version:2,sessionId:L.sessionId,workspace:{kind:"local",projectPath:L.projectPath}})}catch{Y7.warn("[slashCommandRouter] Task attention activation unavailable")}return{type:"handled",commandResult:{success:!0}}}if(B.success&&K7(B.data))return Y.restoreSession(B.data.sessionId,B.data.visibleMessages,B.data.messages),J.setTasks([]),{type:"handled",commandResult:{success:!0}};if(B.message){if(q7(B.message,B.data,J,Y))return{type:"handled",commandResult:{success:!0}}}if(X7(B.data)){let{skillName:F,skillArgs:M}=B.data,L=M?`Please use the "${F}" skill to help me with: ${M}`:`Please use the "${F}" skill.`;return Y.addUserMessage(L),{type:"continue_as_agent",result:{userDisplayMessage:L,agentInput:{displayText:L,text:L,images:[],parts:[{type:"text",text:L}]},userMessageAlreadyAdded:!0}}}if(Z7(B.data)){let{commandName:F,processedContent:M}=B.data;Y.addUserMessage(b);let L=`# Custom Command: /${F}
13
+ ${$.displayCwd} · ${$.messageCount} messages · ${J}${$.hasErrors?" [!]":""}`}let Q=eZ($.taskStatus),U=$.relationType==="subagent"?" ↳ subagent":$.relationType==="fork"?" ↳ fork":"";return`${X}[${Q}] ${Z} · ${J} | ${oZ($.displayCwd)} | ${$.messageCount} 条消息${$.hasErrors?" [!]":""}${U}`}function oJ($){return{title:$==="fork"?"选择要 fork 的会话:":"选择要恢复的会话:",instructions:"(Left/Right to page | Up/Down to select | Enter to confirm | Esc to cancel)"}}function eZ($){switch($){case"queued":return"QUEUED";case"running":return"RUNNING";case"failed":return"FAILED";case"cancelled":return"CANCELLED";case"interrupted":return"INTERRUPTED";case"completed":return"DONE"}}async function YY($,J,Y,Z={}){if($.locator.workspace.kind==="acp-remote"){if(J==="fork"&&Z.newSessionId)throw Error("Custom Session IDs are unavailable for remote history forks");return await Y.openHistory($,J),"history-only"}let X=await w6($);return await Y.activateLocal(X,J),"interactive"}function G4($){if($.remoteWorkspace)throw Error("Remote history cannot enter the local compatibility path");let J=$.archivedAt!==void 0,Y=JY($.taskCompletedAt);return U4.parse({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}},displayCwd:$.projectPath,title:$.title,rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,taskStatus:$.taskStatus,...Y!==void 0?{taskCompletedAt:Y}:{},messageCount:$.messageCount,firstMessageTime:$.firstMessageTime,lastMessageTime:$.lastMessageTime,hasErrors:$.hasErrors,archivedAt:$.archivedAt,selectedModelId:$.selectedModelId,capabilities:{connection:"local",history:{read:!0,fork:!J},turn:J?{start:!1,reason:"archived"}:{start:!0},files:J?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:J?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}}})}async function w6($){if($.locator.workspace.kind!=="local")throw Error("Remote history cannot enter the local activation path");let J=eJ($.locator.workspace.projectPath),Y=await a0.findSessionMetadata($.locator.sessionId,J);if(!Y)throw Error("Session history is no longer available");if(Y.remoteWorkspace)throw Error("Remote history cannot enter the local activation path");return Y}function nJ($){if($.length<=8)return $;return`${$.slice(0,8)}…`}function J7($){return $7.resolve($)}function tJ($){if(!$||!$Y($))return;m0().config.actions.updateConfig({currentModelId:$})}function sJ($){if(!$)return;m0().config.actions.updateConfig({permissionMode:$})}async function K4($,J,Y){let Z=Y?await Y.listAll():(await a0.listSessions({includeSubagents:!1})).map(G4);return Q4(Z,$)}async function z4($,J,Y,Z){let{intent:X,session:Q,newSessionId:U,announceFork:G,permissionModeOverride:z}=$,K=J7(Q.projectPath);if(X==="fork"){let _=await a0.forkSession(Q.sessionId,{...U?{newSessionId:U}:{},sourceProjectPath:K,targetProjectPath:K}),W=await a0.loadSessionModelContext(_.sessionId,_.metadata.projectPath),H=[...a0.toUISafeMessages(_.messages)];if(G!==!1){let A=Date.parse(_.metadata.lastMessageTime);H.push({id:"fork-announcement-"+_.sessionId,role:"assistant",content:"Forked "+nJ(Q.sessionId)+" → "+nJ(_.sessionId),timestamp:Number.isNaN(A)?0:A})}return await Z(),sJ(z??_.metadata.permissionMode),tJ(_.metadata.selectedModelId),Y.restoreSession(_.sessionId,H,W,_.metadata.projectPath),{sessionId:_.sessionId,messages:W,projectPath:_.metadata.projectPath}}await a0.assertSessionWritable(Q.sessionId,Q.projectPath);let[O,q]=await Promise.all([a0.loadSession(Q.sessionId,Q.projectPath),a0.loadSessionModelContext(Q.sessionId,Q.projectPath)]),N=a0.toUISafeMessages(O);return await Z(),sJ(z??Q.permissionMode),tJ(Q.selectedModelId),Y.restoreSession(Q.sessionId,N,q,Q.projectPath),{sessionId:Q.sessionId,messages:q,projectPath:Q.projectPath}}var Y7=H1("UI");function GY($){return typeof $==="object"&&$!==null&&typeof $.sessionId==="string"&&typeof $.projectPath==="string"&&typeof $.rootId==="string"&&typeof $.messageCount==="number"&&typeof $.firstMessageTime==="string"&&typeof $.lastMessageTime==="string"&&typeof $.hasErrors==="boolean"}function KY($){return U4.safeParse($).success}function XY($){if(typeof $!=="object"||$===null)return!1;return Object.hasOwn($,"locator")?KY($):GY($)}function ZY($){return KY($)?$:G4($)}function X7($){return typeof $==="object"&&$!==null&&$.action==="invoke_skill"&&typeof $.skillName==="string"}function Z7($){return typeof $==="object"&&$!==null&&$.action==="invoke_custom_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function Q7($){return typeof $==="object"&&$!==null&&$.action==="invoke_plugin_command"&&typeof $.commandName==="string"&&typeof $.processedContent==="string"}function U7($){return typeof $==="object"&&$!==null&&$.action==="invoke_once_model"&&typeof $.modelId==="string"&&typeof $.prompt==="string"}function G7($){return typeof $==="object"&&$!==null&&["start_goal","resume_goal"].includes(String($.action))&&typeof $.goal?.objective==="string"}function K7($){return typeof $==="object"&&$!==null&&$.action==="rewind_session"&&typeof $.sessionId==="string"&&Array.isArray($.messages)&&Array.isArray($.visibleMessages)}function z7($){if(typeof $!=="object"||$===null)return!1;let J=$.intent;if(J!=="resume"&&J!=="fork")return!1;let Y=$.action;if(Y==="select_session"){let Z=$.sessions;return Array.isArray(Z)&&Z.every(XY)}if(Y==="activate_session"){let Z=$.session;return XY(Z)}return!1}function q7($,J,Y,Z){switch($){case"show_theme_selector":return Y.setActiveModal("themeSelector"),!0;case"show_model_selector":return Y.setActiveModal("modelSelector"),!0;case"show_model_add_wizard":return Y.setActiveModal("modelAddWizard"),!0;case"show_permissions_manager":return Y.setActiveModal("permissionsManager"),!0;case"show_agents_manager":return Y.setActiveModal("agentsManager"),!0;case"show_skills_manager":return Y.setActiveModal("skillsManager"),!0;case"show_hooks_manager":return Y.setActiveModal("hooksManager"),!0;case"show_plugins_manager":return Y.setActiveModal("pluginsManager"),!0;case"show_follow_up_queue":return Y.setActiveModal("followUpQueue"),!0;case"show_agent_creation_wizard":return Y.setActiveModal("agentCreationWizard"),!0;case"show_session_selector":{let X=J?.sessions;return Y.showSessionSelector((X??[]).map(G4),"resume"),!0}case"session_forked":{let X=J;if(X?.action!=="restore_forked_session"||!X.sessionId||!Array.isArray(X.messages)||!Array.isArray(X.visibleMessages))return!1;return Z.restoreSession(X.sessionId,X.visibleMessages,X.messages),!0}case"session_archived":{let X=J?.session;return Z.addAssistantMessage(X?`会话 ${X.sessionId} 已归档。`:"当前会话已归档。"),Y1(0),!0}case"clear_screen":return Z.clearMessages(),Z.setError(null),Z.resetTokenUsage(),Y.setTasks([]),!0;case"compact_completed":case"compact_fallback":case"compact_cancelled":{let X=J,Q=X?.compactedMessages;if(Q&&$!=="compact_cancelled")Z.setCompactedContext(Q);if(X?.usage)Z.updateTokenUsage({...$==="compact_cancelled"?{scope:"auxiliary"}:{},inputTokens:X.usage.promptTokens,outputTokens:X.usage.completionTokens,totalTokens:X.usage.totalTokens,maxContextTokens:X.maxContextTokens,cacheReadTokens:X.usage.cacheReadInputTokens??0,cacheWriteTokens:X.usage.cacheCreationInputTokens??0,costUsd:X.usage.costUsd});if($!=="compact_cancelled")Z.resetContextUsage();return!0}case"exit_application":return Y1(0),!0;default:return!1}}async function P6($,J,Y,Z,X,Q,U,G,z,K,O,q,N,_,W=K$(),H,A){let{text:b}=$;if(!QY(b))return{type:"not_slash"};let B=await UY(b,{cwd:W,surface:"tui",workspaceRoot:W,sessionId:Q,messages:U,rewind:G,lifecycle:Q===void 0?void 0:{archiveCurrent:async()=>{return await X(),a0.archiveSession(Q,W)}},subagents:z,mcp:K,reasoning:O,serviceTier:q,responseVerbosity:N,communicationStyle:_,codeReview:H,sessionSurfaces:A,signal:Z});if(B.success&&z7(B.data)){if(B.data.action==="select_session")return J.showSessionSelector(B.data.sessions.map(ZY),B.data.intent),{type:"handled",commandResult:{success:!0}};let F=ZY(B.data.session);if(F.locator.workspace.kind==="acp-remote")return J.showSessionHistoryViewer(F,B.data.intent),{type:"handled",commandResult:{success:!0}};let M=GY(B.data.session)?B.data.session:await w6(F),L=await z4({...B.data,session:M},W,Y,X);try{if(B.data.intent==="resume")await A?.acknowledge?.(F),await A?.setVisibleLocator?.(F.locator);else await A?.setVisibleLocator?.({version:2,sessionId:L.sessionId,workspace:{kind:"local",projectPath:L.projectPath}})}catch{Y7.warn("[slashCommandRouter] Task attention activation unavailable")}return{type:"handled",commandResult:{success:!0}}}if(B.success&&K7(B.data))return Y.restoreSession(B.data.sessionId,B.data.visibleMessages,B.data.messages),J.setTasks([]),{type:"handled",commandResult:{success:!0}};if(B.message){if(q7(B.message,B.data,J,Y))return{type:"handled",commandResult:{success:B.message!=="compact_cancelled"}}}if(X7(B.data)){let{skillName:F,skillArgs:M}=B.data,L=M?`Please use the "${F}" skill to help me with: ${M}`:`Please use the "${F}" skill.`;return Y.addUserMessage(L),{type:"continue_as_agent",result:{userDisplayMessage:L,agentInput:{displayText:L,text:L,images:[],parts:[{type:"text",text:L}]},userMessageAlreadyAdded:!0}}}if(Z7(B.data)){let{commandName:F,processedContent:M}=B.data;Y.addUserMessage(b);let L=`# Custom Command: /${F}
14
14
 
15
15
  The user has invoked the custom command "/${F}". Follow the instructions below to complete the task.
16
16
 
@@ -1,2 +1,2 @@
1
1
  import{clampThinkingLevel as t,getSupportedThinkingLevels as i}from"@earendil-works/pi-ai";var f=["auto","off","minimal","low","medium","high","xhigh","max"];function s(e){return typeof e==="string"&&f.includes(e)}function g(e,o){let n=i(e);if(o!=="auto"&&!n.includes(o))throw Error(`Reasoning effort ${o} is not supported by ${e.name}`);return{selection:o,effective:o==="auto"?t(e,"high"):o,supported:n}}
2
- export{s as vg,g as wg};
2
+ export{s as wg,g as xg};
@@ -1,2 +1,2 @@
1
- import{N as GP}from"./chunk-epe57k9k.js";import{he as N}from"./chunk-acq26c7b.js";import{$e as JP,Oe as r,Pe as e,Se as L,Ue as PP,Xe as d,Ze as l,bf as QP,cf as ZP,df as $P,ef as w}from"./chunk-y5wngtz0.js";import{gf as t,hf as a,jf as R,lf as y,mf as A,of as p}from"./chunk-w33zjw8m.js";import{Pj as q}from"./chunk-j8hbddjp.js";import{Ak as n,fk as o,zk as s}from"./chunk-4wx5sya5.js";async function qP(){return q().listProviders()}async function EP(P){return q().listModels(P)}import{randomBytes as XP}from"node:crypto";var NP=600000,OP=2048,jP=64,MP=32,HP=67108864,WP=4,D={catalog:"session-surface-catalog:",history:"session-surface-history:",snapshot:"session-surface-snapshot:"},c={session_surface_cursor_invalid:{message:"session surface cursor is invalid",retryable:!1},session_surface_snapshot_changed:{message:"session surface snapshot changed",retryable:!1},session_surface_capacity:{message:"session surface cursor capacity exceeded",retryable:!0},session_surface_unavailable:{message:"session surface cursor registry is unavailable",retryable:!0}};class U extends Error{code;retryable;constructor(P){super(c[P].message);this.code=P;this.name="SessionSurfaceCursorRegistryError",this.retryable=c[P].retryable}}class g{now;tokenSource;tokenCollisionRetries;limitsValue;entries=new Map;chains=new Map;closed=!1;closePromise;totalIssues=0;activeLoads=0;frozenSnapshotBytes=0;retainedPayloadBytes=0;constructor(P={}){if(this.now=P.now??(()=>Date.now()),this.tokenSource=P.tokenSource??(()=>XP(32).toString("base64url")),this.tokenCollisionRetries=P.tokenCollisionRetries??WP,this.limitsValue=_P(P.limits??{}),!Number.isSafeInteger(this.tokenCollisionRetries)||this.tokenCollisionRetries<0)throw Error("tokenCollisionRetries must be a non-negative safe integer")}issueCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=m(P.boundary);if(J.value===void 0)throw new U("session_surface_cursor_invalid");let Q=T(P.request);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Z=this.createToken("catalog"),$=this.now(),G=this.ensureChain(P.chainId,$),Y={token:Z,chainId:P.chainId,kind:"catalog",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,scopeKey:P.scopeKey,epoch:P.epoch,revision:P.revision,boundary:J.value,boundaryBytes:J.bytes,requestHash:Q,cachedResultBytes:0};return this.storeEntry(G,Y),this.retainedPayloadBytes+=J.bytes,G.retainedPayloadBytes+=J.bytes,Z}issueHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=T(P.request),Q=this.assertSnapshotIssuableForHistory(P);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:0,chainId:P.chainId});let Z=this.createToken("history"),$=this.now(),G=this.ensureChain(P.chainId,$);this.touch(Q);let Y={token:Z,chainId:P.chainId,kind:"history",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,nextSequence:P.nextSequence,snapshotToken:P.snapshotToken,requestHash:J,cachedResultBytes:0};return this.storeEntry(G,Y),Z}issueSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=P.frozenSnapshot===void 0?{value:void 0,bytes:0}:m(P.frozenSnapshot);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Q=this.createToken("snapshot"),Z=this.now(),$=this.ensureChain(P.chainId,Z),G={token:Q,chainId:P.chainId,kind:"snapshot",expiresAt:Z+this.limitsValue.idleTtlMs,lastAccessAt:Z,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,frozenBytes:J.bytes,frozenSnapshot:J.value};return this.storeEntry($,G),this.frozenSnapshotBytes+=J.bytes,this.retainedPayloadBytes+=J.bytes,$.frozenSnapshotBytes+=J.bytes,$.retainedPayloadBytes+=J.bytes,Q}async redeemCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"catalog");if(J.scopeKey!==P.scopeKey)throw new U("session_surface_cursor_invalid");if(J.epoch!==P.epoch||J.revision!==P.revision)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");if(this.touch(J),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startCatalogLoad(J,P.loader)}async redeemHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"history");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_snapshot_changed");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");let Q=this.resolveHistorySnapshot(J);if(this.touch(J),this.touch(Q),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startHistoryLoad(J,Q,P.loader)}async assertSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"snapshot");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_cursor_invalid");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return this.touch(J),{chainId:J.chainId,locatorDigest:J.locatorDigest,transcriptFingerprint:J.transcriptFingerprint,frozenBytes:J.frozenBytes,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)}}completeChain(P){this.cleanup();let J=this.chains.get(P);if(!J)return;J.completed=!0,J.lastAccessAt=this.now()}stats(){this.cleanup();let P=0;for(let J of this.chains.values())if(J.completed)P+=1;return{closed:this.closed,chainCount:this.chains.size,activeChains:this.chains.size-P,completedChains:P,entryCount:this.entries.size,activeLoads:this.activeLoads,frozenSnapshotBytes:this.frozenSnapshotBytes,retainedPayloadBytes:this.retainedPayloadBytes,totalIssues:this.totalIssues,limits:{...this.limitsValue}}}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;let J=[];for(let Q of this.entries.values())if((Q.kind==="catalog"||Q.kind==="history")&&Q.activeLoad)J.push(Q.activeLoad.promise),Q.activeLoad.controller.abort(_());return this.closePromise=Promise.allSettled(J).then(()=>{this.entries.clear(),this.chains.clear(),this.activeLoads=0,this.frozenSnapshotBytes=0,this.retainedPayloadBytes=0}),this.closePromise}startCatalogLoad(P,J){let Q=this.requireChain(P.chainId),Z=new AbortController;this.activeLoads+=1,Q.activeLoads+=1;let $=Promise.resolve().then(()=>J({boundary:W(P.boundary)},Z.signal)).then((G)=>{return this.assertLoadAvailable(Z.signal),this.admitCachedResult(P,G)}).catch((G)=>{if(this.closed||Z.signal.aborted)throw _();throw G}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Q.activeLoads-=1});return P.activeLoad={controller:Z,promise:$},this.cloneActiveLoadResult(P.activeLoad)}startHistoryLoad(P,J,Q){let Z=this.requireChain(P.chainId),$=new AbortController;this.activeLoads+=1,Z.activeLoads+=1;let G=Promise.resolve().then(()=>Q({nextSequence:P.nextSequence,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)},$.signal)).then((Y)=>{return this.assertLoadAvailable($.signal),this.admitCachedResult(P,Y)}).catch((Y)=>{if(this.closed||$.signal.aborted)throw _();throw Y}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Z.activeLoads-=1});return P.activeLoad={controller:$,promise:G},this.cloneActiveLoadResult(P.activeLoad)}resolveHistorySnapshot(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}assertSnapshotIssuableForHistory(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.chainId!==P.chainId||Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}requireChain(P){let J=this.chains.get(P);if(!J)throw new U("session_surface_cursor_invalid");return J}assertLoadAvailable(P){if(this.closed||P.aborted)throw _()}getEntry(P,J){if(E(P)!==J)throw new U("session_surface_cursor_invalid");let Z=this.entries.get(P);if(!Z)throw new U("session_surface_cursor_invalid");if(Z.kind!==J)throw new U("session_surface_cursor_invalid");if(Z.expiresAt<=this.now()&&!f(Z))throw this.removeEntry(Z),new U("session_surface_cursor_invalid");return Z}touch(P){let J=this.now();P.lastAccessAt=J,P.expiresAt=J+this.limitsValue.idleTtlMs;let Q=this.chains.get(P.chainId);if(Q)Q.lastAccessAt=J}storeEntry(P,J){if(P.tokens.size>=this.limitsValue.maxEntriesPerChain)throw new U("session_surface_capacity");this.entries.set(J.token,J),P.tokens.add(J.token),P.completed=!1,P.lastAccessAt=J.lastAccessAt,P.issueCount+=1,this.totalIssues+=1}ensureChain(P,J){let Q=this.chains.get(P);if(Q)return Q.lastAccessAt=J,Q;let Z={chainId:P,tokens:new Set,completed:!1,lastAccessAt:J,issueCount:0,activeLoads:0,frozenSnapshotBytes:0,retainedPayloadBytes:0};return this.chains.set(P,Z),Z}cloneActiveLoadResult(P){return P.promise.then((J)=>W(J))}admitCachedResult(P,J){let Q=m(J),Z=this.requireChain(P.chainId),$=Q.bytes-P.cachedResultBytes;if(this.ensureCapacity({requestedEntries:0,requestedRetainedBytes:Math.max(0,$),chainId:P.chainId}),this.releaseCachedResult(P,Z),Q.value===void 0)throw new U("session_surface_cursor_invalid");return P.cachedResult=Q.value,P.cachedResultBytes=Q.bytes,this.retainedPayloadBytes+=Q.bytes,Z.retainedPayloadBytes+=Q.bytes,P.cachedResult}createToken(P){let J=D[P];for(let Q=0;Q<=this.tokenCollisionRetries;Q+=1){this.assertAvailable();let Z=`${J}${this.tokenSource()}`;if(!this.entries.has(Z))return Z}throw new U("session_surface_capacity")}ensureCapacity(P){this.reclaimCompletedChains(P);let J=this.entries.size+P.requestedEntries,Q=this.chains.size+(this.chains.has(P.chainId)?0:1),Z=this.retainedPayloadBytes+P.requestedRetainedBytes,$=(this.chains.get(P.chainId)?.tokens.size??0)+P.requestedEntries;if(J>this.limitsValue.maxEntries||Q>this.limitsValue.maxChains||$>this.limitsValue.maxEntriesPerChain||Z>this.limitsValue.maxFrozenSnapshotBytes)throw new U("session_surface_capacity")}reclaimCompletedChains(P){let J=[...this.chains.values()].filter((Q)=>Q.completed&&Q.activeLoads===0).sort((Q,Z)=>Q.lastAccessAt-Z.lastAccessAt);for(let Q of J){if(!(this.entries.size+P.requestedEntries>this.limitsValue.maxEntries||this.chains.size+(P.chainId!==""&&this.chains.has(P.chainId)?0:1)>this.limitsValue.maxChains||this.retainedPayloadBytes+P.requestedRetainedBytes>this.limitsValue.maxFrozenSnapshotBytes))break;this.removeChain(Q.chainId)}}cleanup(){let P=this.now();for(let J of[...this.entries.values()]){if(J.expiresAt>P||f(J))continue;this.removeEntry(J)}for(let J of[...this.chains.values()])if(J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}removeEntry(P){this.entries.delete(P.token);let J=this.chains.get(P.chainId);if(J){if(J.tokens.delete(P.token),this.releaseEntryRetainedPayload(P,J),J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}else this.releaseEntryRetainedPayload(P)}removeChain(P){let J=this.chains.get(P);if(!J)return;for(let Q of J.tokens){let Z=this.entries.get(Q);if(!Z||f(Z))continue;this.entries.delete(Q),this.releaseEntryRetainedPayload(Z,J)}this.chains.delete(P)}releaseEntryRetainedPayload(P,J){if(P.kind==="snapshot"){if(this.frozenSnapshotBytes-=P.frozenBytes,this.retainedPayloadBytes-=P.frozenBytes,J)J.frozenSnapshotBytes-=P.frozenBytes,J.retainedPayloadBytes-=P.frozenBytes;return}if(P.kind==="catalog"){if(this.retainedPayloadBytes-=P.boundaryBytes,J)J.retainedPayloadBytes-=P.boundaryBytes}this.releaseCachedResult(P,J)}releaseCachedResult(P,J){if(P.cachedResultBytes===0){P.cachedResult=void 0;return}if(this.retainedPayloadBytes-=P.cachedResultBytes,J)J.retainedPayloadBytes-=P.cachedResultBytes;P.cachedResult=void 0,P.cachedResultBytes=0}assertAvailable(){if(this.closed)throw _()}}function E(P){if(P.startsWith(D.catalog))return"catalog";if(P.startsWith(D.history))return"history";if(P.startsWith(D.snapshot))return"snapshot";return}function f(P){return P.kind!=="snapshot"&&P.activeLoad!==void 0}function _P(P){let J={idleTtlMs:P.idleTtlMs??NP,maxEntries:P.maxEntries??OP,maxChains:P.maxChains??jP,maxEntriesPerChain:P.maxEntriesPerChain??MP,maxFrozenSnapshotBytes:P.maxFrozenSnapshotBytes??HP};for(let Q of Object.values(J))if(!Number.isSafeInteger(Q)||Q<=0)throw Error("session surface cursor registry limits must be positive safe integers");return J}function _(){return new U("session_surface_unavailable")}function T(P){return B(W(P))}function W(P){try{return S(P,new Set)}catch{throw new U("session_surface_cursor_invalid")}}function S(P,J){if(P===null)return null;if(typeof P==="string"||typeof P==="boolean")return P;if(typeof P==="number"){if(!Number.isFinite(P))throw Error("invalid number");return P}if(typeof P>"u"||typeof P==="function"||typeof P==="symbol"||typeof P==="bigint")throw Error("invalid JSON type");if(!P||typeof P!=="object")throw Error("invalid JSON value");if(J.has(P))throw Error("cycle");J.add(P);try{if(Array.isArray(P)){let $=[];for(let G=0;G<P.length;G+=1){if(!(G in P))throw Error("sparse array");$.push(S(P[G],J))}return $}if(Object.getOwnPropertySymbols(P).length>0)throw Error("symbol keys");let Q=Object.getPrototypeOf(P);if(Q!==Object.prototype&&Q!==null)throw Error("non-plain object");let Z={};for(let $ of Object.keys(P)){let G=Reflect.get(P,$);if(G===void 0)throw Error("undefined object value");Z[$]=S(G,J)}return Z}finally{J.delete(P)}}function B(P){if(P===null)return"null";if(typeof P==="string"||typeof P==="number")return JSON.stringify(P);if(typeof P==="boolean")return P?"true":"false";if(Array.isArray(P))return`[${P.map((Q)=>B(Q)).join(",")}]`;return`{${Object.keys(P).sort().map((Q)=>`${JSON.stringify(Q)}:${B(P[Q])}`).join(",")}}`}function m(P,J={}){if(P===void 0){if(J.allowUndefined)return{value:void 0,bytes:0};throw new U("session_surface_cursor_invalid")}let Q=W(P);return{value:Q,bytes:Buffer.byteLength(B(Q),"utf8")}}import{createHash as C,randomBytes as F}from"node:crypto";import FP from"node:path";var YP=50,zP=100,AP=16,TP=1e4,DP=16777216;class z extends Error{code;retryable;constructor(P){let J=CP(P);super(J.message);this.code=P;this.name="SessionSurfaceServiceError",this.retryable=J.retryable}}class BP{database;registry;epoch;maxConcurrentOperations;activeControllers=new Set;activeOperations=new Set;closed=!1;closePromise;concurrentOperations=0;constructor(P={}){if(this.database=P.database,this.registry=P.cursorRegistry??new g(P.cursorRegistryOptions),this.epoch=P.epochSource?.()??`session-surface-epoch:${F(32).toString("base64url")}`,this.maxConcurrentOperations=P.maxConcurrentOperations??AP,!Number.isSafeInteger(this.maxConcurrentOperations)||this.maxConcurrentOperations<1||this.maxConcurrentOperations>256)throw Error("maxConcurrentOperations must be an integer from 1 to 256")}async listPage(P={}){return this.runOperation(async(J)=>{let Q=K(P.limit),Z=P.archived??!1,$={archived:Z,limit:Q,workspaceKind:P.workspaceKind??null},G=JSON.stringify([Z,P.workspaceKind??null]),Y=await this.requireDatabase();if(J.throwIfAborted(),!Y)return this.listFallbackPage($,G,J,P.cursor);if(await this.syncAllSurfaces(Y,J),P.cursor){let V=String(ZP(Y));return this.registry.redeemCatalogCursor({token:P.cursor,scopeKey:G,epoch:this.epoch,revision:V,request:$,loader:async({boundary:X})=>{let O=KP(X);return this.loadCatalogPage(Y,$,G,V,O,O.chainId,J)}})}return this.loadCatalogPage(Y,$,G,void 0,void 0,void 0,J)})}async open(P,J={}){return this.runOperation((Q)=>this.openInternal(P,J,Q))}async historyPage(P,J){return this.runOperation(async(Q)=>{let Z=I(P),$=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.readFallbackHistoryPage(Z,J,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:1}),X=x(Z);await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint});let O={expectedSnapshot:J.expectedSnapshot,limit:$},j=await this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint,request:O,loader:async({nextSequence:M})=>{let H=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,beforeSequence:M,limit:$});return this.publicHistoryPage({history:H,snapshot:J.expectedSnapshot,chainId:(await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint})).chainId,locatorDigest:X,limit:$})}});return A.parse(j)})}async fork(P){return this.runOperation(async(J)=>{let Q=I(P),Z=await this.requireDatabase(),$=Z?await this.resolveFromProjectionAfterSync(Z,Q,J):await this.resolveFallback(Q,J);if($.candidate.summary.archivedAt)throw new z("session_surface_read_only");J.throwIfAborted();let G=await N.forkSession(Q.sessionId,{sourceProjectPath:$.candidate.projectPath,targetProjectPath:$.candidate.projectPath,...$.remoteCandidate?{remote:{expectedDescriptor:$.remoteCandidate.descriptor}}:{}}),Y=$.remoteCandidate?{version:2,sessionId:G.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.candidate.publicWorkspaceRef}}:{version:2,sessionId:G.sessionId,workspace:{kind:"local",projectPath:$.candidate.projectPath}};return Z?this.openInternal(Y,{},J):this.openFallback(Y,YP,J)})}async resolveFromProjectionAfterSync(P,J,Q){return await this.syncForLocator(P,J,Q),this.resolveFromProjection(P,J,Q)}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;for(let J of this.activeControllers)J.abort(new z("session_surface_unavailable"));return this.closePromise=Promise.allSettled([...this.activeOperations,this.registry.close()]).then(()=>{return}),this.closePromise}async openInternal(P,J={},Q){let Z=I(P),$=K(J.limit);if(J.cursor!==void 0||J.expectedSnapshot!==void 0)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.openFallback(Z,$,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:$}),X=`history-chain:${F(16).toString("base64url")}`,O=x(Z),j=this.registry.issueSnapshotToken({chainId:X,locatorDigest:O,transcriptFingerprint:V.transcriptFingerprint}),M={session:this.toSummary(Y),history:this.publicHistoryPage({history:V,snapshot:j,chainId:X,locatorDigest:O,limit:$})};return p.parse(M)}runOperation(P){if(this.assertAvailable(),this.concurrentOperations>=this.maxConcurrentOperations)throw new z("session_surface_capacity");let J=new AbortController;this.activeControllers.add(J),this.concurrentOperations+=1;let Q;return Q=Promise.resolve().then(()=>P(J.signal)).then((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");return Z}).catch((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");throw kP(Z)}).finally(()=>{this.activeControllers.delete(J),this.activeOperations.delete(Q),this.concurrentOperations-=1}),this.activeOperations.add(Q),Q}async loadCatalogPage(P,J,Q,Z,$,G,Y){let V=$P(P,{archived:J.archived,limit:J.limit,...J.workspaceKind?{workspaceKind:J.workspaceKind}:{},...$?{boundary:$}:{}}),X=String(V.revision);if(Z!==void 0&&Z!==X)throw new z("session_surface_snapshot_changed");let O=G??`catalog-chain:${F(16).toString("base64url")}`,j={sessions:await Promise.all(V.sessions.map(async(M)=>this.toSummary(await this.resolveCandidate(M,Y)))),...V.nextBoundary?{nextCursor:this.registry.issueCatalogCursor({chainId:O,scopeKey:Q,epoch:this.epoch,revision:X,boundary:{...V.nextBoundary,chainId:O},request:J})}:{}};if(!V.nextBoundary)this.registry.completeChain(O);return y.parse(j)}publicHistoryPage(P){let J=h(P.history.messages,L()),Q={messages:J.messages,snapshot:P.snapshot,truncated:P.history.hasOlder||J.truncated||J.messages.some((Z)=>Z.truncated===!0),...P.history.hasOlder&&P.history.nextSequence!==void 0?{olderCursor:this.registry.issueHistoryCursor({chainId:P.chainId,locatorDigest:P.locatorDigest,transcriptFingerprint:P.history.transcriptFingerprint,nextSequence:P.history.nextSequence,snapshotToken:P.snapshot,request:{expectedSnapshot:P.snapshot,limit:P.limit}})}:{}};if(!P.history.hasOlder)this.registry.completeChain(P.chainId);return A.parse(Q)}async syncForLocator(P,J,Q){if(Q?.throwIfAborted(),J.workspace.kind==="local"){await N.findSessionMetadata(J.sessionId,J.workspace.projectPath),Q?.throwIfAborted(),await d(P,J.sessionId,J.workspace.projectPath,N.projectionDeriverForSearch(),void 0,"local",Q);return}await N.listValidatedRemoteSurfaceCandidates(Q),await l(P,N.projectionDeriverForSearch(),Q)}async syncAllSurfaces(P,J){let Q=N.projectionDeriverForSearch(),Z=await N.listValidatedLocalSurfaceCandidates(J),$=new Set(Z.map((Y)=>`${Y.projectPath}\x00${Y.sessionId}`)),G=P.prepare("SELECT project_path, session_id FROM sessions WHERE source_kind='local'").all();for(let Y of G)if(!$.has(`${Y.project_path}\x00${Y.session_id}`))JP(P,Y.session_id,Y.project_path,"local");for(let Y of Z)J?.throwIfAborted(),await d(P,Y.sessionId,Y.projectPath,Q,void 0,"local",J);await N.listValidatedRemoteSurfaceCandidates(J),await l(P,Q,J)}async listFallbackPage(P,J,Q,Z){if(Z)return this.registry.redeemCatalogCursor({token:Z,scopeKey:J,epoch:this.epoch,revision:"fallback",request:P,loader:async({boundary:G})=>{let Y=LP(G);return this.pageFallbackCatalog(Y.entries,P,J,Y.chainId)}});let $=await this.loadFallbackCatalog(P,Q);return this.pageFallbackCatalog($,P,J,`catalog-fallback:${F(16).toString("base64url")}`)}async loadFallbackCatalog(P,J){let Q=[];if(P.workspaceKind!=="acp-remote")for(let $ of await N.listValidatedLocalSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedLocalSurfaceSnapshot($.sessionId,$.projectPath,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}},summary:Y})}if(P.workspaceKind!=="local")for(let $ of await N.listValidatedRemoteSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedRemoteSurfaceSnapshot($,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.workspaceRef}},summary:Y})}Q.sort(IP);let Z=Buffer.byteLength(JSON.stringify(Q));if(Q.length>TP||Z>DP)throw new z("session_surface_capacity");return Q}async pageFallbackCatalog(P,J,Q,Z){let $=P.slice(0,J.limit),G=P.slice($.length),V={sessions:$.map((X)=>R.parse({locator:X.locator,...X.summary,capabilities:X.locator.workspace.kind==="local"?UP(Boolean(X.summary.archivedAt)):RP(Boolean(X.summary.archivedAt))})),...G.length>0?{nextCursor:this.registry.issueCatalogCursor({chainId:Z,scopeKey:Q,epoch:this.epoch,revision:"fallback",boundary:{chainId:Z,entries:G},request:J})}:{}};if(G.length===0)this.registry.completeChain(Z);return y.parse(V)}async openFallback(P,J,Q){let Z=await this.resolveFallback(P,Q),$=Z.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(Z.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(Z.candidate.sessionId,Z.candidate.projectPath,Q),G=e($.entries,{...Z.remoteCandidate?r(Z.remoteCandidate.hostStateRoot,Z.remoteCandidate.descriptor):{privateRoots:[]},bladeStorageRoots:[o()]}),Y=h(G.slice(-J),L()),V=`history-fallback:${F(16).toString("base64url")}`,X=x(P),O=C("sha256").update(JSON.stringify($.entries)).digest("hex"),j=this.registry.issueSnapshotToken({chainId:V,locatorDigest:X,transcriptFingerprint:O,frozenSnapshot:G}),M={session:this.toSummary(Z),history:A.parse({messages:Y.messages,snapshot:j,truncated:Y.messages.length<G.length||Y.truncated||Y.messages.some((H)=>H.truncated===!0),...G.length>Y.messages.length&&Y.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:V,locatorDigest:X,transcriptFingerprint:O,nextSequence:v(Y.messages[0].id),snapshotToken:j,request:{expectedSnapshot:j,limit:J}})}:{}})};if(G.length<=Y.messages.length)this.registry.completeChain(V);return p.parse(M)}async readFallbackHistoryPage(P,J,Q){let Z=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let $=x(P),G=await this.resolveFallback(P,Q),Y=G.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(G.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(G.candidate.sessionId,G.candidate.projectPath,Q),V=C("sha256").update(JSON.stringify(Y.entries)).digest("hex");await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V});let X={expectedSnapshot:J.expectedSnapshot,limit:Z};return this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:$,transcriptFingerprint:V,request:X,loader:async({nextSequence:O,frozenSnapshot:j})=>{let M=xP(j).filter((b)=>v(b.id)<O),H=h(M.slice(-Z),L()),u=await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V}),k=H.messages.length<M.length,VP={messages:H.messages,snapshot:J.expectedSnapshot,truncated:k||H.truncated||H.messages.some((b)=>b.truncated===!0),...k&&H.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:u.chainId,locatorDigest:$,transcriptFingerprint:V,nextSequence:v(H.messages[0].id),snapshotToken:J.expectedSnapshot,request:X})}:{}};if(!k)this.registry.completeChain(u.chainId);return A.parse(VP)}})}async resolveFallback(P,J){let Q=[];for(let G of[!1,!0]){let Y={archived:G,limit:zP,workspaceKind:P.workspace.kind};Q.push(...(await this.loadFallbackCatalog(Y,J)).filter((V)=>JSON.stringify(V.locator)===JSON.stringify(P)))}if(Q.length!==1)throw new z("session_surface_not_found");let Z=Q[0],$;if(P.workspace.kind==="acp-remote"){let G=P.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(J)).find((Y)=>Y.sessionId===P.sessionId&&Y.workspaceRef===G),!$)throw new z("workspace_binding_mismatch")}return{candidate:{sourceKind:P.workspace.kind,projectPath:P.workspace.kind==="local"?P.workspace.projectPath:$.hostStateRoot,sessionId:P.sessionId,...P.workspace.kind==="acp-remote"?{publicWorkspaceRef:P.workspace.workspaceRef}:{},publicWorkspaceSortKey:"",surfaceDigest:i(Z),transcriptFingerprint:i(Z),lastMessageTime:Z.summary.lastMessageTime,sessionSortKey:"",summary:Z.summary},...$?{remoteCandidate:$}:{}}}async resolveFromProjection(P,J,Q){let Z=QP(P,J.sessionId).filter((G)=>J.workspace.kind==="local"?G.sourceKind==="local"&&G.projectPath===FP.resolve(J.workspace.projectPath):G.sourceKind==="acp-remote"&&G.publicWorkspaceRef===J.workspace.workspaceRef);if(Z.length!==1)throw new z(Z.length===0?"session_surface_not_found":"workspace_binding_mismatch");let $;if(J.workspace.kind==="acp-remote"){let G=J.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(Q)).filter((Y)=>Y.sessionId===J.sessionId&&Y.workspaceRef===G),$.length===0)throw new z("workspace_binding_mismatch");if($.length>1)throw new z("session_surface_state_invalid")}return $?{candidate:Z[0],remoteCandidate:$[0]}:{candidate:Z[0]}}async resolveCandidate(P,J){if(P.sourceKind==="local")return{candidate:P};let Q=(await N.listValidatedRemoteSurfaceCandidates(J)).filter((Z)=>Z.sessionId===P.sessionId&&Z.workspaceRef===P.publicWorkspaceRef);if(Q.length!==1)throw new z(Q.length===0?"workspace_binding_mismatch":"session_surface_state_invalid");return{candidate:P,remoteCandidate:Q[0]}}toSummary(P){let J=P.candidate,Q=J.sourceKind==="local"?{version:2,sessionId:J.sessionId,workspace:{kind:"local",projectPath:J.projectPath}}:{version:2,sessionId:J.sessionId,workspace:{kind:"acp-remote",workspaceRef:J.publicWorkspaceRef}};return R.parse({locator:Q,...J.summary,capabilities:this.capabilitiesFor(P)})}capabilitiesFor(P){let J=P.candidate.summary.archivedAt!==void 0;if(!P.remoteCandidate)return{connection:"local",history:{read:!0,fork:!J},turn:J?{start:!1,reason:"archived"}:{start:!0},files:J?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:J?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}};return{connection:GP.getRemoteSurfaceOwnerSnapshot(P.candidate.sessionId,P.remoteCandidate.descriptor).connection,history:{read:!0,fork:!J},turn:{start:!1,reason:J?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:J?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:J?"archived":"history-only"}}}async requireDatabase(){if(this.database===null)return null;return this.database??await PP()}assertAvailable(){if(this.closed)throw new z("session_surface_unavailable")}}function K(P){let J=P??YP;if(!Number.isSafeInteger(J)||J<1||J>zP)throw new z("invalid_session_surface_request");return J}function I(P){try{let J=t.parse(P);if(!n(J.sessionId))throw Error("invalid");if(J.workspace.kind==="local"){if(s(J.workspace.projectPath)!==J.workspace.projectPath)throw Error("invalid")}return J}catch{throw new z("invalid_session_locator")}}function x(P){return C("sha256").update("session-surface-locator-v2\x00").update(JSON.stringify(P)).digest("hex")}function KP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.lastMessageTime!=="string"||J.sourceKind!=="local"&&J.sourceKind!=="acp-remote"||typeof J.publicWorkspaceSortKey!=="string"||typeof J.sessionSortKey!=="string"||typeof J.chainId!=="string"||!J.chainId)throw new z("session_surface_cursor_invalid");return{lastMessageTime:J.lastMessageTime,sourceKind:J.sourceKind,publicWorkspaceSortKey:J.publicWorkspaceSortKey,sessionSortKey:J.sessionSortKey,chainId:J.chainId}}function h(P,J){let Q=[];for(let Z=P.length-1;Z>=0;Z-=1){let $=P[Z];if(!$)continue;let G=[$,...Q];if(Q.length>0&&Buffer.byteLength(JSON.stringify(G))>J)break;Q.unshift($)}return{messages:Q,truncated:Q.length<P.length}}function v(P){let J=/^surface-message:([0-9]+):/.exec(P),Q=J?Number(J[1]):Number.NaN;if(!Number.isSafeInteger(Q)||Q<=0)throw new z("session_surface_state_invalid");return Q}function xP(P){if(!Array.isArray(P))throw new z("session_surface_snapshot_changed");return P.map((J)=>{try{return a.parse(J)}catch{throw new z("session_surface_snapshot_changed")}})}function LP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.chainId!=="string"||J.chainId.length===0||!Array.isArray(J.entries))throw new z("session_surface_cursor_invalid");let Q=J.entries.map((Z)=>{if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new z("session_surface_cursor_invalid");let $=Z;return{locator:I($.locator),summary:wP($.summary)}});return{chainId:J.chainId,entries:Q}}function wP(P){let J={version:2,sessionId:"placeholder",workspace:{kind:"local",projectPath:"/"}},Q=R.parse({...P&&typeof P==="object"&&!Array.isArray(P)?P:{},locator:J,capabilities:UP(!1)}),{locator:Z,capabilities:$,...G}=Q;return G}function IP(P,J){if(P.summary.lastMessageTime>J.summary.lastMessageTime)return-1;if(P.summary.lastMessageTime<J.summary.lastMessageTime)return 1;if(P.locator.workspace.kind!==J.locator.workspace.kind)return P.locator.workspace.kind==="local"?-1:1;let Q=P.locator.workspace.kind==="local"?P.locator.workspace.projectPath:P.locator.workspace.workspaceRef,Z=J.locator.workspace.kind==="local"?J.locator.workspace.projectPath:J.locator.workspace.workspaceRef;if(Q<Z)return-1;if(Q>Z)return 1;return P.locator.sessionId<J.locator.sessionId?-1:P.locator.sessionId>J.locator.sessionId?1:0}function i(P){return C("sha256").update("session-surface-fallback-entry\x00").update(JSON.stringify(P)).digest("hex")}function UP(P){return{connection:"local",history:{read:!0,fork:!P},turn:P?{start:!1,reason:"archived"}:{start:!0},files:P?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:P?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}}}function RP(P){return{connection:"offline",history:{read:!0,fork:!P},turn:{start:!1,reason:P?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:P?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:P?"archived":"history-only"}}}function CP(P){if(P==="session_surface_cursor_invalid")return{message:"Session surface cursor is invalid",retryable:!1};if(P==="session_surface_snapshot_changed")return{message:"Session surface snapshot changed",retryable:!1};if(P==="session_surface_state_invalid")return{message:"Session surface state is invalid",retryable:!1};if(P==="session_surface_capability_unavailable")return{message:"Session surface capability is unavailable",retryable:!1};if(P==="session_surface_unavailable")return{message:"Session surface is unavailable",retryable:!0};if(P==="session_surface_not_found")return{message:"Session surface was not found",retryable:!1};if(P==="workspace_binding_mismatch")return{message:"Session workspace binding changed",retryable:!1};if(P==="session_surface_read_only")return{message:"Session surface is read only",retryable:!1};if(P==="session_surface_capacity")return{message:"Session surface capacity is exhausted",retryable:!0};if(P==="invalid_session_locator")return{message:"Session locator is invalid",retryable:!1};return{message:"Session surface request is invalid",retryable:!1}}function kP(P){if(P instanceof z)return P;if(P&&typeof P==="object"&&"code"in P&&typeof P.code==="string"){let J=P.code;if(J==="session_surface_cursor_invalid"||J==="session_surface_snapshot_changed"||J==="session_surface_capacity"||J==="session_surface_unavailable"||J==="session_surface_state_invalid")return new z(J);if(J==="acp_remote_workspace_state_invalid")return new z("session_surface_state_invalid")}return P instanceof Error?P:new z("session_surface_state_invalid")}
1
+ import{N as GP}from"./chunk-4vcea99r.js";import{ie as N}from"./chunk-czrktgmy.js";import{Pe as r,Qe as e,Te as L,Ve as PP,Ye as d,_e as l,af as JP,cf as QP,df as ZP,ef as $P,ff as w}from"./chunk-ztreczac.js";import{hf as t,if as a,kf as R,mf as y,nf as A,pf as p}from"./chunk-p6586ftx.js";import{Qj as q}from"./chunk-j89qk7bp.js";import{Ak as s,Bk as n,gk as o}from"./chunk-n52n2w5v.js";async function qP(){return q().listProviders()}async function EP(P){return q().listModels(P)}import{randomBytes as XP}from"node:crypto";var NP=600000,OP=2048,jP=64,MP=32,HP=67108864,WP=4,D={catalog:"session-surface-catalog:",history:"session-surface-history:",snapshot:"session-surface-snapshot:"},c={session_surface_cursor_invalid:{message:"session surface cursor is invalid",retryable:!1},session_surface_snapshot_changed:{message:"session surface snapshot changed",retryable:!1},session_surface_capacity:{message:"session surface cursor capacity exceeded",retryable:!0},session_surface_unavailable:{message:"session surface cursor registry is unavailable",retryable:!0}};class U extends Error{code;retryable;constructor(P){super(c[P].message);this.code=P;this.name="SessionSurfaceCursorRegistryError",this.retryable=c[P].retryable}}class g{now;tokenSource;tokenCollisionRetries;limitsValue;entries=new Map;chains=new Map;closed=!1;closePromise;totalIssues=0;activeLoads=0;frozenSnapshotBytes=0;retainedPayloadBytes=0;constructor(P={}){if(this.now=P.now??(()=>Date.now()),this.tokenSource=P.tokenSource??(()=>XP(32).toString("base64url")),this.tokenCollisionRetries=P.tokenCollisionRetries??WP,this.limitsValue=_P(P.limits??{}),!Number.isSafeInteger(this.tokenCollisionRetries)||this.tokenCollisionRetries<0)throw Error("tokenCollisionRetries must be a non-negative safe integer")}issueCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=m(P.boundary);if(J.value===void 0)throw new U("session_surface_cursor_invalid");let Q=T(P.request);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Z=this.createToken("catalog"),$=this.now(),G=this.ensureChain(P.chainId,$),Y={token:Z,chainId:P.chainId,kind:"catalog",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,scopeKey:P.scopeKey,epoch:P.epoch,revision:P.revision,boundary:J.value,boundaryBytes:J.bytes,requestHash:Q,cachedResultBytes:0};return this.storeEntry(G,Y),this.retainedPayloadBytes+=J.bytes,G.retainedPayloadBytes+=J.bytes,Z}issueHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=T(P.request),Q=this.assertSnapshotIssuableForHistory(P);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:0,chainId:P.chainId});let Z=this.createToken("history"),$=this.now(),G=this.ensureChain(P.chainId,$);this.touch(Q);let Y={token:Z,chainId:P.chainId,kind:"history",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,nextSequence:P.nextSequence,snapshotToken:P.snapshotToken,requestHash:J,cachedResultBytes:0};return this.storeEntry(G,Y),Z}issueSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=P.frozenSnapshot===void 0?{value:void 0,bytes:0}:m(P.frozenSnapshot);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Q=this.createToken("snapshot"),Z=this.now(),$=this.ensureChain(P.chainId,Z),G={token:Q,chainId:P.chainId,kind:"snapshot",expiresAt:Z+this.limitsValue.idleTtlMs,lastAccessAt:Z,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,frozenBytes:J.bytes,frozenSnapshot:J.value};return this.storeEntry($,G),this.frozenSnapshotBytes+=J.bytes,this.retainedPayloadBytes+=J.bytes,$.frozenSnapshotBytes+=J.bytes,$.retainedPayloadBytes+=J.bytes,Q}async redeemCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"catalog");if(J.scopeKey!==P.scopeKey)throw new U("session_surface_cursor_invalid");if(J.epoch!==P.epoch||J.revision!==P.revision)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");if(this.touch(J),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startCatalogLoad(J,P.loader)}async redeemHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"history");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_snapshot_changed");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");let Q=this.resolveHistorySnapshot(J);if(this.touch(J),this.touch(Q),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startHistoryLoad(J,Q,P.loader)}async assertSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"snapshot");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_cursor_invalid");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return this.touch(J),{chainId:J.chainId,locatorDigest:J.locatorDigest,transcriptFingerprint:J.transcriptFingerprint,frozenBytes:J.frozenBytes,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)}}completeChain(P){this.cleanup();let J=this.chains.get(P);if(!J)return;J.completed=!0,J.lastAccessAt=this.now()}stats(){this.cleanup();let P=0;for(let J of this.chains.values())if(J.completed)P+=1;return{closed:this.closed,chainCount:this.chains.size,activeChains:this.chains.size-P,completedChains:P,entryCount:this.entries.size,activeLoads:this.activeLoads,frozenSnapshotBytes:this.frozenSnapshotBytes,retainedPayloadBytes:this.retainedPayloadBytes,totalIssues:this.totalIssues,limits:{...this.limitsValue}}}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;let J=[];for(let Q of this.entries.values())if((Q.kind==="catalog"||Q.kind==="history")&&Q.activeLoad)J.push(Q.activeLoad.promise),Q.activeLoad.controller.abort(_());return this.closePromise=Promise.allSettled(J).then(()=>{this.entries.clear(),this.chains.clear(),this.activeLoads=0,this.frozenSnapshotBytes=0,this.retainedPayloadBytes=0}),this.closePromise}startCatalogLoad(P,J){let Q=this.requireChain(P.chainId),Z=new AbortController;this.activeLoads+=1,Q.activeLoads+=1;let $=Promise.resolve().then(()=>J({boundary:W(P.boundary)},Z.signal)).then((G)=>{return this.assertLoadAvailable(Z.signal),this.admitCachedResult(P,G)}).catch((G)=>{if(this.closed||Z.signal.aborted)throw _();throw G}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Q.activeLoads-=1});return P.activeLoad={controller:Z,promise:$},this.cloneActiveLoadResult(P.activeLoad)}startHistoryLoad(P,J,Q){let Z=this.requireChain(P.chainId),$=new AbortController;this.activeLoads+=1,Z.activeLoads+=1;let G=Promise.resolve().then(()=>Q({nextSequence:P.nextSequence,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)},$.signal)).then((Y)=>{return this.assertLoadAvailable($.signal),this.admitCachedResult(P,Y)}).catch((Y)=>{if(this.closed||$.signal.aborted)throw _();throw Y}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Z.activeLoads-=1});return P.activeLoad={controller:$,promise:G},this.cloneActiveLoadResult(P.activeLoad)}resolveHistorySnapshot(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}assertSnapshotIssuableForHistory(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.chainId!==P.chainId||Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}requireChain(P){let J=this.chains.get(P);if(!J)throw new U("session_surface_cursor_invalid");return J}assertLoadAvailable(P){if(this.closed||P.aborted)throw _()}getEntry(P,J){if(E(P)!==J)throw new U("session_surface_cursor_invalid");let Z=this.entries.get(P);if(!Z)throw new U("session_surface_cursor_invalid");if(Z.kind!==J)throw new U("session_surface_cursor_invalid");if(Z.expiresAt<=this.now()&&!f(Z))throw this.removeEntry(Z),new U("session_surface_cursor_invalid");return Z}touch(P){let J=this.now();P.lastAccessAt=J,P.expiresAt=J+this.limitsValue.idleTtlMs;let Q=this.chains.get(P.chainId);if(Q)Q.lastAccessAt=J}storeEntry(P,J){if(P.tokens.size>=this.limitsValue.maxEntriesPerChain)throw new U("session_surface_capacity");this.entries.set(J.token,J),P.tokens.add(J.token),P.completed=!1,P.lastAccessAt=J.lastAccessAt,P.issueCount+=1,this.totalIssues+=1}ensureChain(P,J){let Q=this.chains.get(P);if(Q)return Q.lastAccessAt=J,Q;let Z={chainId:P,tokens:new Set,completed:!1,lastAccessAt:J,issueCount:0,activeLoads:0,frozenSnapshotBytes:0,retainedPayloadBytes:0};return this.chains.set(P,Z),Z}cloneActiveLoadResult(P){return P.promise.then((J)=>W(J))}admitCachedResult(P,J){let Q=m(J),Z=this.requireChain(P.chainId),$=Q.bytes-P.cachedResultBytes;if(this.ensureCapacity({requestedEntries:0,requestedRetainedBytes:Math.max(0,$),chainId:P.chainId}),this.releaseCachedResult(P,Z),Q.value===void 0)throw new U("session_surface_cursor_invalid");return P.cachedResult=Q.value,P.cachedResultBytes=Q.bytes,this.retainedPayloadBytes+=Q.bytes,Z.retainedPayloadBytes+=Q.bytes,P.cachedResult}createToken(P){let J=D[P];for(let Q=0;Q<=this.tokenCollisionRetries;Q+=1){this.assertAvailable();let Z=`${J}${this.tokenSource()}`;if(!this.entries.has(Z))return Z}throw new U("session_surface_capacity")}ensureCapacity(P){this.reclaimCompletedChains(P);let J=this.entries.size+P.requestedEntries,Q=this.chains.size+(this.chains.has(P.chainId)?0:1),Z=this.retainedPayloadBytes+P.requestedRetainedBytes,$=(this.chains.get(P.chainId)?.tokens.size??0)+P.requestedEntries;if(J>this.limitsValue.maxEntries||Q>this.limitsValue.maxChains||$>this.limitsValue.maxEntriesPerChain||Z>this.limitsValue.maxFrozenSnapshotBytes)throw new U("session_surface_capacity")}reclaimCompletedChains(P){let J=[...this.chains.values()].filter((Q)=>Q.completed&&Q.activeLoads===0).sort((Q,Z)=>Q.lastAccessAt-Z.lastAccessAt);for(let Q of J){if(!(this.entries.size+P.requestedEntries>this.limitsValue.maxEntries||this.chains.size+(P.chainId!==""&&this.chains.has(P.chainId)?0:1)>this.limitsValue.maxChains||this.retainedPayloadBytes+P.requestedRetainedBytes>this.limitsValue.maxFrozenSnapshotBytes))break;this.removeChain(Q.chainId)}}cleanup(){let P=this.now();for(let J of[...this.entries.values()]){if(J.expiresAt>P||f(J))continue;this.removeEntry(J)}for(let J of[...this.chains.values()])if(J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}removeEntry(P){this.entries.delete(P.token);let J=this.chains.get(P.chainId);if(J){if(J.tokens.delete(P.token),this.releaseEntryRetainedPayload(P,J),J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}else this.releaseEntryRetainedPayload(P)}removeChain(P){let J=this.chains.get(P);if(!J)return;for(let Q of J.tokens){let Z=this.entries.get(Q);if(!Z||f(Z))continue;this.entries.delete(Q),this.releaseEntryRetainedPayload(Z,J)}this.chains.delete(P)}releaseEntryRetainedPayload(P,J){if(P.kind==="snapshot"){if(this.frozenSnapshotBytes-=P.frozenBytes,this.retainedPayloadBytes-=P.frozenBytes,J)J.frozenSnapshotBytes-=P.frozenBytes,J.retainedPayloadBytes-=P.frozenBytes;return}if(P.kind==="catalog"){if(this.retainedPayloadBytes-=P.boundaryBytes,J)J.retainedPayloadBytes-=P.boundaryBytes}this.releaseCachedResult(P,J)}releaseCachedResult(P,J){if(P.cachedResultBytes===0){P.cachedResult=void 0;return}if(this.retainedPayloadBytes-=P.cachedResultBytes,J)J.retainedPayloadBytes-=P.cachedResultBytes;P.cachedResult=void 0,P.cachedResultBytes=0}assertAvailable(){if(this.closed)throw _()}}function E(P){if(P.startsWith(D.catalog))return"catalog";if(P.startsWith(D.history))return"history";if(P.startsWith(D.snapshot))return"snapshot";return}function f(P){return P.kind!=="snapshot"&&P.activeLoad!==void 0}function _P(P){let J={idleTtlMs:P.idleTtlMs??NP,maxEntries:P.maxEntries??OP,maxChains:P.maxChains??jP,maxEntriesPerChain:P.maxEntriesPerChain??MP,maxFrozenSnapshotBytes:P.maxFrozenSnapshotBytes??HP};for(let Q of Object.values(J))if(!Number.isSafeInteger(Q)||Q<=0)throw Error("session surface cursor registry limits must be positive safe integers");return J}function _(){return new U("session_surface_unavailable")}function T(P){return B(W(P))}function W(P){try{return S(P,new Set)}catch{throw new U("session_surface_cursor_invalid")}}function S(P,J){if(P===null)return null;if(typeof P==="string"||typeof P==="boolean")return P;if(typeof P==="number"){if(!Number.isFinite(P))throw Error("invalid number");return P}if(typeof P>"u"||typeof P==="function"||typeof P==="symbol"||typeof P==="bigint")throw Error("invalid JSON type");if(!P||typeof P!=="object")throw Error("invalid JSON value");if(J.has(P))throw Error("cycle");J.add(P);try{if(Array.isArray(P)){let $=[];for(let G=0;G<P.length;G+=1){if(!(G in P))throw Error("sparse array");$.push(S(P[G],J))}return $}if(Object.getOwnPropertySymbols(P).length>0)throw Error("symbol keys");let Q=Object.getPrototypeOf(P);if(Q!==Object.prototype&&Q!==null)throw Error("non-plain object");let Z={};for(let $ of Object.keys(P)){let G=Reflect.get(P,$);if(G===void 0)throw Error("undefined object value");Z[$]=S(G,J)}return Z}finally{J.delete(P)}}function B(P){if(P===null)return"null";if(typeof P==="string"||typeof P==="number")return JSON.stringify(P);if(typeof P==="boolean")return P?"true":"false";if(Array.isArray(P))return`[${P.map((Q)=>B(Q)).join(",")}]`;return`{${Object.keys(P).sort().map((Q)=>`${JSON.stringify(Q)}:${B(P[Q])}`).join(",")}}`}function m(P,J={}){if(P===void 0){if(J.allowUndefined)return{value:void 0,bytes:0};throw new U("session_surface_cursor_invalid")}let Q=W(P);return{value:Q,bytes:Buffer.byteLength(B(Q),"utf8")}}import{createHash as C,randomBytes as F}from"node:crypto";import FP from"node:path";var YP=50,zP=100,AP=16,TP=1e4,DP=16777216;class z extends Error{code;retryable;constructor(P){let J=CP(P);super(J.message);this.code=P;this.name="SessionSurfaceServiceError",this.retryable=J.retryable}}class BP{database;registry;epoch;maxConcurrentOperations;activeControllers=new Set;activeOperations=new Set;closed=!1;closePromise;concurrentOperations=0;constructor(P={}){if(this.database=P.database,this.registry=P.cursorRegistry??new g(P.cursorRegistryOptions),this.epoch=P.epochSource?.()??`session-surface-epoch:${F(32).toString("base64url")}`,this.maxConcurrentOperations=P.maxConcurrentOperations??AP,!Number.isSafeInteger(this.maxConcurrentOperations)||this.maxConcurrentOperations<1||this.maxConcurrentOperations>256)throw Error("maxConcurrentOperations must be an integer from 1 to 256")}async listPage(P={}){return this.runOperation(async(J)=>{let Q=K(P.limit),Z=P.archived??!1,$={archived:Z,limit:Q,workspaceKind:P.workspaceKind??null},G=JSON.stringify([Z,P.workspaceKind??null]),Y=await this.requireDatabase();if(J.throwIfAborted(),!Y)return this.listFallbackPage($,G,J,P.cursor);if(await this.syncAllSurfaces(Y,J),P.cursor){let V=String(ZP(Y));return this.registry.redeemCatalogCursor({token:P.cursor,scopeKey:G,epoch:this.epoch,revision:V,request:$,loader:async({boundary:X})=>{let O=KP(X);return this.loadCatalogPage(Y,$,G,V,O,O.chainId,J)}})}return this.loadCatalogPage(Y,$,G,void 0,void 0,void 0,J)})}async open(P,J={}){return this.runOperation((Q)=>this.openInternal(P,J,Q))}async historyPage(P,J){return this.runOperation(async(Q)=>{let Z=I(P),$=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.readFallbackHistoryPage(Z,J,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:1}),X=x(Z);await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint});let O={expectedSnapshot:J.expectedSnapshot,limit:$},j=await this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint,request:O,loader:async({nextSequence:M})=>{let H=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,beforeSequence:M,limit:$});return this.publicHistoryPage({history:H,snapshot:J.expectedSnapshot,chainId:(await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint})).chainId,locatorDigest:X,limit:$})}});return A.parse(j)})}async fork(P){return this.runOperation(async(J)=>{let Q=I(P),Z=await this.requireDatabase(),$=Z?await this.resolveFromProjectionAfterSync(Z,Q,J):await this.resolveFallback(Q,J);if($.candidate.summary.archivedAt)throw new z("session_surface_read_only");J.throwIfAborted();let G=await N.forkSession(Q.sessionId,{sourceProjectPath:$.candidate.projectPath,targetProjectPath:$.candidate.projectPath,...$.remoteCandidate?{remote:{expectedDescriptor:$.remoteCandidate.descriptor}}:{}}),Y=$.remoteCandidate?{version:2,sessionId:G.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.candidate.publicWorkspaceRef}}:{version:2,sessionId:G.sessionId,workspace:{kind:"local",projectPath:$.candidate.projectPath}};return Z?this.openInternal(Y,{},J):this.openFallback(Y,YP,J)})}async resolveFromProjectionAfterSync(P,J,Q){return await this.syncForLocator(P,J,Q),this.resolveFromProjection(P,J,Q)}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;for(let J of this.activeControllers)J.abort(new z("session_surface_unavailable"));return this.closePromise=Promise.allSettled([...this.activeOperations,this.registry.close()]).then(()=>{return}),this.closePromise}async openInternal(P,J={},Q){let Z=I(P),$=K(J.limit);if(J.cursor!==void 0||J.expectedSnapshot!==void 0)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.openFallback(Z,$,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:$}),X=`history-chain:${F(16).toString("base64url")}`,O=x(Z),j=this.registry.issueSnapshotToken({chainId:X,locatorDigest:O,transcriptFingerprint:V.transcriptFingerprint}),M={session:this.toSummary(Y),history:this.publicHistoryPage({history:V,snapshot:j,chainId:X,locatorDigest:O,limit:$})};return p.parse(M)}runOperation(P){if(this.assertAvailable(),this.concurrentOperations>=this.maxConcurrentOperations)throw new z("session_surface_capacity");let J=new AbortController;this.activeControllers.add(J),this.concurrentOperations+=1;let Q;return Q=Promise.resolve().then(()=>P(J.signal)).then((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");return Z}).catch((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");throw kP(Z)}).finally(()=>{this.activeControllers.delete(J),this.activeOperations.delete(Q),this.concurrentOperations-=1}),this.activeOperations.add(Q),Q}async loadCatalogPage(P,J,Q,Z,$,G,Y){let V=$P(P,{archived:J.archived,limit:J.limit,...J.workspaceKind?{workspaceKind:J.workspaceKind}:{},...$?{boundary:$}:{}}),X=String(V.revision);if(Z!==void 0&&Z!==X)throw new z("session_surface_snapshot_changed");let O=G??`catalog-chain:${F(16).toString("base64url")}`,j={sessions:await Promise.all(V.sessions.map(async(M)=>this.toSummary(await this.resolveCandidate(M,Y)))),...V.nextBoundary?{nextCursor:this.registry.issueCatalogCursor({chainId:O,scopeKey:Q,epoch:this.epoch,revision:X,boundary:{...V.nextBoundary,chainId:O},request:J})}:{}};if(!V.nextBoundary)this.registry.completeChain(O);return y.parse(j)}publicHistoryPage(P){let J=h(P.history.messages,L()),Q={messages:J.messages,snapshot:P.snapshot,truncated:P.history.hasOlder||J.truncated||J.messages.some((Z)=>Z.truncated===!0),...P.history.hasOlder&&P.history.nextSequence!==void 0?{olderCursor:this.registry.issueHistoryCursor({chainId:P.chainId,locatorDigest:P.locatorDigest,transcriptFingerprint:P.history.transcriptFingerprint,nextSequence:P.history.nextSequence,snapshotToken:P.snapshot,request:{expectedSnapshot:P.snapshot,limit:P.limit}})}:{}};if(!P.history.hasOlder)this.registry.completeChain(P.chainId);return A.parse(Q)}async syncForLocator(P,J,Q){if(Q?.throwIfAborted(),J.workspace.kind==="local"){await N.findSessionMetadata(J.sessionId,J.workspace.projectPath),Q?.throwIfAborted(),await d(P,J.sessionId,J.workspace.projectPath,N.projectionDeriverForSearch(),void 0,"local",Q);return}await N.listValidatedRemoteSurfaceCandidates(Q),await l(P,N.projectionDeriverForSearch(),Q)}async syncAllSurfaces(P,J){let Q=N.projectionDeriverForSearch(),Z=await N.listValidatedLocalSurfaceCandidates(J),$=new Set(Z.map((Y)=>`${Y.projectPath}\x00${Y.sessionId}`)),G=P.prepare("SELECT project_path, session_id FROM sessions WHERE source_kind='local'").all();for(let Y of G)if(!$.has(`${Y.project_path}\x00${Y.session_id}`))JP(P,Y.session_id,Y.project_path,"local");for(let Y of Z)J?.throwIfAborted(),await d(P,Y.sessionId,Y.projectPath,Q,void 0,"local",J);await N.listValidatedRemoteSurfaceCandidates(J),await l(P,Q,J)}async listFallbackPage(P,J,Q,Z){if(Z)return this.registry.redeemCatalogCursor({token:Z,scopeKey:J,epoch:this.epoch,revision:"fallback",request:P,loader:async({boundary:G})=>{let Y=LP(G);return this.pageFallbackCatalog(Y.entries,P,J,Y.chainId)}});let $=await this.loadFallbackCatalog(P,Q);return this.pageFallbackCatalog($,P,J,`catalog-fallback:${F(16).toString("base64url")}`)}async loadFallbackCatalog(P,J){let Q=[];if(P.workspaceKind!=="acp-remote")for(let $ of await N.listValidatedLocalSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedLocalSurfaceSnapshot($.sessionId,$.projectPath,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}},summary:Y})}if(P.workspaceKind!=="local")for(let $ of await N.listValidatedRemoteSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedRemoteSurfaceSnapshot($,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.workspaceRef}},summary:Y})}Q.sort(IP);let Z=Buffer.byteLength(JSON.stringify(Q));if(Q.length>TP||Z>DP)throw new z("session_surface_capacity");return Q}async pageFallbackCatalog(P,J,Q,Z){let $=P.slice(0,J.limit),G=P.slice($.length),V={sessions:$.map((X)=>R.parse({locator:X.locator,...X.summary,capabilities:X.locator.workspace.kind==="local"?UP(Boolean(X.summary.archivedAt)):RP(Boolean(X.summary.archivedAt))})),...G.length>0?{nextCursor:this.registry.issueCatalogCursor({chainId:Z,scopeKey:Q,epoch:this.epoch,revision:"fallback",boundary:{chainId:Z,entries:G},request:J})}:{}};if(G.length===0)this.registry.completeChain(Z);return y.parse(V)}async openFallback(P,J,Q){let Z=await this.resolveFallback(P,Q),$=Z.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(Z.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(Z.candidate.sessionId,Z.candidate.projectPath,Q),G=e($.entries,{...Z.remoteCandidate?r(Z.remoteCandidate.hostStateRoot,Z.remoteCandidate.descriptor):{privateRoots:[]},bladeStorageRoots:[o()]}),Y=h(G.slice(-J),L()),V=`history-fallback:${F(16).toString("base64url")}`,X=x(P),O=C("sha256").update(JSON.stringify($.entries)).digest("hex"),j=this.registry.issueSnapshotToken({chainId:V,locatorDigest:X,transcriptFingerprint:O,frozenSnapshot:G}),M={session:this.toSummary(Z),history:A.parse({messages:Y.messages,snapshot:j,truncated:Y.messages.length<G.length||Y.truncated||Y.messages.some((H)=>H.truncated===!0),...G.length>Y.messages.length&&Y.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:V,locatorDigest:X,transcriptFingerprint:O,nextSequence:v(Y.messages[0].id),snapshotToken:j,request:{expectedSnapshot:j,limit:J}})}:{}})};if(G.length<=Y.messages.length)this.registry.completeChain(V);return p.parse(M)}async readFallbackHistoryPage(P,J,Q){let Z=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let $=x(P),G=await this.resolveFallback(P,Q),Y=G.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(G.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(G.candidate.sessionId,G.candidate.projectPath,Q),V=C("sha256").update(JSON.stringify(Y.entries)).digest("hex");await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V});let X={expectedSnapshot:J.expectedSnapshot,limit:Z};return this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:$,transcriptFingerprint:V,request:X,loader:async({nextSequence:O,frozenSnapshot:j})=>{let M=xP(j).filter((b)=>v(b.id)<O),H=h(M.slice(-Z),L()),u=await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V}),k=H.messages.length<M.length,VP={messages:H.messages,snapshot:J.expectedSnapshot,truncated:k||H.truncated||H.messages.some((b)=>b.truncated===!0),...k&&H.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:u.chainId,locatorDigest:$,transcriptFingerprint:V,nextSequence:v(H.messages[0].id),snapshotToken:J.expectedSnapshot,request:X})}:{}};if(!k)this.registry.completeChain(u.chainId);return A.parse(VP)}})}async resolveFallback(P,J){let Q=[];for(let G of[!1,!0]){let Y={archived:G,limit:zP,workspaceKind:P.workspace.kind};Q.push(...(await this.loadFallbackCatalog(Y,J)).filter((V)=>JSON.stringify(V.locator)===JSON.stringify(P)))}if(Q.length!==1)throw new z("session_surface_not_found");let Z=Q[0],$;if(P.workspace.kind==="acp-remote"){let G=P.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(J)).find((Y)=>Y.sessionId===P.sessionId&&Y.workspaceRef===G),!$)throw new z("workspace_binding_mismatch")}return{candidate:{sourceKind:P.workspace.kind,projectPath:P.workspace.kind==="local"?P.workspace.projectPath:$.hostStateRoot,sessionId:P.sessionId,...P.workspace.kind==="acp-remote"?{publicWorkspaceRef:P.workspace.workspaceRef}:{},publicWorkspaceSortKey:"",surfaceDigest:i(Z),transcriptFingerprint:i(Z),lastMessageTime:Z.summary.lastMessageTime,sessionSortKey:"",summary:Z.summary},...$?{remoteCandidate:$}:{}}}async resolveFromProjection(P,J,Q){let Z=QP(P,J.sessionId).filter((G)=>J.workspace.kind==="local"?G.sourceKind==="local"&&G.projectPath===FP.resolve(J.workspace.projectPath):G.sourceKind==="acp-remote"&&G.publicWorkspaceRef===J.workspace.workspaceRef);if(Z.length!==1)throw new z(Z.length===0?"session_surface_not_found":"workspace_binding_mismatch");let $;if(J.workspace.kind==="acp-remote"){let G=J.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(Q)).filter((Y)=>Y.sessionId===J.sessionId&&Y.workspaceRef===G),$.length===0)throw new z("workspace_binding_mismatch");if($.length>1)throw new z("session_surface_state_invalid")}return $?{candidate:Z[0],remoteCandidate:$[0]}:{candidate:Z[0]}}async resolveCandidate(P,J){if(P.sourceKind==="local")return{candidate:P};let Q=(await N.listValidatedRemoteSurfaceCandidates(J)).filter((Z)=>Z.sessionId===P.sessionId&&Z.workspaceRef===P.publicWorkspaceRef);if(Q.length!==1)throw new z(Q.length===0?"workspace_binding_mismatch":"session_surface_state_invalid");return{candidate:P,remoteCandidate:Q[0]}}toSummary(P){let J=P.candidate,Q=J.sourceKind==="local"?{version:2,sessionId:J.sessionId,workspace:{kind:"local",projectPath:J.projectPath}}:{version:2,sessionId:J.sessionId,workspace:{kind:"acp-remote",workspaceRef:J.publicWorkspaceRef}};return R.parse({locator:Q,...J.summary,capabilities:this.capabilitiesFor(P)})}capabilitiesFor(P){let J=P.candidate.summary.archivedAt!==void 0;if(!P.remoteCandidate)return{connection:"local",history:{read:!0,fork:!J},turn:J?{start:!1,reason:"archived"}:{start:!0},files:J?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:J?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}};return{connection:GP.getRemoteSurfaceOwnerSnapshot(P.candidate.sessionId,P.remoteCandidate.descriptor).connection,history:{read:!0,fork:!J},turn:{start:!1,reason:J?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:J?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:J?"archived":"history-only"}}}async requireDatabase(){if(this.database===null)return null;return this.database??await PP()}assertAvailable(){if(this.closed)throw new z("session_surface_unavailable")}}function K(P){let J=P??YP;if(!Number.isSafeInteger(J)||J<1||J>zP)throw new z("invalid_session_surface_request");return J}function I(P){try{let J=t.parse(P);if(!n(J.sessionId))throw Error("invalid");if(J.workspace.kind==="local"){if(s(J.workspace.projectPath)!==J.workspace.projectPath)throw Error("invalid")}return J}catch{throw new z("invalid_session_locator")}}function x(P){return C("sha256").update("session-surface-locator-v2\x00").update(JSON.stringify(P)).digest("hex")}function KP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.lastMessageTime!=="string"||J.sourceKind!=="local"&&J.sourceKind!=="acp-remote"||typeof J.publicWorkspaceSortKey!=="string"||typeof J.sessionSortKey!=="string"||typeof J.chainId!=="string"||!J.chainId)throw new z("session_surface_cursor_invalid");return{lastMessageTime:J.lastMessageTime,sourceKind:J.sourceKind,publicWorkspaceSortKey:J.publicWorkspaceSortKey,sessionSortKey:J.sessionSortKey,chainId:J.chainId}}function h(P,J){let Q=[];for(let Z=P.length-1;Z>=0;Z-=1){let $=P[Z];if(!$)continue;let G=[$,...Q];if(Q.length>0&&Buffer.byteLength(JSON.stringify(G))>J)break;Q.unshift($)}return{messages:Q,truncated:Q.length<P.length}}function v(P){let J=/^surface-message:([0-9]+):/.exec(P),Q=J?Number(J[1]):Number.NaN;if(!Number.isSafeInteger(Q)||Q<=0)throw new z("session_surface_state_invalid");return Q}function xP(P){if(!Array.isArray(P))throw new z("session_surface_snapshot_changed");return P.map((J)=>{try{return a.parse(J)}catch{throw new z("session_surface_snapshot_changed")}})}function LP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.chainId!=="string"||J.chainId.length===0||!Array.isArray(J.entries))throw new z("session_surface_cursor_invalid");let Q=J.entries.map((Z)=>{if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new z("session_surface_cursor_invalid");let $=Z;return{locator:I($.locator),summary:wP($.summary)}});return{chainId:J.chainId,entries:Q}}function wP(P){let J={version:2,sessionId:"placeholder",workspace:{kind:"local",projectPath:"/"}},Q=R.parse({...P&&typeof P==="object"&&!Array.isArray(P)?P:{},locator:J,capabilities:UP(!1)}),{locator:Z,capabilities:$,...G}=Q;return G}function IP(P,J){if(P.summary.lastMessageTime>J.summary.lastMessageTime)return-1;if(P.summary.lastMessageTime<J.summary.lastMessageTime)return 1;if(P.locator.workspace.kind!==J.locator.workspace.kind)return P.locator.workspace.kind==="local"?-1:1;let Q=P.locator.workspace.kind==="local"?P.locator.workspace.projectPath:P.locator.workspace.workspaceRef,Z=J.locator.workspace.kind==="local"?J.locator.workspace.projectPath:J.locator.workspace.workspaceRef;if(Q<Z)return-1;if(Q>Z)return 1;return P.locator.sessionId<J.locator.sessionId?-1:P.locator.sessionId>J.locator.sessionId?1:0}function i(P){return C("sha256").update("session-surface-fallback-entry\x00").update(JSON.stringify(P)).digest("hex")}function UP(P){return{connection:"local",history:{read:!0,fork:!P},turn:P?{start:!1,reason:"archived"}:{start:!0},files:P?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:P?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}}}function RP(P){return{connection:"offline",history:{read:!0,fork:!P},turn:{start:!1,reason:P?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:P?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:P?"archived":"history-only"}}}function CP(P){if(P==="session_surface_cursor_invalid")return{message:"Session surface cursor is invalid",retryable:!1};if(P==="session_surface_snapshot_changed")return{message:"Session surface snapshot changed",retryable:!1};if(P==="session_surface_state_invalid")return{message:"Session surface state is invalid",retryable:!1};if(P==="session_surface_capability_unavailable")return{message:"Session surface capability is unavailable",retryable:!1};if(P==="session_surface_unavailable")return{message:"Session surface is unavailable",retryable:!0};if(P==="session_surface_not_found")return{message:"Session surface was not found",retryable:!1};if(P==="workspace_binding_mismatch")return{message:"Session workspace binding changed",retryable:!1};if(P==="session_surface_read_only")return{message:"Session surface is read only",retryable:!1};if(P==="session_surface_capacity")return{message:"Session surface capacity is exhausted",retryable:!0};if(P==="invalid_session_locator")return{message:"Session locator is invalid",retryable:!1};return{message:"Session surface request is invalid",retryable:!1}}function kP(P){if(P instanceof z)return P;if(P&&typeof P==="object"&&"code"in P&&typeof P.code==="string"){let J=P.code;if(J==="session_surface_cursor_invalid"||J==="session_surface_snapshot_changed"||J==="session_surface_capacity"||J==="session_surface_unavailable"||J==="session_surface_state_invalid")return new z(J);if(J==="acp_remote_workspace_state_invalid")return new z("session_surface_state_invalid")}return P instanceof Error?P:new z("session_surface_state_invalid")}
2
2
  export{qP as e,EP as f,g,z as h,BP as i};