sliccy 5.64.0 → 5.65.0

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 (71) hide show
  1. package/dist/node-server/_cloud_core/tests/e2b-workerd-patch.test.d.ts +2 -0
  2. package/dist/node-server/_cloud_core/tests/e2b-workerd-patch.test.d.ts.map +1 -0
  3. package/dist/node-server/_cloud_core/tests/e2b-workerd-patch.test.js +27 -0
  4. package/dist/node-server/_shared/tray-sync-protocol.d.ts +15 -0
  5. package/dist/node-server/_shared/tray-sync-protocol.d.ts.map +1 -1
  6. package/dist/node-server/_shared/tray-sync-protocol.js.map +1 -1
  7. package/dist/ui/assets/{account-store-0KfyaB_Y.js → account-store-CK-N94Ou.js} +1 -1
  8. package/dist/ui/assets/{account-store-O8B4A1Cp.js → account-store-DBH6AYjF.js} +1 -1
  9. package/dist/ui/assets/{adobe-BA1lmOYx.js → adobe-BYSVTvmv.js} +1 -1
  10. package/dist/ui/assets/{adobe-DPWNL1tn.js → adobe-Byh9WsIW.js} +1 -1
  11. package/dist/ui/assets/{apps--X4sn_V2.js → apps-uHATN2fM.js} +1 -1
  12. package/dist/ui/assets/{azure-openai-DWNTc7zl.js → azure-openai-C1XJjbYl.js} +1 -1
  13. package/dist/ui/assets/{azure-openai-DG3rPUFz.js → azure-openai-WkZ8spz3.js} +1 -1
  14. package/dist/ui/assets/{cerebras-D8FzL0rQ.js → cerebras-DA8bHzeO.js} +1 -1
  15. package/dist/ui/assets/{cerebras-_3t84WRb.js → cerebras-d6g3fFrY.js} +1 -1
  16. package/dist/ui/assets/{connect-surface-DaZKS0Lr.js → connect-surface-C-sQsVm2.js} +1 -1
  17. package/dist/ui/assets/{fs-DVjU94G5.js → fs-BAbgPf5q.js} +1 -1
  18. package/dist/ui/assets/{fs-Bu2r8jU8.js → fs-D7BpCwRt.js} +2 -2
  19. package/dist/ui/assets/{github-DBqthTVS.js → github-68iLVdCs.js} +1 -1
  20. package/dist/ui/assets/{github-IAPS6ldF.js → github-BnId_hvT.js} +2 -2
  21. package/dist/ui/assets/{github-copilot-CYCZVUKg.js → github-copilot-CU-jRR03.js} +1 -1
  22. package/dist/ui/assets/{github-copilot-BCnsU1ES.js → github-copilot-Ctek3hky.js} +1 -1
  23. package/dist/ui/assets/{kernel-worker-DwA7Ndre.js → kernel-worker-D2aGb_82.js} +18 -18
  24. package/dist/ui/assets/leader-session-events-m7I5BMZy.js +1 -0
  25. package/dist/ui/assets/{lick-ws-bridge-BkMe-xPV.js → lick-ws-bridge-CJh2_Uld.js} +1 -1
  26. package/dist/ui/assets/{local-llm-BW8Tu5rb.js → local-llm-C00fbHJr.js} +1 -1
  27. package/dist/ui/assets/{local-llm-BaiaM-eK.js → local-llm-CPSWctNS.js} +1 -1
  28. package/dist/ui/assets/{main-BtekKitA.js → main-CmZaYL6M.js} +3 -3
  29. package/dist/ui/assets/{mount-DXVsSVpg.js → mount-BO2basnO.js} +2 -2
  30. package/dist/ui/assets/{mount-YiUVBgZj.js → mount-FCXht0UA.js} +1 -1
  31. package/dist/ui/assets/{mount-recovery-B98mAfuD.js → mount-recovery-Bbg4vjsg.js} +1 -1
  32. package/dist/ui/assets/{new-session-C7oDK2Kk.js → new-session-fSh3JDic.js} +2 -2
  33. package/dist/ui/assets/{oauth-bootstrap-B_ydSM5a.js → oauth-bootstrap-C6MrQSJ4.js} +2 -2
  34. package/dist/ui/assets/{openai-codex-Cx2WiSHz.js → openai-codex-B_EviANH.js} +1 -1
  35. package/dist/ui/assets/{openai-codex-Dx55_uE7.js → openai-codex-Bd8504PC.js} +1 -1
  36. package/dist/ui/assets/page-follower-tray-CuPgRSdw.js +5 -0
  37. package/dist/ui/assets/{panel-rpc-handlers-g-IcBZgz.js → panel-rpc-handlers-rjB40MzJ.js} +2 -2
  38. package/dist/ui/assets/{provider-D7tuUspk.js → provider-DQbRhNCb.js} +2 -2
  39. package/dist/ui/assets/{provider-DlfrkDnN.js → provider-DXYk5b_-.js} +1 -1
  40. package/dist/ui/assets/{provider-settings-DXZqWMxH.js → provider-settings-AHSP9_xw.js} +1 -1
  41. package/dist/ui/assets/{provider-settings-CLFfVTte.js → provider-settings-BAQroSjB.js} +1 -1
  42. package/dist/ui/assets/provider-store-access-CBm2YBYD.js +1 -0
  43. package/dist/ui/assets/{provider-store-access-B48zmrjF.js → provider-store-access-CX6QCCkY.js} +2 -2
  44. package/dist/ui/assets/{providers-DSGqRskI.js → providers-CMlMnOkB.js} +1 -1
  45. package/dist/ui/assets/{providers-C5IxOdJy.js → providers-lerk0za2.js} +2 -2
  46. package/dist/ui/assets/{quick-llm-DEwzmM-S.js → quick-llm-B7BQQiYz.js} +1 -1
  47. package/dist/ui/assets/{session-freezer-DdYYo55y.js → session-freezer-81utLS2y.js} +2 -2
  48. package/dist/ui/assets/{setup-sudo-CpuvPX2I.js → setup-sudo-h7qRDT2t.js} +2 -2
  49. package/dist/ui/assets/{skills-CllGu9dI.js → skills-AlJ6rIGf.js} +1 -1
  50. package/dist/ui/assets/{store-DJbSm8Z_.js → store-D5jYcqHh.js} +1 -1
  51. package/dist/ui/assets/{sudo-xF6nYDZf.js → sudo-FsW0M_G3.js} +1 -1
  52. package/dist/ui/assets/{upgrade-detection-Cein6N3L.js → upgrade-detection-B4owg_Xz.js} +1 -1
  53. package/dist/ui/assets/{wc-extension-D3wWW1XJ.js → wc-extension-7TX44Qkh.js} +2 -2
  54. package/dist/ui/assets/{wc-follower-DwatFMHA.js → wc-follower-C--23seG.js} +3 -3
  55. package/dist/ui/assets/wc-live-CUrQxCqR.js +8 -0
  56. package/dist/ui/assets/{wc-nav-wVpt4FYo.js → wc-nav-BDEr5OE6.js} +2 -2
  57. package/dist/ui/assets/{wc-onboarding-B5Jx6i_M.js → wc-onboarding-2Kx6qZhM.js} +2 -2
  58. package/dist/ui/assets/{wc-placeholder-DJEXeUOp.js → wc-placeholder-DxR1_zlj.js} +2 -2
  59. package/dist/ui/assets/{wc-settings-HdKp6PRa.js → wc-settings-C91mtm3p.js} +2 -2
  60. package/dist/ui/assets/{wc-shell-BcLe36CI.js → wc-shell-BSCmpIWS.js} +2 -2
  61. package/dist/ui/assets/{wc-sprinkles-Ce05-7PD.js → wc-sprinkles-Dn2Fn2mr.js} +2 -2
  62. package/dist/ui/assets/wc-tray-BV5t38Gb.js +2 -0
  63. package/dist/ui/assets/{xai-grok-170AT997.js → xai-grok-CI55pQsA.js} +1 -1
  64. package/dist/ui/assets/{xai-grok-C2qHyLFl.js → xai-grok-EQeZdJC8.js} +1 -1
  65. package/dist/ui/index.html +5 -5
  66. package/dist/ui/packages/webapp/index.html +5 -5
  67. package/package.json +2 -2
  68. package/dist/ui/assets/page-follower-tray-DFeLlotx.js +0 -5
  69. package/dist/ui/assets/provider-store-access-2_FnhYqS.js +0 -1
  70. package/dist/ui/assets/wc-live-DcaNrDBs.js +0 -8
  71. package/dist/ui/assets/wc-tray-CLX4el5K.js +0 -2
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/account-store-0KfyaB_Y.js","assets/rolldown-runtime-aKtaBQYM.js","assets/preload-helper-Czpn1I53.js","assets/compat-DyT25qXb.js","assets/models-CzSI8IsT.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/context-compaction-dcYYajWb.js","assets/logger-DDBAeTLF.js","assets/src-CS5gSDhT.js","assets/proxied-fetch-DETjVL-j.js","assets/base64-DpPqYZJF.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-D2k1IxFk.js","assets/secrets-bridge-client-CONYX8PU.js","assets/port-bridge-client-CdvMlimf.js","assets/tool-ui-DfXu6quJ.js","assets/providers-C5IxOdJy.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-BEi8MYUS.js","assets/transform-messages-fFaW-DLG.js"])))=>i.map(i=>d[i]);
2
- import{t as e}from"./preload-helper-Czpn1I53.js";import{t}from"./mime-types-ugOWOUZ9.js";import{n,t as r}from"./base64-DpPqYZJF.js";import"./src-CS5gSDhT.js";import{o as i,r as a,t as o}from"./proxied-fetch-DETjVL-j.js";import{n as s}from"./runtime-env-DH4NDw4t.js";import{t as c}from"./types-idfTVsM8.js";import"./backend-local-smcj-_Ox.js";import"./mount-table-store-CfQUN_2R.js";import{t as l}from"./mount-bridge-client-BVLVI9yX.js";function u(e,t,n){let r=`----DaMount${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,i=new TextEncoder,a=i.encode(`--${r}\r\nContent-Disposition: form-data; name="data"; filename="${e}"\r\nContent-Type: ${t}\r\n\r\n`),o=i.encode(`\r\n--${r}--\r\n`),s=new Uint8Array(a.byteLength+n.byteLength+o.byteLength);return s.set(a,0),s.set(n,a.byteLength),s.set(o,a.byteLength+n.byteLength),{contentType:`multipart/form-data; boundary=${r}`,body:s}}function d(e){return e.split(`/`).pop()||`data`}function f(e){let t=e.match(/^da:\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid DA source '${e}' — expected da://org/repo[/path]`);return{org:t[1],repo:t[2],path:(t[3]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var p=5*1024*1024,m=class{kind=`da`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=f(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??p,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new c(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toSourcePath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/source/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}toListPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/list/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,path:this.toSourcePath(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new c(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new c(`EACCES`,`da access denied`,e);if(i.status>=400)throw new c(`EIO`,`da readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes`,e);let s=new Uint8Array(await i.arrayBuffer());if(s.byteLength>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``,u=l.startsWith(`W/`)?l.slice(2):l;return await this.cache.putBody(t,s,u),s}async writeFile(e,n){if(this.assertOpen(e),n.byteLength>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=this.toMountRelative(e),i=await this.cache.getBody(r),a=u(d(e),t(e),n),o={"content-type":a.contentType,"content-length":String(a.body.byteLength)};i?.etag?o[`if-match`]=i.etag.startsWith(`W/`)?i.etag.slice(2):i.etag:i||(o[`if-none-match`]=`*`);let s=()=>this.transport({method:`POST`,path:this.toSourcePath(r),headers:o,body:a.body}),l,f=1;try{l=await s()}catch{f=2,l=await s()}if(l.status===412){if(f===2){let t=await this.transport({method:`HEAD`,path:this.toSourcePath(r)});if(t.status>=400)throw new c(`EIO`,`da reconcile HEAD failed: ${t.status}`,e);let i=t.headers.get(`etag`)??``;await this.cache.putBody(r,n,i);let a=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(r);try{await this.readFile(e)}catch{}throw new c(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(l.status===401||l.status===403)throw new c(`EACCES`,`da write denied`,e);if(l.status>=400)throw new c(`EIO`,`da writeFile failed: ${l.status}`,e);let p=l.headers.get(`etag`)??``;await this.cache.putBody(r,n,p);let m=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(m)}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.transport({method:`GET`,path:this.toListPath(t)});if(r.status===404)throw new c(`ENOENT`,`no such directory`,e);if(r.status>=400)throw new c(`EIO`,`da list failed: ${r.status}`,e);let i=(await r.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(t,i),i}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.size,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new c(`ENOENT`,`no such file or directory`,e)}let s=await this.transport({method:`HEAD`,path:this.toSourcePath(t)});if(s.status===200){let e=Number(s.headers.get(`content-length`)??`0`),t=s.headers.get(`etag`)??``,n=s.headers.get(`last-modified`),r=n?Date.parse(n):0;if(o){let n=o.entries.map(n=>n.name===i&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(a,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(s.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new c(`ENOENT`,`no such file or directory`,e)}throw new c(`EIO`,`da stat failed: ${s.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.transport({method:`DELETE`,path:this.toSourcePath(t)});if(n.status===404)throw new c(`ENOENT`,`no such file`,e);if(n.status===401||n.status===403)throw new c(`EACCES`,`da delete denied`,e);if(n.status>=400)throw new c(`EIO`,`da delete failed: ${n.status}`,e);await this.cache.invalidateBody(t);let r=t.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(r)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{await this.refreshDir(e,t,n)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}return e?.bodies&&await this.refreshBodies(t),t}async classifyFile(e,t,n){let r=await this.cache.getBody(e);r?t&&r.etag!==t?(await this.cache.invalidateBody(e),n.changed.push(e)):n.unchanged++:n.added.push(e)}async refreshDir(e,t,n){let r=await this.transport({method:`GET`,path:this.toListPath(e)});if(r.status>=400){t.errors.push({path:e,message:`list failed: ${r.status}`});return}let i=await r.json(),a=[];for(let r of i)if(r.ext){let n=e?`${e}/${r.name}.${r.ext}`:`${r.name}.${r.ext}`;a.push({name:`${r.name}.${r.ext}`,kind:`file`,etag:r.etag,lastModified:r.lastModified}),await this.classifyFile(n,r.etag,t)}else a.push({name:r.name,kind:`directory`}),n.push(e?`${e}/${r.name}`:r.name);await this.cache.putListing(e,a)}async refreshBodies(e){for(let t of e.changed)try{await this.readFile(t)}catch(n){e.errors.push({path:t,message:n instanceof Error?n.message:String(n)})}}describe(){return{displayName:`${this.parsed.org}/${this.parsed.repo}${this.parsed.path?`/${this.parsed.path}`:``}`,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function h(e){let t=e.match(/^s3:\/\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid S3 source '${e}' — expected s3://bucket[/prefix]`);return{bucket:t[1],prefix:(t[2]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var g=25*1024*1024,_=class{kind=`s3`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=h(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??g,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new c(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toS3Key(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``);return[this.parsed.prefix,t].filter(e=>e.length>0).join(`/`)}toMountRelativeKey(e){return this.parsed.prefix?e.slice(this.parsed.prefix.length+1):e}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new c(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new c(`EACCES`,`s3 access denied`,e);if(i.status>=400)throw new c(`EIO`,`s3 readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes (${o} > ${this.maxBodyBytes})`,e);let s=new Uint8Array(await i.arrayBuffer());if(s.byteLength>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``;return await this.cache.putBody(t,s,l),s}async writeFile(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t.byteLength>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=await this.cache.getBody(n),i={"content-type":`application/octet-stream`,"content-length":String(t.byteLength)};r?i[`if-match`]=r.etag:i[`if-none-match`]=`*`;let a=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:i,body:t}),o,s=1;try{o=await a()}catch{s=2,o=await a()}if(o.status===412){if(s===2){let r=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status>=400)throw new c(`EIO`,`s3 reconcile HEAD failed: ${r.status}`,e);let i=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,i);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new c(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(o.status===401||o.status===403)throw new c(`EACCES`,`s3 write denied`,e);if(o.status>=400)throw new c(`EIO`,`s3 writeFile failed: ${o.status}`,e);let l=o.headers.get(`etag`)??``;await this.cache.putBody(n,t,l);let u=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],t;do{let n={"list-type":`2`};this.parsed.prefix&&(n.prefix=`${this.parsed.prefix}/`),t&&(n[`continuation-token`]=t);let r=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:n});if(r.status>=400)throw new c(`EIO`,`s3 list failed: ${r.status}`,`/`);let i=await r.text(),a=this.parseListingXml(i);e.push(...a.contents),t=a.nextContinuationToken}while(t);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.body.byteLength,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new c(`ENOENT`,`no such file or directory`,e)}let s=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(t)});if(s.status===200){let e=Number(s.headers.get(`content-length`)??`0`),t=s.headers.get(`etag`)??``,n=s.headers.get(`last-modified`);return{kind:`file`,size:e,mtime:n?Date.parse(n):0,etag:t}}if(s.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new c(`ENOENT`,`no such file or directory`,e)}throw new c(`EIO`,`s3 stat failed: ${s.status}`,e)}async refresh(e){this.assertOpen(`/`);let t=await this.listObjectsV2(),n=new Set(t.map(e=>this.toMountRelativeKey(e.key))),r=new Map(t.map(e=>[this.toMountRelativeKey(e.key),e.etag])),i={added:[],removed:[],changed:[],unchanged:0,errors:[]};for(let e of n){let t=await this.cache.getBody(e),n=r.get(e);t?t.etag===n?i.unchanged++:(await this.cache.invalidateBody(e),i.changed.push(e)):i.added.push(e)}let a=this.groupByDir(t);for(let[e,t]of a)await this.cache.putListing(e,t);if(e?.bodies)for(let e of i.changed)try{await this.readFile(e)}catch(t){i.errors.push({path:e,message:t instanceof Error?t.message:String(t)})}return i}async mkdir(e){}async remove(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t?.recursive)throw new c(`EINVAL`,`recursive remove not yet supported on S3`,e);let r=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status===404)throw new c(`ENOENT`,`no such file`,e);if(r.status===401||r.status===403)throw new c(`EACCES`,`s3 delete denied`,e);if(r.status>=400)throw new c(`EIO`,`s3 delete failed: ${r.status}`,e);await this.cache.invalidateBody(n);let i=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}},v=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function y(){let{getAccounts:t}=await e(async()=>{let{getAccounts:e}=await import(`./account-store-0KfyaB_Y.js`).then(e=>e.r);return{getAccounts:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21])),n=t().find(e=>e.providerId===`adobe`);if(!n?.accessToken)throw new v(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>n.accessToken}}var b=`slicc-mount-cache`,x=`listings`,S=`bodies`,C=class{mountId;ttlMs;dbName;dbPromise=null;constructor(e){this.mountId=e.mountId,this.ttlMs=e.ttlMs,this.dbName=e.dbName??b}isStale(e,t){return Date.now()-e>=(t??this.ttlMs)}async openDb(){return this.dbPromise||=new Promise((e,t)=>{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(x)||e.createObjectStore(x),e.objectStoreNames.contains(S)||e.createObjectStore(S)},n.onsuccess=()=>{let t=n.result;t.onversionchange=()=>{t.close(),this.dbPromise=null},t.onclose=()=>{this.dbPromise=null},e(t)},n.onerror=()=>t(n.error)}),this.dbPromise}key(e){return`${this.mountId}::${e}`}async getListing(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(x,`readonly`).objectStore(x).get(this.key(e));i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async putListing(e,t){let n=await this.openDb();return new Promise((r,i)=>{let a=n.transaction(x,`readwrite`),o={entries:t,cachedAt:Date.now()};a.objectStore(x).put(o,this.key(e)),a.oncomplete=()=>r(),a.onerror=()=>i(a.error)})}async invalidateListing(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(x,`readwrite`);i.objectStore(x).delete(this.key(e)),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async getBody(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(S,`readonly`).objectStore(S).get(this.key(e));i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async putBody(e,t,n){let r=await this.openDb(),i={body:t,etag:n,size:t.byteLength,cachedAt:Date.now()};try{await this.txPut(r,S,this.key(e),i)}catch(t){if(t instanceof DOMException&&t.name===`QuotaExceededError`){await this.evictLru(.25);try{await this.txPut(r,S,this.key(e),i)}catch{}return}throw t}}async invalidateBody(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(S,`readwrite`);i.objectStore(S).delete(this.key(e)),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async clearMount(){let e=await this.openDb(),t=`${this.mountId}::`,n=n=>new Promise((r,i)=>{let a=e.transaction(n,`readwrite`),o=a.objectStore(n),s=o.getAllKeys();s.onsuccess=()=>{for(let e of s.result)typeof e==`string`&&e.startsWith(t)&&o.delete(e)},a.oncomplete=()=>r(),a.onerror=()=>i(a.error)});await Promise.all([n(x),n(S)])}txPut(e,t,n,r){return new Promise((i,a)=>{let o=e.transaction(t,`readwrite`);o.objectStore(t).put(r,n),o.oncomplete=()=>i(),o.onerror=()=>a(o.error)})}async evictLru(e){let t=await this.openDb(),n=`${this.mountId}::`,r=await new Promise((e,r)=>{let i=t.transaction(S,`readonly`).objectStore(S),a=[],o=i.openCursor();o.onsuccess=()=>{let t=o.result;if(!t){e(a);return}if(typeof t.key==`string`&&t.key.startsWith(n)){let e=t.value;a.push({key:t.key,cachedAt:e.cachedAt})}t.continue()},o.onerror=()=>r(o.error)});r.sort((e,t)=>e.cachedAt-t.cachedAt);let i=Math.max(1,Math.ceil(r.length*e)),a=r.slice(0,i);await new Promise((e,n)=>{let r=t.transaction(S,`readwrite`),i=r.objectStore(S);for(let{key:e}of a)i.delete(e);r.oncomplete=()=>e(),r.onerror=()=>n(r.error)})}},w=r,T=n,E=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),D=new Set([101,103,204,205,304]);function O(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new c(`EACCES`,e.error):e.errorCode===`invalid_request`?new c(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||E.has(String(e.errorCode))?new c(`EIO`,e.error):new c(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let t;try{t=w(e.bodyBase64)}catch(e){throw new c(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let n=D.has(e.status)?null:t;return new Response(n,{status:e.status,headers:new Headers(e.headers)})}async function k(e,t){let n;try{n=await fetch(i(e),{method:`POST`,headers:o({"content-type":`application/json`}),body:JSON.stringify(t)})}catch(e){throw new c(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await n.json()}catch(e){throw new c(`EIO`,`mount transport: response is not a JSON envelope (status ${n.status}): ${e instanceof Error?e.message:String(e)}`)}}async function A(e,t){try{return await chrome.runtime.sendMessage({type:e,envelope:t})}catch(e){throw new c(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}async function j(e,t,n){return s()?A(e,n):a()?l(e,n):k(t,n)}function M(e){return async t=>O(await j(`mount.s3-sign-and-forward`,`/api/s3-sign-and-forward`,{profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?T(t.body):void 0}))}function N(e){let t=e?.getImsToken??(async()=>(await y()).getBearerToken());return async e=>{let n;try{n=await t()}catch(e){throw new c(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}return O(await j(`mount.da-sign-and-forward`,`/api/da-sign-and-forward`,{imsToken:n,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?T(e.body):void 0}))}}export{m as DaMountBackend,C as RemoteMountCache,_ as S3MountBackend,N as makeSignedFetchDa,M as makeSignedFetchS3};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/account-store-CK-N94Ou.js","assets/rolldown-runtime-aKtaBQYM.js","assets/preload-helper-Czpn1I53.js","assets/compat-DyT25qXb.js","assets/models-CzSI8IsT.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/context-compaction-dcYYajWb.js","assets/logger-DDBAeTLF.js","assets/src-CS5gSDhT.js","assets/proxied-fetch-DETjVL-j.js","assets/base64-DpPqYZJF.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-D2k1IxFk.js","assets/secrets-bridge-client-CONYX8PU.js","assets/port-bridge-client-CdvMlimf.js","assets/tool-ui-DfXu6quJ.js","assets/providers-lerk0za2.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-BEi8MYUS.js","assets/transform-messages-fFaW-DLG.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./preload-helper-Czpn1I53.js";import{t}from"./mime-types-ugOWOUZ9.js";import{n,t as r}from"./base64-DpPqYZJF.js";import"./src-CS5gSDhT.js";import{o as i,r as a,t as o}from"./proxied-fetch-DETjVL-j.js";import{n as s}from"./runtime-env-DH4NDw4t.js";import{t as c}from"./types-idfTVsM8.js";import"./backend-local-smcj-_Ox.js";import"./mount-table-store-CfQUN_2R.js";import{t as l}from"./mount-bridge-client-BVLVI9yX.js";function u(e,t,n){let r=`----DaMount${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,i=new TextEncoder,a=i.encode(`--${r}\r\nContent-Disposition: form-data; name="data"; filename="${e}"\r\nContent-Type: ${t}\r\n\r\n`),o=i.encode(`\r\n--${r}--\r\n`),s=new Uint8Array(a.byteLength+n.byteLength+o.byteLength);return s.set(a,0),s.set(n,a.byteLength),s.set(o,a.byteLength+n.byteLength),{contentType:`multipart/form-data; boundary=${r}`,body:s}}function d(e){return e.split(`/`).pop()||`data`}function f(e){let t=e.match(/^da:\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid DA source '${e}' — expected da://org/repo[/path]`);return{org:t[1],repo:t[2],path:(t[3]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var p=5*1024*1024,m=class{kind=`da`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=f(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??p,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new c(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toSourcePath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/source/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}toListPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/list/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,path:this.toSourcePath(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new c(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new c(`EACCES`,`da access denied`,e);if(i.status>=400)throw new c(`EIO`,`da readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes`,e);let s=new Uint8Array(await i.arrayBuffer());if(s.byteLength>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``,u=l.startsWith(`W/`)?l.slice(2):l;return await this.cache.putBody(t,s,u),s}async writeFile(e,n){if(this.assertOpen(e),n.byteLength>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=this.toMountRelative(e),i=await this.cache.getBody(r),a=u(d(e),t(e),n),o={"content-type":a.contentType,"content-length":String(a.body.byteLength)};i?.etag?o[`if-match`]=i.etag.startsWith(`W/`)?i.etag.slice(2):i.etag:i||(o[`if-none-match`]=`*`);let s=()=>this.transport({method:`POST`,path:this.toSourcePath(r),headers:o,body:a.body}),l,f=1;try{l=await s()}catch{f=2,l=await s()}if(l.status===412){if(f===2){let t=await this.transport({method:`HEAD`,path:this.toSourcePath(r)});if(t.status>=400)throw new c(`EIO`,`da reconcile HEAD failed: ${t.status}`,e);let i=t.headers.get(`etag`)??``;await this.cache.putBody(r,n,i);let a=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(r);try{await this.readFile(e)}catch{}throw new c(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(l.status===401||l.status===403)throw new c(`EACCES`,`da write denied`,e);if(l.status>=400)throw new c(`EIO`,`da writeFile failed: ${l.status}`,e);let p=l.headers.get(`etag`)??``;await this.cache.putBody(r,n,p);let m=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(m)}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.transport({method:`GET`,path:this.toListPath(t)});if(r.status===404)throw new c(`ENOENT`,`no such directory`,e);if(r.status>=400)throw new c(`EIO`,`da list failed: ${r.status}`,e);let i=(await r.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(t,i),i}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.size,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new c(`ENOENT`,`no such file or directory`,e)}let s=await this.transport({method:`HEAD`,path:this.toSourcePath(t)});if(s.status===200){let e=Number(s.headers.get(`content-length`)??`0`),t=s.headers.get(`etag`)??``,n=s.headers.get(`last-modified`),r=n?Date.parse(n):0;if(o){let n=o.entries.map(n=>n.name===i&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(a,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(s.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new c(`ENOENT`,`no such file or directory`,e)}throw new c(`EIO`,`da stat failed: ${s.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.transport({method:`DELETE`,path:this.toSourcePath(t)});if(n.status===404)throw new c(`ENOENT`,`no such file`,e);if(n.status===401||n.status===403)throw new c(`EACCES`,`da delete denied`,e);if(n.status>=400)throw new c(`EIO`,`da delete failed: ${n.status}`,e);await this.cache.invalidateBody(t);let r=t.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(r)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{await this.refreshDir(e,t,n)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}return e?.bodies&&await this.refreshBodies(t),t}async classifyFile(e,t,n){let r=await this.cache.getBody(e);r?t&&r.etag!==t?(await this.cache.invalidateBody(e),n.changed.push(e)):n.unchanged++:n.added.push(e)}async refreshDir(e,t,n){let r=await this.transport({method:`GET`,path:this.toListPath(e)});if(r.status>=400){t.errors.push({path:e,message:`list failed: ${r.status}`});return}let i=await r.json(),a=[];for(let r of i)if(r.ext){let n=e?`${e}/${r.name}.${r.ext}`:`${r.name}.${r.ext}`;a.push({name:`${r.name}.${r.ext}`,kind:`file`,etag:r.etag,lastModified:r.lastModified}),await this.classifyFile(n,r.etag,t)}else a.push({name:r.name,kind:`directory`}),n.push(e?`${e}/${r.name}`:r.name);await this.cache.putListing(e,a)}async refreshBodies(e){for(let t of e.changed)try{await this.readFile(t)}catch(n){e.errors.push({path:t,message:n instanceof Error?n.message:String(n)})}}describe(){return{displayName:`${this.parsed.org}/${this.parsed.repo}${this.parsed.path?`/${this.parsed.path}`:``}`,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function h(e){let t=e.match(/^s3:\/\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid S3 source '${e}' — expected s3://bucket[/prefix]`);return{bucket:t[1],prefix:(t[2]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var g=25*1024*1024,_=class{kind=`s3`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=h(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??g,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new c(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toS3Key(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``);return[this.parsed.prefix,t].filter(e=>e.length>0).join(`/`)}toMountRelativeKey(e){return this.parsed.prefix?e.slice(this.parsed.prefix.length+1):e}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new c(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new c(`EACCES`,`s3 access denied`,e);if(i.status>=400)throw new c(`EIO`,`s3 readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes (${o} > ${this.maxBodyBytes})`,e);let s=new Uint8Array(await i.arrayBuffer());if(s.byteLength>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``;return await this.cache.putBody(t,s,l),s}async writeFile(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t.byteLength>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=await this.cache.getBody(n),i={"content-type":`application/octet-stream`,"content-length":String(t.byteLength)};r?i[`if-match`]=r.etag:i[`if-none-match`]=`*`;let a=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:i,body:t}),o,s=1;try{o=await a()}catch{s=2,o=await a()}if(o.status===412){if(s===2){let r=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status>=400)throw new c(`EIO`,`s3 reconcile HEAD failed: ${r.status}`,e);let i=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,i);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new c(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(o.status===401||o.status===403)throw new c(`EACCES`,`s3 write denied`,e);if(o.status>=400)throw new c(`EIO`,`s3 writeFile failed: ${o.status}`,e);let l=o.headers.get(`etag`)??``;await this.cache.putBody(n,t,l);let u=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],t;do{let n={"list-type":`2`};this.parsed.prefix&&(n.prefix=`${this.parsed.prefix}/`),t&&(n[`continuation-token`]=t);let r=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:n});if(r.status>=400)throw new c(`EIO`,`s3 list failed: ${r.status}`,`/`);let i=await r.text(),a=this.parseListingXml(i);e.push(...a.contents),t=a.nextContinuationToken}while(t);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.body.byteLength,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new c(`ENOENT`,`no such file or directory`,e)}let s=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(t)});if(s.status===200){let e=Number(s.headers.get(`content-length`)??`0`),t=s.headers.get(`etag`)??``,n=s.headers.get(`last-modified`);return{kind:`file`,size:e,mtime:n?Date.parse(n):0,etag:t}}if(s.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new c(`ENOENT`,`no such file or directory`,e)}throw new c(`EIO`,`s3 stat failed: ${s.status}`,e)}async refresh(e){this.assertOpen(`/`);let t=await this.listObjectsV2(),n=new Set(t.map(e=>this.toMountRelativeKey(e.key))),r=new Map(t.map(e=>[this.toMountRelativeKey(e.key),e.etag])),i={added:[],removed:[],changed:[],unchanged:0,errors:[]};for(let e of n){let t=await this.cache.getBody(e),n=r.get(e);t?t.etag===n?i.unchanged++:(await this.cache.invalidateBody(e),i.changed.push(e)):i.added.push(e)}let a=this.groupByDir(t);for(let[e,t]of a)await this.cache.putListing(e,t);if(e?.bodies)for(let e of i.changed)try{await this.readFile(e)}catch(t){i.errors.push({path:e,message:t instanceof Error?t.message:String(t)})}return i}async mkdir(e){}async remove(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t?.recursive)throw new c(`EINVAL`,`recursive remove not yet supported on S3`,e);let r=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status===404)throw new c(`ENOENT`,`no such file`,e);if(r.status===401||r.status===403)throw new c(`EACCES`,`s3 delete denied`,e);if(r.status>=400)throw new c(`EIO`,`s3 delete failed: ${r.status}`,e);await this.cache.invalidateBody(n);let i=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}},v=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function y(){let{getAccounts:t}=await e(async()=>{let{getAccounts:e}=await import(`./account-store-CK-N94Ou.js`).then(e=>e.r);return{getAccounts:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21])),n=t().find(e=>e.providerId===`adobe`);if(!n?.accessToken)throw new v(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>n.accessToken}}var b=`slicc-mount-cache`,x=`listings`,S=`bodies`,C=class{mountId;ttlMs;dbName;dbPromise=null;constructor(e){this.mountId=e.mountId,this.ttlMs=e.ttlMs,this.dbName=e.dbName??b}isStale(e,t){return Date.now()-e>=(t??this.ttlMs)}async openDb(){return this.dbPromise||=new Promise((e,t)=>{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(x)||e.createObjectStore(x),e.objectStoreNames.contains(S)||e.createObjectStore(S)},n.onsuccess=()=>{let t=n.result;t.onversionchange=()=>{t.close(),this.dbPromise=null},t.onclose=()=>{this.dbPromise=null},e(t)},n.onerror=()=>t(n.error)}),this.dbPromise}key(e){return`${this.mountId}::${e}`}async getListing(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(x,`readonly`).objectStore(x).get(this.key(e));i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async putListing(e,t){let n=await this.openDb();return new Promise((r,i)=>{let a=n.transaction(x,`readwrite`),o={entries:t,cachedAt:Date.now()};a.objectStore(x).put(o,this.key(e)),a.oncomplete=()=>r(),a.onerror=()=>i(a.error)})}async invalidateListing(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(x,`readwrite`);i.objectStore(x).delete(this.key(e)),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async getBody(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(S,`readonly`).objectStore(S).get(this.key(e));i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async putBody(e,t,n){let r=await this.openDb(),i={body:t,etag:n,size:t.byteLength,cachedAt:Date.now()};try{await this.txPut(r,S,this.key(e),i)}catch(t){if(t instanceof DOMException&&t.name===`QuotaExceededError`){await this.evictLru(.25);try{await this.txPut(r,S,this.key(e),i)}catch{}return}throw t}}async invalidateBody(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(S,`readwrite`);i.objectStore(S).delete(this.key(e)),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async clearMount(){let e=await this.openDb(),t=`${this.mountId}::`,n=n=>new Promise((r,i)=>{let a=e.transaction(n,`readwrite`),o=a.objectStore(n),s=o.getAllKeys();s.onsuccess=()=>{for(let e of s.result)typeof e==`string`&&e.startsWith(t)&&o.delete(e)},a.oncomplete=()=>r(),a.onerror=()=>i(a.error)});await Promise.all([n(x),n(S)])}txPut(e,t,n,r){return new Promise((i,a)=>{let o=e.transaction(t,`readwrite`);o.objectStore(t).put(r,n),o.oncomplete=()=>i(),o.onerror=()=>a(o.error)})}async evictLru(e){let t=await this.openDb(),n=`${this.mountId}::`,r=await new Promise((e,r)=>{let i=t.transaction(S,`readonly`).objectStore(S),a=[],o=i.openCursor();o.onsuccess=()=>{let t=o.result;if(!t){e(a);return}if(typeof t.key==`string`&&t.key.startsWith(n)){let e=t.value;a.push({key:t.key,cachedAt:e.cachedAt})}t.continue()},o.onerror=()=>r(o.error)});r.sort((e,t)=>e.cachedAt-t.cachedAt);let i=Math.max(1,Math.ceil(r.length*e)),a=r.slice(0,i);await new Promise((e,n)=>{let r=t.transaction(S,`readwrite`),i=r.objectStore(S);for(let{key:e}of a)i.delete(e);r.oncomplete=()=>e(),r.onerror=()=>n(r.error)})}},w=r,T=n,E=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),D=new Set([101,103,204,205,304]);function O(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new c(`EACCES`,e.error):e.errorCode===`invalid_request`?new c(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||E.has(String(e.errorCode))?new c(`EIO`,e.error):new c(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let t;try{t=w(e.bodyBase64)}catch(e){throw new c(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let n=D.has(e.status)?null:t;return new Response(n,{status:e.status,headers:new Headers(e.headers)})}async function k(e,t){let n;try{n=await fetch(i(e),{method:`POST`,headers:o({"content-type":`application/json`}),body:JSON.stringify(t)})}catch(e){throw new c(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await n.json()}catch(e){throw new c(`EIO`,`mount transport: response is not a JSON envelope (status ${n.status}): ${e instanceof Error?e.message:String(e)}`)}}async function A(e,t){try{return await chrome.runtime.sendMessage({type:e,envelope:t})}catch(e){throw new c(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}async function j(e,t,n){return s()?A(e,n):a()?l(e,n):k(t,n)}function M(e){return async t=>O(await j(`mount.s3-sign-and-forward`,`/api/s3-sign-and-forward`,{profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?T(t.body):void 0}))}function N(e){let t=e?.getImsToken??(async()=>(await y()).getBearerToken());return async e=>{let n;try{n=await t()}catch(e){throw new c(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}return O(await j(`mount.da-sign-and-forward`,`/api/da-sign-and-forward`,{imsToken:n,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?T(e.body):void 0}))}}export{m as DaMountBackend,C as RemoteMountCache,_ as S3MountBackend,N as makeSignedFetchDa,M as makeSignedFetchS3};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{m as t,o as n,p as r,r as i,t as a}from"./proxied-fetch-sbHa3Tte.js";import"./src-Dk1QVJRd.js";import{t as o}from"./runtime-env-byAg9ij-.js";import"./backend-local-D4WZgy4J.js";import{t as s}from"./types-idfTVsM8.js";import{t as c}from"./mime-types-D7IV6i7k.js";import{t as l}from"./remote-cache-D59F5FOx.js";import{t as u}from"./port-bridge-client-CsrXhMWo.js";function d(e,t,n){let r=`----DaMount${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,i=new TextEncoder,a=i.encode(`--${r}\r\nContent-Disposition: form-data; name="data"; filename="${e}"\r\nContent-Type: ${t}\r\n\r\n`),o=i.encode(`\r\n--${r}--\r\n`),s=new Uint8Array(a.byteLength+n.byteLength+o.byteLength);return s.set(a,0),s.set(n,a.byteLength),s.set(o,a.byteLength+n.byteLength),{contentType:`multipart/form-data; boundary=${r}`,body:s}}function f(e){return e.split(`/`).pop()||`data`}function p(e){let t=e.match(/^da:\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid DA source '${e}' — expected da://org/repo[/path]`);return{org:t[1],repo:t[2],path:(t[3]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var m=class{kind=`da`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=p(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??5242880,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new s(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toSourcePath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/source/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}toListPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/list/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,path:this.toSourcePath(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new s(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new s(`EACCES`,`da access denied`,e);if(i.status>=400)throw new s(`EIO`,`da readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let c=new Uint8Array(await i.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``,u=l.startsWith(`W/`)?l.slice(2):l;return await this.cache.putBody(t,c,u),c}async writeFile(e,t){if(this.assertOpen(e),t.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let n=this.toMountRelative(e),r=await this.cache.getBody(n),i=d(f(e),c(e),t),a={"content-type":i.contentType,"content-length":String(i.body.byteLength)};r?.etag?a[`if-match`]=r.etag.startsWith(`W/`)?r.etag.slice(2):r.etag:r||(a[`if-none-match`]=`*`);let o=()=>this.transport({method:`POST`,path:this.toSourcePath(n),headers:a,body:i.body}),l,u=1;try{l=await o()}catch{u=2,l=await o()}if(l.status===412){if(u===2){let r=await this.transport({method:`HEAD`,path:this.toSourcePath(n)});if(r.status>=400)throw new s(`EIO`,`da reconcile HEAD failed: ${r.status}`,e);let i=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,i);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new s(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(l.status===401||l.status===403)throw new s(`EACCES`,`da write denied`,e);if(l.status>=400)throw new s(`EIO`,`da writeFile failed: ${l.status}`,e);let p=l.headers.get(`etag`)??``;await this.cache.putBody(n,t,p);let m=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(m)}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.transport({method:`GET`,path:this.toListPath(t)});if(r.status===404)throw new s(`ENOENT`,`no such directory`,e);if(r.status>=400)throw new s(`EIO`,`da list failed: ${r.status}`,e);let i=(await r.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(t,i),i}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.size,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new s(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,path:this.toSourcePath(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`),r=n?Date.parse(n):0;if(o){let n=o.entries.map(n=>n.name===i&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(a,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new s(`ENOENT`,`no such file or directory`,e)}throw new s(`EIO`,`da stat failed: ${c.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.transport({method:`DELETE`,path:this.toSourcePath(t)});if(n.status===404)throw new s(`ENOENT`,`no such file`,e);if(n.status===401||n.status===403)throw new s(`EACCES`,`da delete denied`,e);if(n.status>=400)throw new s(`EIO`,`da delete failed: ${n.status}`,e);await this.cache.invalidateBody(t);let r=t.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(r)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{await this.refreshDir(e,t,n)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}return e?.bodies&&await this.refreshBodies(t),t}async classifyFile(e,t,n){let r=await this.cache.getBody(e);r?t&&r.etag!==t?(await this.cache.invalidateBody(e),n.changed.push(e)):n.unchanged++:n.added.push(e)}async refreshDir(e,t,n){let r=await this.transport({method:`GET`,path:this.toListPath(e)});if(r.status>=400){t.errors.push({path:e,message:`list failed: ${r.status}`});return}let i=await r.json(),a=[];for(let r of i)if(r.ext){let n=e?`${e}/${r.name}.${r.ext}`:`${r.name}.${r.ext}`;a.push({name:`${r.name}.${r.ext}`,kind:`file`,etag:r.etag,lastModified:r.lastModified}),await this.classifyFile(n,r.etag,t)}else a.push({name:r.name,kind:`directory`}),n.push(e?`${e}/${r.name}`:r.name);await this.cache.putListing(e,a)}async refreshBodies(e){for(let t of e.changed)try{await this.readFile(t)}catch(n){e.errors.push({path:t,message:n instanceof Error?n.message:String(n)})}}describe(){return{displayName:`${this.parsed.org}/${this.parsed.repo}${this.parsed.path?`/${this.parsed.path}`:``}`,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function h(e){let t=e.match(/^s3:\/\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid S3 source '${e}' — expected s3://bucket[/prefix]`);return{bucket:t[1],prefix:(t[2]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var g=class{kind=`s3`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=h(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??26214400,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new s(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toS3Key(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``);return[this.parsed.prefix,t].filter(e=>e.length>0).join(`/`)}toMountRelativeKey(e){return this.parsed.prefix?e.slice(this.parsed.prefix.length+1):e}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new s(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new s(`EACCES`,`s3 access denied`,e);if(i.status>=400)throw new s(`EIO`,`s3 readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes (${o} > ${this.maxBodyBytes})`,e);let c=new Uint8Array(await i.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``;return await this.cache.putBody(t,c,l),c}async writeFile(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=await this.cache.getBody(n),i={"content-type":`application/octet-stream`,"content-length":String(t.byteLength)};r?i[`if-match`]=r.etag:i[`if-none-match`]=`*`;let a=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:i,body:t}),o,c=1;try{o=await a()}catch{c=2,o=await a()}if(o.status===412){if(c===2){let r=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status>=400)throw new s(`EIO`,`s3 reconcile HEAD failed: ${r.status}`,e);let i=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,i);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new s(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(o.status===401||o.status===403)throw new s(`EACCES`,`s3 write denied`,e);if(o.status>=400)throw new s(`EIO`,`s3 writeFile failed: ${o.status}`,e);let l=o.headers.get(`etag`)??``;await this.cache.putBody(n,t,l);let u=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],t;do{let n={"list-type":`2`};this.parsed.prefix&&(n.prefix=`${this.parsed.prefix}/`),t&&(n[`continuation-token`]=t);let r=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:n});if(r.status>=400)throw new s(`EIO`,`s3 list failed: ${r.status}`,`/`);let i=await r.text(),a=this.parseListingXml(i);e.push(...a.contents),t=a.nextContinuationToken}while(t);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.body.byteLength,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new s(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`);return{kind:`file`,size:e,mtime:n?Date.parse(n):0,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new s(`ENOENT`,`no such file or directory`,e)}throw new s(`EIO`,`s3 stat failed: ${c.status}`,e)}async refresh(e){this.assertOpen(`/`);let t=await this.listObjectsV2(),n=new Set(t.map(e=>this.toMountRelativeKey(e.key))),r=new Map(t.map(e=>[this.toMountRelativeKey(e.key),e.etag])),i={added:[],removed:[],changed:[],unchanged:0,errors:[]};for(let e of n){let t=await this.cache.getBody(e),n=r.get(e);t?t.etag===n?i.unchanged++:(await this.cache.invalidateBody(e),i.changed.push(e)):i.added.push(e)}let a=this.groupByDir(t);for(let[e,t]of a)await this.cache.putListing(e,t);if(e?.bodies)for(let e of i.changed)try{await this.readFile(e)}catch(t){i.errors.push({path:e,message:t instanceof Error?t.message:String(t)})}return i}async mkdir(e){}async remove(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t?.recursive)throw new s(`EINVAL`,`recursive remove not yet supported on S3`,e);let r=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status===404)throw new s(`ENOENT`,`no such file`,e);if(r.status===401||r.status===403)throw new s(`EACCES`,`s3 delete denied`,e);if(r.status>=400)throw new s(`EIO`,`s3 delete failed: ${r.status}`,e);await this.cache.invalidateBody(n);let i=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}},_=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function v(){let{getAccounts:e}=await import(`./account-store-O8B4A1Cp.js`).then(e=>e.n),t=e().find(e=>e.providerId===`adobe`);if(!t?.accessToken)throw new _(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>t.accessToken}}const y=u({portName:`mount.sign-and-forward`,panelRpcOp:`mount-sign-and-forward`,timeoutMs:12e4,onUnavailable:`reject`,makeError:e=>new s(`EIO`,`mount transport failed: ${e}`),logNamespace:`mount-bridge`,toPortMessage:({type:e,envelope:t})=>({type:e,envelope:t}),toPanelRpcPayload:({type:e,envelope:t})=>({type:e,envelope:t})});function b(e,t){return y({type:e,envelope:t})}const x=r,S=t,C=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),w=new Set([101,103,204,205,304]);function T(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new s(`EACCES`,e.error):e.errorCode===`invalid_request`?new s(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||C.has(String(e.errorCode))?new s(`EIO`,e.error):new s(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let t;try{t=x(e.bodyBase64)}catch(e){throw new s(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let n=w.has(e.status)?null:t;return new Response(n,{status:e.status,headers:new Headers(e.headers)})}async function E(e,t){let r;try{r=await fetch(n(e),{method:`POST`,headers:a({"content-type":`application/json`}),body:JSON.stringify(t)})}catch(e){throw new s(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await r.json()}catch(e){throw new s(`EIO`,`mount transport: response is not a JSON envelope (status ${r.status}): ${e instanceof Error?e.message:String(e)}`)}}async function D(e,t){try{return await chrome.runtime.sendMessage({type:e,envelope:t})}catch(e){throw new s(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}async function O(e,t,n){return o()?D(e,n):i()?b(e,n):E(t,n)}function k(e){return async t=>T(await O(`mount.s3-sign-and-forward`,`/api/s3-sign-and-forward`,{profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?S(t.body):void 0}))}function A(e){let t=e?.getImsToken??(async()=>(await v()).getBearerToken());return async e=>{let n;try{n=await t()}catch(e){throw new s(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}return T(await O(`mount.da-sign-and-forward`,`/api/da-sign-and-forward`,{imsToken:n,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?S(e.body):void 0}))}}var j=e({DaMountBackend:()=>m,RemoteMountCache:()=>l,S3MountBackend:()=>g,makeSignedFetchDa:()=>A,makeSignedFetchS3:()=>k});export{m as a,g as i,A as n,k as r,j as t};
1
+ import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{m as t,o as n,p as r,r as i,t as a}from"./proxied-fetch-sbHa3Tte.js";import"./src-Dk1QVJRd.js";import{t as o}from"./runtime-env-byAg9ij-.js";import"./backend-local-D4WZgy4J.js";import{t as s}from"./types-idfTVsM8.js";import{t as c}from"./mime-types-D7IV6i7k.js";import{t as l}from"./remote-cache-D59F5FOx.js";import{t as u}from"./port-bridge-client-CsrXhMWo.js";function d(e,t,n){let r=`----DaMount${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,i=new TextEncoder,a=i.encode(`--${r}\r\nContent-Disposition: form-data; name="data"; filename="${e}"\r\nContent-Type: ${t}\r\n\r\n`),o=i.encode(`\r\n--${r}--\r\n`),s=new Uint8Array(a.byteLength+n.byteLength+o.byteLength);return s.set(a,0),s.set(n,a.byteLength),s.set(o,a.byteLength+n.byteLength),{contentType:`multipart/form-data; boundary=${r}`,body:s}}function f(e){return e.split(`/`).pop()||`data`}function p(e){let t=e.match(/^da:\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid DA source '${e}' — expected da://org/repo[/path]`);return{org:t[1],repo:t[2],path:(t[3]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var m=class{kind=`da`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=p(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??5242880,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new s(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toSourcePath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/source/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}toListPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/list/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,path:this.toSourcePath(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new s(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new s(`EACCES`,`da access denied`,e);if(i.status>=400)throw new s(`EIO`,`da readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let c=new Uint8Array(await i.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``,u=l.startsWith(`W/`)?l.slice(2):l;return await this.cache.putBody(t,c,u),c}async writeFile(e,t){if(this.assertOpen(e),t.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let n=this.toMountRelative(e),r=await this.cache.getBody(n),i=d(f(e),c(e),t),a={"content-type":i.contentType,"content-length":String(i.body.byteLength)};r?.etag?a[`if-match`]=r.etag.startsWith(`W/`)?r.etag.slice(2):r.etag:r||(a[`if-none-match`]=`*`);let o=()=>this.transport({method:`POST`,path:this.toSourcePath(n),headers:a,body:i.body}),l,u=1;try{l=await o()}catch{u=2,l=await o()}if(l.status===412){if(u===2){let r=await this.transport({method:`HEAD`,path:this.toSourcePath(n)});if(r.status>=400)throw new s(`EIO`,`da reconcile HEAD failed: ${r.status}`,e);let i=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,i);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new s(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(l.status===401||l.status===403)throw new s(`EACCES`,`da write denied`,e);if(l.status>=400)throw new s(`EIO`,`da writeFile failed: ${l.status}`,e);let p=l.headers.get(`etag`)??``;await this.cache.putBody(n,t,p);let m=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(m)}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.transport({method:`GET`,path:this.toListPath(t)});if(r.status===404)throw new s(`ENOENT`,`no such directory`,e);if(r.status>=400)throw new s(`EIO`,`da list failed: ${r.status}`,e);let i=(await r.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(t,i),i}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.size,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new s(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,path:this.toSourcePath(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`),r=n?Date.parse(n):0;if(o){let n=o.entries.map(n=>n.name===i&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(a,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new s(`ENOENT`,`no such file or directory`,e)}throw new s(`EIO`,`da stat failed: ${c.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.transport({method:`DELETE`,path:this.toSourcePath(t)});if(n.status===404)throw new s(`ENOENT`,`no such file`,e);if(n.status===401||n.status===403)throw new s(`EACCES`,`da delete denied`,e);if(n.status>=400)throw new s(`EIO`,`da delete failed: ${n.status}`,e);await this.cache.invalidateBody(t);let r=t.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(r)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{await this.refreshDir(e,t,n)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}return e?.bodies&&await this.refreshBodies(t),t}async classifyFile(e,t,n){let r=await this.cache.getBody(e);r?t&&r.etag!==t?(await this.cache.invalidateBody(e),n.changed.push(e)):n.unchanged++:n.added.push(e)}async refreshDir(e,t,n){let r=await this.transport({method:`GET`,path:this.toListPath(e)});if(r.status>=400){t.errors.push({path:e,message:`list failed: ${r.status}`});return}let i=await r.json(),a=[];for(let r of i)if(r.ext){let n=e?`${e}/${r.name}.${r.ext}`:`${r.name}.${r.ext}`;a.push({name:`${r.name}.${r.ext}`,kind:`file`,etag:r.etag,lastModified:r.lastModified}),await this.classifyFile(n,r.etag,t)}else a.push({name:r.name,kind:`directory`}),n.push(e?`${e}/${r.name}`:r.name);await this.cache.putListing(e,a)}async refreshBodies(e){for(let t of e.changed)try{await this.readFile(t)}catch(n){e.errors.push({path:t,message:n instanceof Error?n.message:String(n)})}}describe(){return{displayName:`${this.parsed.org}/${this.parsed.repo}${this.parsed.path?`/${this.parsed.path}`:``}`,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function h(e){let t=e.match(/^s3:\/\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid S3 source '${e}' — expected s3://bucket[/prefix]`);return{bucket:t[1],prefix:(t[2]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var g=class{kind=`s3`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=h(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??26214400,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new s(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toS3Key(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``);return[this.parsed.prefix,t].filter(e=>e.length>0).join(`/`)}toMountRelativeKey(e){return this.parsed.prefix?e.slice(this.parsed.prefix.length+1):e}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new s(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new s(`EACCES`,`s3 access denied`,e);if(i.status>=400)throw new s(`EIO`,`s3 readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes (${o} > ${this.maxBodyBytes})`,e);let c=new Uint8Array(await i.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``;return await this.cache.putBody(t,c,l),c}async writeFile(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=await this.cache.getBody(n),i={"content-type":`application/octet-stream`,"content-length":String(t.byteLength)};r?i[`if-match`]=r.etag:i[`if-none-match`]=`*`;let a=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:i,body:t}),o,c=1;try{o=await a()}catch{c=2,o=await a()}if(o.status===412){if(c===2){let r=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status>=400)throw new s(`EIO`,`s3 reconcile HEAD failed: ${r.status}`,e);let i=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,i);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new s(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(o.status===401||o.status===403)throw new s(`EACCES`,`s3 write denied`,e);if(o.status>=400)throw new s(`EIO`,`s3 writeFile failed: ${o.status}`,e);let l=o.headers.get(`etag`)??``;await this.cache.putBody(n,t,l);let u=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],t;do{let n={"list-type":`2`};this.parsed.prefix&&(n.prefix=`${this.parsed.prefix}/`),t&&(n[`continuation-token`]=t);let r=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:n});if(r.status>=400)throw new s(`EIO`,`s3 list failed: ${r.status}`,`/`);let i=await r.text(),a=this.parseListingXml(i);e.push(...a.contents),t=a.nextContinuationToken}while(t);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.body.byteLength,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new s(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`);return{kind:`file`,size:e,mtime:n?Date.parse(n):0,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new s(`ENOENT`,`no such file or directory`,e)}throw new s(`EIO`,`s3 stat failed: ${c.status}`,e)}async refresh(e){this.assertOpen(`/`);let t=await this.listObjectsV2(),n=new Set(t.map(e=>this.toMountRelativeKey(e.key))),r=new Map(t.map(e=>[this.toMountRelativeKey(e.key),e.etag])),i={added:[],removed:[],changed:[],unchanged:0,errors:[]};for(let e of n){let t=await this.cache.getBody(e),n=r.get(e);t?t.etag===n?i.unchanged++:(await this.cache.invalidateBody(e),i.changed.push(e)):i.added.push(e)}let a=this.groupByDir(t);for(let[e,t]of a)await this.cache.putListing(e,t);if(e?.bodies)for(let e of i.changed)try{await this.readFile(e)}catch(t){i.errors.push({path:e,message:t instanceof Error?t.message:String(t)})}return i}async mkdir(e){}async remove(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t?.recursive)throw new s(`EINVAL`,`recursive remove not yet supported on S3`,e);let r=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status===404)throw new s(`ENOENT`,`no such file`,e);if(r.status===401||r.status===403)throw new s(`EACCES`,`s3 delete denied`,e);if(r.status>=400)throw new s(`EIO`,`s3 delete failed: ${r.status}`,e);await this.cache.invalidateBody(n);let i=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}},_=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function v(){let{getAccounts:e}=await import(`./account-store-DBH6AYjF.js`).then(e=>e.n),t=e().find(e=>e.providerId===`adobe`);if(!t?.accessToken)throw new _(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>t.accessToken}}const y=u({portName:`mount.sign-and-forward`,panelRpcOp:`mount-sign-and-forward`,timeoutMs:12e4,onUnavailable:`reject`,makeError:e=>new s(`EIO`,`mount transport failed: ${e}`),logNamespace:`mount-bridge`,toPortMessage:({type:e,envelope:t})=>({type:e,envelope:t}),toPanelRpcPayload:({type:e,envelope:t})=>({type:e,envelope:t})});function b(e,t){return y({type:e,envelope:t})}const x=r,S=t,C=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),w=new Set([101,103,204,205,304]);function T(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new s(`EACCES`,e.error):e.errorCode===`invalid_request`?new s(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||C.has(String(e.errorCode))?new s(`EIO`,e.error):new s(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let t;try{t=x(e.bodyBase64)}catch(e){throw new s(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let n=w.has(e.status)?null:t;return new Response(n,{status:e.status,headers:new Headers(e.headers)})}async function E(e,t){let r;try{r=await fetch(n(e),{method:`POST`,headers:a({"content-type":`application/json`}),body:JSON.stringify(t)})}catch(e){throw new s(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await r.json()}catch(e){throw new s(`EIO`,`mount transport: response is not a JSON envelope (status ${r.status}): ${e instanceof Error?e.message:String(e)}`)}}async function D(e,t){try{return await chrome.runtime.sendMessage({type:e,envelope:t})}catch(e){throw new s(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}async function O(e,t,n){return o()?D(e,n):i()?b(e,n):E(t,n)}function k(e){return async t=>T(await O(`mount.s3-sign-and-forward`,`/api/s3-sign-and-forward`,{profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?S(t.body):void 0}))}function A(e){let t=e?.getImsToken??(async()=>(await v()).getBearerToken());return async e=>{let n;try{n=await t()}catch(e){throw new s(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}return T(await O(`mount.da-sign-and-forward`,`/api/da-sign-and-forward`,{imsToken:n,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?S(e.body):void 0}))}}var j=e({DaMountBackend:()=>m,RemoteMountCache:()=>l,S3MountBackend:()=>g,makeSignedFetchDa:()=>A,makeSignedFetchS3:()=>k});export{m as a,g as i,A as n,k as r,j as t};
@@ -1,2 +1,2 @@
1
- import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./backend-local-D4WZgy4J.js";import{a as n,i as r,n as i,r as a}from"./mount-YiUVBgZj.js";import{n as o}from"./mount-table-store-CTrzlrNn.js";import{t as s}from"./remote-cache-D59F5FOx.js";var c=e({formatMountRecoveryPrompt:()=>f,mdInlineCode:()=>d,recoverMounts:()=>l,shellQuote:()=>u});async function l(e,c,l){let u=[],d=[];for(let f of e){let{targetPath:e,descriptor:p}=f;if(p.kind===`local`){let n=await o(p.idbHandleKey),r=typeof n?.name==`string`?n.name:``;if(!n||!(`queryPermission`in n)){d.push({kind:`local`,path:e,dirName:r});continue}let i;try{i=await n.queryPermission({mode:`readwrite`})}catch(t){l?.warn?.(`queryPermission threw on persisted handle`,{path:e,error:t instanceof Error?t.message:String(t)}),d.push({kind:`local`,path:e,dirName:r});continue}if(i!==`granted`){d.push({kind:`local`,path:e,dirName:r});continue}try{let i=t.fromHandle(n,{mountId:p.mountId});await c.mount(e,i),l?.info?.(`Restored mount from previous session`,{path:e,name:r}),u.push({kind:`local`,path:e,dirName:r})}catch(t){l?.warn?.(`Failed to re-mount persisted handle`,{path:e,error:t instanceof Error?t.message:String(t)}),d.push({kind:`local`,path:e,dirName:r})}continue}if(p.kind===`s3`){try{let t=new s({mountId:p.mountId,ttlMs:3e4}),n=new r({source:p.source,profile:p.profile,cache:t,mountId:p.mountId,signedFetch:a(p.profile)});await c.mount(e,n),l?.info?.(`Restored S3 mount from previous session`,{path:e,source:p.source}),u.push({kind:`s3`,path:e,source:p.source,profile:p.profile,reason:``})}catch(t){let n=t instanceof Error?t.message:String(t);l?.warn?.(`Failed to restore S3 mount`,{path:e,error:n}),d.push({kind:`s3`,path:e,source:p.source,profile:p.profile,reason:n})}continue}if(p.kind===`da`)try{let t=new s({mountId:p.mountId,ttlMs:3e4}),r=new n({source:p.source,profile:p.profile,cache:t,mountId:p.mountId,signedFetch:i()});await c.mount(e,r),l?.info?.(`Restored DA mount from previous session`,{path:e,source:p.source}),u.push({kind:`da`,path:e,source:p.source,profile:p.profile,reason:``})}catch(t){let n=t instanceof Error?t.message:String(t);l?.warn?.(`Failed to restore DA mount`,{path:e,error:n}),d.push({kind:`da`,path:e,source:p.source,profile:p.profile,reason:n})}}return{restored:u,needsRecovery:d}}function u(e){return`'${e.replace(/'/g,`'\\''`)}'`}function d(e){let t=e.replace(/\r\n|[\r\n]/g,` `),n=t.match(/`+/g),r=n?Math.max(...n.map(e=>e.length))+1:1,i="`".repeat(r);return`${i}${t.startsWith("`")||t.endsWith("`")?` ${t} `:t}${i}`}function f(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.length===1?`mount point`:`mount points`,n=e.length===1?`it`:`them`,r=e.filter(e=>e.kind===`local`),i=e.filter(e=>e.kind===`s3`||e.kind===`da`),a=[`[Session Reload] Mount recovery required for ${e.length} ${t}.`,``];if(r.length>0){let e=r.map(({path:e,dirName:t})=>{let n=t?` (previously mounted from ${d(t)})`:``;return`- ${d(e)}${n}`}),i=r.map(({path:e})=>` mount ${u(e)}`);a.push(`The page was reloaded and the following local ${t} lost filesystem permission. The browser cannot restore access without a fresh user gesture, so ${n} cannot be used until the user re-authorizes:`,``,...e,``,`Please tell the user what happened and ask whether they want to re-mount. If yes, run the corresponding command(s) so the folder picker opens and they can re-select the same directory:`,``,...i,``)}if(i.length>0){let e=i.map(({path:e,source:t,profile:n,reason:r})=>{let i=n==="default"?``:` --profile ${u(n)}`,a=`mount --source ${u(t)}${i} ${u(e)}`;return`- ${d(e)} (${d(t)}, profile ${d(n)}) — ${r}\n Retry: ${d(a)}`});a.push(`The following remote ${t} could not be auto-restored:`,``,...e,``)}return a.push("If the user no longer needs a mount, run `mount unmount <path>` (with the path shell-quoted the same way) to clear the stale entry instead."),a.join(`
1
+ import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./backend-local-D4WZgy4J.js";import{a as n,i as r,n as i,r as a}from"./mount-FCXht0UA.js";import{n as o}from"./mount-table-store-CTrzlrNn.js";import{t as s}from"./remote-cache-D59F5FOx.js";var c=e({formatMountRecoveryPrompt:()=>f,mdInlineCode:()=>d,recoverMounts:()=>l,shellQuote:()=>u});async function l(e,c,l){let u=[],d=[];for(let f of e){let{targetPath:e,descriptor:p}=f;if(p.kind===`local`){let n=await o(p.idbHandleKey),r=typeof n?.name==`string`?n.name:``;if(!n||!(`queryPermission`in n)){d.push({kind:`local`,path:e,dirName:r});continue}let i;try{i=await n.queryPermission({mode:`readwrite`})}catch(t){l?.warn?.(`queryPermission threw on persisted handle`,{path:e,error:t instanceof Error?t.message:String(t)}),d.push({kind:`local`,path:e,dirName:r});continue}if(i!==`granted`){d.push({kind:`local`,path:e,dirName:r});continue}try{let i=t.fromHandle(n,{mountId:p.mountId});await c.mount(e,i),l?.info?.(`Restored mount from previous session`,{path:e,name:r}),u.push({kind:`local`,path:e,dirName:r})}catch(t){l?.warn?.(`Failed to re-mount persisted handle`,{path:e,error:t instanceof Error?t.message:String(t)}),d.push({kind:`local`,path:e,dirName:r})}continue}if(p.kind===`s3`){try{let t=new s({mountId:p.mountId,ttlMs:3e4}),n=new r({source:p.source,profile:p.profile,cache:t,mountId:p.mountId,signedFetch:a(p.profile)});await c.mount(e,n),l?.info?.(`Restored S3 mount from previous session`,{path:e,source:p.source}),u.push({kind:`s3`,path:e,source:p.source,profile:p.profile,reason:``})}catch(t){let n=t instanceof Error?t.message:String(t);l?.warn?.(`Failed to restore S3 mount`,{path:e,error:n}),d.push({kind:`s3`,path:e,source:p.source,profile:p.profile,reason:n})}continue}if(p.kind===`da`)try{let t=new s({mountId:p.mountId,ttlMs:3e4}),r=new n({source:p.source,profile:p.profile,cache:t,mountId:p.mountId,signedFetch:i()});await c.mount(e,r),l?.info?.(`Restored DA mount from previous session`,{path:e,source:p.source}),u.push({kind:`da`,path:e,source:p.source,profile:p.profile,reason:``})}catch(t){let n=t instanceof Error?t.message:String(t);l?.warn?.(`Failed to restore DA mount`,{path:e,error:n}),d.push({kind:`da`,path:e,source:p.source,profile:p.profile,reason:n})}}return{restored:u,needsRecovery:d}}function u(e){return`'${e.replace(/'/g,`'\\''`)}'`}function d(e){let t=e.replace(/\r\n|[\r\n]/g,` `),n=t.match(/`+/g),r=n?Math.max(...n.map(e=>e.length))+1:1,i="`".repeat(r);return`${i}${t.startsWith("`")||t.endsWith("`")?` ${t} `:t}${i}`}function f(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.length===1?`mount point`:`mount points`,n=e.length===1?`it`:`them`,r=e.filter(e=>e.kind===`local`),i=e.filter(e=>e.kind===`s3`||e.kind===`da`),a=[`[Session Reload] Mount recovery required for ${e.length} ${t}.`,``];if(r.length>0){let e=r.map(({path:e,dirName:t})=>{let n=t?` (previously mounted from ${d(t)})`:``;return`- ${d(e)}${n}`}),i=r.map(({path:e})=>` mount ${u(e)}`);a.push(`The page was reloaded and the following local ${t} lost filesystem permission. The browser cannot restore access without a fresh user gesture, so ${n} cannot be used until the user re-authorizes:`,``,...e,``,`Please tell the user what happened and ask whether they want to re-mount. If yes, run the corresponding command(s) so the folder picker opens and they can re-select the same directory:`,``,...i,``)}if(i.length>0){let e=i.map(({path:e,source:t,profile:n,reason:r})=>{let i=n==="default"?``:` --profile ${u(n)}`,a=`mount --source ${u(t)}${i} ${u(e)}`;return`- ${d(e)} (${d(t)}, profile ${d(n)}) — ${r}\n Retry: ${d(a)}`});a.push(`The following remote ${t} could not be auto-restored:`,``,...e,``)}return a.push("If the user no longer needs a mount, run `mount unmount <path>` (with the path shell-quoted the same way) to clear the stale entry instead."),a.join(`
2
2
  `)}export{c as n,u as r,f as t};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/quick-llm-DEwzmM-S.js","assets/rolldown-runtime-aKtaBQYM.js","assets/compat-DyT25qXb.js","assets/models-CzSI8IsT.js","assets/preload-helper-Czpn1I53.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/account-store-0KfyaB_Y.js","assets/context-compaction-dcYYajWb.js","assets/logger-DDBAeTLF.js","assets/src-CS5gSDhT.js","assets/proxied-fetch-DETjVL-j.js","assets/base64-DpPqYZJF.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-D2k1IxFk.js","assets/secrets-bridge-client-CONYX8PU.js","assets/port-bridge-client-CdvMlimf.js","assets/tool-ui-DfXu6quJ.js","assets/providers-C5IxOdJy.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-BEi8MYUS.js","assets/transform-messages-fFaW-DLG.js","assets/llm-session-id-bZQs6gBN.js","assets/icons-C5g936Qd.js"])))=>i.map(i=>d[i]);
2
- import{t as e}from"./preload-helper-Czpn1I53.js";import{F as t,m as n}from"./account-store-0KfyaB_Y.js";import{t as r}from"./logger-DDBAeTLF.js";import"./provider-settings-CLFfVTte.js";import{t as i}from"./llm-session-id-bZQs6gBN.js";import{n as a,r as o}from"./session-freezer-DdYYo55y.js";import{SessionStore as s}from"./session-store-DAM8GRJ0.js";var c=r(`new-session`),l=`ui-new-session`,u=2e4,d=250;async function f(e,t,n,r){for(let i of n){let n=`${t}/${i.name}`;r.has(n)||i.type===`directory`&&(await f(e,n,await e.readDir(n),r),[...r].some(e=>e.startsWith(`${n}/`)))||await e.rm(n)}}async function p(e){let t=new Set((await e.listMountPoints()).map(({path:e})=>e).filter(e=>e===`/tmp`||e.startsWith(`/tmp/`)));if(t.has(`/tmp`))return;let n;try{n=await e.readDir(`/tmp`)}catch(t){if(t?.code!==`ENOENT`)throw t;await e.mkdir(`/tmp`,{recursive:!0});return}await f(e,`/tmp`,n,t),await e.mkdir(`/tmp`,{recursive:!0})}async function m(r){let d=r.enrichmentRaceMs??u,f=n()??void 0,p;try{p=t()}catch(e){c.info(`No active model — freezing without LLM enrichment`,{error:e instanceof Error?e.message:String(e)})}let m=p?.provider===`adobe`?{"X-Session-Id":i(l)}:void 0,g=new s;try{await g.init()}catch(e){return c.warn(`SessionStore init failed — cannot freeze`,{error:e instanceof Error?e.message:String(e)}),null}let _=await o({sessionStore:g,vfs:r.vfs,mode:`quick`});if(!_)return null;if(!f||!p)return c.info(`Frozen without enrichment (no LLM credentials) — left pending`,{filename:_.filename}),_;let v=p,y=a(r.vfs,_,{model:v,apiKey:f,headers:m,pickIcon:t=>e(async()=>{let{pickLucideIcon:e}=await import(`./quick-llm-DEwzmM-S.js`).then(e=>e.n);return{pickLucideIcon:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24])).then(({pickLucideIcon:e})=>e(t))}).catch(e=>(c.warn(`Single-click enrichment threw (entry stays pending)`,{filename:_.filename,error:e instanceof Error?e.message:String(e)}),null)),b=await h(y,d,r.onProgress);return b.kind===`llm`?b.updated?{...b.updated,archive:_.archive}:_:(y.then(e=>{c.info(`Background enrichment resolved after race window`,{filename:_.filename,enriched:e?.filename??null}),r.onBackgroundEnriched?.(e)}),_)}async function h(e,t,n){let r=Date.now(),i,a;n?.(0),n&&(i=setInterval(()=>{n(Math.min(1,(Date.now()-r)/t))},d));let o=new Promise(e=>{a=setTimeout(()=>e({kind:`timer`}),t)}),s=e.then(e=>({kind:`llm`,updated:e}));try{return await Promise.race([s,o])}finally{i&&clearInterval(i),a&&clearTimeout(a),n?.(null)}}async function g(e){let t=new s;try{await t.init()}catch(e){return c.warn(`SessionStore init failed — cannot quick-freeze`,{error:e instanceof Error?e.message:String(e)}),null}return o({sessionStore:t,vfs:e.vfs,mode:`quick`})}export{p as resetNewSessionTmp,m as runNewSessionFreeze,g as runNewSessionFreezeQuick};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/quick-llm-B7BQQiYz.js","assets/rolldown-runtime-aKtaBQYM.js","assets/compat-DyT25qXb.js","assets/models-CzSI8IsT.js","assets/preload-helper-Czpn1I53.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/account-store-CK-N94Ou.js","assets/context-compaction-dcYYajWb.js","assets/logger-DDBAeTLF.js","assets/src-CS5gSDhT.js","assets/proxied-fetch-DETjVL-j.js","assets/base64-DpPqYZJF.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-D2k1IxFk.js","assets/secrets-bridge-client-CONYX8PU.js","assets/port-bridge-client-CdvMlimf.js","assets/tool-ui-DfXu6quJ.js","assets/providers-lerk0za2.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-BEi8MYUS.js","assets/transform-messages-fFaW-DLG.js","assets/llm-session-id-bZQs6gBN.js","assets/icons-C5g936Qd.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./preload-helper-Czpn1I53.js";import{F as t,m as n}from"./account-store-CK-N94Ou.js";import{t as r}from"./logger-DDBAeTLF.js";import"./provider-settings-BAQroSjB.js";import{t as i}from"./llm-session-id-bZQs6gBN.js";import{n as a,r as o}from"./session-freezer-81utLS2y.js";import{SessionStore as s}from"./session-store-DAM8GRJ0.js";var c=r(`new-session`),l=`ui-new-session`,u=2e4,d=250;async function f(e,t,n,r){for(let i of n){let n=`${t}/${i.name}`;r.has(n)||i.type===`directory`&&(await f(e,n,await e.readDir(n),r),[...r].some(e=>e.startsWith(`${n}/`)))||await e.rm(n)}}async function p(e){let t=new Set((await e.listMountPoints()).map(({path:e})=>e).filter(e=>e===`/tmp`||e.startsWith(`/tmp/`)));if(t.has(`/tmp`))return;let n;try{n=await e.readDir(`/tmp`)}catch(t){if(t?.code!==`ENOENT`)throw t;await e.mkdir(`/tmp`,{recursive:!0});return}await f(e,`/tmp`,n,t),await e.mkdir(`/tmp`,{recursive:!0})}async function m(r){let d=r.enrichmentRaceMs??u,f=n()??void 0,p;try{p=t()}catch(e){c.info(`No active model — freezing without LLM enrichment`,{error:e instanceof Error?e.message:String(e)})}let m=p?.provider===`adobe`?{"X-Session-Id":i(l)}:void 0,g=new s;try{await g.init()}catch(e){return c.warn(`SessionStore init failed — cannot freeze`,{error:e instanceof Error?e.message:String(e)}),null}let _=await o({sessionStore:g,vfs:r.vfs,mode:`quick`});if(!_)return null;if(!f||!p)return c.info(`Frozen without enrichment (no LLM credentials) — left pending`,{filename:_.filename}),_;let v=p,y=a(r.vfs,_,{model:v,apiKey:f,headers:m,pickIcon:t=>e(async()=>{let{pickLucideIcon:e}=await import(`./quick-llm-B7BQQiYz.js`).then(e=>e.n);return{pickLucideIcon:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24])).then(({pickLucideIcon:e})=>e(t))}).catch(e=>(c.warn(`Single-click enrichment threw (entry stays pending)`,{filename:_.filename,error:e instanceof Error?e.message:String(e)}),null)),b=await h(y,d,r.onProgress);return b.kind===`llm`?b.updated?{...b.updated,archive:_.archive}:_:(y.then(e=>{c.info(`Background enrichment resolved after race window`,{filename:_.filename,enriched:e?.filename??null}),r.onBackgroundEnriched?.(e)}),_)}async function h(e,t,n){let r=Date.now(),i,a;n?.(0),n&&(i=setInterval(()=>{n(Math.min(1,(Date.now()-r)/t))},d));let o=new Promise(e=>{a=setTimeout(()=>e({kind:`timer`}),t)}),s=e.then(e=>({kind:`llm`,updated:e}));try{return await Promise.race([s,o])}finally{i&&clearInterval(i),a&&clearTimeout(a),n?.(null)}}async function g(e){let t=new s;try{await t.init()}catch(e){return c.warn(`SessionStore init failed — cannot quick-freeze`,{error:e instanceof Error?e.message:String(e)}),null}return o({sessionStore:t,vfs:e.vfs,mode:`quick`})}export{p as resetNewSessionTmp,m as runNewSessionFreeze,g as runNewSessionFreezeQuick};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/provider-D7tuUspk.js","assets/preload-helper-Czpn1I53.js","assets/account-store-0KfyaB_Y.js","assets/rolldown-runtime-aKtaBQYM.js","assets/compat-DyT25qXb.js","assets/models-CzSI8IsT.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/context-compaction-dcYYajWb.js","assets/logger-DDBAeTLF.js","assets/src-CS5gSDhT.js","assets/proxied-fetch-DETjVL-j.js","assets/base64-DpPqYZJF.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-D2k1IxFk.js","assets/secrets-bridge-client-CONYX8PU.js","assets/port-bridge-client-CdvMlimf.js","assets/tool-ui-DfXu6quJ.js","assets/providers-C5IxOdJy.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-BEi8MYUS.js","assets/transform-messages-fFaW-DLG.js","assets/provider-store-access-B48zmrjF.js","assets/global-db-CbuLl-zx.js","assets/types-idfTVsM8.js"])))=>i.map(i=>d[i]);
2
- import{t as e}from"./preload-helper-Czpn1I53.js";import{R as t,d as n}from"./account-store-0KfyaB_Y.js";import{t as r}from"./logger-DDBAeTLF.js";import{t as i}from"./providers-C5IxOdJy.js";import"./provider-settings-CLFfVTte.js";var a=r(`oauth-bootstrap`),o=6e4;async function s(){try{let{ensureAllMcpProvidersRegistered:t}=await e(async()=>{let{ensureAllMcpProvidersRegistered:e}=await import(`./provider-D7tuUspk.js`);return{ensureAllMcpProvidersRegistered:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])),n=await t();n.length>0&&a.debug(`Pre-registered MCP providers for OAuth bootstrap`,{count:n.length})}catch(e){a.warn(`Failed to pre-register MCP providers for OAuth bootstrap`,{error:e instanceof Error?e.message:String(e)})}let r=n();a.info(`Bootstrap OAuth replicas`,{count:r.length});for(let e of r){if(!e.accessToken){a.debug(`Skipping account without token`,{providerId:e.providerId});continue}if((e.tokenExpiresAt??1/0)-Date.now()<=o){let t=i(e.providerId);if(t?.onSilentRenew)try{if(await t.onSilentRenew()){a.info(`Silently renewed OAuth token`,{providerId:e.providerId});continue}a.warn(`Silent renewal yielded no token; user must re-authenticate`,{providerId:e.providerId});continue}catch(t){a.warn(`Silent renewal failed`,{providerId:e.providerId,error:t instanceof Error?t.message:String(t)});continue}a.debug(`Skipping expired account (no silent-renew hook)`,{providerId:e.providerId});continue}try{await t({providerId:e.providerId,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenExpiresAt:e.tokenExpiresAt,userName:e.userName,userAvatar:e.userAvatar}),a.debug(`Bootstrapped OAuth replica`,{providerId:e.providerId})}catch(t){a.error(`OAuth bootstrap failed`,{providerId:e.providerId,error:t instanceof Error?t.message:String(t)})}}}export{s as bootstrapOAuthReplicas};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/provider-DQbRhNCb.js","assets/preload-helper-Czpn1I53.js","assets/account-store-CK-N94Ou.js","assets/rolldown-runtime-aKtaBQYM.js","assets/compat-DyT25qXb.js","assets/models-CzSI8IsT.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/context-compaction-dcYYajWb.js","assets/logger-DDBAeTLF.js","assets/src-CS5gSDhT.js","assets/proxied-fetch-DETjVL-j.js","assets/base64-DpPqYZJF.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-D2k1IxFk.js","assets/secrets-bridge-client-CONYX8PU.js","assets/port-bridge-client-CdvMlimf.js","assets/tool-ui-DfXu6quJ.js","assets/providers-lerk0za2.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-BEi8MYUS.js","assets/transform-messages-fFaW-DLG.js","assets/provider-store-access-CX6QCCkY.js","assets/global-db-CbuLl-zx.js","assets/types-idfTVsM8.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./preload-helper-Czpn1I53.js";import{R as t,d as n}from"./account-store-CK-N94Ou.js";import{t as r}from"./logger-DDBAeTLF.js";import{t as i}from"./providers-lerk0za2.js";import"./provider-settings-BAQroSjB.js";var a=r(`oauth-bootstrap`),o=6e4;async function s(){try{let{ensureAllMcpProvidersRegistered:t}=await e(async()=>{let{ensureAllMcpProvidersRegistered:e}=await import(`./provider-DQbRhNCb.js`);return{ensureAllMcpProvidersRegistered:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])),n=await t();n.length>0&&a.debug(`Pre-registered MCP providers for OAuth bootstrap`,{count:n.length})}catch(e){a.warn(`Failed to pre-register MCP providers for OAuth bootstrap`,{error:e instanceof Error?e.message:String(e)})}let r=n();a.info(`Bootstrap OAuth replicas`,{count:r.length});for(let e of r){if(!e.accessToken){a.debug(`Skipping account without token`,{providerId:e.providerId});continue}if((e.tokenExpiresAt??1/0)-Date.now()<=o){let t=i(e.providerId);if(t?.onSilentRenew)try{if(await t.onSilentRenew()){a.info(`Silently renewed OAuth token`,{providerId:e.providerId});continue}a.warn(`Silent renewal yielded no token; user must re-authenticate`,{providerId:e.providerId});continue}catch(t){a.warn(`Silent renewal failed`,{providerId:e.providerId,error:t instanceof Error?t.message:String(t)});continue}a.debug(`Skipping expired account (no silent-renew hook)`,{providerId:e.providerId});continue}try{await t({providerId:e.providerId,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenExpiresAt:e.tokenExpiresAt,userName:e.userName,userAvatar:e.userAvatar}),a.debug(`Bootstrapped OAuth replica`,{providerId:e.providerId})}catch(t){a.error(`OAuth bootstrap failed`,{providerId:e.providerId,error:t instanceof Error?t.message:String(t)})}}}export{s as bootstrapOAuthReplicas};
@@ -1 +1 @@
1
- import{O as e,i as t}from"./account-store-O8B4A1Cp.js";import{p as n}from"./transform-messages-CVIV-EgO.js";import{p as r}from"./bedrock-camp-CvxD6hHk.js";import{n as i,o as a}from"./legacy-api-aliases-DWJHPSiz.js";import"./provider-settings-DXZqWMxH.js";const o=`openai-codex`,s=`app_EMoamEEZ73f0CkXaXp7hrann`,c=`https://auth.openai.com/oauth/token`,l=`http://localhost:1455/auth/callback`,u=`https://chatgpt.com/backend-api`,d=`openai-codex-responses`,f=`${o}-openai`,p={xhigh:`xhigh`,minimal:`low`},m=[{id:`gpt-5.5`,name:`GPT-5.5`,input:[`text`,`image`]},{id:`gpt-5.4`,name:`GPT-5.4`,input:[`text`,`image`]},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,input:[`text`,`image`]},{id:`gpt-5.3-codex`,name:`GPT-5.3 Codex`,input:[`text`,`image`]},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,input:[`text`]},{id:`gpt-5.2`,name:`GPT-5.2`,input:[`text`,`image`]}].map(e=>({...e,api:`openai`,reasoning:!0,context_window:272e3,max_tokens:128e3,thinkingLevelMap:p}));function h(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function g(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),t}function _(){return h(g(32))}async function v(e){let t=new TextEncoder().encode(e);return h(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}function y(){return h(g(16))}async function b(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,client_id:s,code:e,code_verifier:t,redirect_uri:l}),r=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw Error(`OpenAI Codex token exchange failed: ${r.status} ${await r.text()}`);let i=await r.json();if(!i.access_token)throw Error(`OpenAI Codex token exchange did not return access_token.`);return i}async function x(e){try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:s}),n=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});return n.ok?await n.json():(console.error(`[openai-codex] refresh failed:`,n.status,await n.text()),null)}catch(e){return console.error(`[openai-codex] refresh error:`,e instanceof Error?e.message:String(e)),null}}function S(e){try{let t=e.split(`.`);if(t.length!==3)return;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`);return n.length%4&&(n+=`=`.repeat(4-n.length%4)),JSON.parse(atob(n))}catch{return}}function C(e){let t=S(e)?.[`https://api.openai.com/profile`];return typeof t?.email==`string`?t.email:void 0}function w(e){let t=S(e)?.[`https://api.openai.com/auth`],n=C(e),r=typeof t?.chatgpt_plan_type==`string`?t.chatgpt_plan_type:void 0,i=r?r.charAt(0).toUpperCase()+r.slice(1):void 0;if(n&&i)return`${n} (${i})`;if(n)return n;if(i)return`ChatGPT ${i}`}async function T(e){let t=C(e);if(t)try{let e=t.trim().toLowerCase(),n=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));return`https://www.gravatar.com/avatar/${Array.from(n).map(e=>e.toString(16).padStart(2,`0`)).join(``)}?s=128&d=404`}catch{return}}function E(){return t().find(e=>e.providerId===o)}async function D(){let t=E();if(!t?.accessToken)throw Error("Not signed in to OpenAI Codex — run `oauth-token openai-codex` or /login");let n=t.tokenExpiresAt??0;if(n&&Date.now()+6e4<n)return t.accessToken;if(t.refreshToken){let n=await x(t.refreshToken);if(n?.access_token)return await e({providerId:o,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:u,userName:w(n.access_token),userAvatar:await T(n.access_token)}),n.access_token}return t.accessToken}function O(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:f,provider:o,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}const k=(e,t,r={})=>{let a=n();return(async()=>{try{let n=await D(),o=i({...e,baseUrl:u,api:d},t,{...r,apiKey:n,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),a.push(O(e,t)),a.end()}})(),a},A=(e,t,r)=>{let i=n();return(async()=>{try{let n=await D(),o=a({...e,baseUrl:u,api:d},t,{...r,apiKey:n,transport:`sse`});for await(let e of o)i.push(e);i.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),i.push(O(e,t)),i.end()}})(),i},j={id:o,name:`OpenAI Codex (ChatGPT Subscription)`,description:`GPT-5 Codex via your ChatGPT Plus/Pro/Business subscription — OAuth login, no API key needed. Default model is GPT-5.5.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`gpt-5.5`,oauthTokenDomains:[`chatgpt.com`,`*.chatgpt.com`,`auth.openai.com`,`api.openai.com`],getModelIds:()=>m,onOAuthLoginIntercepted:async(t,n,r)=>{let i=_(),a=await v(i),c=y(),d=new URL(`https://auth.openai.com/oauth/authorize`);d.searchParams.set(`response_type`,`code`),d.searchParams.set(`client_id`,s),d.searchParams.set(`redirect_uri`,l),d.searchParams.set(`scope`,r?.scopes??`openid profile email offline_access`),d.searchParams.set(`code_challenge`,a),d.searchParams.set(`code_challenge_method`,`S256`),d.searchParams.set(`state`,c),d.searchParams.set(`id_token_add_organizations`,`true`),d.searchParams.set(`codex_cli_simplified_flow`,`true`),d.searchParams.set(`originator`,`pi`);let f=await t({authorizeUrl:d.toString(),redirectUriPattern:`http://localhost:1455/auth/callback*`,onCapture:`close`});if(!f)throw Error(`OpenAI Codex OAuth login was cancelled or timed out`);let p=new URL(f),m=p.searchParams.get(`code`),h=p.searchParams.get(`state`);if(!m)throw Error(`OpenAI Codex OAuth redirect did not include a code`);if(h!==c)throw Error(`OpenAI Codex OAuth state mismatch — possible CSRF, aborting`);let g=await b(m,i);await e({providerId:o,accessToken:g.access_token,refreshToken:g.refresh_token,tokenExpiresAt:Date.now()+(g.expires_in??3600)*1e3,baseUrl:u,userName:w(g.access_token),userAvatar:await T(g.access_token)}),n()},onOAuthLogout:async()=>{await e({providerId:o,accessToken:``})},onSilentRenew:async()=>{let t=E();if(!t?.refreshToken)return null;let n=await x(t.refreshToken);return n?.access_token?(await e({providerId:o,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:u,userName:w(n.access_token),userAvatar:await T(n.access_token)}),n.access_token):null}};function M(){r({api:f,stream:k,streamSimple:A})}export{j as config,M as register};
1
+ import{O as e,i as t}from"./account-store-DBH6AYjF.js";import{p as n}from"./transform-messages-CVIV-EgO.js";import{p as r}from"./bedrock-camp-CvxD6hHk.js";import{n as i,o as a}from"./legacy-api-aliases-DWJHPSiz.js";import"./provider-settings-AHSP9_xw.js";const o=`openai-codex`,s=`app_EMoamEEZ73f0CkXaXp7hrann`,c=`https://auth.openai.com/oauth/token`,l=`http://localhost:1455/auth/callback`,u=`https://chatgpt.com/backend-api`,d=`openai-codex-responses`,f=`${o}-openai`,p={xhigh:`xhigh`,minimal:`low`},m=[{id:`gpt-5.5`,name:`GPT-5.5`,input:[`text`,`image`]},{id:`gpt-5.4`,name:`GPT-5.4`,input:[`text`,`image`]},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,input:[`text`,`image`]},{id:`gpt-5.3-codex`,name:`GPT-5.3 Codex`,input:[`text`,`image`]},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,input:[`text`]},{id:`gpt-5.2`,name:`GPT-5.2`,input:[`text`,`image`]}].map(e=>({...e,api:`openai`,reasoning:!0,context_window:272e3,max_tokens:128e3,thinkingLevelMap:p}));function h(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function g(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),t}function _(){return h(g(32))}async function v(e){let t=new TextEncoder().encode(e);return h(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}function y(){return h(g(16))}async function b(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,client_id:s,code:e,code_verifier:t,redirect_uri:l}),r=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw Error(`OpenAI Codex token exchange failed: ${r.status} ${await r.text()}`);let i=await r.json();if(!i.access_token)throw Error(`OpenAI Codex token exchange did not return access_token.`);return i}async function x(e){try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:s}),n=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});return n.ok?await n.json():(console.error(`[openai-codex] refresh failed:`,n.status,await n.text()),null)}catch(e){return console.error(`[openai-codex] refresh error:`,e instanceof Error?e.message:String(e)),null}}function S(e){try{let t=e.split(`.`);if(t.length!==3)return;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`);return n.length%4&&(n+=`=`.repeat(4-n.length%4)),JSON.parse(atob(n))}catch{return}}function C(e){let t=S(e)?.[`https://api.openai.com/profile`];return typeof t?.email==`string`?t.email:void 0}function w(e){let t=S(e)?.[`https://api.openai.com/auth`],n=C(e),r=typeof t?.chatgpt_plan_type==`string`?t.chatgpt_plan_type:void 0,i=r?r.charAt(0).toUpperCase()+r.slice(1):void 0;if(n&&i)return`${n} (${i})`;if(n)return n;if(i)return`ChatGPT ${i}`}async function T(e){let t=C(e);if(t)try{let e=t.trim().toLowerCase(),n=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));return`https://www.gravatar.com/avatar/${Array.from(n).map(e=>e.toString(16).padStart(2,`0`)).join(``)}?s=128&d=404`}catch{return}}function E(){return t().find(e=>e.providerId===o)}async function D(){let t=E();if(!t?.accessToken)throw Error("Not signed in to OpenAI Codex — run `oauth-token openai-codex` or /login");let n=t.tokenExpiresAt??0;if(n&&Date.now()+6e4<n)return t.accessToken;if(t.refreshToken){let n=await x(t.refreshToken);if(n?.access_token)return await e({providerId:o,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:u,userName:w(n.access_token),userAvatar:await T(n.access_token)}),n.access_token}return t.accessToken}function O(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:f,provider:o,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}const k=(e,t,r={})=>{let a=n();return(async()=>{try{let n=await D(),o=i({...e,baseUrl:u,api:d},t,{...r,apiKey:n,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),a.push(O(e,t)),a.end()}})(),a},A=(e,t,r)=>{let i=n();return(async()=>{try{let n=await D(),o=a({...e,baseUrl:u,api:d},t,{...r,apiKey:n,transport:`sse`});for await(let e of o)i.push(e);i.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),i.push(O(e,t)),i.end()}})(),i},j={id:o,name:`OpenAI Codex (ChatGPT Subscription)`,description:`GPT-5 Codex via your ChatGPT Plus/Pro/Business subscription — OAuth login, no API key needed. Default model is GPT-5.5.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`gpt-5.5`,oauthTokenDomains:[`chatgpt.com`,`*.chatgpt.com`,`auth.openai.com`,`api.openai.com`],getModelIds:()=>m,onOAuthLoginIntercepted:async(t,n,r)=>{let i=_(),a=await v(i),c=y(),d=new URL(`https://auth.openai.com/oauth/authorize`);d.searchParams.set(`response_type`,`code`),d.searchParams.set(`client_id`,s),d.searchParams.set(`redirect_uri`,l),d.searchParams.set(`scope`,r?.scopes??`openid profile email offline_access`),d.searchParams.set(`code_challenge`,a),d.searchParams.set(`code_challenge_method`,`S256`),d.searchParams.set(`state`,c),d.searchParams.set(`id_token_add_organizations`,`true`),d.searchParams.set(`codex_cli_simplified_flow`,`true`),d.searchParams.set(`originator`,`pi`);let f=await t({authorizeUrl:d.toString(),redirectUriPattern:`http://localhost:1455/auth/callback*`,onCapture:`close`});if(!f)throw Error(`OpenAI Codex OAuth login was cancelled or timed out`);let p=new URL(f),m=p.searchParams.get(`code`),h=p.searchParams.get(`state`);if(!m)throw Error(`OpenAI Codex OAuth redirect did not include a code`);if(h!==c)throw Error(`OpenAI Codex OAuth state mismatch — possible CSRF, aborting`);let g=await b(m,i);await e({providerId:o,accessToken:g.access_token,refreshToken:g.refresh_token,tokenExpiresAt:Date.now()+(g.expires_in??3600)*1e3,baseUrl:u,userName:w(g.access_token),userAvatar:await T(g.access_token)}),n()},onOAuthLogout:async()=>{await e({providerId:o,accessToken:``})},onSilentRenew:async()=>{let t=E();if(!t?.refreshToken)return null;let n=await x(t.refreshToken);return n?.access_token?(await e({providerId:o,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:u,userName:w(n.access_token),userAvatar:await T(n.access_token)}),n.access_token):null}};function M(){r({api:f,stream:k,streamSimple:A})}export{j as config,M as register};
@@ -1 +1 @@
1
- import{s as e}from"./models-CzSI8IsT.js";import{a as t}from"./compat-DyT25qXb.js";import{n,o as r}from"./legacy-api-aliases-BQSsmFIS.js";import{R as i,d as a}from"./account-store-0KfyaB_Y.js";import"./provider-settings-CLFfVTte.js";var o=`openai-codex`,s=`app_EMoamEEZ73f0CkXaXp7hrann`,c=`https://auth.openai.com/oauth/authorize`,l=`https://auth.openai.com/oauth/token`,u=`openid profile email offline_access`,d=`http://localhost:1455/auth/callback`,f=`http://localhost:1455/auth/callback*`,p=`https://chatgpt.com/backend-api`,m=`openai-codex-responses`,h=`${o}-openai`,g={xhigh:`xhigh`,minimal:`low`},_=[{id:`gpt-5.5`,name:`GPT-5.5`,input:[`text`,`image`]},{id:`gpt-5.4`,name:`GPT-5.4`,input:[`text`,`image`]},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,input:[`text`,`image`]},{id:`gpt-5.3-codex`,name:`GPT-5.3 Codex`,input:[`text`,`image`]},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,input:[`text`]},{id:`gpt-5.2`,name:`GPT-5.2`,input:[`text`,`image`]}].map(e=>({...e,api:`openai`,reasoning:!0,context_window:272e3,max_tokens:128e3,thinkingLevelMap:g}));function v(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function y(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),t}function b(){return v(y(32))}async function x(e){let t=new TextEncoder().encode(e);return v(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}function S(){return v(y(16))}async function C(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,client_id:s,code:e,code_verifier:t,redirect_uri:d}),r=await fetch(l,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw Error(`OpenAI Codex token exchange failed: ${r.status} ${await r.text()}`);let i=await r.json();if(!i.access_token)throw Error(`OpenAI Codex token exchange did not return access_token.`);return i}async function w(e){try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:s}),n=await fetch(l,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});return n.ok?await n.json():(console.error(`[openai-codex] refresh failed:`,n.status,await n.text()),null)}catch(e){return console.error(`[openai-codex] refresh error:`,e instanceof Error?e.message:String(e)),null}}function T(e){try{let t=e.split(`.`);if(t.length!==3)return;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`);return n.length%4&&(n+=`=`.repeat(4-n.length%4)),JSON.parse(atob(n))}catch{return}}function E(e){let t=T(e)?.[`https://api.openai.com/profile`];return typeof t?.email==`string`?t.email:void 0}function D(e){let t=T(e)?.[`https://api.openai.com/auth`],n=E(e),r=typeof t?.chatgpt_plan_type==`string`?t.chatgpt_plan_type:void 0,i=r?r.charAt(0).toUpperCase()+r.slice(1):void 0;if(n&&i)return`${n} (${i})`;if(n)return n;if(i)return`ChatGPT ${i}`}async function O(e){let t=E(e);if(t)try{let e=t.trim().toLowerCase(),n=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));return`https://www.gravatar.com/avatar/${Array.from(n).map(e=>e.toString(16).padStart(2,`0`)).join(``)}?s=128&d=404`}catch{return}}function k(){return a().find(e=>e.providerId===o)}async function A(){let e=k();if(!e?.accessToken)throw Error("Not signed in to OpenAI Codex — run `oauth-token openai-codex` or /login");let t=e.tokenExpiresAt??0;if(t&&Date.now()+6e4<t)return e.accessToken;if(e.refreshToken){let t=await w(e.refreshToken);if(t?.access_token)return await i({providerId:o,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??3600)*1e3,baseUrl:p,userName:D(t.access_token),userAvatar:await O(t.access_token)}),t.access_token}return e.accessToken}function j(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:h,provider:o,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}var M=(t,r,i={})=>{let a=e();return(async()=>{try{let e=await A(),o=n({...t,baseUrl:p,api:m},r,{...i,apiKey:e,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(e){console.error(`[openai-codex] Stream error:`,e instanceof Error?e.message:String(e)),a.push(j(t,e)),a.end()}})(),a},N=(t,n,i)=>{let a=e();return(async()=>{try{let e=await A(),o=r({...t,baseUrl:p,api:m},n,{...i,apiKey:e,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(e){console.error(`[openai-codex] Stream error:`,e instanceof Error?e.message:String(e)),a.push(j(t,e)),a.end()}})(),a},P={id:o,name:`OpenAI Codex (ChatGPT Subscription)`,description:`GPT-5 Codex via your ChatGPT Plus/Pro/Business subscription — OAuth login, no API key needed. Default model is GPT-5.5.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`gpt-5.5`,oauthTokenDomains:[`chatgpt.com`,`*.chatgpt.com`,`auth.openai.com`,`api.openai.com`],getModelIds:()=>_,onOAuthLoginIntercepted:async(e,t,n)=>{let r=b(),a=await x(r),l=S(),m=new URL(c);m.searchParams.set(`response_type`,`code`),m.searchParams.set(`client_id`,s),m.searchParams.set(`redirect_uri`,d),m.searchParams.set(`scope`,n?.scopes??u),m.searchParams.set(`code_challenge`,a),m.searchParams.set(`code_challenge_method`,`S256`),m.searchParams.set(`state`,l),m.searchParams.set(`id_token_add_organizations`,`true`),m.searchParams.set(`codex_cli_simplified_flow`,`true`),m.searchParams.set(`originator`,`pi`);let h=await e({authorizeUrl:m.toString(),redirectUriPattern:f,onCapture:`close`});if(!h)throw Error(`OpenAI Codex OAuth login was cancelled or timed out`);let g=new URL(h),_=g.searchParams.get(`code`),v=g.searchParams.get(`state`);if(!_)throw Error(`OpenAI Codex OAuth redirect did not include a code`);if(v!==l)throw Error(`OpenAI Codex OAuth state mismatch — possible CSRF, aborting`);let y=await C(_,r);await i({providerId:o,accessToken:y.access_token,refreshToken:y.refresh_token,tokenExpiresAt:Date.now()+(y.expires_in??3600)*1e3,baseUrl:p,userName:D(y.access_token),userAvatar:await O(y.access_token)}),t()},onOAuthLogout:async()=>{await i({providerId:o,accessToken:``})},onSilentRenew:async()=>{let e=k();if(!e?.refreshToken)return null;let t=await w(e.refreshToken);return t?.access_token?(await i({providerId:o,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??3600)*1e3,baseUrl:p,userName:D(t.access_token),userAvatar:await O(t.access_token)}),t.access_token):null}};function F(){t({api:h,stream:M,streamSimple:N})}export{P as config,F as register};
1
+ import{s as e}from"./models-CzSI8IsT.js";import{a as t}from"./compat-DyT25qXb.js";import{n,o as r}from"./legacy-api-aliases-BQSsmFIS.js";import{R as i,d as a}from"./account-store-CK-N94Ou.js";import"./provider-settings-BAQroSjB.js";var o=`openai-codex`,s=`app_EMoamEEZ73f0CkXaXp7hrann`,c=`https://auth.openai.com/oauth/authorize`,l=`https://auth.openai.com/oauth/token`,u=`openid profile email offline_access`,d=`http://localhost:1455/auth/callback`,f=`http://localhost:1455/auth/callback*`,p=`https://chatgpt.com/backend-api`,m=`openai-codex-responses`,h=`${o}-openai`,g={xhigh:`xhigh`,minimal:`low`},_=[{id:`gpt-5.5`,name:`GPT-5.5`,input:[`text`,`image`]},{id:`gpt-5.4`,name:`GPT-5.4`,input:[`text`,`image`]},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,input:[`text`,`image`]},{id:`gpt-5.3-codex`,name:`GPT-5.3 Codex`,input:[`text`,`image`]},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,input:[`text`]},{id:`gpt-5.2`,name:`GPT-5.2`,input:[`text`,`image`]}].map(e=>({...e,api:`openai`,reasoning:!0,context_window:272e3,max_tokens:128e3,thinkingLevelMap:g}));function v(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function y(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),t}function b(){return v(y(32))}async function x(e){let t=new TextEncoder().encode(e);return v(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}function S(){return v(y(16))}async function C(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,client_id:s,code:e,code_verifier:t,redirect_uri:d}),r=await fetch(l,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw Error(`OpenAI Codex token exchange failed: ${r.status} ${await r.text()}`);let i=await r.json();if(!i.access_token)throw Error(`OpenAI Codex token exchange did not return access_token.`);return i}async function w(e){try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:s}),n=await fetch(l,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});return n.ok?await n.json():(console.error(`[openai-codex] refresh failed:`,n.status,await n.text()),null)}catch(e){return console.error(`[openai-codex] refresh error:`,e instanceof Error?e.message:String(e)),null}}function T(e){try{let t=e.split(`.`);if(t.length!==3)return;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`);return n.length%4&&(n+=`=`.repeat(4-n.length%4)),JSON.parse(atob(n))}catch{return}}function E(e){let t=T(e)?.[`https://api.openai.com/profile`];return typeof t?.email==`string`?t.email:void 0}function D(e){let t=T(e)?.[`https://api.openai.com/auth`],n=E(e),r=typeof t?.chatgpt_plan_type==`string`?t.chatgpt_plan_type:void 0,i=r?r.charAt(0).toUpperCase()+r.slice(1):void 0;if(n&&i)return`${n} (${i})`;if(n)return n;if(i)return`ChatGPT ${i}`}async function O(e){let t=E(e);if(t)try{let e=t.trim().toLowerCase(),n=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));return`https://www.gravatar.com/avatar/${Array.from(n).map(e=>e.toString(16).padStart(2,`0`)).join(``)}?s=128&d=404`}catch{return}}function k(){return a().find(e=>e.providerId===o)}async function A(){let e=k();if(!e?.accessToken)throw Error("Not signed in to OpenAI Codex — run `oauth-token openai-codex` or /login");let t=e.tokenExpiresAt??0;if(t&&Date.now()+6e4<t)return e.accessToken;if(e.refreshToken){let t=await w(e.refreshToken);if(t?.access_token)return await i({providerId:o,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??3600)*1e3,baseUrl:p,userName:D(t.access_token),userAvatar:await O(t.access_token)}),t.access_token}return e.accessToken}function j(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:h,provider:o,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}var M=(t,r,i={})=>{let a=e();return(async()=>{try{let e=await A(),o=n({...t,baseUrl:p,api:m},r,{...i,apiKey:e,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(e){console.error(`[openai-codex] Stream error:`,e instanceof Error?e.message:String(e)),a.push(j(t,e)),a.end()}})(),a},N=(t,n,i)=>{let a=e();return(async()=>{try{let e=await A(),o=r({...t,baseUrl:p,api:m},n,{...i,apiKey:e,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(e){console.error(`[openai-codex] Stream error:`,e instanceof Error?e.message:String(e)),a.push(j(t,e)),a.end()}})(),a},P={id:o,name:`OpenAI Codex (ChatGPT Subscription)`,description:`GPT-5 Codex via your ChatGPT Plus/Pro/Business subscription — OAuth login, no API key needed. Default model is GPT-5.5.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`gpt-5.5`,oauthTokenDomains:[`chatgpt.com`,`*.chatgpt.com`,`auth.openai.com`,`api.openai.com`],getModelIds:()=>_,onOAuthLoginIntercepted:async(e,t,n)=>{let r=b(),a=await x(r),l=S(),m=new URL(c);m.searchParams.set(`response_type`,`code`),m.searchParams.set(`client_id`,s),m.searchParams.set(`redirect_uri`,d),m.searchParams.set(`scope`,n?.scopes??u),m.searchParams.set(`code_challenge`,a),m.searchParams.set(`code_challenge_method`,`S256`),m.searchParams.set(`state`,l),m.searchParams.set(`id_token_add_organizations`,`true`),m.searchParams.set(`codex_cli_simplified_flow`,`true`),m.searchParams.set(`originator`,`pi`);let h=await e({authorizeUrl:m.toString(),redirectUriPattern:f,onCapture:`close`});if(!h)throw Error(`OpenAI Codex OAuth login was cancelled or timed out`);let g=new URL(h),_=g.searchParams.get(`code`),v=g.searchParams.get(`state`);if(!_)throw Error(`OpenAI Codex OAuth redirect did not include a code`);if(v!==l)throw Error(`OpenAI Codex OAuth state mismatch — possible CSRF, aborting`);let y=await C(_,r);await i({providerId:o,accessToken:y.access_token,refreshToken:y.refresh_token,tokenExpiresAt:Date.now()+(y.expires_in??3600)*1e3,baseUrl:p,userName:D(y.access_token),userAvatar:await O(y.access_token)}),t()},onOAuthLogout:async()=>{await i({providerId:o,accessToken:``})},onSilentRenew:async()=>{let e=k();if(!e?.refreshToken)return null;let t=await w(e.refreshToken);return t?.access_token?(await i({providerId:o,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??3600)*1e3,baseUrl:p,userName:D(t.access_token),userAvatar:await O(t.access_token)}),t.access_token):null}};function F(){t({api:h,stream:M,streamSimple:N})}export{P as config,F as register};
@@ -0,0 +1,5 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/theme-engine-jfuTMXZM.js","assets/rolldown-runtime-aKtaBQYM.js","assets/logger-DDBAeTLF.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./preload-helper-Czpn1I53.js";import{n as t}from"./attachments-CByeG2Ru.js";import{t as n}from"./logger-DDBAeTLF.js";import{n as r,t as i}from"./base64-DpPqYZJF.js";import"./src-CS5gSDhT.js";import{a,i as o,r as s,t as c,u as l}from"./tray-sync-protocol-CVdiCvfU.js";import{i as u,n as d,r as f}from"./tray-follower-status-CyJIKXH4.js";import{t as p}from"./remote-cdp-transport-DOoXIxy3.js";import{n as m}from"./shared-Dwjvg8S5.js";import{t as h}from"./sprinkle-renderer-B0y9_9py.js";var g=class{logger;failureMessage;recoveryMessage;throttleMs;sustainedRelogMs;recoveryDebounceTicks;now;lastErrorLogAt=-1/0;inFailingState=!1;consecutiveSuccesses=0;constructor(e,t){if(!t.failureMessage.trim())throw RangeError(`ThrottledErrorTracker: failureMessage must be non-empty`);if(!t.recoveryMessage.trim())throw RangeError(`ThrottledErrorTracker: recoveryMessage must be non-empty`);let n=t.throttleMs??6e4;if(!Number.isFinite(n)||n<0)throw RangeError(`ThrottledErrorTracker: throttleMs must be a non-negative finite number, got ${n}`);let r=t.sustainedRelogMs??3e5;if(!Number.isFinite(r)||r<0)throw RangeError(`ThrottledErrorTracker: sustainedRelogMs must be a non-negative finite number, got ${r}`);let i=t.recoveryDebounceTicks??5;if(!Number.isInteger(i)||i<1)throw RangeError(`ThrottledErrorTracker: recoveryDebounceTicks must be a positive integer, got ${i}`);this.logger=e,this.failureMessage=t.failureMessage,this.recoveryMessage=t.recoveryMessage,this.throttleMs=n,this.sustainedRelogMs=r,this.recoveryDebounceTicks=i,this.now=t.now??(()=>performance.now())}reportFailure(e){let t=this.inFailingState;this.inFailingState=!0,this.consecutiveSuccesses=0;let n=this.now(),r=n-this.lastErrorLogAt;if(r>(t?this.sustainedRelogMs:this.throttleMs)){let i=t,a=i?`${this.failureMessage} (sustained)`:this.failureMessage;try{try{this.logger.error(a,i?{error:e instanceof Error?e.message:String(e),elapsedMs:Math.round(r)}:{error:e instanceof Error?e.message:String(e)})}catch(t){try{console.error(`[throttled-error-tracker] logger.error threw`,t,{originalMessage:a,originalError:e instanceof Error?e.message:String(e)})}catch{}}}finally{this.lastErrorLogAt=n}}}reportSuccess(){if(this.inFailingState&&(this.consecutiveSuccesses++,!(this.consecutiveSuccesses<this.recoveryDebounceTicks)))try{try{this.logger.error(this.recoveryMessage,{kind:`recovery`})}catch(e){try{console.error(`[throttled-error-tracker] logger.error (recovery) threw`,e,{originalMessage:this.recoveryMessage})}catch{}}}finally{this.inFailingState=!1,this.consecutiveSuccesses=0,this.lastErrorLogAt=-1/0}}},_=n(`data-channel-keepalive`),v=class{sendPing;onDead;intervalMs;maxMissed;timer=null;missedPongs=0;awaitingPong=!1;stopped=!1;constructor(e){this.sendPing=e.sendPing,this.onDead=e.onDead,this.intervalMs=e.intervalMs??1e4,this.maxMissed=e.maxMissed??3}start(){this.timer||this.stopped||(this.timer=setInterval(()=>this.tick(),this.intervalMs))}stop(){this.stopped=!0,this.timer&&=(clearInterval(this.timer),null)}receivePong(){this.awaitingPong=!1,this.missedPongs=0}receivePing(){this.missedPongs=0,this.awaitingPong=!1}get missed(){return this.missedPongs}tick(){if(!this.stopped){if(this.awaitingPong&&(this.missedPongs++,_.debug(`Missed pong`,{missedPongs:this.missedPongs,maxMissed:this.maxMissed}),this.missedPongs>=this.maxMissed)){_.warn(`Channel declared dead`,{missedPongs:this.missedPongs}),this.stop(),this.onDead();return}this.awaitingPong=!0,this.sendPing()}}},y=64*1024;async function b(e,t){try{switch(t.op){case`readFile`:return await x(e,t.path,t.encoding);case`writeFile`:return[await ee(e,t.path,t.content,t.encoding)];case`stat`:return[await te(e,t.path)];case`readDir`:return[await ne(e,t.path)];case`mkdir`:return[await S(e,t.path,t.recursive)];case`rm`:return[await C(e,t.path,t.recursive)];case`exists`:return[await re(e,t.path)];case`walk`:return[await w(e,t.path)];default:return[{ok:!1,error:`Unknown fs operation: ${t.op}`}]}}catch(e){return[ie(e)]}}async function x(e,t,n){return(n??`utf-8`)===`utf-8`?T(await e.readFile(t,{encoding:`utf-8`}),`utf-8`):T(r(await e.readFile(t,{encoding:`binary`})),`base64`)}async function ee(e,t,n,r){if(r===`base64`){let r=i(n);await e.writeFile(t,r)}else await e.writeFile(t,n);return{ok:!0,data:{type:`void`}}}async function te(e,t){return{ok:!0,data:{type:`stat`,stat:await e.stat(t)}}}async function ne(e,t){return{ok:!0,data:{type:`dirEntries`,entries:await e.readDir(t)}}}async function S(e,t,n){return await e.mkdir(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function C(e,t,n){return await e.rm(t,{recursive:n}),{ok:!0,data:{type:`void`}}}async function re(e,t){return{ok:!0,data:{type:`exists`,exists:await e.exists(t)}}}async function w(e,t){let n=[];for await(let r of e.walk(t))n.push(r);return{ok:!0,data:{type:`paths`,paths:n}}}function T(e,t){if(e.length<=y)return[{ok:!0,data:{type:`file`,content:e,encoding:t}}];let n=Math.ceil(e.length/y),r=[];for(let i=0;i<n;i++){let a=i*y,o=e.slice(a,a+y);r.push({ok:!0,data:{type:`file`,content:o,encoding:t},chunkIndex:i,totalChunks:n})}return r}function ie(e){return e instanceof Error&&`code`in e?{ok:!1,error:e.message,code:e.code}:{ok:!1,error:e instanceof Error?e.message:String(e)}}var E=n(`tray-follower-sync`),D=15e3,O=class{options;sync;eventListeners=new Set;unsubscribe;keepalive;latestSnapshot=null;sentMessageIds=new Set;targetEntries=[];remoteTransports=new Map;cdpChunkBuffers=new Map;snapshotChunkBuffer=null;remoteCDPSessions=new Set;cdpEventCleanups=[];tabOpenResolvers=new Map;fsResolvers=new Map;leaderProtocolVersion;legacyLeaderLogged=!1;latestSprinkles=[];sprinkleContentCache=new Map;pendingSprinkleFetches=new Map;inflightSprinkleByName=new Map;sprinkleContentWaiters=new Map;cacheEpoch=0;fetchEpoch=new Map;constructor(e,t={}){this.options=t;let n=t.sprinkleFetchTimeoutMs;if(n!==void 0&&(!Number.isFinite(n)||n<0))throw RangeError(`sprinkleFetchTimeoutMs must be a non-negative finite number (0 disables the timer); got ${n}`);this.sync=c(e),this.unsubscribe=this.sync.onMessage(e=>{this.handleLeaderMessage(e)}),this.sync.send({type:`hello`,protocolVersion:1,...this.options.selfRuntimeId?{runtime:this.options.selfRuntimeId}:{}}),this.keepalive=new v({sendPing:()=>this.sync.send({type:`ping`}),onDead:()=>{E.warn(`Leader keepalive dead, cleaning up`),this.handleDisconnect(`Keepalive timeout — leader not responding`),this.options.onDead?.()}}),this.keepalive.start(),e.addEventListener(`close`,()=>{E.warn(`Data channel closed`),this.handleDisconnect(`Data channel closed`)}),e.addEventListener(`error`,()=>{E.warn(`Data channel error`),this.handleDisconnect(`Data channel error`)})}sendMessage(e,n,r){let i=n??`follower-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.sentMessageIds.add(i);let a=r?.length?t(r):r;this.sync.send({type:`user_message`,text:e,messageId:i,attachments:a}),E.info(`Sent user message to leader`,{messageId:i})}onEvent(e){return this.eventListeners.add(e),()=>this.eventListeners.delete(e)}stop(){this.sync.send({type:`abort`}),E.info(`Sent abort to leader`)}requestSnapshot(){this.sync.send({type:`request_snapshot`})}requestNewSession(e){this.sync.send({type:`new_session`,action:e}),E.info(`Sent new_session to leader`,{action:e})}selectScoop(e){this.sync.send({type:`scoops.select`,scoopJid:e})}getLatestSnapshot(){return this.latestSnapshot}close(){this.disconnected||(this.disconnected=!0,this.keepalive.stop(),this.unsubscribe(),this.sync.close(),this.eventListeners.clear(),this.cleanupCDPEventForwarding(),this.rejectPendingRequests(`Follower sync closed`),E.info(`Follower sync closed`))}rejectPendingRequests(e){this.rejectPendingSprinkleFetches(e);let t=Error(e);for(let{reject:e}of this.tabOpenResolvers.values())e(t);this.tabOpenResolvers.clear();for(let{reject:e}of this.fsResolvers.values())e(t);this.fsResolvers.clear(),this.cdpChunkBuffers.clear();for(let e of this.remoteTransports.values())e.disconnect();this.remoteTransports.clear()}advertiseTargets(e,t){this.sync.send({type:`targets.advertise`,targets:e,runtimeId:t})}getTargets(){return this.targetEntries}sendCherryHostEvent(e,t){this.sync.send({type:`cherry.host_event`,targetId:this.options.selfRuntimeId??``,name:e,detail:t})}getSprinkles(){return this.latestSprinkles}refreshSprinkles(){this.sync.send({type:`sprinkles.refresh`})}fetchSprinkleContent(e){let t=this.sprinkleContentCache.get(e);if(t!==void 0)return Promise.resolve(t);let n=this.options.sprinkleFetchTimeoutMs??D;return new Promise((t,r)=>{let i=Symbol(`sprinkle-waiter`),a,o=e=>{a!==void 0&&clearTimeout(a),t(e)},s=e=>{a!==void 0&&clearTimeout(a),r(e)},c=this.sprinkleContentWaiters.get(e)??[];if(c.push({id:i,resolve:o,reject:s}),this.sprinkleContentWaiters.set(e,c),n>0&&(a=setTimeout(()=>{let t=this.sprinkleContentWaiters.get(e);if(t){let r=t.findIndex(e=>e.id===i);r>=0&&t.splice(r,1),t.length===0&&(this.sprinkleContentWaiters.delete(e),this.cancelSprinkleFetch(e,`Sprinkle fetch for "${e}" timed out after ${n}ms`))}r(Error(`Sprinkle fetch for "${e}" timed out after ${n}ms`))},n)),this.inflightSprinkleByName.has(e))return;let l=`sprinkle-fetch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.inflightSprinkleByName.set(e,l),this.pendingSprinkleFetches.set(l,{sprinkleName:e,chunks:new Map,totalChunks:1}),this.fetchEpoch.set(l,this.cacheEpoch),this.sync.send({type:`sprinkle.fetch`,requestId:l,sprinkleName:e})})}sendSprinkleLick(e,t,n){this.sync.send({type:`sprinkle.lick`,sprinkleName:e,body:t,targetScoop:n})||E.warn(`sendSprinkleLick dropped: tray channel closed`,{sprinkleName:e})}forwardLick(e){let t=this.sync.send({type:`lick`,event:e});return t||E.warn(`forwardLick dropped: tray channel closed`,{type:e.type}),t}clearSprinkleCache(e){e===void 0?this.sprinkleContentCache.clear():this.sprinkleContentCache.delete(e)}cancelSprinkleFetch(e,t=`fetch cancelled`){let n=this.sprinkleContentWaiters.get(e)??[];this.sprinkleContentWaiters.delete(e);let r=this.inflightSprinkleByName.get(e);if(r!==void 0&&(this.inflightSprinkleByName.delete(e),this.pendingSprinkleFetches.delete(r),this.fetchEpoch.delete(r)),n.length===0)return;let i=Error(t);for(let e of n)e.reject(i)}disconnected=!1;handleDisconnect(e){this.disconnected||(this.disconnected=!0,u({...d(),state:`error`,error:e}),this.emitEvent({type:`error`,error:`Connection to leader lost: ${e}`}),this.keepalive.stop(),this.cleanupCDPEventForwarding(),this.unsubscribe(),this.sync.close(),this.rejectPendingRequests(`Follower sync disconnected: ${e}`),this.options.onDisconnect?.(e))}handleLeaderHello(e){this.leaderProtocolVersion=e,e>1?E.warn(`Leader speaks a newer tray sync protocol — update this build`,{leaderVersion:e,ourVersion:1}):E.info(`Leader hello`,{protocolVersion:e})}noteLegacyLeader(e){e===`hello`||this.leaderProtocolVersion!==void 0||this.legacyLeaderLogged||(this.legacyLeaderLogged=!0,E.info(`Leader sent no hello — legacy peer (pre-versioning build)`))}handleLeaderMessage(e){if(this.noteLegacyLeader(e.type),e.type===`theme.apply`){this.applyLeaderTheme(e.themeJson);return}switch(e.type){case`snapshot`:E.info(`Snapshot received from leader`,{messageCount:e.messages.length,scoopJid:e.scoopJid}),this.snapshotChunkBuffer=null,this.latestSnapshot={messages:e.messages,scoopJid:e.scoopJid},this.options.onSnapshot?.(e.messages,e.scoopJid);break;case`snapshot_chunk`:{let t=o(this.snapshotChunkBuffer,e);this.snapshotChunkBuffer=t.buffer,t.result&&(E.info(`Chunked snapshot reassembled from leader`,{messageCount:t.result.messages.length,scoopJid:t.result.scoopJid}),this.latestSnapshot=t.result,this.options.onSnapshot?.(t.result.messages,t.result.scoopJid));break}case`agent_event`:this.emitEvent(e.event);break;case`user_message_echo`:this.handleUserMessageEcho(e);break;case`status`:this.options.onStatus?.(e.scoopStatus);break;case`error`:E.warn(`Error from leader`,{error:e.error}),this.emitEvent({type:`error`,error:e.error});break;case`targets.registry`:E.info(`Target registry received from leader`,{targetCount:e.targets.length}),this.targetEntries=e.targets,this.options.onTargetsUpdated?.(this.targetEntries);break;case`cdp.request`:{let{requestId:t,localTargetId:n,method:r,params:i,sessionId:a}=e;this.executeLocalCDP(t,n,r,i,a);break}case`cdp.response`:this.routeCDPResponse(e);break;case`cdp.event`:for(let t of this.remoteTransports.values())t.handleEvent(e.method,e.params);break;case`tab.open`:case`preview.open`:this.executeLocalTabOpen(e.requestId,e.url);break;case`tab.opened`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.resolve(e.targetId));break}case`tab.open.error`:{let t=this.tabOpenResolvers.get(e.requestId);t&&(this.tabOpenResolvers.delete(e.requestId),t.reject(Error(e.error)));break}case`fs.request`:this.executeLocalFs(e.requestId,e.request);break;case`fs.response`:this.routeFsResponse(e.requestId,e.response);break;case`scoops.list`:this.handleScoopsList(e.scoops,e.activeScoopJid);break;case`sprinkles.list`:E.info(`Sprinkles list received from leader`,{sprinkleCount:e.sprinkles.length}),this.sprinkleContentCache.clear(),this.cacheEpoch++,this.latestSprinkles=e.sprinkles,this.options.onSprinklesList?.(e.sprinkles);break;case`sprinkle.content`:this.handleSprinkleContent(e);break;case`sprinkle.update`:this.options.onSprinkleUpdate?.(e.sprinkleName,e.data);break;case`sprinkle.reloaded`:this.handleSprinkleReloaded(e.sprinkleName);break;case`cherry.slicc_event`:this.options.onCherrySliccEvent?.(e.name,e.detail);break;case`ping`:this.keepalive.receivePing(),this.sync.send({type:`pong`});break;case`pong`:this.keepalive.receivePong(),f(Date.now());break;case`hello`:this.handleLeaderHello(e.protocolVersion);break;default:{let t=l(e);E.warn(`Unknown leader message type — skewed leader?`,{type:t.type});break}}}handleUserMessageEcho(e){if(this.sentMessageIds.has(e.messageId)){this.sentMessageIds.delete(e.messageId),E.debug(`Skipping own message echo`,{messageId:e.messageId});return}E.info(`User message echo received`,{messageId:e.messageId,scoopJid:e.scoopJid}),this.options.onUserMessage?.(e.text,e.messageId,e.scoopJid,e.attachments)}handleScoopsList(e,t){E.info(`Scoops list received from leader`,{scoopCount:e.length}),this.options.onScoopsList?.(e,t)}handleSprinkleReloaded(e){this.sprinkleContentCache.delete(e),this.options.onSprinkleReloaded?.(e)}handleSprinkleContent(e){let{requestId:t,sprinkleName:n,content:r,chunkIndex:i,totalChunks:a,error:o}=e;if(o){E.warn(`sprinkle.content error from leader`,{sprinkleName:n,error:o}),this.pendingSprinkleFetches.delete(t),this.inflightSprinkleByName.delete(n),this.fetchEpoch.delete(t);let e=this.sprinkleContentWaiters.get(n)??[];this.sprinkleContentWaiters.delete(n);for(let t of e)t.reject(Error(o));return}if(!this.pendingSprinkleFetches.has(t)){E.debug(`Dropping sprinkle.content for unknown requestId`,{sprinkleName:n,requestId:t});return}let s=null;if(i!==void 0&&a!==void 0){if(i<0||i>=a){E.warn(`Dropping sprinkle.content with out-of-range chunkIndex`,{sprinkleName:n,chunkIndex:i,totalChunks:a});return}let e=this.pendingSprinkleFetches.get(t);if(e.totalChunks=a,e.chunks.has(i)?E.warn(`Dropping duplicate sprinkle.content chunk`,{sprinkleName:n,chunkIndex:i}):e.chunks.set(i,r),e.chunks.size>=a){let r=[];for(let t=0;t<a;t++){let i=e.chunks.get(t);if(i===void 0){E.warn(`Chunked sprinkle.content missing chunk after assembly`,{sprinkleName:n,missingIndex:t});return}r.push(i)}s=r.join(``),this.pendingSprinkleFetches.delete(t)}}else s=r,this.pendingSprinkleFetches.delete(t);if(s===null)return;let c=this.fetchEpoch.get(t);this.fetchEpoch.delete(t),c===this.cacheEpoch&&this.sprinkleContentCache.set(n,s),this.inflightSprinkleByName.delete(n);let l=this.sprinkleContentWaiters.get(n)??[];this.sprinkleContentWaiters.delete(n);for(let e of l)e.resolve(s)}rejectPendingSprinkleFetches(e){let t=Error(e);for(let[,e]of this.sprinkleContentWaiters)for(let n of e)n.reject(t);this.sprinkleContentWaiters.clear(),this.pendingSprinkleFetches.clear(),this.inflightSprinkleByName.clear(),this.fetchEpoch.clear()}applyLeaderTheme(t){e(async()=>{let{importTheme:e,saveCustomTheme:t,setActiveTheme:n,clearActiveTheme:r,applyThemeOverrides:i}=await import(`./theme-engine-jfuTMXZM.js`).then(e=>e.p);return{importTheme:e,saveCustomTheme:t,setActiveTheme:n,clearActiveTheme:r,applyThemeOverrides:i}},__vite__mapDeps([0,1,2])).then(({importTheme:e,saveCustomTheme:n,setActiveTheme:r,clearActiveTheme:i,applyThemeOverrides:a})=>{if(!t)i();else{let i=e(t);n(i),r(i.id)}a()}).catch(e=>E.error(`Failed to apply leader theme`,{err:e}))}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch(t){E.error(`Listener error`,{eventType:e.type,error:t instanceof Error?t.message:String(t)})}}createRemoteTransport(e,t){let n=new p({sendCDPRequest:(n,r,i,a)=>{this.sync.send({type:`cdp.request`,requestId:n,targetRuntimeId:e,localTargetId:t,method:r,params:i,sessionId:a})}});return this.remoteTransports.set(`${e}:${t}`,n),n}removeRemoteTransport(e,t){let n=`${e}:${t}`,r=this.remoteTransports.get(n);r&&(r.disconnect(),this.remoteTransports.delete(n))}openRemoteTab(e,t){let n=`tab-open-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((r,i)=>{this.tabOpenResolvers.set(n,{resolve:r,reject:i}),this.sync.send({type:`tab.open`,requestId:n,targetRuntimeId:e,url:t})})}async executeLocalTabOpen(e,t){let n=this.options.browserTransport;if(!n){this.sync.send({type:`tab.open.error`,requestId:e,error:`Follower has no browser transport`});return}try{let r=(await n.send(`Target.createTarget`,{url:t,background:!0})).targetId;if(typeof r!=`string`||r.length===0){this.sync.send({type:`tab.open.error`,requestId:e,error:`Target.createTarget did not return a usable targetId`});return}this.sync.send({type:`tab.opened`,requestId:e,targetId:r}),this.options.onTargetsChanged?.()}catch(t){this.sync.send({type:`tab.open.error`,requestId:e,error:t instanceof Error?t.message:String(t)})}}async executeLocalCDP(e,t,n,r,i){let o=this.options.browserTransport;if(!o){this.sync.send({type:`cdp.response`,requestId:e,error:`Follower has no browser transport`});return}try{let t=await o.send(n,r,i);if(n===`Target.attachToTarget`&&t.sessionId){let e=t.sessionId;this.remoteCDPSessions.add(e),this.setupCDPEventForwarding(o,e),E.debug(`Tracking remote CDP session`,{remoteSessionId:e})}n===`Target.detachFromTarget`&&i&&this.remoteCDPSessions.has(i)&&(this.remoteCDPSessions.delete(i),E.debug(`Removed remote CDP session on detach`,{sessionId:i})),a(this.sync,e,t)}catch(t){this.sync.send({type:`cdp.response`,requestId:e,error:t instanceof Error?t.message:String(t)})}}setupCDPEventForwarding(e,t){for(let n of[`Page.frameNavigated`,`Page.loadEventFired`,`Page.domContentEventFired`,`Network.responseReceived`,`Network.loadingFinished`,`Network.requestWillBeSent`]){let r=e=>{if(e.sessionId!==t||!this.remoteCDPSessions.has(t))return;let{sessionId:r,...i}=e;this.sync.send({type:`cdp.event`,method:n,params:i,sessionId:t})};e.on(n,r),this.cdpEventCleanups.push(()=>e.off(n,r))}}cleanupCDPEventForwarding(){for(let e of this.cdpEventCleanups)e();this.cdpEventCleanups.length=0,this.remoteCDPSessions.clear()}routeCDPResponse(e){let t=s(this.cdpChunkBuffers,e);if(t)for(let n of this.remoteTransports.values())n.handleResponse(e.requestId,t.result,t.error)}async executeLocalFs(e,t){let n=this.options.vfs;if(!n){this.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:`Follower has no VFS`}});return}let r;try{r=await b(n,t)}catch(t){this.sync.send({type:`fs.response`,requestId:e,response:{ok:!1,error:t instanceof Error?t.message:String(t)}});return}for(let t of r)this.sync.send({type:`fs.response`,requestId:e,response:t})}routeFsResponse(e,t){let n=this.fsResolvers.get(e);if(!n)return;n.responses.push(t);let r=t.ok&&t.totalChunks||1;n.responses.length>=r&&(this.fsResolvers.delete(e),n.resolve(n.responses))}sendFsRequest(e,t){let n=`fs-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((r,i)=>{this.fsResolvers.set(n,{resolve:r,reject:i,responses:[]}),this.sync.send({type:`fs.request`,requestId:n,targetRuntimeId:e,request:t})})}},k=n(`tray-follower`);function A(e){let t=new URL(e);return t.searchParams.set(`json`,`true`),t.toString()}async function ae(e){let t=A(e.joinUrl),n=await I(await(e.fetchImpl??fetch)(t,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({controllerId:e.controllerId,runtime:e.runtime})}));return k.info(`Follower tray attach response`,{trayId:n.trayId,action:n.result.action,code:n.result.code,participantCount:n.participantCount}),oe(n)}function oe(e){let t={trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,action:e.result.action,code:e.result.code,iceServers:e.iceServers};return e.result.action===`wait`?{...t,retryAfterMs:e.result.retryAfterMs}:e.result.action===`signal`?{...t,bootstrap:e.result.bootstrap}:e.result.action===`fail`?{...t,error:e.result.error,...e.result.code===`TRAY_SUPERSEDED`?{supersededByJoinUrl:e.result.joinUrl}:{}}:t}async function j(e){return F(await L(e,{action:`poll`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,cursor:e.cursor}))}async function M(e){return F(await L(e,{action:`answer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,answer:e.answer}))}async function N(e){return F(await L(e,{action:`ice-candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:e.candidate}))}async function P(e){return F(await L(e,{action:`retry`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,runtime:e.runtime}))}function F(e){return{trayId:e.trayId,controllerId:e.controllerId,participantCount:e.participantCount,leader:e.leader,bootstrap:e.bootstrap,events:e.events}}async function I(e){let t=null,n=null;try{t=await e.text(),n=JSON.parse(t)}catch{}if(!R(n)){let n=t?t.slice(0,200):`(empty)`;throw k.warn(`Tray follower attach returned an invalid response`,{status:e.status,body:n}),Error(`Tray follower attach returned an invalid response (${e.status}): ${n}`)}return n}async function L(e,t){let n=A(e.joinUrl),r=await(e.fetchImpl??fetch)(n,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),i=await r.json().catch(()=>null);if(!z(i))throw Error(`Tray follower bootstrap returned an invalid response (${r.status})`);return i}function R(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.trayId!=`string`||typeof t.controllerId!=`string`||t.role!==`follower`||typeof t.participantCount!=`number`)return!1;let n=t.result;if(!n||typeof n!=`object`)return!1;let r=n;return r.action===`wait`?(r.code===`LEADER_NOT_ELECTED`||r.code===`LEADER_NOT_CONNECTED`)&&typeof r.retryAfterMs==`number`:r.action===`signal`?r.code===`LEADER_CONNECTED`&&B(r.bootstrap):r.action===`fail`?r.code===`TRAY_SUPERSEDED`?typeof r.error==`string`&&typeof r.joinUrl==`string`:(r.code===`INVALID_JOIN_CAPABILITY`||r.code===`TRAY_EXPIRED`)&&typeof r.error==`string`:!1}function z(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.trayId==`string`&&typeof t.controllerId==`string`&&t.role===`follower`&&typeof t.participantCount==`number`&&B(t.bootstrap)&&Array.isArray(t.events)}function B(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.controllerId==`string`&&typeof t.bootstrapId==`string`&&typeof t.attempt==`number`&&typeof t.state==`string`&&typeof t.expiresAt==`string`&&typeof t.cursor==`number`&&typeof t.maxRetries==`number`&&typeof t.retriesRemaining==`number`}var V=n(`tray-webrtc`),H=`tray-control`,U=250,W=5,G=1e3,K=class{options;peerConnectionFactory;dataChannelLabel;peers=new Map;iceServers;constructor(e){this.options=e,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>q(this.iceServers)),this.dataChannelLabel=e.dataChannelLabel??H}setIceServers(e){this.iceServers=e}async handleControlMessage(e){e.type===`follower.join_requested`?(e.iceServers&&!this.iceServers&&(this.iceServers=e.iceServers),await this.handleJoinRequested(e)):e.type===`bootstrap.answer`?await this.peers.get(e.bootstrapId)?.peer.setRemoteDescription(e.answer):e.type===`bootstrap.ice_candidate`&&await this.peers.get(e.bootstrapId)?.peer.addIceCandidate(e.candidate)}getPeers(){return Array.from(this.peers.values()).map(({state:e})=>({...e}))}getChannel(e){return this.peers.get(e)?.channel??null}stop(){for(let e of this.peers.values())e.peer.close();this.peers.clear()}async handleJoinRequested(e){this.closeControllerPeers(e.controllerId);let t=this.peerConnectionFactory(),n={controllerId:e.controllerId,bootstrapId:e.bootstrapId,attempt:e.attempt,state:`connecting`,connectedAt:null,runtime:e.runtime},r=t.createDataChannel(this.dataChannelLabel);this.peers.set(e.bootstrapId,{state:n,peer:t,channel:r}),t.addEventListener(`icecandidate`,({candidate:t})=>{let n=Y(t);n&&this.options.sendControlMessage({type:`bootstrap.ice_candidate`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,candidate:n})}),t.addEventListener(`connectionstatechange`,()=>{let n=this.peers.get(e.bootstrapId);n&&(n.state.state===`connected`?(t.connectionState===`disconnected`||t.connectionState===`failed`)&&(V.warn(`Leader peer connection state changed post-connect`,{bootstrapId:e.bootstrapId,state:t.connectionState}),this.options.onPeerDisconnected?.(e.bootstrapId,`Peer connection ${t.connectionState}`)):t.connectionState===`failed`&&this.failPeer(e,`Leader peer connection failed before the data channel opened`))}),r.addEventListener(`open`,()=>{let t=this.peers.get(e.bootstrapId);!t||t.state.state===`connected`||(t.state.state=`connected`,t.state.connectedAt=new Date().toISOString(),this.options.onPeerConnected?.({...t.state},t.channel))}),r.addEventListener(`close`,()=>{let t=this.peers.get(e.bootstrapId);t&&(t.state.state===`connected`?(V.warn(`Leader data channel closed post-connect`,{bootstrapId:e.bootstrapId}),this.options.onPeerDisconnected?.(e.bootstrapId,`Data channel closed`)):this.failPeer(e,`Leader data channel closed before opening`))}),r.addEventListener(`error`,()=>{let t=this.peers.get(e.bootstrapId);t&&(t.state.state===`connected`?(V.warn(`Leader data channel error post-connect`,{bootstrapId:e.bootstrapId}),this.options.onPeerDisconnected?.(e.bootstrapId,`Data channel error`)):this.failPeer(e,`Leader data channel failed before opening`))});try{let n=await t.createOffer();await t.setLocalDescription(n),this.options.sendControlMessage({type:`bootstrap.offer`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,offer:J(t.localDescription??n,`offer`)})}catch(t){this.failPeer(e,t instanceof Error?t.message:String(t))}}closeControllerPeers(e){for(let[t,n]of this.peers.entries())n.state.controllerId===e&&(n.peer.close(),this.peers.delete(t))}failPeer(e,t){let n=this.peers.get(e.bootstrapId);if(n){n.peer.close(),this.peers.delete(e.bootstrapId);try{this.options.sendControlMessage({type:`bootstrap.failed`,controllerId:e.controllerId,bootstrapId:e.bootstrapId,code:`WEBRTC_BOOTSTRAP_FAILED`,message:t,retryable:!0,retryAfterMs:1e3})}catch(e){V.warn(`Failed to report tray bootstrap failure`,{error:e instanceof Error?e.message:String(e)})}}}},se=class{options;fetchImpl;peerConnectionFactory;controllerIdFactory;sleep;pollIntervalMs;iceServers;activePeer=null;stopped=!1;constructor(e){this.options=e,this.fetchImpl=e.fetchImpl??fetch,this.iceServers=e.iceServers,this.peerConnectionFactory=e.peerConnectionFactory??(()=>q(this.iceServers)),this.controllerIdFactory=e.controllerIdFactory??(()=>crypto.randomUUID()),this.sleep=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),this.pollIntervalMs=e.pollIntervalMs??U}async start(){this.stopped=!1;let e=this.controllerIdFactory(),t=Date.now();u({state:`connecting`,joinUrl:this.options.joinUrl,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:t,lastError:null}),V.info(`Follower tray join starting`,{joinUrl:this.options.joinUrl});let n=0,r=0;for(;;){X(this.stopped),n++;let t;try{t=await ae({joinUrl:this.options.joinUrl,controllerId:e,runtime:this.options.runtime,fetchImpl:this.fetchImpl})}catch(e){let t=e instanceof Error?e.message:String(e);throw u({...d(),attachAttempts:n,lastError:t}),e}if(u({...d(),attachAttempts:n,lastAttachCode:t.code}),this.followSupersededJoinUrl(t,r)){r++,await this.sleep(G);continue}if(t.action===`wait`){let e=t.retryAfterMs??1e3;V.info(`Follower tray attach waiting`,{attempt:n,code:t.code,retryAfterMs:e}),n%10==0&&V.warn(`Follower tray attach still waiting after ${n} attempts`,{attempt:n,code:t.code,retryAfterMs:e}),await this.sleep(e);continue}if(t.action===`fail`||!t.bootstrap){let e=t.error??`Tray follower attach failed (${t.code})`;throw u({state:`error`,joinUrl:this.options.joinUrl,trayId:null,error:e,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:e}),V.warn(`Follower tray attach failed`,{error:e}),Error(e)}t.iceServers&&(this.iceServers=t.iceServers);try{let r=await this.completeBootstrap(t.trayId,e,t.bootstrap);return u({state:`connected`,joinUrl:this.options.joinUrl,trayId:r.trayId,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:null}),V.info(`Follower tray connected`,{trayId:r.trayId,controllerId:e}),r}catch(e){let r=e instanceof Error?e.message:String(e);throw u({state:`error`,joinUrl:this.options.joinUrl,trayId:t.trayId,error:r,lastPingTime:null,reconnectAttempts:0,attachAttempts:n,lastAttachCode:t.code,connectingSince:null,lastError:r}),V.warn(`Follower tray bootstrap failed`,{error:r}),e}}}followSupersededJoinUrl(e,t){if(e.action!==`fail`||e.code!==`TRAY_SUPERSEDED`||!e.supersededByJoinUrl)return!1;if(t>=W)throw Error(`Follower tray attach gave up after ${t} supersede redirects (possible redirect cycle)`);let n;try{n=new URL(e.supersededByJoinUrl)}catch{throw Error(`Follower tray superseded with an invalid joinUrl: ${e.supersededByJoinUrl}`)}return V.info(`Follower tray superseded, following redirect`,{oldJoinUrl:this.options.joinUrl,newJoinUrl:n.toString()}),this.options.joinUrl=n.toString(),this.options.onJoinUrlChanged?.(n.toString()),!0}stop(){this.stopped=!0,this.activePeer?.peer.close(),this.activePeer?.channel?.close(),this.activePeer=null,u({state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null})}async completeBootstrap(e,t,n){let r=n,i=0;for(this.activePeer=this.createFollowerPeer(t,r.bootstrapId);;){if(X(this.stopped),this.activePeer.open&&this.activePeer.channel)return{trayId:e,controllerId:t,bootstrapId:r.bootstrapId,channel:this.activePeer.channel};if(this.activePeer.openError)throw Error(this.activePeer.openError);let n=await j({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,cursor:i,fetchImpl:this.fetchImpl});r=n.bootstrap,i=r.cursor;try{await this.applyBootstrapEvents(n.events,this.activePeer,t,r.bootstrapId)}catch(e){if(r.failure?.retryable&&r.retriesRemaining>0){r=(await P({joinUrl:this.options.joinUrl,controllerId:t,bootstrapId:r.bootstrapId,runtime:this.options.runtime,fetchImpl:this.fetchImpl})).bootstrap,i=0,this.activePeer.peer.close(),this.activePeer=this.createFollowerPeer(t,r.bootstrapId);continue}throw e}this.activePeer.open||await this.sleep(this.pollIntervalMs)}}async applyBootstrapEvents(e,t,n,r){for(let i of e)if(i.type===`bootstrap.offer`){await t.peer.setRemoteDescription(i.offer);let e=await t.peer.createAnswer();await t.peer.setLocalDescription(e),await M({joinUrl:this.options.joinUrl,controllerId:n,bootstrapId:r,answer:J(t.peer.localDescription??e,`answer`),fetchImpl:this.fetchImpl})}else if(i.type===`bootstrap.ice_candidate`)await t.peer.addIceCandidate(i.candidate);else if(i.type===`bootstrap.failed`)throw Error(i.failure.message)}createFollowerPeer(e,t){let n=this.peerConnectionFactory(),r={peer:n,channel:null,open:!1,openError:null};return n.addEventListener(`connectionstatechange`,()=>{r.open&&(n.connectionState===`disconnected`||n.connectionState===`failed`)&&(V.warn(`Follower peer connection state changed post-connect`,{bootstrapId:t,state:n.connectionState}),this.options.onDisconnected?.(`Peer connection ${n.connectionState}`))}),n.addEventListener(`datachannel`,({channel:e})=>{r.channel=e,e.addEventListener(`open`,()=>{r.open=!0}),e.addEventListener(`close`,()=>{r.open?(V.warn(`Follower data channel closed post-connect`,{bootstrapId:t}),this.options.onDisconnected?.(`Data channel closed`)):r.openError=`Follower data channel closed before opening`}),e.addEventListener(`error`,()=>{r.open?(V.warn(`Follower data channel error post-connect`,{bootstrapId:t}),this.options.onDisconnected?.(`Data channel error`)):r.openError=`Follower data channel failed before opening`})}),n.addEventListener(`icecandidate`,({candidate:n})=>{let r=Y(n);r&&N({joinUrl:this.options.joinUrl,controllerId:e,bootstrapId:t,candidate:r,fetchImpl:this.fetchImpl}).catch(e=>{V.warn(`Failed to send follower ICE candidate`,{error:e instanceof Error?e.message:String(e)})})}),r}};function ce(e,t){let n=t.baseDelayMs??1e3,r=t.backoffMultiplier??2,i=t.maxDelayMs??3e4,a=t.maxAttempts??10,o=t.sleep??e.sleep??(e=>new Promise(t=>setTimeout(t,e))),s=!1,c=!1,l=null,f={cancel(){s=!0,c=!1,l?.stop(),l=null},get reconnecting(){return c}},p=()=>{let t=new se({...e,sleep:o,onDisconnected:e=>{s||(V.warn(`Follower disconnected, starting reconnect loop`,{reason:e}),m(e))},onJoinUrlChanged:t=>{e.joinUrl=t,e.onJoinUrlChanged?.(t)}});return l=t,{manager:t,connectionPromise:t.start()}},m=async f=>{if(s||c)return;c=!0,l?.stop(),l=null;let m=0,h=n,g=f??`Unknown disconnect`;for(;!s&&m<a&&(m++,t.onReconnecting?.(m),u({...d(),state:`reconnecting`,error:null,reconnectAttempts:m}),V.info(`Reconnect attempt`,{attempt:m,delay:h}),await o(h),!s);){let n=null;try{let r=p();n=r.manager;let i=await r.connectionPromise;if(s){n.stop();break}c=!1,u({...d(),state:`connected`,joinUrl:e.joinUrl,trayId:i.trayId,error:null,lastPingTime:null,reconnectAttempts:0,connectingSince:null,lastError:null}),V.info(`Reconnect successful`,{attempt:m,trayId:i.trayId}),t.onConnected(i);return}catch(e){g=e instanceof Error?e.message:String(e),V.warn(`Reconnect attempt failed`,{attempt:m,error:g}),n?.stop(),l=null}h=Math.min(h*r,i)}s||(c=!1,u({...d(),state:`error`,error:`Reconnect failed after ${m} attempts: ${g}`,reconnectAttempts:m}),V.warn(`Reconnect gave up`,{attempts:m,lastError:g}),t.onGaveUp?.(g))},{connectionPromise:h}=p();return h.then(e=>{s||t.onConnected(e)}).catch(e=>{s||(V.error(`Initial follower connection failed`,{error:e instanceof Error?e.message:String(e)}),m(e instanceof Error?e.message:String(e)))}),f}function q(e){if(typeof RTCPeerConnection>`u`)throw Error(`RTCPeerConnection is not available in this runtime`);let t=e?.length?{iceServers:e}:void 0;return new RTCPeerConnection(t)}function J(e,t){if(!e||e.type!==t||typeof e.sdp!=`string`)throw Error(`Expected a local ${t} description before signaling`);return{type:e.type,sdp:e.sdp}}function Y(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.candidate==`string`?{candidate:t.candidate,sdpMid:typeof t.sdpMid==`string`?t.sdpMid:null,sdpMLineIndex:typeof t.sdpMLineIndex==`number`?t.sdpMLineIndex:null,usernameFragment:typeof t.usernameFragment==`string`?t.usernameFragment:null}:null}function X(e){if(e)throw Error(`Tray follower stopped before WebRTC bootstrap completed`)}function Z(e){if(!e)throw Error(`canonicalRuntimeId: bootstrapId is required`);return e.startsWith(`follower-`)?e:`follower-${e}`}var Q=n(`sprinkle-follower`),le=class{sync;addSprinkle;removeSprinkle;zone;openPath;open=new Map;opening=new Set;latestDesiredOpen=new Set;pendingUpdates=new Map;updateListeners=new Map;disposed=!1;constructor(e){this.sync=e.sync,this.addSprinkle=e.addSprinkle,this.removeSprinkle=e.removeSprinkle,this.zone=e.zone,this.openPath=e.open}async updateAvailable(e){if(this.disposed)return;let t=new Map;for(let n of e)n.open&&t.set(n.name,n);this.latestDesiredOpen=new Set(t.keys());for(let e of[...this.open.keys()])t.has(e)||this.closeLocally(e);for(let e of[...this.pendingUpdates.keys()])t.has(e)||this.pendingUpdates.delete(e);let n=[];for(let[e,r]of t)this.open.has(e)||this.opening.has(e)||n.push(this.openLocally(e,r));await Promise.allSettled(n)}handleSprinkleUpdate(e,t){if(this.disposed)return;let n=this.open.get(e);if(n){n.renderer.pushUpdate(t),this.fanOutToListeners(e,t);return}if(this.opening.has(e)){this.pendingUpdates.set(e,t);return}Q.debug(`Dropping sprinkle.update for unknown sprinkle`,{sprinkleName:e})}async handleSprinkleReloaded(e){if(this.disposed)return;let t=this.open.get(e);if(!t){this.opening.has(e)&&this.pendingUpdates.delete(e);return}this.updateListeners.delete(e);let n;try{n=await this.sync.fetchSprinkleContent(e)}catch(t){Q.warn(`Failed to fetch sprinkle content for reload`,{sprinkleName:e,error:t instanceof Error?t.message:String(t)});return}if(this.disposed||!this.open.has(e))return;try{t.renderer.dispose()}catch(t){Q.warn(`Sprinkle dispose threw during reload`,{sprinkleName:e,error:t instanceof Error?t.message:String(t)})}let r=this.createBridge(e),i=new h(t.container,r);try{await i.render(n,e)}catch(t){Q.warn(`Sprinkle re-render failed during reload`,{sprinkleName:e,error:t instanceof Error?t.message:String(t)})}if(this.disposed||!this.open.has(e)){i.dispose();return}t.renderer=i,Q.info(`Sprinkle reloaded in place`,{sprinkleName:e})}dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.open.keys()])this.closeLocally(e);this.pendingUpdates.clear(),this.latestDesiredOpen.clear(),this.updateListeners.clear()}}async openLocally(e,t){this.opening.add(e);let n;try{n=await this.sync.fetchSprinkleContent(e)}catch(t){this.opening.delete(e),this.pendingUpdates.delete(e),Q.warn(`Failed to fetch sprinkle content from leader`,{sprinkleName:e,error:t instanceof Error?t.message:String(t)});return}if(this.disposed||!this.latestDesiredOpen.has(e)){this.opening.delete(e),this.pendingUpdates.delete(e);return}let r=document.createElement(`div`);r.className=`sprinkle-panel`,r.style.cssText=`width: 100%; height: 100%; display: flex; flex-direction: column; overflow-y: auto;`,r.dataset.sprinkle=e;let i=new h(r,this.createBridge(e));this.addSprinkle(e,t.title,r,this.zone,{icon:t.icon});try{await i.render(n,e)}catch(t){Q.warn(`Sprinkle render failed`,{sprinkleName:e,error:t instanceof Error?t.message:String(t)})}if(this.disposed||!this.latestDesiredOpen.has(e)){this.updateListeners.delete(e),this.opening.delete(e),this.pendingUpdates.delete(e);try{i.dispose()}catch(t){Q.warn(`Sprinkle dispose threw during post-render cleanup`,{sprinkleName:e,error:t instanceof Error?t.message:String(t)})}r.remove();try{this.removeSprinkle(e)}catch(t){Q.warn(`removeSprinkle callback threw during post-render cleanup`,{sprinkleName:e,error:t instanceof Error?t.message:String(t)})}return}this.open.set(e,{renderer:i,container:r}),this.opening.delete(e);let a=this.pendingUpdates.get(e);a!==void 0&&(this.pendingUpdates.delete(e),i.pushUpdate(a),this.fanOutToListeners(e,a))}fanOutToListeners(e,t){let n=this.updateListeners.get(e);if(n)for(let r of[...n])try{r(t)}catch(t){Q.warn(`Sprinkle update listener threw`,{sprinkleName:e,error:t instanceof Error?t.message:String(t)})}}closeLocally(e){this.updateListeners.delete(e),this.pendingUpdates.delete(e);let t=this.open.get(e);if(t){try{t.renderer.dispose()}catch(t){Q.warn(`Sprinkle dispose threw`,{sprinkleName:e,error:t instanceof Error?t.message:String(t)})}t.container.remove(),this.open.delete(e);try{this.removeSprinkle(e)}catch(t){Q.warn(`removeSprinkle callback threw`,{sprinkleName:e,error:t instanceof Error?t.message:String(t)})}}}createBridge(e){return{name:e,lick:t=>{let n=typeof t==`string`?t:t.action,r=typeof t==`string`?void 0:t.data;this.sync.sendSprinkleLick(e,{action:n,data:r})},on:(t,n)=>{if(t!==`update`)return;let r=this.updateListeners.get(e);r||(r=new Set,this.updateListeners.set(e,r)),r.add(n)},off:(t,n)=>{t===`update`&&this.updateListeners.get(e)?.delete(n)},readFile:()=>Promise.reject(Error(`readFile not supported in follower-rendered sprinkle`)),writeFile:()=>Promise.reject(Error(`writeFile not supported in follower-rendered sprinkle`)),readDir:()=>Promise.reject(Error(`readDir not supported in follower-rendered sprinkle`)),exists:()=>Promise.resolve(!1),stat:()=>Promise.reject(Error(`stat not supported in follower-rendered sprinkle`)),mkdir:()=>Promise.reject(Error(`mkdir not supported in follower-rendered sprinkle`)),rm:()=>Promise.reject(Error(`rm not supported in follower-rendered sprinkle`)),screenshot:()=>Promise.reject(Error(`screenshot not supported in follower-rendered sprinkle`)),setState:t=>{try{localStorage.setItem(`slicc-sprinkle-state:${e}`,JSON.stringify(t))}catch(t){Q.warn(`Sprinkle setState failed`,{sprinkleName:e,error:t instanceof Error?t.message:String(t)})}},getState:()=>{try{let t=localStorage.getItem(`slicc-sprinkle-state:${e}`);return t?JSON.parse(t):null}catch(t){return Q.warn(`Sprinkle getState failed`,{sprinkleName:e,error:t instanceof Error?t.message:String(t)}),null}},open:e=>{if(this.openPath){this.openPath(e);return}let t=/^https?:|^chrome-extension:/.test(e)?e:m(e);window.open(t,`_blank`)},close:()=>this.closeLocally(e),minimize:()=>{},stopCone:()=>{this.sync.sendSprinkleLick(e,{action:`__stopCone__`})},attachImage:()=>{},captureScreen:()=>Promise.reject(Error(`captureScreen not supported in follower-rendered sprinkle`)),exec:Object.assign(()=>Promise.resolve({stdout:``,stderr:`exec not supported in follower-rendered sprinkle
3
+ `,exitCode:127}),{spawn:()=>Promise.resolve({stdout:``,stderr:`exec.spawn not supported in follower-rendered sprinkle
4
+ `,exitCode:127})}),agent:()=>Promise.resolve({stdout:`agent not supported in follower-rendered sprinkle
5
+ `,exitCode:127}),fetch:()=>Promise.reject(Error(`fetch not supported in follower-rendered sprinkle`)),http:{client:()=>{let e=()=>Promise.reject(Error(`http not supported in follower-rendered sprinkle`));return{get:e,post:e,put:e,patch:e,delete:e}}},browser:{findTab:()=>Promise.reject(Error(`browser not supported in follower-rendered sprinkle`)),ensureTab:()=>Promise.reject(Error(`browser not supported in follower-rendered sprinkle`)),eval:()=>Promise.reject(Error(`browser not supported in follower-rendered sprinkle`)),evalAsync:()=>Promise.reject(Error(`browser not supported in follower-rendered sprinkle`)),cookie:()=>Promise.reject(Error(`browser not supported in follower-rendered sprinkle`)),localStorage:()=>Promise.reject(Error(`browser not supported in follower-rendered sprinkle`)),fetch:()=>Promise.reject(Error(`browser not supported in follower-rendered sprinkle`))},hid:{list:()=>Promise.reject(Error(`hid not supported in follower-rendered sprinkle`)),request:()=>Promise.reject(Error(`hid not supported in follower-rendered sprinkle`)),open:()=>Promise.reject(Error(`hid not supported in follower-rendered sprinkle`)),close:()=>Promise.reject(Error(`hid not supported in follower-rendered sprinkle`)),sendReport:()=>Promise.reject(Error(`hid not supported in follower-rendered sprinkle`)),on:()=>{},off:()=>{}},serial:{list:()=>Promise.reject(Error(`serial not supported in follower-rendered sprinkle`)),request:()=>Promise.reject(Error(`serial not supported in follower-rendered sprinkle`)),open:()=>Promise.reject(Error(`serial not supported in follower-rendered sprinkle`)),close:()=>Promise.reject(Error(`serial not supported in follower-rendered sprinkle`))},usb:{list:()=>Promise.reject(Error(`usb not supported in follower-rendered sprinkle`)),request:()=>Promise.reject(Error(`usb not supported in follower-rendered sprinkle`)),open:()=>Promise.reject(Error(`usb not supported in follower-rendered sprinkle`)),close:()=>Promise.reject(Error(`usb not supported in follower-rendered sprinkle`))},readFileBinary:()=>Promise.reject(Error(`readFileBinary not supported in follower-rendered sprinkle`)),writeFileBinary:()=>Promise.reject(Error(`writeFileBinary not supported in follower-rendered sprinkle`)),fetchToFile:()=>Promise.reject(Error(`fetchToFile not supported in follower-rendered sprinkle`)),_jsh:()=>Promise.reject(Error(`jsh globals not supported in follower-rendered sprinkle`)),_device:()=>Promise.reject(Error(`device ops not supported in follower-rendered sprinkle`))}}},$=n(`page-follower-tray`);function ue(e,t){return t===`slicc-cherry`?e.map(e=>({targetId:e.targetId,title:e.title,url:e.url,kind:`cherry`,capabilities:{navigate:!0,network:!1,screenshot:!0}})):e.map(e=>({targetId:e.targetId,title:e.title,url:e.url}))}function de(e){let t=e._refreshIntervalMs??5e3,n=null,r=null,i=null,a=null,o=(t=!0)=>{i&&=(clearInterval(i),null),r&&=(r.dispose(),null),n&&=(e.onForwardingToggle?.(!1),t&&e.onConnectionChange?.(!1),e.browserAPI.setTrayTargetProvider(null),n.close(),null)};return a=ce({joinUrl:e.joinUrl,runtime:e.runtime??`slicc-standalone`,fetchImpl:e._fetchImpl,peerConnectionFactory:e._peerConnectionFactory,sleep:e._sleep,onJoinUrlChanged:e.onJoinUrlChanged},{onConnected:a=>{o();let s=Z(a.bootstrapId),c=null,l=new O(a.channel,{browserTransport:e.browserAPI.getTransport(),browserAPI:e.browserAPI,onSnapshot:e.onSnapshot,onUserMessage:e.onUserMessage,onStatus:e.onStatus,onCherrySliccEvent:e.onCherrySliccEvent,onScoopsList:e.onScoopsList,selfRuntimeId:s,onTargetsChanged:()=>void d(),onSprinklesList:t=>{e.onSprinklesList?.(t),c?.updateAvailable(t)},onSprinkleUpdate:(e,t)=>c?.handleSprinkleUpdate(e,t),onSprinkleReloaded:e=>void c?.handleSprinkleReloaded(e),onDisconnect:e=>{$.warn(`Follower sync disconnected`,{reason:e}),o()}});e.addSprinkle&&e.removeSprinkle&&(c=new le({sync:l,addSprinkle:e.addSprinkle,removeSprinkle:e.removeSprinkle,open:e.onOpen}),r=c);let u=new g($,{failureMessage:`Follower CDP target listing failed (best-effort, throttled)`,recoveryMessage:`Follower CDP target listing recovered (stable for debounce window)`}),d=async()=>{if(e.uiOnly)return;let t;try{t=await e.browserAPI.listPages()}catch(e){u.reportFailure(e);return}if(n===l){u.reportSuccess();try{l.advertiseTargets(ue(t,e.runtime??`slicc-standalone`),s)}catch(e){$.error(`Follower target advertisement broadcast failed (sync.advertiseTargets threw)`,{error:e instanceof Error?e.message:String(e)})}}};n=l,e.browserAPI.setTrayTargetProvider(l),e.setChatAgent(l),e.onForwardingToggle?.(!0),e.onConnectionChange?.(!0),l.requestSnapshot(),e.uiOnly||(i=setInterval(()=>void d(),t),d()),$.info(`Follower sync wired`,{trayId:a.trayId})},onReconnecting:e=>{$.info(`Follower reconnecting`,{attempt:e})},onGaveUp:t=>{$.warn(`Follower reconnect gave up`,{lastError:t}),o(!1),e.onGaveUp?.(t)},sleep:e._sleep}),{stop(){o(),a?.cancel(),a=null,u({state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null})},get currentSync(){return n}}}export{v as a,b as i,Z as n,g as o,K as r,de as t};