blade-code 0.10.140 → 0.10.144

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 (135) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-ma1mn6hn.js → chunk-06hkf59s.js} +1 -1
  3. package/dist/{chunk-d1qe06f0.js → chunk-0tzecdv3.js} +1 -1
  4. package/dist/chunk-10947adv.js +181 -0
  5. package/dist/{chunk-ppmy3n74.js → chunk-1xa8z2h3.js} +399 -393
  6. package/dist/{chunk-g38d2ezm.js → chunk-2f8d0km4.js} +1 -1
  7. package/dist/{chunk-pg7cgvs8.js → chunk-2mk914vk.js} +2 -2
  8. package/dist/{chunk-w5057h27.js → chunk-2n97dt2h.js} +2 -2
  9. package/dist/chunk-3kszepm6.js +2 -0
  10. package/dist/{chunk-nxsarfy6.js → chunk-3y2x6fb6.js} +1 -1
  11. package/dist/chunk-4bgsnpg0.js +1 -0
  12. package/dist/{chunk-2g8avyq6.js → chunk-4cdk4mds.js} +1 -1
  13. package/dist/chunk-4jqvrgpm.js +1 -0
  14. package/dist/{chunk-mnk0b4nz.js → chunk-4wx5sya5.js} +1 -1
  15. package/dist/chunk-5v0jcyea.js +2 -0
  16. package/dist/chunk-5y4btx3c.js +1 -0
  17. package/dist/{chunk-e6j4vzta.js → chunk-65cxn7bb.js} +2 -2
  18. package/dist/chunk-66wk3exc.js +1 -0
  19. package/dist/{chunk-g4kydkyz.js → chunk-6a16zba3.js} +2 -2
  20. package/dist/chunk-6c972n1p.js +6 -0
  21. package/dist/chunk-6vcqajdc.js +1 -0
  22. package/dist/{chunk-hvmrcd84.js → chunk-7wcxjbyg.js} +1 -1
  23. package/dist/{chunk-c562kd2m.js → chunk-7xhw74hk.js} +1 -1
  24. package/dist/chunk-8vd9y7ar.js +10 -0
  25. package/dist/chunk-96t1d492.js +1 -0
  26. package/dist/{chunk-1myft5nb.js → chunk-99t5b3qh.js} +1 -1
  27. package/dist/chunk-9p0zyba2.js +1 -0
  28. package/dist/{chunk-kmg8ad2j.js → chunk-9xbwtjac.js} +1 -1
  29. package/dist/{chunk-rrtptbzv.js → chunk-a9h3xfdj.js} +2 -2
  30. package/dist/{chunk-pwct7cj7.js → chunk-atcpkhxt.js} +1 -1
  31. package/dist/chunk-b5qxype0.js +1 -0
  32. package/dist/{chunk-6zxm9pen.js → chunk-b7b1h83p.js} +1 -1
  33. package/dist/{chunk-n6tvswa8.js → chunk-bwm0jt16.js} +2 -2
  34. package/dist/chunk-c1qjdcf9.js +1 -0
  35. package/dist/{chunk-eh901zhx.js → chunk-cd150xf2.js} +2 -2
  36. package/dist/chunk-cr6d4zxs.js +1 -0
  37. package/dist/{chunk-n8qg68y2.js → chunk-ddvdc2p0.js} +1 -1
  38. package/dist/chunk-e12xrg41.js +2 -0
  39. package/dist/{chunk-tecbx0ek.js → chunk-eg3ms291.js} +1 -1
  40. package/dist/{chunk-0c2y17xy.js → chunk-ehwn05np.js} +1 -1
  41. package/dist/chunk-ekjaa3h2.js +1 -0
  42. package/dist/{chunk-es0cbtx1.js → chunk-fd7ez529.js} +2 -2
  43. package/dist/{chunk-svsgtj41.js → chunk-j8hbddjp.js} +2 -2
  44. package/dist/{chunk-9ced7jf0.js → chunk-jq5bhnrd.js} +1 -1
  45. package/dist/{chunk-w2m4yczv.js → chunk-kv458q06.js} +1 -1
  46. package/dist/{chunk-hj1yrssp.js → chunk-m7j6mq32.js} +1 -1
  47. package/dist/{chunk-kxwc5wrx.js → chunk-m9srdfa1.js} +1 -1
  48. package/dist/{chunk-zfaenqqx.js → chunk-mh9nqbwa.js} +2 -2
  49. package/dist/{chunk-2ff55pvt.js → chunk-mw3e5scz.js} +3 -3
  50. package/dist/chunk-n14kcb52.js +1 -0
  51. package/dist/{chunk-0kghtvxj.js → chunk-ny2g84m0.js} +2 -2
  52. package/dist/{chunk-ffkzessq.js → chunk-p102vt6w.js} +1 -1
  53. package/dist/{chunk-19zsecpx.js → chunk-pe6kcmvn.js} +2 -2
  54. package/dist/chunk-qdxk9rcw.js +1 -0
  55. package/dist/{chunk-7eepxhcp.js → chunk-qhr61n4y.js} +45 -45
  56. package/dist/{chunk-8vqhcx3s.js → chunk-qm0j4szw.js} +1 -1
  57. package/dist/{chunk-15fpc0qg.js → chunk-rqz0589c.js} +1 -1
  58. package/dist/{chunk-50m1czz9.js → chunk-rrb49j43.js} +1 -1
  59. package/dist/{chunk-85b3kacc.js → chunk-rvs364rz.js} +2 -2
  60. package/dist/{chunk-eqe3smcg.js → chunk-s32yz7eq.js} +2 -2
  61. package/dist/{chunk-xagh2qb6.js → chunk-s6x7fme7.js} +2 -2
  62. package/dist/{chunk-8fx20am1.js → chunk-shb7g2vr.js} +2 -2
  63. package/dist/{chunk-cf3dvysj.js → chunk-srd0aqsm.js} +1 -1
  64. package/dist/{chunk-y5bqd8gh.js → chunk-sy59x1ts.js} +1 -1
  65. package/dist/chunk-v67t8jmc.js +1 -0
  66. package/dist/{chunk-r4q06wbs.js → chunk-vbjgcn49.js} +1 -1
  67. package/dist/{chunk-q9qts6bq.js → chunk-vgxzpvyb.js} +3 -3
  68. package/dist/{chunk-5cw3bevx.js → chunk-vw9paban.js} +1 -1
  69. package/dist/{chunk-cww9pp1q.js → chunk-w6qfbea8.js} +2 -2
  70. package/dist/chunk-wcps5gjm.js +2 -0
  71. package/dist/{chunk-0sx7ak0b.js → chunk-wm896gnx.js} +1 -1
  72. package/dist/{chunk-08z32sky.js → chunk-wzqcea6x.js} +2 -2
  73. package/dist/{chunk-tagzy876.js → chunk-x7gcmasv.js} +1 -1
  74. package/dist/{chunk-gq727fet.js → chunk-xmymx75h.js} +1 -1
  75. package/dist/{chunk-g5scqxq3.js → chunk-ypfe8j02.js} +2 -2
  76. package/dist/{chunk-pw9axk0e.js → chunk-z2k08r1h.js} +2 -2
  77. package/dist/{chunk-5jq1mrqd.js → chunk-zj1g4nbq.js} +1 -1
  78. package/dist/web/assets/ChatView-DuCQPnTY.js +63 -0
  79. package/dist/web/assets/{CodeBlockHighlighter-BM1MZv6w.js → CodeBlockHighlighter-QAgXsft7.js} +1 -1
  80. package/dist/web/assets/{FilePreview-P77KS9tr.js → FilePreview-4CWWDjOH.js} +1 -1
  81. package/dist/web/assets/{KanbanBoard-B0c7sE2y.js → KanbanBoard-Ck-cWvPd.js} +1 -1
  82. package/dist/web/assets/{MarkdownRenderer-DHa0FqU0.js → MarkdownRenderer-BT_XxFwe.js} +3 -3
  83. package/dist/web/assets/{ScrollArea-C6yf2fqq.js → ScrollArea-pHWxoYad.js} +1 -1
  84. package/dist/web/assets/{SessionHistorySurface-CXYBWqlN.js → SessionHistorySurface-ot9S7y0a.js} +1 -1
  85. package/dist/web/assets/{SettingsModal-BVjVlENY.js → SettingsModal-CadB2Ewl.js} +1 -1
  86. package/dist/web/assets/{Sidebar-DDW9Xs6e.js → Sidebar-Ch8ljTll.js} +1 -1
  87. package/dist/web/assets/{TaskSwitcher-D74_5q1F.js → TaskSwitcher-DKMYqwyA.js} +1 -1
  88. package/dist/web/assets/{TerminalPanel-DNEKapEi.js → TerminalPanel-DiibeBVa.js} +1 -1
  89. package/dist/web/assets/{archive-Ao0WD7pU.js → archive-RtNeCZxZ.js} +1 -1
  90. package/dist/web/assets/{arrow-left-a5_iLemp.js → arrow-left-ozhIfGE6.js} +1 -1
  91. package/dist/web/assets/{calendar-clock-BKbdz6Cu.js → calendar-clock-HYACxDy_.js} +1 -1
  92. package/dist/web/assets/{chevron-right-8qYRfCj4.js → chevron-right-DzAXXFGA.js} +1 -1
  93. package/dist/web/assets/{chevrons-up-down-BXNG4GvK.js → chevrons-up-down-DABp_klC.js} +1 -1
  94. package/dist/web/assets/{clock-3-DEL1ixyh.js → clock-3-DTi7hWra.js} +1 -1
  95. package/dist/web/assets/{copy-Bd5v-KkM.js → copy-DTdeEIqL.js} +1 -1
  96. package/dist/web/assets/{download-CIKvpDBW.js → download-BmAUw5eK.js} +1 -1
  97. package/dist/web/assets/{external-link-B33h3DQN.js → external-link-Bgh_DKjS.js} +1 -1
  98. package/dist/web/assets/{folder-lOczceoh.js → folder-CcFAxEz0.js} +1 -1
  99. package/dist/web/assets/index-B0JUjEnb.js +203 -0
  100. package/dist/web/assets/index-RGoMvYl5.css +1 -0
  101. package/dist/web/assets/{pause-nnvVbgsj.js → pause-Ch9b-6bD.js} +1 -1
  102. package/dist/web/assets/{pencil-_yfoOmUq.js → pencil-Dplt4XbT.js} +1 -1
  103. package/dist/web/assets/{play-BilJ7SDs.js → play-BfcPlDek.js} +1 -1
  104. package/dist/web/assets/{plus-BqqpYKaK.js → plus-99fbVJwp.js} +1 -1
  105. package/dist/web/assets/session-events-CGQa6VXb.js +29 -0
  106. package/dist/web/assets/{settings-CmJXtYTH.js → settings-DNDRXm8y.js} +1 -1
  107. package/dist/web/assets/{team-Bb04o2Tb.js → team-Cw3NxMX6.js} +1 -1
  108. package/dist/web/assets/{teamService-B5w9cpsa.js → teamService-a7uKjSKx.js} +1 -1
  109. package/dist/web/assets/{terminal-DOjdChj0.js → terminal-IkGhZXro.js} +1 -1
  110. package/dist/web/index.html +2 -2
  111. package/package.json +1 -1
  112. package/dist/chunk-1nreg14s.js +0 -1
  113. package/dist/chunk-2d3zksr0.js +0 -1
  114. package/dist/chunk-3kvt23m3.js +0 -1
  115. package/dist/chunk-4rh40xhc.js +0 -1
  116. package/dist/chunk-4xr4hz19.js +0 -2
  117. package/dist/chunk-61yd46c0.js +0 -1
  118. package/dist/chunk-8774agqd.js +0 -1
  119. package/dist/chunk-8brb7c6j.js +0 -6
  120. package/dist/chunk-abpmpyqa.js +0 -1
  121. package/dist/chunk-ascjys4e.js +0 -2
  122. package/dist/chunk-bb0z7c3g.js +0 -1
  123. package/dist/chunk-m9dv5177.js +0 -10
  124. package/dist/chunk-mwgx87vw.js +0 -1
  125. package/dist/chunk-ntq4h4jh.js +0 -1
  126. package/dist/chunk-r324qme7.js +0 -1
  127. package/dist/chunk-ra6ksfdy.js +0 -1
  128. package/dist/chunk-tnts2de5.js +0 -1
  129. package/dist/chunk-w0710yj4.js +0 -1
  130. package/dist/chunk-we13xwds.js +0 -180
  131. package/dist/chunk-zp5097qk.js +0 -2
  132. package/dist/web/assets/ChatView-BlAGPVC-.js +0 -63
  133. package/dist/web/assets/index-DC2p1vGD.css +0 -1
  134. package/dist/web/assets/index-hZ37pkxs.js +0 -203
  135. package/dist/web/assets/session-events-FPOvcMBw.js +0 -29
@@ -1,2 +1,2 @@
1
- import{Hk as K}from"./chunk-tecbx0ek.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{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}`))})})}
2
2
  export{P as Ea,V as Fa,R as Ga,N as Ha};
@@ -1,2 +1,2 @@
1
- import{V as I}from"./chunk-ppmy3n74.js";import{ee as M}from"./chunk-n6tvswa8.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
1
+ import{V as I}from"./chunk-1xa8z2h3.js";import{ge as M}from"./chunk-bwm0jt16.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
2
2
  export{C as B,$ as C,V as D,x as E,i as F,K as G};
@@ -1,2 +1,2 @@
1
- import{N as GP}from"./chunk-ppmy3n74.js";import{ee as N}from"./chunk-n6tvswa8.js";import{$e as ZP,Le as r,Me as e,Pe as L,Re as PP,Ue as l,We as d,Ye as JP,_e as QP,af as $P,bf as w}from"./chunk-es0cbtx1.js";import{df as t,ef as a,gf as R,if as y,jf as A,lf as p}from"./chunk-zfaenqqx.js";import{Kj as q}from"./chunk-svsgtj41.js";import{ak as o,uk as s,vk as n}from"./chunk-mnk0b4nz.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 l(P,J.sessionId,J.workspace.projectPath,N.projectionDeriverForSearch(),void 0,"local",Q);return}await d(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 l(P,Y.sessionId,Y.projectPath,Q,void 0,"local",J);await d(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-1xa8z2h3.js";import{ge as N}from"./chunk-bwm0jt16.js";import{Ne as r,Oe as e,Re as L,Te as PP,We as l,Ye as d,_e as JP,af as QP,bf as ZP,cf as $P,df as w}from"./chunk-fd7ez529.js";import{ff as t,gf as a,if as R,kf as y,lf as A,nf as p}from"./chunk-mh9nqbwa.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 l(P,J.sessionId,J.workspace.projectPath,N.projectionDeriverForSearch(),void 0,"local",Q);return}await d(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 l(P,Y.sessionId,Y.projectPath,Q,void 0,"local",J);await d(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};
@@ -1,3 +1,3 @@
1
- import{$j as I,_j as C}from"./chunk-5cw3bevx.js";import{ak as _}from"./chunk-mnk0b4nz.js";import{createHash as S}from"node:crypto";import{constants as A,promises as B}from"node:fs";import N from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import E from"write-file-atomic";var X=1,j=65536,T=1048576,z=100,R=64;function t(q){return q.state==="trusted"||q.state==="not_required"}function K(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function V(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function M(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return V(`${Q.origin}${Q.pathname}`)}catch{return V(q)}}function D(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=D($.args),L=H==="stdio"?V([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function g(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.command==="string"?V($.command):void 0,G=K($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function P(q){if(!Array.isArray(q))return[];return q.slice(0,z).flatMap((Q)=>{if(!K(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",G=K(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function y(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function f(q){if(!K(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of D(q[Z]).slice(0,z))Q.push({kind:"permission",name:`${Z}: ${V($,512)}`});return Q}function h(q){let Q=[...m(q.mcpServers),...g(q.lspServers),...P(q.models),...y(q.modelProviders),...f(q.permissions)];if(K(q.env))for(let Z of Object.keys(q.env).slice(0,z))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function v(q){return q!=="hooks"&&q!=="disableAllHooks"}function l(q){return S("sha256").update(q).digest("hex")}function p(q,Q){let Z=F.relative(q,Q);return Z===""||!Z.startsWith(`..${F.sep}`)&&Z!==".."&&!F.isAbsolute(Z)}class x{storeDir;static instance=null;mutex=new w;statusCache=new k({max:R});constructor(q=F.join(_(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async getStatus(q){let Q=await C(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let O={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,O),O}if(Z.length===0){let Y={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,Y),Y}let $;try{$=await this.readDecisions()}catch(Y){let O={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,O),O}let H=$.filter((Y)=>p(Y.path,Q.trustRoot)),G=Math.max(-1,...H.map((Y)=>Y.path.split(F.sep).length)),J=H.filter((Y)=>Y.path.split(F.sep).length===G),L=J.length>0&&J.every((Y)=>Y.trusted),U=J[0],b=U?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:U?b?U.trusted?"trusted":"untrusted":"inherited":"undecided",...U?.decidedAt?{decidedAt:U.decidedAt}:{},...!b&&U?.path?{inheritedFrom:U.path}:{}};return this.cacheStatus(q,W),W}cacheStatus(q,Q){this.statusCache.set(F.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(F.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:R,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await I(q);let Z=await C(q);await this.assertSafeTrustRoot(Z);let $={version:X,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=F.parse(q.trustRoot).root,Z=await B.realpath(N.homedir()).catch(()=>F.resolve(N.homedir()));if(!F.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let G=await this.reviewConfigFile(q,$,H);if(G)Q.push(G)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,G]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let J=await this.reviewResourceDirectory(q,$,H,G);if(J)Q.push(J)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=F.join(q,"package.json"),Z;try{Z=await B.stat(Q)}catch(J){if(J.code==="ENOENT")return;throw J}if(!Z.isFile())return;if(Z.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await B.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!K($)||!K($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,z);if(G.length===0)return;return{path:"package.json",kind:"package",keys:G,effects:G.map((J)=>({kind:"command",name:`package script: ${J}`}))}}async reviewInstructionFile(q,Q){try{if(!(await B.stat(F.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=F.join(q,Q),H;try{H=await B.stat($)}catch(b){if(b.code==="ENOENT")return;throw b}if(!H.isFile())return;if(H.size>T)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let G;try{G=JSON.parse(await B.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!K(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(v).sort();if(J.length===0)return;let L=h(G),U=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let b of J)if(!U.has(b))L.push({kind:"configuration",name:b});return{path:Q,kind:Z,keys:J,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=F.join(q,Q),G;try{G=await B.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let J=G.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,z);if(J.length===0)return;return{path:Q,kind:Z,keys:J.map((L)=>L.name),effects:J.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await B.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await B.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(F.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await B.open(q,A.O_RDONLY|A.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>j)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!K($)||$.version!==X||typeof $.path!=="string"||!F.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:X,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${l(q.path)}.json`);try{let Z=await B.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await E(Q,`${JSON.stringify(q,null,2)}
1
+ import{dk as C,ek as I}from"./chunk-vw9paban.js";import{fk as _}from"./chunk-4wx5sya5.js";import{createHash as S}from"node:crypto";import{constants as A,promises as B}from"node:fs";import N from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import E from"write-file-atomic";var X=1,j=65536,T=1048576,z=100,R=64;function t(q){return q.state==="trusted"||q.state==="not_required"}function K(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function V(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function M(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return V(`${Q.origin}${Q.pathname}`)}catch{return V(q)}}function D(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=D($.args),L=H==="stdio"?V([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function g(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.command==="string"?V($.command):void 0,G=K($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function P(q){if(!Array.isArray(q))return[];return q.slice(0,z).flatMap((Q)=>{if(!K(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",G=K(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function y(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function f(q){if(!K(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of D(q[Z]).slice(0,z))Q.push({kind:"permission",name:`${Z}: ${V($,512)}`});return Q}function h(q){let Q=[...m(q.mcpServers),...g(q.lspServers),...P(q.models),...y(q.modelProviders),...f(q.permissions)];if(K(q.env))for(let Z of Object.keys(q.env).slice(0,z))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function v(q){return q!=="hooks"&&q!=="disableAllHooks"}function l(q){return S("sha256").update(q).digest("hex")}function p(q,Q){let Z=F.relative(q,Q);return Z===""||!Z.startsWith(`..${F.sep}`)&&Z!==".."&&!F.isAbsolute(Z)}class x{storeDir;static instance=null;mutex=new w;statusCache=new k({max:R});constructor(q=F.join(_(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async getStatus(q){let Q=await C(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let O={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,O),O}if(Z.length===0){let Y={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,Y),Y}let $;try{$=await this.readDecisions()}catch(Y){let O={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,O),O}let H=$.filter((Y)=>p(Y.path,Q.trustRoot)),G=Math.max(-1,...H.map((Y)=>Y.path.split(F.sep).length)),J=H.filter((Y)=>Y.path.split(F.sep).length===G),L=J.length>0&&J.every((Y)=>Y.trusted),U=J[0],b=U?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:U?b?U.trusted?"trusted":"untrusted":"inherited":"undecided",...U?.decidedAt?{decidedAt:U.decidedAt}:{},...!b&&U?.path?{inheritedFrom:U.path}:{}};return this.cacheStatus(q,W),W}cacheStatus(q,Q){this.statusCache.set(F.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(F.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:R,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await I(q);let Z=await C(q);await this.assertSafeTrustRoot(Z);let $={version:X,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=F.parse(q.trustRoot).root,Z=await B.realpath(N.homedir()).catch(()=>F.resolve(N.homedir()));if(!F.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let G=await this.reviewConfigFile(q,$,H);if(G)Q.push(G)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,G]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let J=await this.reviewResourceDirectory(q,$,H,G);if(J)Q.push(J)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=F.join(q,"package.json"),Z;try{Z=await B.stat(Q)}catch(J){if(J.code==="ENOENT")return;throw J}if(!Z.isFile())return;if(Z.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await B.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!K($)||!K($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,z);if(G.length===0)return;return{path:"package.json",kind:"package",keys:G,effects:G.map((J)=>({kind:"command",name:`package script: ${J}`}))}}async reviewInstructionFile(q,Q){try{if(!(await B.stat(F.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=F.join(q,Q),H;try{H=await B.stat($)}catch(b){if(b.code==="ENOENT")return;throw b}if(!H.isFile())return;if(H.size>T)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let G;try{G=JSON.parse(await B.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!K(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(v).sort();if(J.length===0)return;let L=h(G),U=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let b of J)if(!U.has(b))L.push({kind:"configuration",name:b});return{path:Q,kind:Z,keys:J,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=F.join(q,Q),G;try{G=await B.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let J=G.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,z);if(J.length===0)return;return{path:Q,kind:Z,keys:J.map((L)=>L.name),effects:J.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await B.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await B.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(F.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await B.open(q,A.O_RDONLY|A.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>j)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!K($)||$.version!==X||typeof $.path!=="string"||!F.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:X,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${l(q.path)}.json`);try{let Z=await B.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await E(Q,`${JSON.stringify(q,null,2)}
2
2
  `,{mode:384}),await B.chmod(Q,384)}async ensureStoreDirectoryForWrite(){try{let q=await B.lstat(this.storeDir);if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(q){if(q.code!=="ENOENT")throw q;await B.mkdir(this.storeDir,{recursive:!0,mode:448}),await B.chmod(this.storeDir,448)}}}
3
- export{R as Xj,t as Yj,x as Zj};
3
+ export{R as ak,t as bk,x as ck};
@@ -1,2 +1,2 @@
1
- import{Mi as I}from"./chunk-e6j4vzta.js";import{Jj as G,Kj as H}from"./chunk-svsgtj41.js";import B from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function D(b){return A(b)}function E(b,q){let w=new G(q?.credentials??H().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=B.resolve(b),x=I.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...D(q),...J,...K},F=E(z);return x.validateConfig(z,F),{projectRoot:w,config:z,catalog:F}}function T(b){let q=D(b.config);return{projectRoot:B.resolve(b.projectRoot),config:q,catalog:E(q,b.catalog)}}function U(b,q){let w=D(q);return{projectRoot:B.resolve(b),config:w,catalog:E(w)}}
2
- export{D as ug,Q as vg,T as wg,U as xg};
1
+ import{Ri as I}from"./chunk-65cxn7bb.js";import{Oj as G,Pj as H}from"./chunk-j8hbddjp.js";import B from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function D(b){return A(b)}function E(b,q){let w=new G(q?.credentials??H().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=B.resolve(b),x=I.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...D(q),...J,...K},F=E(z);return x.validateConfig(z,F),{projectRoot:w,config:z,catalog:F}}function T(b){let q=D(b.config);return{projectRoot:B.resolve(b.projectRoot),config:q,catalog:E(q,b.catalog)}}function U(b,q){let w=D(q);return{projectRoot:B.resolve(b),config:w,catalog:E(w)}}
2
+ export{D as wg,Q as xg,T as yg,U as zg};
@@ -1,4 +1,4 @@
1
- import{$g as A1,ah as L0,bh as M1,gh as v0}from"./chunk-ascjys4e.js";import{nh as SO,oh as F1}from"./chunk-r4q06wbs.js";import{rh as x1}from"./chunk-ma1mn6hn.js";import{sh as A0,uh as J0}from"./chunk-2ff55pvt.js";import{Hi as z0,Ii as WO,Mi as b0}from"./chunk-e6j4vzta.js";import{Yi as M}from"./chunk-g38d2ezm.js";import{Aj as u,Cj as L,Fj as l1,yj as P,zj as S}from"./chunk-pg7cgvs8.js";import{Sj as c0}from"./chunk-19zsecpx.js";import{Zj as N}from"./chunk-85b3kacc.js";import{uk as qO}from"./chunk-mnk0b4nz.js";import N0 from"node:path";import YO from"node:path";import y0 from"node:fs";import W0 from"node:os";import E from"node:path";import pO from"yaml";var V1=2000,j1=50,B1=1000,X4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:V1},findings:{type:"array",maxItems:j1,items:{type:"string",minLength:1,maxLength:B1}}},required:["verdict","summary","findings"],additionalProperties:!1};function U1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function kO(O){if(O.length<=v0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,v0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function S1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>V1||!Array.isArray($.findings)||$.findings.length>j1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=B1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function H4(O,$){let Q=S1(O);if(!Q)return;let Z=U1(Q.summary,$),J=Q.findings.map((K)=>U1(K,$));return kO([Z,J.length>0?`Findings:
1
+ import{bh as A1,ch as L0,dh as M1}from"./chunk-3kszepm6.js";import{jh as v0}from"./chunk-wcps5gjm.js";import{sh as SO,th as F1}from"./chunk-vbjgcn49.js";import{wh as x1}from"./chunk-06hkf59s.js";import{xh as A0,zh as J0}from"./chunk-mw3e5scz.js";import{Mi as z0,Ni as WO,Ri as b0}from"./chunk-65cxn7bb.js";import{bj as M}from"./chunk-2f8d0km4.js";import{Dj as P,Ej as S,Fj as u,Hj as L,Kj as l1}from"./chunk-2mk914vk.js";import{Xj as c0}from"./chunk-pe6kcmvn.js";import{ck as N}from"./chunk-rvs364rz.js";import{zk as qO}from"./chunk-4wx5sya5.js";import N0 from"node:path";import YO from"node:path";import y0 from"node:fs";import W0 from"node:os";import E from"node:path";import pO from"yaml";var V1=2000,j1=50,B1=1000,X4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:V1},findings:{type:"array",maxItems:j1,items:{type:"string",minLength:1,maxLength:B1}}},required:["verdict","summary","findings"],additionalProperties:!1};function U1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function kO(O){if(O.length<=v0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,v0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function S1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>V1||!Array.isArray($.findings)||$.findings.length>j1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=B1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function H4(O,$){let Q=S1(O);if(!Q)return;let Z=U1(Q.summary,$),J=Q.findings.map((K)=>U1(K,$));return kO([Z,J.length>0?`Findings:
2
2
  ${J.map((K)=>`- ${K}`).join(`
3
3
  `)}`:""].filter(Boolean).join(`
4
4
 
@@ -730,4 +730,4 @@ ${Z.join(`
730
730
  </${Q}>`:"";return{content:K,files:[...O],references:O.map($4),triggerPaths:[...$],contentBytes:Buffer.byteLength(K,"utf8"),provenanceSha256:D0(O.map((q)=>`${q.id}:${q.contentSha256}`).join(`
731
731
  `))}}function TO(O,$){let Q=$,Z=[];for(let J=O.length-1;J>=0;J-=1){let K=O[J];if(!K)continue;let q=Buffer.byteLength(K.content,"utf8");if(q>Q)continue;Z.push(K),Q-=q}return Z.reverse()}class m{projectRoot;catalogSha256;definitions;byId;constructor(O,$=[]){this.projectRoot=O;this.projectRoot=G1(O),this.definitions=Object.freeze([...$].sort(W1).map((Q)=>Object.freeze({...Q}))),this.byId=new Map(this.definitions.map((Q)=>[Q.id,Q])),this.catalogSha256=D0(this.definitions.map((Q)=>`${Q.id}:${Q.contentSha256}`).join(`
732
732
  `))}static empty(O){return new m(O)}list(){return this.definitions.map((O)=>({id:O.id,relativePath:O.relativePath,source:O.source,kind:O.kind,conditional:O.conditional,contentSha256:O.contentSha256}))}snapshot(){return new m(this.projectRoot,this.definitions.map((O)=>({...O,patterns:O.patterns?[...O.patterns]:void 0})))}staticRules(O,$=l$){if(this.definitions.length===0)return q0([],[],"project-instructions");let Q=this.relativeSourcePath(O),Z=this.definitions.filter((J)=>!J.conditional&&L1(J.scopeDirectory,Q));return q0(TO(Z,$),[],"project-instructions")}contextualRules(O,$,Q,Z=s$){if(this.definitions.length===0)return q0([],[],"contextual-project-instructions");let J=this.relativeSourcePath(O),K=[...new Set($.map((G)=>Y1(z.relative(this.projectRoot,G1(G)))).filter(X1))].sort(),q=new Map;for(let G of K)for(let Y of this.definitions){if(Q.has(Y.id))continue;if(!L1(Y.scopeDirectory,G))continue;if(Y.conditional){let X=z.posix.relative(Y.scopeDirectory||".",G);if(!Y.patterns?.some((U)=>_O(U,{dot:!0})(X)))continue}else if(L1(Y.scopeDirectory,J))continue;q.set(Y.id,Y)}let W=TO([...q.values()].sort(W1),Z);return q0(W,K,"contextual-project-instructions")}hydrate(O){let $=O.map((Q)=>{let Z=this.byId.get(Q.id);if(!Z||Z.contentSha256!==Q.contentSha256||Z.relativePath!==Q.relativePath||Z.source!==Q.source)throw Error(`Project rule provenance mismatch: ${Q.relativePath}`);return Z});return q0([...new Map($.map((Q)=>[Q.id,Q])).values()].sort(W1),[],"contextual-project-instructions")}relativeSourcePath(O){let $=Y1(z.relative(this.projectRoot,G1(O)));if($&&!X1($))throw Error("Project instruction source is outside the catalog root");return $}}async function Q4(O,$){let Q=await d.lstat($);if(!Q.isFile()||Q.isSymbolicLink())throw Error("Project rule must be a regular file");if(Q.size>IO)throw Error(`Project rule exceeds ${IO} bytes`);let Z=await d.realpath($),J=Y1(z.relative(O,Z));if(!X1(J))throw Error("Project rule escapes its repository root");let K=await d.readFile(Z,"utf8");if(wO(K))throw Error("Project rule contains hidden control characters");let q=c$(K),W=q.content.trim();if(!W)throw Error("Project rule content must not be empty");let G=e$(q.data.paths),Y=O4(J),X=D0(JSON.stringify({relativePath:J,patterns:G??[],content:W}));return{id:`${Y.source}:${D0(J).slice(0,20)}`,relativePath:J,source:Y.source,kind:Y.kind,scopeDirectory:Y.scopeDirectory,priority:Y.priority,conditional:Boolean(G),...G?{patterns:G}:{},content:W,contentSha256:X}}async function DO(O,$){let Q=r$(O);if(!$.projectTrusted)return m.empty(Q);let Z=await d.realpath(Q),J=u$.stream([...a$],{cwd:Z,absolute:!0,dot:!0,deep:n$,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:[...t$]}),K=[];for await(let Y of J)if(K.push(Y.toString()),K.length>MO)throw Error(`Project rule catalog exceeds ${MO} files`);K.sort();let q=new Set(K.filter((Y)=>z.basename(Y)==="AGENTS.override.md").map((Y)=>z.dirname(Y))),W=[],G=0;for(let Y of K){if(z.basename(Y)==="AGENTS.md"&&q.has(z.dirname(Y)))continue;try{let X=await Q4(Z,Y);if(G+=Buffer.byteLength(X.content,"utf8"),G>bO)throw Error(`Project rule catalog exceeds ${bO} bytes`);W.push(X)}catch(X){o$.warn(`[ProjectRules] Ignoring rule: ${X instanceof Error?X.message:String(X)}`)}}return new m(Z,W)}var CO=32,C0=64;class NO extends Error{capacity=C0;constructor(){super(`Workspace agent resource capacity is full (${C0})`);this.name="WorkspaceAgentResourceCapacityError"}}var T=new Map,H1=0,EO=[];async function Z4(O){let $=await N.getInstance().getStatus(O.workspaceRoot);O.communicationStyles=await K1(O.workspaceRoot,{projectTrusted:$.state==="trusted",plugins:O.plugins.getActive()})}function J4(O){let $={...O};for(let Q of Object.values(A0))$[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((J)=>({...J}))}));return $}function K5(O){EO=[...new Set(O.map(($)=>N0.resolve($)))]}function vO(O,$){HO(O,$.plugins),w.releaseInstance(O,$.subagents),h.releaseInstance({cwd:O},$.skills),x.releaseInstance(O,$.commands),C.releaseInstance(O,$.plugins)}function RO(O){vO(O.workspaceRoot,O)}function K0(){while(T.size>CO){let O=!1;for(let[$,Q]of T){if(!Q.resources||Q.users>0)continue;if(T.get($)!==Q)continue;T.delete($),RO(Q.resources),O=!0;break}if(!O)return}}function q4(O){setImmediate(()=>{O.users=Math.max(0,O.users-1),K0()}).unref?.()}async function K4(O,$){let Q=await N.getInstance().getStatus(O),Z=o(O),J=g({cwd:O}),K=x.getInstance(O),q=Q0(O);try{if(Z.getAllNames().length===0)Z.loadFromStandardLocations(Q.state==="trusted");await Promise.all([J.initialize(),K.isInitialized()?void 0:K.initialize(O),q.isInitialized()?void 0:q.initialize(O,[...$.cliPluginDirs??EO])]),x0(O),await J1(O);let W=await K1(O,{projectTrusted:Q.state==="trusted",plugins:q.getActive()}),G=await DO(O,{projectTrusted:Q.state==="trusted"});return{workspaceRoot:O,subagents:Z,skills:J,commands:K,plugins:q,communicationStyles:W,projectRules:G}}catch(W){throw vO(O,{subagents:Z,skills:J,commands:K,plugins:q}),W}}function G4(O,$){let Q={generation:H1,users:0};return Q.promise=K4(O,$).then((Z)=>{if(Q.generation!==H1||T.get(O)!==Q)return RO(Z),Z;return Q.resources=Z,K0(),Z},(Z)=>{if(T.get(O)===Q)T.delete(O);throw Z}),T.set(O,Q),Q}async function yO(O,$){let Q=N0.resolve(O),Z=T.get(Q);if(!Z){if(K0(),T.size>=C0)throw new NO;Z=G4(Q,$)}else T.delete(Q),T.set(Q,Z);Z.users++;let J;try{J=await Z.promise}catch(K){throw Z.users=Math.max(0,Z.users-1),K0(),K}return{entry:Z,resources:J}}async function fO(O,$){if(!$)return;x0(O.workspaceRoot),await J1(O.workspaceRoot),await Z4(O)}async function G5(O,$={}){let Q=await yO(O,$);try{return await fO(Q.resources,$.reconcilePlugins),Q.resources}finally{q4(Q.entry)}}async function L5(O,$,Q={}){let Z=await yO(O,Q);try{return await fO(Z.resources,Q.reconcilePlugins),await $(Z.resources)}finally{Z.entry.users=Math.max(0,Z.entry.users-1),K0()}}function W5(){let O=0,$=0;for(let Q of T.values()){if(Q.resources)O++;$+=Q.users}return{capacity:CO,activeCapacity:C0,entries:T.size,initialized:O,inFlight:T.size-O,activeUsers:$}}function Y5(O){let $="projectRoot"in O?O.projectRoot:O.workspaceRoot;return{projectRoot:N0.resolve($),subagents:O.subagents.snapshot(),skills:O.skills.snapshot(),commands:O.commands.snapshot(),communicationStyles:O.communicationStyles?.snapshot()??F1.snapshot(),projectRules:O.projectRules?.snapshot()??m.empty($),hooks:J4("hooks"in O&&O.hooks?O.hooks:J0.getInstance().getConfig($))}}function X5(O){let $=N0.resolve(O);return{projectRoot:$,subagents:new w,skills:new h,commands:x.empty($),hooks:{enabled:!1},communicationStyles:F1.snapshot(),projectRules:m.empty($)}}function H5(){H1++;for(let[O,$]of T)if($.resources)x0(O);T.clear(),w.resetInstances(),h.resetInstance(),x.resetInstance(),C.resetInstance()}
733
- export{X4 as yg,H4 as zg,F4 as Ag,I1 as Bg,S4 as Cg,z4 as Dg,o as Eg,f4 as Fg,D1 as Gg,g as Hg,x as Ig,e0 as Jg,I0 as Kg,C as Lg,Q0 as Mg,J1 as Ng,x0 as Og,m as Pg,CO as Qg,C0 as Rg,NO as Sg,Z4 as Tg,K5 as Ug,G5 as Vg,L5 as Wg,W5 as Xg,Y5 as Yg,X5 as Zg,H5 as _g};
733
+ export{X4 as Ag,H4 as Bg,F4 as Cg,I1 as Dg,S4 as Eg,z4 as Fg,o as Gg,f4 as Hg,D1 as Ig,g as Jg,x as Kg,e0 as Lg,I0 as Mg,C as Ng,Q0 as Og,J1 as Pg,x0 as Qg,m as Rg,CO as Sg,C0 as Tg,NO as Ug,Z4 as Vg,K5 as Wg,G5 as Xg,L5 as Yg,W5 as Zg,Y5 as _g,X5 as $g,H5 as ah};
@@ -1,2 +1,2 @@
1
- import{tg as B}from"./chunk-hvmrcd84.js";import{Kj as Y}from"./chunk-svsgtj41.js";import{Nj as Z,Qj as $}from"./chunk-2g8avyq6.js";import{createHash as H}from"node:crypto";var N="fast-mode-2026-02-01";function R(q,x,z){if(x.api!=="anthropic-messages"||z.providerValue!=="fast")return q;let J={...q},w=Object.keys(J).find((G)=>G.toLowerCase()==="anthropic-beta")??"anthropic-beta",Q=new Set((J[w]??"").split(",").map((G)=>G.trim()).filter(Boolean));return Q.add(N),J[w]=[...Q].join(","),J}function D(q){return`BLADE_MODEL_API_KEY_${H("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function F(q,x){if(!q.fallbackModels?.length)return;return q.fallbackModels.map((z)=>{let J=(x.models??[]).filter((G)=>G.provider===z.provider&&G.model===z.model),w=z.configId?(x.models??[]).find((G)=>G.id===z.configId):J.length===1?J[0]:void 0;if(z.configId&&!w)throw Error(`Unknown fallback model config ID: ${z.configId}`);if(w&&(w.provider!==z.provider||w.model!==z.model))throw Error(`Fallback model config ${w.id} does not match ${z.provider}/${z.model}`);if(!z.configId&&J.length>1)throw Error(`Fallback model ${z.provider}/${z.model} is ambiguous; set configId`);if(!w)return z;let Q=w.provider===q.provider;return{...z,configId:w.id,channel:{apiKey:process.env[D(w.id)]??(Q?process.env.BLADE_API_KEY:void 0),baseUrl:w.overrides?.baseUrl??(Q?process.env.BLADE_BASE_URL:void 0),temperature:w.overrides?.temperature??x.temperature,maxOutputTokens:w.overrides?.maxOutputTokens,timeout:w.overrides?.timeout??x.timeout,streamIdleTimeout:w.overrides?.streamIdleTimeout,apiVersion:w.overrides?.apiVersion,customHeaders:w.overrides?.customHeaders,enablePromptCaching:w.overrides?.enablePromptCaching}}})}function h(q,x,z,J=Y(),w="auto",Q="auto"){let G=J.resolveConfig(q),U=B(G,z),W=$(G,w),X=Z(G,Q),L=q.overrides;return{config:q,model:G,displayName:q.displayName??G.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[D(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??L?.baseUrl,temperature:L?.temperature??x.temperature,maxContextTokens:G.contextWindow,maxOutputTokens:L?.maxOutputTokens,timeout:L?.timeout??x.timeout,streamIdleTimeout:L?.streamIdleTimeout,reasoningEnabled:U.effective!=="off",...U.effective==="off"?{}:{reasoningEffort:U.effective},...W.providerValue?{serviceTier:W.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:F(q,x),enablePromptCaching:L?.enablePromptCaching,customHeaders:R(L?.customHeaders,G,W),apiVersion:L?.apiVersion,maxRetries:L?.maxRetries,providerCircuitBreakerOpenMs:x.providerCircuitBreakerOpenMs,providerRequestConcurrency:x.providerRequestConcurrency,providerGlobalConcurrency:x.providerGlobalConcurrency,providerOwnerConcurrency:x.providerOwnerConcurrency,providerRequestAdmissionMs:x.providerRequestAdmissionMs,providerRequestPendingBytes:x.providerRequestPendingBytes,modelCatalog:J},reasoning:U,serviceTier:W,responseVerbosity:X}}function j(q,x=Y()){try{return q.displayName??x.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
- export{D as pg,h as qg,j as rg};
1
+ import{vg as B}from"./chunk-7wcxjbyg.js";import{Pj as Y}from"./chunk-j8hbddjp.js";import{Sj as Z,Vj as $}from"./chunk-4cdk4mds.js";import{createHash as H}from"node:crypto";var N="fast-mode-2026-02-01";function R(q,x,z){if(x.api!=="anthropic-messages"||z.providerValue!=="fast")return q;let J={...q},w=Object.keys(J).find((G)=>G.toLowerCase()==="anthropic-beta")??"anthropic-beta",Q=new Set((J[w]??"").split(",").map((G)=>G.trim()).filter(Boolean));return Q.add(N),J[w]=[...Q].join(","),J}function D(q){return`BLADE_MODEL_API_KEY_${H("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function F(q,x){if(!q.fallbackModels?.length)return;return q.fallbackModels.map((z)=>{let J=(x.models??[]).filter((G)=>G.provider===z.provider&&G.model===z.model),w=z.configId?(x.models??[]).find((G)=>G.id===z.configId):J.length===1?J[0]:void 0;if(z.configId&&!w)throw Error(`Unknown fallback model config ID: ${z.configId}`);if(w&&(w.provider!==z.provider||w.model!==z.model))throw Error(`Fallback model config ${w.id} does not match ${z.provider}/${z.model}`);if(!z.configId&&J.length>1)throw Error(`Fallback model ${z.provider}/${z.model} is ambiguous; set configId`);if(!w)return z;let Q=w.provider===q.provider;return{...z,configId:w.id,channel:{apiKey:process.env[D(w.id)]??(Q?process.env.BLADE_API_KEY:void 0),baseUrl:w.overrides?.baseUrl??(Q?process.env.BLADE_BASE_URL:void 0),temperature:w.overrides?.temperature??x.temperature,maxOutputTokens:w.overrides?.maxOutputTokens,timeout:w.overrides?.timeout??x.timeout,streamIdleTimeout:w.overrides?.streamIdleTimeout,apiVersion:w.overrides?.apiVersion,customHeaders:w.overrides?.customHeaders,enablePromptCaching:w.overrides?.enablePromptCaching}}})}function h(q,x,z,J=Y(),w="auto",Q="auto"){let G=J.resolveConfig(q),U=B(G,z),W=$(G,w),X=Z(G,Q),L=q.overrides;return{config:q,model:G,displayName:q.displayName??G.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[D(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??L?.baseUrl,temperature:L?.temperature??x.temperature,maxContextTokens:G.contextWindow,maxOutputTokens:L?.maxOutputTokens,timeout:L?.timeout??x.timeout,streamIdleTimeout:L?.streamIdleTimeout,reasoningEnabled:U.effective!=="off",...U.effective==="off"?{}:{reasoningEffort:U.effective},...W.providerValue?{serviceTier:W.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:F(q,x),enablePromptCaching:L?.enablePromptCaching,customHeaders:R(L?.customHeaders,G,W),apiVersion:L?.apiVersion,maxRetries:L?.maxRetries,providerCircuitBreakerOpenMs:x.providerCircuitBreakerOpenMs,providerRequestConcurrency:x.providerRequestConcurrency,providerGlobalConcurrency:x.providerGlobalConcurrency,providerOwnerConcurrency:x.providerOwnerConcurrency,providerRequestAdmissionMs:x.providerRequestAdmissionMs,providerRequestPendingBytes:x.providerRequestPendingBytes,modelCatalog:J},reasoning:U,serviceTier:W,responseVerbosity:X}}function j(q,x=Y()){try{return q.displayName??x.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
+ export{D as rg,h as sg,j as tg};
@@ -1,4 +1,4 @@
1
- import{da as p}from"./chunk-ppmy3n74.js";import{Mb as _}from"./chunk-we13xwds.js";import{Ad as z,Ld as q,ee as O,wd as N,xd as U,yd as I,zd as A}from"./chunk-n6tvswa8.js";import{qe as o}from"./chunk-es0cbtx1.js";import{ag as P}from"./chunk-c562kd2m.js";import{Bg as e}from"./chunk-xagh2qb6.js";import{xk as j}from"./chunk-mnk0b4nz.js";import{createHash as ff}from"node:crypto";var af=4,cf=1000,E=4000,wf=120000,M=0.2;function $f(a){try{return q(a)&&a.retryable}catch{return!1}}function gf(a,c){let f=Number.isSafeInteger(c)&&c>0?c:1,w=f-1,h=Math.min(cf*2**w,E),$=ff("sha256").update(`${a}\x00${f}`).digest().readUInt32BE(0)/4294967295,k=1-M+2*M*$;return Math.min(E,Math.max(0,Math.round(h*k)))}function Tf(a){let c=gf(a.sessionIdentity,a.failedAttempt),f=a.evidence,w=a.workStillPending===!0&&f!==void 0&&$f(f.taskFailure)&&f.outputStarted===!1&&f.toolExecutionStarted===!1&&Number.isInteger(f.toolCallsCount)&&f.toolCallsCount===0,h=Number.isSafeInteger(a.failedAttempt)&&a.failedAttempt>0&&a.failedAttempt<af,g=a.now??Date.now(),$=g-a.recoveryStartedAt,k=Number.isFinite(g)&&Number.isFinite(a.recoveryStartedAt)&&Number.isFinite($)&&$>=0&&$+c<=wf;return{phase:w?h&&k?"retry_scheduled":"exhausted":"failed",delayMs:c,retryable:w,withinAttemptBudget:h,withinTimeBudget:k}}import R from"node:path";import{nanoid as Lf}from"nanoid";import{execFile as hf}from"node:child_process";import{createHash as xf}from"node:crypto";import{lstat as bf,readFile as mf,realpath as i}from"node:fs/promises";import n from"node:path";import{promisify as kf}from"node:util";var lf=kf(hf),T=8388608,s=500,u=200;async function C(a,c){try{return(await lf("git",["-c","core.pager=cat",...c],{cwd:a,encoding:"utf8",timeout:30000,maxBuffer:T+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let w=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${T} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${w}`)}}function d(a,c){let f=a?.trim();if(!f||f.length>u||f.includes("\x00")||f.includes(`
1
+ import{da as p}from"./chunk-1xa8z2h3.js";import{Ob as _}from"./chunk-10947adv.js";import{Ad as I,Bd as A,Cd as z,Nd as q,ge as O,yd as N,zd as U}from"./chunk-bwm0jt16.js";import{se as o}from"./chunk-fd7ez529.js";import{cg as P}from"./chunk-7xhw74hk.js";import{Dg as e}from"./chunk-s6x7fme7.js";import{Ck as j}from"./chunk-4wx5sya5.js";import{createHash as ff}from"node:crypto";var af=4,cf=1000,E=4000,wf=120000,M=0.2;function $f(a){try{return q(a)&&a.retryable}catch{return!1}}function gf(a,c){let f=Number.isSafeInteger(c)&&c>0?c:1,w=f-1,h=Math.min(cf*2**w,E),$=ff("sha256").update(`${a}\x00${f}`).digest().readUInt32BE(0)/4294967295,k=1-M+2*M*$;return Math.min(E,Math.max(0,Math.round(h*k)))}function Tf(a){let c=gf(a.sessionIdentity,a.failedAttempt),f=a.evidence,w=a.workStillPending===!0&&f!==void 0&&$f(f.taskFailure)&&f.outputStarted===!1&&f.toolExecutionStarted===!1&&Number.isInteger(f.toolCallsCount)&&f.toolCallsCount===0,h=Number.isSafeInteger(a.failedAttempt)&&a.failedAttempt>0&&a.failedAttempt<af,g=a.now??Date.now(),$=g-a.recoveryStartedAt,k=Number.isFinite(g)&&Number.isFinite(a.recoveryStartedAt)&&Number.isFinite($)&&$>=0&&$+c<=wf;return{phase:w?h&&k?"retry_scheduled":"exhausted":"failed",delayMs:c,retryable:w,withinAttemptBudget:h,withinTimeBudget:k}}import R from"node:path";import{nanoid as Lf}from"nanoid";import{execFile as hf}from"node:child_process";import{createHash as xf}from"node:crypto";import{lstat as bf,readFile as mf,realpath as i}from"node:fs/promises";import n from"node:path";import{promisify as kf}from"node:util";var lf=kf(hf),T=8388608,s=500,u=200;async function C(a,c){try{return(await lf("git",["-c","core.pager=cat",...c],{cwd:a,encoding:"utf8",timeout:30000,maxBuffer:T+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let w=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${T} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${w}`)}}function d(a,c){let f=a?.trim();if(!f||f.length>u||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${c} must contain 1-${u} characters`);return f}function Q(a){return a.split("\x00").filter(Boolean)}async function X(a,c){return(await C(a,["rev-parse","--verify",`${c}^{commit}`])).trim()}async function Ff(a,c,f,w,h){let g=h,$=await i(a);for(let k of c){let l=n.resolve($,k),x=n.relative($,l);if(!x||x.startsWith("..")||n.isAbsolute(x))throw Error(`Untracked review path escapes the workspace: ${k}`);let b=await bf(l);if(!b.isFile()||b.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${k}`);if(g+=b.size,g>T)throw Error(`Review target exceeds ${T} bytes`);f.update("\x00untracked\x00"),f.update(x.replaceAll(n.sep,"/")),f.update("\x00");let F=await mf(l);f.update(F);let m=Math.max(1,F.toString("utf8").split(`
3
3
  `).length);w.set(x.replaceAll(n.sep,"/"),[{start:1,end:m}])}}function Y(a,c){let f=new Map,w,h,g,$,k=!1,l=(x,b)=>{let F=f.get(x)??[],m=F.at(-1);if(m&&b<=m.end+1)m.end=Math.max(m.end,b);else F.push({start:b,end:b});f.set(x,F)};for(let x of a.split(`
4
4
  `)){if(x.startsWith("--- ")){let b=x.slice(4).split("\t")[0]?.trim();w=b&&b!=="/dev/null"?b.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(x.startsWith("+++ ")){let b=x.slice(4).split("\t")[0]?.trim();k=b==="/dev/null",h=k?w:b?b.replace(/^b\//,"").replaceAll("\\","/"):void 0,g=void 0,$=void 0;continue}if(x.startsWith("@@ ")){let b=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(x);g=b?Math.max(1,Number(b[1])):void 0,$=b?Math.max(1,Number(b[2])):void 0;continue}if(!h||g===void 0||$===void 0)continue;if(x.startsWith("+")&&!x.startsWith("+++"))l(h,$),$++;else if(x.startsWith("-")&&!x.startsWith("---"))l(h,k?g:$),g++;else if(!x.startsWith("\\"))g++,$++}for(let x of c)if(!f.has(x))f.set(x,[{start:1,end:1}]);return f}function D(a){if(a.length>s)throw Error(`Review target exceeds the ${s} file limit`)}class K{static async resolve(a,c){let f=await i(a);await C(f,["rev-parse","--is-inside-work-tree"]);let w=await X(f,"HEAD"),h=xf("sha256");h.update(`kind\x00${c.kind}\x00head\x00${w}\x00`);let g="",$=[],k,l,x,b,F=new Map;switch(c.kind){case"uncommitted":{g=await C(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=Q(await C(f,["diff","--name-only","-z","--relative","HEAD","--","."])),L=Q(await C(f,["ls-files","--others","--exclude-standard","-z","--","."]));if($=[...new Set([...m,...L])].sort(),D($),$.length===0)throw Error("No uncommitted changes to review");h.update(g),F=Y(g,m),await Ff(f,L,h,F,Buffer.byteLength(g)),x="uncommitted changes",b=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=d(c.ref,"Base ref");k=await X(f,m);let L=(await C(f,["merge-base",k,w])).trim();if(g=await C(f,["diff","--binary","--no-ext-diff","--relative",`${L}..${w}`,"--","."]),$=Q(await C(f,["diff","--name-only","-z","--relative",`${L}..${w}`,"--","."])),D($),$.length===0)throw Error(`No changes between ${m} and HEAD`);h.update(g),h.update(`\x00merge-base\x00${L}`),F=Y(g,$),x=`changes against ${m}`,b=`Review changes introduced by ${L}..${w}.`;break}case"commit":{let m=d(c.ref,"Commit ref");if(l=await X(f,m),g=await C(f,["show","--format=","--binary","--no-ext-diff","--relative",l,"--","."]),$=Q(await C(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",l,"--","."])),D($),$.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);h.update(g),h.update(`\x00commit\x00${l}`),F=Y(g,$),x=`commit ${m}`,b=`Review only the changes introduced by commit ${l}.`;break}}if(Buffer.byteLength(g)>T)throw Error(`Review diff exceeds ${T} bytes`);return{info:{kind:c.kind,label:x,headSha:w,...k?{baseSha:k}:{},...l?{commitSha:l}:{},digest:h.digest("hex"),fileCount:$.length},instruction:b,changedLines:F}}}var Wf=131072,t=50,Z=new Set;function v(a,c){return`${R.resolve(a)}\x00${c}`}function S(a){return`/review ${a.kind}${a.kind==="uncommitted"?"":` ${a.ref?.trim()??""}`}`}function V(a,c,f,w=!1){if(typeof a!=="string")throw Error(`${c} must be a string`);let h=a.trim();if(!w&&!h||h.length>f)throw Error(`${c} exceeds its allowed length`);return h}function Hf(a,c,f){if(!a||typeof a!=="object"||Array.isArray(a))throw Error("Review finding must be an object");let w=a,h=typeof w.line==="number"&&Number.isInteger(w.line)?w.line:void 0,g=w.code_location??(typeof w.file==="string"&&h!==void 0?{path:w.file,line_start:h,line_end:h}:void 0);if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Review finding has no code_location");let $=g,k=V($.path,"Finding path",1000),l=R.posix.normalize(k.replaceAll("\\","/"));if(R.posix.isAbsolute(l)||l===".."||l.startsWith("../"))throw Error("Review finding path must be workspace-relative");let x=R.resolve(c,l),b=R.relative(R.resolve(c),x);if(b.startsWith("..")||R.isAbsolute(b))throw Error("Review finding path escapes the workspace");let F=typeof w.severity==="string"?w.severity.toLowerCase():"",m=F==="critical"?0:F==="high"?1:F==="medium"?2:F==="low"?3:void 0,L=w.priority??m;if(L!==0&&L!==1&&L!==2&&L!==3)throw Error("Review finding priority must be 0-3");let W=w.confidence_score??w.confidence??0.8;if(typeof W!=="number"||!Number.isFinite(W)||W<0||W>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:H,line_end:r}=$;if(!Number.isInteger(H)||!Number.isInteger(r)||H<1||r<H||r-H>=10)throw Error("Review finding line range is invalid");let G=f.changedLines.get(l);if(!G)throw Error("Review finding path is outside the review target");if(!G.some((y)=>H<=y.end&&r>=y.start))throw Error("Review finding line range does not overlap the changed lines");let B=V(w.title??`[P${L}] ${String(w.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(y)=>y.toUpperCase())}`,"Finding title",120);if(!B.startsWith(`[P${L}] `))throw Error("Review finding title priority does not match priority");return{title:B,body:V(w.body??w.description,"Finding body",4000),priority:L,confidenceScore:W,codeLocation:{path:l,lineStart:H,lineEnd:r}}}function Rf(a,c,f){if(Buffer.byteLength(a)>Wf)throw Error("Review output exceeds the 128 KiB limit");let w=a.indexOf("{"),h=a.lastIndexOf("}");if(w<0||h<=w)throw Error("Reviewer did not return a JSON object");let g;try{g=JSON.parse(a.slice(w,h+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Reviewer output must be an object");let $=g;if(!Array.isArray($.findings))throw Error("Reviewer output must contain findings");if($.findings.length>t)throw Error(`Reviewer returned more than ${t} findings`);return{overallExplanation:V($.overall_explanation??$.summary,"Review explanation",1e4,!0),findings:$.findings.map((k)=>Hf(k,c,f))}}async function J(a,c){return new o(j(a,c)).readAll()}class rf{static async start(a){let{sessionId:c,projectPath:f,runtime:w,request:h,onEvent:g}=a;if(w.sessionId!==c||R.resolve(w.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(w.hasTurnOwner())throw Error("Cannot start a review during an active turn");await O.assertSessionWritable(c,f);let $=v(f,c);if(Z.has($))throw Error("Session already has an active review");let k=await J(f,c);if(U(k))throw Error("Session has an interrupted review that must be recovered");let l=h.instructions?.trim();if(l&&l.length>4000)throw Error("Review instructions exceed 4,000 characters");let x=await K.resolve(f,h),b=Lf(16),F=P("review"),m=new Date().toISOString(),L={reviewId:b,reviewerSessionId:F,target:x.info,startedAt:m},W=new _(f);await W.saveReviewStart(c,L),await W.saveMessage(c,"user",S(h),null,{codeReview:{reviewId:b,phase:"started",targetKind:x.info.kind,targetDigest:x.info.digest}}),await O.updateSessionMetadata(c,f,{taskStatus:"running",taskStatusReason:`Reviewing ${x.info.label}`,taskPromptSummary:S(h),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),Z.add($);let H=this.execute({...a,target:x,reviewId:b,reviewerSessionId:F,instructions:l,store:W,onEvent:g}).finally(()=>{Z.delete($)});return{reviewId:b,completion:H}}static async execute(a){let{sessionId:c,projectPath:f,runtime:w,request:h,signal:g,onEvent:$,target:k,reviewId:l,reviewerSessionId:x,instructions:b,store:F}=a,m;try{let W=[k.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${k.info.digest}`,`Changed file count: ${k.info.fileCount}`,b?`Additional review instructions:
@@ -1,4 +1,4 @@
1
- import{Ba as L,za as F}from"./chunk-ppmy3n74.js";import{Wd as $,Yd as B,ee as Q}from"./chunk-n6tvswa8.js";import{Vg as y}from"./chunk-xagh2qb6.js";import{Yi as V}from"./chunk-g38d2ezm.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
1
+ import{Ba as L,za as F}from"./chunk-1xa8z2h3.js";import{Yd as $,_d as B,ge as Q}from"./chunk-bwm0jt16.js";import{Xg as y}from"./chunk-s6x7fme7.js";import{bj as V}from"./chunk-2f8d0km4.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
2
2
 
3
3
  ${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{j as p,I as q,M as r,R as s,_ as t,C as u};
@@ -0,0 +1 @@
1
+ import{$j as f,Wj as a,Xj as b,Yj as c,Zj as d,_j as e}from"./chunk-pe6kcmvn.js";import"./chunk-eg3ms291.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -15,4 +15,4 @@ More specific user instructions about presentation take precedence for that resp
15
15
  <communication_style>
16
16
  ${h.prompt}
17
17
  </communication_style>`}
18
- export{R as mh,z as nh,H as oh,W as ph,Z as qh};
18
+ export{R as rh,z as sh,H as th,W as uh,Z as vh};