pipane 0.1.5 → 0.1.7

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 (138) hide show
  1. package/README.md +45 -1
  2. package/THIRD_PARTY_NOTICES.md +29 -0
  3. package/bin/pipane-rendezvous.js +21 -0
  4. package/bin/pipane.js +21 -1
  5. package/dist/client/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  6. package/dist/client/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  7. package/dist/client/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  8. package/dist/client/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  9. package/dist/client/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  10. package/dist/client/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  11. package/dist/client/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  12. package/dist/client/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  13. package/dist/client/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  14. package/dist/client/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  15. package/dist/client/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  16. package/dist/client/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  17. package/dist/client/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  18. package/dist/client/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  19. package/dist/client/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  20. package/dist/client/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  21. package/dist/client/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  22. package/dist/client/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  23. package/dist/client/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  24. package/dist/client/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  25. package/dist/client/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  26. package/dist/client/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  27. package/dist/client/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  28. package/dist/client/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  29. package/dist/client/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  30. package/dist/client/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  31. package/dist/client/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  32. package/dist/client/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  33. package/dist/client/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  34. package/dist/client/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  35. package/dist/client/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  36. package/dist/client/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  37. package/dist/client/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  38. package/dist/client/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  39. package/dist/client/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  40. package/dist/client/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  41. package/dist/client/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  42. package/dist/client/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  43. package/dist/client/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  44. package/dist/client/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  45. package/dist/client/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  46. package/dist/client/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  47. package/dist/client/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  48. package/dist/client/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  49. package/dist/client/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  50. package/dist/client/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  51. package/dist/client/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  52. package/dist/client/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  53. package/dist/client/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  54. package/dist/client/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  55. package/dist/client/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  56. package/dist/client/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  57. package/dist/client/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  58. package/dist/client/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  59. package/dist/client/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  60. package/dist/client/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  61. package/dist/client/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  62. package/dist/client/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  63. package/dist/client/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  64. package/dist/client/assets/__vite-browser-external-DtLbhLGx.js +1 -0
  65. package/dist/client/assets/app-runtime-Rw-O-AwW.js +1 -0
  66. package/dist/client/assets/backend-landing-page-B7SbyIXQ.js +1 -0
  67. package/dist/client/assets/index-DwbBcYUf.js +2 -0
  68. package/dist/client/assets/index-iblQYBAl.css +1 -0
  69. package/dist/client/assets/main-LGItV9Aj.js +2807 -0
  70. package/dist/client/assets/pairing-page-D-WxlWZR.js +1 -0
  71. package/dist/client/assets/remote-backend-manager-BWuGh30I.js +1 -0
  72. package/dist/client/assets/rendezvous-trust-api-C2Zob5i4.js +4 -0
  73. package/dist/client/assets/webrtc-frame-transport-BijNnA7N.js +1 -0
  74. package/dist/client/assets/ws-agent-adapter-BRysf-Y7.js +6 -0
  75. package/dist/client/index.html +2 -2
  76. package/dist/server/rendezvous/rendezvous-hub.js +426 -0
  77. package/dist/server/rendezvous/server.js +247 -0
  78. package/dist/server/rendezvous/trust-store.js +432 -0
  79. package/dist/server/server/auth-guard.js +61 -0
  80. package/dist/server/server/backend-connection-authorizer.js +29 -0
  81. package/dist/server/server/backend-identity.js +167 -0
  82. package/dist/server/server/backend-protocol-handler.js +132 -0
  83. package/dist/server/server/backend-trust-store.js +157 -0
  84. package/dist/server/server/backend-webrtc.js +239 -0
  85. package/dist/server/server/bundled-extensions.js +6 -0
  86. package/dist/server/server/conversation-file-access.js +97 -0
  87. package/dist/server/server/extension-status.js +31 -0
  88. package/dist/server/server/frame-connection.js +48 -0
  89. package/dist/server/server/frame-router.js +45 -0
  90. package/dist/server/server/ice-servers.js +24 -0
  91. package/dist/server/server/local-backend-api.js +389 -0
  92. package/dist/server/server/local-settings.js +28 -0
  93. package/dist/server/server/pi-rpc-protocol.js +407 -0
  94. package/dist/server/server/pi-runtime.js +1 -1
  95. package/dist/server/server/process-pool.js +179 -136
  96. package/dist/server/server/rendezvous-client.js +282 -0
  97. package/dist/server/server/rest-api.js +121 -231
  98. package/dist/server/server/server.js +188 -134
  99. package/dist/server/server/session-actor.js +202 -0
  100. package/dist/server/server/session-index.js +111 -18
  101. package/dist/server/server/session-jsonl.js +128 -8
  102. package/dist/server/server/session-path.js +145 -0
  103. package/dist/server/server/session-registry.js +67 -0
  104. package/dist/server/server/update-api.js +28 -0
  105. package/dist/server/server/update-check.js +33 -13
  106. package/dist/server/server/update-manager.js +231 -0
  107. package/dist/server/server/worktree-name.js +124 -0
  108. package/dist/server/server/ws-handler.js +784 -478
  109. package/dist/server/shared/backend-api.js +1 -0
  110. package/dist/server/shared/backend-protocol.js +164 -0
  111. package/dist/server/shared/jsonl-sync.js +41 -0
  112. package/dist/server/shared/node-trust-crypto.js +61 -0
  113. package/dist/server/shared/rendezvous-protocol.js +243 -0
  114. package/dist/server/shared/rpc-timeouts.js +4 -0
  115. package/dist/server/shared/thinking-levels.js +94 -0
  116. package/dist/server/shared/tool-runtime.js +1 -0
  117. package/dist/server/shared/trust-protocol.js +97 -0
  118. package/dist/server/shared/updates.js +4 -0
  119. package/dist/server/shared/ws-protocol.js +473 -0
  120. package/docs/protocol.md +127 -0
  121. package/extensions/canvas.ts +1 -1
  122. package/package.json +42 -17
  123. package/dist/client/assets/_node-stub_node_crypto-C_7epg3G.js +0 -1
  124. package/dist/client/assets/_node-stub_node_fs-B-VOzeXW.js +0 -1
  125. package/dist/client/assets/_node-stub_node_http-CROXaVGJ.js +0 -1
  126. package/dist/client/assets/_node-stub_node_os-TTKJha15.js +0 -1
  127. package/dist/client/assets/_node-stub_node_path-DJCJiKv7.js +0 -1
  128. package/dist/client/assets/_node-stub_stream-DDexIdn_.js +0 -1
  129. package/dist/client/assets/index-BtDAXAo1.css +0 -1
  130. package/dist/client/assets/index-CAQqlK61.js +0 -131
  131. package/dist/client/assets/index-CJEeBmBj.js +0 -3
  132. package/dist/client/assets/index-DUEhKmPQ.js +0 -1
  133. package/dist/client/assets/index-XEVKscP-.js +0 -4443
  134. package/dist/client/assets/index-woI4agCy.js +0 -45
  135. package/dist/server/server/attached-session.js +0 -209
  136. package/dist/server/server/load-trace-store.js +0 -48
  137. package/dist/server/server/session-lifecycle.js +0 -155
  138. package/patches/@mariozechner+pi-web-ui+0.55.3.patch +0 -3437
@@ -0,0 +1 @@
1
+ import{R as y,l as f,p as h}from"./rendezvous-trust-api-C2Zob5i4.js";import{W as x}from"./webrtc-frame-transport-BijNnA7N.js";const w={loadIdentity:()=>f(),createTrustApi:()=>new y(window.location.origin),createTransport:i=>new x(i)};async function C(i=w){const p=document.getElementById("app")??document.body;p.replaceChildren();const o=document.createElement("main");Object.assign(o.style,{minHeight:"100vh",display:"grid",placeItems:"center",padding:"24px",background:"var(--background, #fff)",color:"var(--foreground, #111827)",fontFamily:"ui-sans-serif, system-ui, sans-serif"});const c=document.createElement("section");Object.assign(c.style,{width:"min(460px, 100%)",border:"1px solid var(--border, #d1d5db)",borderRadius:"12px",padding:"28px",boxShadow:"0 18px 45px rgba(0, 0, 0, 0.10)",background:"var(--card, #fff)"});const s=document.createElement("h1");s.textContent="Pair this browser",Object.assign(s.style,{margin:"0 0 8px",fontSize:"24px"});const d=document.createElement("p");d.textContent="pipane will create a private device key and ask the backend to authorize it.",Object.assign(d.style,{margin:"0 0 20px",lineHeight:"1.5",opacity:"0.75"});const e=document.createElement("p");e.dataset.testid="pairing-status",e.setAttribute("role","status"),Object.assign(e.style,{margin:"0",lineHeight:"1.5",fontWeight:"600"});const t=document.createElement("button");t.type="button",t.textContent="Try again",t.hidden=!0,Object.assign(t.style,{marginTop:"18px",border:"1px solid var(--border, #9ca3af)",borderRadius:"8px",padding:"9px 14px",background:"transparent",color:"inherit",cursor:"pointer"});const n=document.createElement("a");n.textContent="Open backend",n.dataset.testid="pairing-continue",n.hidden=!0,Object.assign(n.style,{display:"inline-block",marginTop:"18px",borderRadius:"8px",padding:"9px 14px",background:"#2563eb",color:"#fff",textDecoration:"none"}),c.append(s,d,e,t,n),o.append(c),p.append(o);let l=!1;const u=async()=>{if(l)return;l=!0,t.hidden=!0,e.textContent="Creating this browser's private device key…",n.hidden=!0;let r;try{const a=h(window.location.href),g=await i.loadIdentity(),m=i.createTrustApi();e.textContent="Contacting the backend…",r=i.createTransport({rendezvousUrl:window.location.origin,backendId:a.backendId,deviceIdentity:g,authorize:async()=>({...await m.createPairingTicket(g,a),pairingSecret:a.secret})}),await r.connect("webrtc"),r.close(1e3,"Pairing complete"),r=void 0;const b=`/backend/${encodeURIComponent(a.backendId)}`;window.history.replaceState(null,"",b),e.textContent="Paired successfully. This browser can now request connections to the backend.",e.style.color="#15803d",n.href=b,n.hidden=!1}catch(a){r?.close(1e3,"Pairing failed"),e.textContent=a instanceof Error?a.message:"Pairing failed",e.style.color="#b91c1c",t.hidden=!1}finally{l=!1}};t.addEventListener("click",()=>{u()}),await u()}export{C as initializePairingPage};
@@ -0,0 +1 @@
1
+ import{B as c,e as f,i as w,d as y}from"./__vite-browser-external-DtLbhLGx.js";import{R as g,l as m}from"./rendezvous-trust-api-C2Zob5i4.js";import{W as v}from"./webrtc-frame-transport-BijNnA7N.js";import{W as k}from"./ws-agent-adapter-BRysf-Y7.js";import"./index-DwbBcYUf.js";const A=3e4,E=10*6e4;class B extends Error{constructor(e){super(e.message),this.payload=e,this.name="DataChannelBackendApiError"}}class q{constructor(e,t,r=A){this.transport=e,this.backendId=t,this.requestTimeoutMs=r,this.requestId=0,this.pending=new Map,e.onFrame(i=>this.handleFrame(i)),e.onConnectionChange(({connected:i,reconnected:o})=>{if(!(!i||!o))for(const d of this.pending.values())try{this.transport.send(d.encodedFrame)}catch{}})}async getCapabilities(){const e=await this.request("backend.capabilities",{});if(!a(e)||e.backendId!==this.backendId||e.semanticProtocolVersion!==c||!S(e.applicationProtocolVersions)||!l(e.features))throw new Error("Backend returned invalid capabilities");return e}async listSessions(){const e=await this.request("sessions.list",{});if(!Array.isArray(e)||!e.every(T))throw new Error("Backend returned an invalid session list");return e.map(t=>({...t,backendId:this.backendId}))}async deleteSession(e){await this.request("sessions.delete",{sessionPath:e})}async listForkMessages(e){const t=await this.request("sessions.forkMessages",{sessionPath:e});if(!Array.isArray(t)||!t.every(r=>a(r)&&s(r.entryId)&&s(r.text)))throw new Error("Backend returned invalid fork messages");return t}async browseDirectory(e){const t=await this.request("host.browse",{path:e});if(!a(t)||!s(t.path)||!Array.isArray(t.dirs)||!t.dirs.every(r=>a(r)&&s(r.name)&&s(r.path)))throw new Error("Backend returned an invalid directory listing");return t}async createDirectory(e,t){const r=await this.request("host.mkdir",{parentPath:e,name:t});if(!a(r)||!s(r.name)||!s(r.path))throw new Error("Backend returned an invalid created folder");return r}async getRawSession(e){const t=await this.request("sessions.raw",{sessionPath:e});if(!s(t))throw new Error("Backend returned invalid raw session content");return t}async getFileContent(e,t){const r=await this.request("files.read",{sessionPath:e,path:t});if(!a(r)||!s(r.path)||!s(r.content))throw new Error("Backend returned invalid file content");return r}async createFileUpload(e){const t=await this.request("files.upload.create",e);if(!a(t)||!s(t.uploadId)||t.uploadId.length===0)throw new Error("Backend returned an invalid file upload session");return t}async appendFileUpload(e){const t=await this.request("files.upload.append",e);if(!a(t)||!Number.isSafeInteger(t.nextOffset)||t.nextOffset<0)throw new Error("Backend returned an invalid file upload offset");return t}async completeFileUpload(e){const t=await this.request("files.upload.complete",{uploadId:e});if(!a(t)||!s(t.path)||!s(t.fileName)||!s(t.mimeType)||!Number.isSafeInteger(t.size)||t.size<0)throw new Error("Backend returned an invalid uploaded file");return t}async getLocalSettings(){const e=await this.request("settings.get",{});if(!a(e)||!s(e.path)||typeof e.exists!="boolean"||!l(e.errors)||!s(e.formatted)||!("settings"in e))throw new Error("Backend returned invalid local settings");return e}validateLocalSettings(e){return this.settingsMutation("settings.validate",{content:e})}patchLocalSettings(e){return this.settingsMutation("settings.patch",{patch:e})}saveLocalSettings(e){return this.settingsMutation("settings.save",{content:e})}async getUpdates(){const e=await this.request("updates.get",{});if(!a(e)||!s(e.checkedAt)||!Array.isArray(e.notices))throw new Error("Backend returned an invalid update snapshot");return e}async runUpdate(e){const t=await this.request("updates.run",{target:e},E);if(!a(t)||!a(t.result)||!a(t.snapshot))throw new Error("Backend returned an invalid update result");return t}async settingsMutation(e,t){const r=await this.request(e,t);if(!a(r)||typeof r.valid!="boolean"||!l(r.errors)||r.formatted!==void 0&&!s(r.formatted))throw new Error("Backend returned an invalid settings response");return r}request(e,t,r=this.requestTimeoutMs){if(!this.transport.isConnected)return Promise.reject(new Error("Backend transport is not connected"));const i=`api_${++this.requestId}_${crypto.randomUUID()}`;return new Promise((o,d)=>{const h=f({v:c,kind:"request",id:i,method:e,params:t}),p=setTimeout(()=>{this.pending.delete(i),d(new Error(`Backend request timed out: ${e}`))},r);this.pending.set(i,{method:e,encodedFrame:h,resolve:o,reject:d,timer:p});try{this.transport.send(h)}catch(u){clearTimeout(p),this.pending.delete(i),d(u instanceof Error?u:new Error(String(u)))}})}handleFrame(e){if(!w(e))return;const t=y(e);if(!t.ok)return;const r=t.value,i=this.pending.get(r.id);if(i){if(clearTimeout(i.timer),this.pending.delete(r.id),r.method!==i.method){i.reject(new Error(`Backend response method mismatch: expected ${i.method}, received ${r.method}`));return}r.success?i.resolve(r.result):i.reject(new B(r.error))}}}function T(n){return a(n)&&s(n.id)&&s(n.path)&&s(n.cwd)&&s(n.created)&&s(n.modified)&&Number.isSafeInteger(n.messageCount)&&s(n.firstMessage)}function a(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function s(n){return typeof n=="string"}function l(n){return Array.isArray(n)&&n.every(s)}function S(n){return Array.isArray(n)&&n.every(e=>Number.isSafeInteger(e)&&e>0)}class F{constructor(e,t={loadIdentity:()=>m(),createTrustApi:()=>new g(e)}){this.rendezvousUrl=e,this.dependencies=t,this.descriptors=[],this.clients=new Map}async initialize(){return this.identity??=await this.dependencies.loadIdentity(),this.trustApi??=this.dependencies.createTrustApi(),this.descriptors=await this.trustApi.listAuthorizedBackends(this.identity),this.authorizedBackends}get authorizedBackends(){return this.descriptors.map(e=>({...e,protocolVersions:[...e.protocolVersions]}))}getClient(e){const t=this.clients.get(e);if(t)return t;if(!this.identity||!this.trustApi)throw new Error("Remote backend manager is not initialized");const r=this.descriptors.find(o=>o.backendId===e);if(!r)throw new Error("This browser is not authorized for the requested backend");if(r.online&&!r.protocolVersions.includes(c))throw new Error(`Backend does not support semantic protocol v${c}`);const i=this.dependencies.createClient?this.dependencies.createClient(e,this.identity,this.trustApi):this.createClient(e,this.identity,this.trustApi);return this.clients.set(e,i),i}async revokeBackend(e){if(!this.identity||!this.trustApi)throw new Error("Remote backend manager is not initialized");await this.trustApi.revokeBackend(this.identity,e),this.clients.get(e)?.disconnect(),this.clients.delete(e),this.descriptors=this.descriptors.filter(t=>t.backendId!==e)}disconnectAll(){for(const e of this.clients.values())e.disconnect();this.clients.clear()}createClient(e,t,r){const i=new v({rendezvousUrl:this.rendezvousUrl,backendId:e,deviceIdentity:t,authorize:()=>r.createConnectionTicket(t,e)}),o=new q(i,e);return new k({transport:i,api:o})}}export{F as RemoteBackendManager};
@@ -0,0 +1,4 @@
1
+ const P=1;const _="pipane",D="pipane.v1";function I(e){return["pipane-device-challenge-v1",e.challengeId,e.nonce,e.purpose,e.deviceId,e.devicePublicKey,e.backendId??"",e.connectionId??"",e.pairId??"",e.targetDeviceId??"",String(e.expiresAt)].join(`
2
+ `)}function g(e){return["pipane-backend-binding-v1",e.backendId,e.publicKey,e.connectionId,e.offerSha256,e.answerSha256,e.dtlsFingerprint,String(e.expiresAt)].join(`
3
+ `)}function S(e,t){return["pipane-device-connection-v1",e,t].join(`
4
+ `)}function N(e){if(!(!k(e)||e.version!==1||e.kind!=="pairing"&&e.kind!=="connection"||!c(e.ticketId)||!c(e.backendId)||!c(e.connectionId)||!c(e.deviceId)||!c(e.devicePublicKey)||!p(e.accountId)||!p(e.pairId)||!m(e.issuedAt)||!E(e.expiresAt)||e.expiresAt<=e.issuedAt)&&!(e.kind==="pairing"&&!c(e.pairId))&&!(e.kind==="connection"&&!c(e.accountId)))return e}function k(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function c(e){return typeof e=="string"&&e.length>0}function p(e){return e===void 0||c(e)}function m(e){return Number.isSafeInteger(e)&&e>=0}function E(e){return Number.isSafeInteger(e)&&e>0}const C=1,s="device-identities",l="default";async function U(e="pipane-device-identity"){const t=await h(e);try{const r=await v(t);return r?await f(r):void 0}finally{t.close()}}async function B(e="pipane-device-identity"){const t=await h(e);try{const r=await v(t);if(r)return f(r);const n=await A(),i=await crypto.subtle.importKey("spki",d(n.publicKey),{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);return await T(t,{version:1,privateKey:n.privateKey,publicKey:i,publicKeySpki:n.publicKey,deviceId:n.deviceId}),n}finally{t.close()}}async function A(){const e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"]);if(e.privateKey.extractable)throw new Error("Browser device private key must be non-exportable");const t=await crypto.subtle.exportKey("spki",e.publicKey),r=a(t);return{deviceId:`d_${a(await crypto.subtle.digest("SHA-256",t))}`,publicKey:r,privateKey:e.privateKey}}async function y(e,t){if(t.deviceId!==e.deviceId||t.devicePublicKey!==e.publicKey)throw new Error("Device challenge does not match this browser identity");return w(e.privateKey,I(t))}async function L(e,t,r){return w(e.privateKey,S(t,r))}async function $(e,t){const r=d(e.publicKey),n=`b_${a(await crypto.subtle.digest("SHA-256",r))}`;if(e.version!==1||n!==t.backendId||e.backendId!==t.backendId||e.connectionId!==t.connectionId||e.offerSha256!==await u(t.offerSdp)||e.answerSha256!==await u(t.answerSdp)||e.dtlsFingerprint!==K(t.answerSdp)||e.expiresAt!==t.expiresAt||e.expiresAt<=(t.now??Date.now()))throw new Error("Backend identity binding does not match the negotiated connection");const i=await crypto.subtle.importKey("spki",r,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),{signature:o,...b}=e;if(!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},i,d(o),new TextEncoder().encode(g(b))))throw new Error("Backend identity binding signature is invalid")}async function f(e){if(e.version!==1||!(e.privateKey instanceof CryptoKey)||!(e.publicKey instanceof CryptoKey)||e.privateKey.type!=="private"||e.privateKey.extractable||e.privateKey.algorithm.name!=="ECDSA"||typeof e.publicKeySpki!="string"||typeof e.deviceId!="string")throw new Error("Stored browser device identity is malformed");const t=await crypto.subtle.exportKey("spki",e.publicKey);if(a(t)!==e.publicKeySpki)throw new Error("Stored browser device public key changed");const r=`d_${a(await crypto.subtle.digest("SHA-256",t))}`;if(r!==e.deviceId)throw new Error("Stored browser device id is invalid");return{deviceId:r,publicKey:e.publicKeySpki,privateKey:e.privateKey}}async function w(e,t){const r=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,new TextEncoder().encode(t));return a(r)}async function u(e){return a(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))}function K(e){const t=/^a=fingerprint:(sha-(?:1|224|256|384|512)) ([A-Fa-f0-9:]+)\r?$/m.exec(e);if(!t)throw new Error("SDP answer is missing a DTLS certificate fingerprint");return`${t[1].toLowerCase()} ${t[2].toUpperCase()}`}function h(e){return new Promise((t,r)=>{const n=indexedDB.open(e,C);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(s)||n.result.createObjectStore(s)},n.onsuccess=()=>t(n.result),n.onerror=()=>r(n.error??new Error("Could not open the browser device database"))})}function v(e){return new Promise((t,r)=>{const n=e.transaction(s,"readonly").objectStore(s).get(l);n.onsuccess=()=>t(n.result),n.onerror=()=>r(n.error??new Error("Could not read the browser device identity"))})}function T(e,t){return new Promise((r,n)=>{const i=e.transaction(s,"readwrite");i.objectStore(s).put(t,l),i.oncomplete=()=>r(),i.onerror=()=>n(i.error??new Error("Could not store the browser device identity"))})}function a(e){const t=new Uint8Array(e);let r="";for(const n of t)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}function d(e){if(!/^[A-Za-z0-9_-]+$/u.test(e))throw new Error("Invalid base64url value");const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),r=atob(t),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return n.buffer}class V{constructor(t,r=globalThis.fetch.bind(globalThis)){const n=new URL(t);n.pathname="/",n.search="",n.hash="",this.baseUrl=n.toString(),this.fetch=r}async createPairingTicket(t,r,n=`c_${crypto.randomUUID()}`){const i=await this.createChallenge({purpose:"pair",deviceId:t.deviceId,devicePublicKey:t.publicKey,backendId:r.backendId,connectionId:n,pairId:r.pairId});return this.completeTicket(`v1/pairings/${encodeURIComponent(r.pairId)}/tickets`,t,i)}async createConnectionTicket(t,r,n=`c_${crypto.randomUUID()}`){const i=await this.createChallenge({purpose:"connect",deviceId:t.deviceId,backendId:r,connectionId:n});return this.completeTicket("v1/connections/tickets",t,i)}async listAuthorizedBackends(t){const r=await this.createChallenge({purpose:"discover",deviceId:t.deviceId}),n=await this.completeSignedRequest("v1/accounts/backends",t,r);if(!Array.isArray(n.backends)||!n.backends.every(O))throw new Error("Rendezvous returned an invalid backend list");return n.backends}async revokeDevice(t,r,n){const i=await this.createChallenge({purpose:"revoke_device",deviceId:t.deviceId,backendId:r,targetDeviceId:n});await this.completeMutation("v1/revocations/devices",t,i)}async revokeBackend(t,r){const n=await this.createChallenge({purpose:"revoke_backend",deviceId:t.deviceId,backendId:r});await this.completeMutation("v1/revocations/backends",t,n)}async createChallenge(t){return this.requestJson("v1/auth/challenges",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}async completeTicket(t,r,n){const i=await y(r,n),o=await this.requestJson(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({challengeId:n.challengeId,signature:i})});if(!o||typeof o.ticket!="string"||!Array.isArray(o.iceServers))throw new Error("Rendezvous returned an invalid connection ticket");return o}async completeMutation(t,r,n){await this.completeSignedRequest(t,r,n)}async completeSignedRequest(t,r,n){const i=await y(r,n);return this.requestJson(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({challengeId:n.challengeId,signature:i})})}async requestJson(t,r){const n=await this.fetch(new URL(t,this.baseUrl),r),i=await n.json().catch(()=>{});if(!n.ok)throw new Error(typeof i?.error=="string"?i.error:`Rendezvous request failed (${n.status})`);return i}}function O(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.backendId=="string"&&t.backendId.length>0&&(t.name===void 0||typeof t.name=="string")&&(t.softwareVersion===void 0||typeof t.softwareVersion=="string")&&Array.isArray(t.protocolVersions)&&t.protocolVersions.every(r=>Number.isSafeInteger(r)&&r>0)&&typeof t.online=="boolean"}function x(e){const t=new URL(e),r=/^\/pair\/([^/]+)$/u.exec(t.pathname),n=new URLSearchParams(t.hash.replace(/^#/u,"")),i=n.get("backend"),o=n.get("secret");if(!r?.[1]||!i||!o)throw new Error("Pairing URL is malformed");return{pairId:decodeURIComponent(r[1]),backendId:i,secret:o}}export{_ as P,V as R,P as T,U as a,D as b,N as c,B as l,x as p,L as s,$ as v};
@@ -0,0 +1 @@
1
+ import{P as L,b as _,s as R,T as S,v as z,c as T}from"./rendezvous-trust-api-C2Zob5i4.js";const I=2;function M(n,e){const t=new URL(n);if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol==="https:")t.protocol="wss:";else if(t.protocol!=="ws:"&&t.protocol!=="wss:")throw new Error(`Unsupported rendezvous URL protocol: ${t.protocol}`);return t.pathname=`/v${I}/rendezvous/${e}`,t.search="",t.hash="",t.toString()}function O(n){return JSON.stringify(n)}function P(n){return N(n)}function N(n,e){const t=B(n);if(!t.ok)return t;const i=t.value;switch(i.type){case"challenge":return a("invalid backend challenge");case"registered":return a("invalid backend registration");case"pairing_opened":return a("invalid pairing acknowledgement");case"pairing_confirmed":return a("invalid pairing confirmation");case"connection_request":return a("invalid connection request");case"backend_connected":if(!c(i.backendId)||!c(i.connectionId))return a("invalid browser connection acknowledgement");break;case"signal":if(!c(i.connectionId)||!A(i.signal))return a("invalid ICE signal");break;case"connection_binding":if(!c(i.connectionId)||!D(i.binding))return a("invalid backend identity binding");break;case"connection_closed":if(!c(i.connectionId)||!c(i.reason))return a("invalid connection closure");break;case"authorization_revoked":return a("invalid authorization revocation");case"error":if(!W(i.code)||!c(i.message)||!U(i.connectionId))return a("invalid rendezvous error");break;default:return x(i.type)}return{ok:!0,value:i}}function B(n){let e;try{e=JSON.parse(n)}catch{return{ok:!1,error:{code:"invalid_json",message:"Message is not valid JSON"}}}return!b(e)||!c(e.type)?a("Message must be an object with a type"):e.protocolVersion!==I?{ok:!1,error:{code:"unsupported_version",message:`Unsupported rendezvous protocol version: ${String(e.protocolVersion)}`}}:{ok:!0,value:e}}function A(n){return!b(n)||!c(n.kind)?!1:n.kind==="description"?(n.type==="offer"||n.type==="answer")&&c(n.sdp):n.kind==="candidate"?c(n.candidate)&&(n.sdpMid===null||c(n.sdpMid))&&(n.sdpMLineIndex===null||Number.isSafeInteger(n.sdpMLineIndex)&&n.sdpMLineIndex>=0):!1}function D(n){return b(n)&&n.version===1&&c(n.backendId)&&c(n.publicKey)&&c(n.connectionId)&&c(n.offerSha256)&&c(n.answerSha256)&&c(n.dtlsFingerprint)&&j(n.expiresAt)&&c(n.signature)}function W(n){return n==="invalid_json"||n==="invalid_message"||n==="unsupported_version"||n==="unknown_message"||n==="backend_offline"||n==="unauthorized_connection"||n==="invalid_ticket"||n==="invalid_pairing"}function a(n){return{ok:!1,error:{code:"invalid_message",message:n}}}function x(n){return{ok:!1,error:{code:"unknown_message",message:`Unknown rendezvous message: ${String(n)}`}}}function b(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}function c(n){return typeof n=="string"&&n.length>0}function U(n){return n===void 0||c(n)}function j(n){return Number.isSafeInteger(n)&&n>0}class V{constructor(e){this.signalListeners=new Set,this.bindingListeners=new Set,this.closedListeners=new Set,this.errorListeners=new Set,this.socket=null,this.endpoint=M(e.url,"browser"),this.backendId=e.backendId,this.ticket=e.ticket,this.createWebSocket=e.createWebSocket??(t=>new WebSocket(t))}get activeConnectionId(){return this.connectionId}connect(){if(this.connectionId)return Promise.resolve(this.connectionId);if(this.connecting)return this.connecting;if(this.connecting=new Promise((t,i)=>{this.resolveConnecting=t,this.rejectConnecting=i}),this.socket?.readyState===WebSocket.OPEN)return this.sendRaw({type:"connect_backend",backendId:this.backendId,ticket:this.ticket}),this.connecting;const e=this.createWebSocket(this.endpoint);return this.socket=e,e.onopen=()=>this.sendRaw({type:"connect_backend",backendId:this.backendId,ticket:this.ticket}),e.onmessage=t=>this.handleMessage(e,String(t.data)),e.onerror=()=>{const t=new Error("Rendezvous WebSocket failed");this.emitError(t),this.failConnection(t)},e.onclose=()=>{if(this.socket!==e)return;this.socket=null;const t=this.connectionId!==void 0;this.connectionId=void 0;const i=new Error("Rendezvous WebSocket closed");if(this.failConnection(i),t)for(const s of this.closedListeners)s(i.message)},this.connecting}onSignal(e){return this.signalListeners.add(e),()=>this.signalListeners.delete(e)}onIdentityBinding(e){return this.bindingListeners.add(e),()=>this.bindingListeners.delete(e)}onConnectionClosed(e){return this.closedListeners.add(e),()=>this.closedListeners.delete(e)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}sendSignal(e){if(!this.connectionId)throw new Error("Browser rendezvous route is not connected");this.sendRaw({type:"signal",connectionId:this.connectionId,signal:e})}close(e="Browser closed connection"){this.connectionId&&this.socket?.readyState===WebSocket.OPEN&&this.sendRaw({type:"close_connection",connectionId:this.connectionId,reason:e}),this.connectionId=void 0,this.socket?.close(1e3,e),this.socket=null,this.failConnection(new Error(e))}handleMessage(e,t){if(e!==this.socket)return;const i=P(t);if(!i.ok){const r=new Error(i.error.message);this.emitError(r),this.failConnection(r),e.close(1002,"Invalid rendezvous message");return}const s=i.value;switch(s.type){case"backend_connected":if(s.backendId!==this.backendId){const r=new Error("Rendezvous connected an unexpected backend");this.emitError(r),this.failConnection(r),e.close(1002,"Backend identity mismatch");return}this.connectionId=s.connectionId,this.resolveConnecting?.(s.connectionId),this.clearConnecting();break;case"signal":if(s.connectionId!==this.connectionId)return;for(const r of this.signalListeners)r(s.signal);break;case"connection_binding":if(s.connectionId!==this.connectionId)return;for(const r of this.bindingListeners)r(s.binding);break;case"connection_closed":if(s.connectionId!==this.connectionId)return;this.connectionId=void 0;for(const r of this.closedListeners)r(s.reason);break;case"error":this.emitError(s),this.connectionId||this.failConnection(new Error(s.message));break}}sendRaw(e){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw new Error("Rendezvous WebSocket is not connected");this.socket.send(O({protocolVersion:I,...e}))}failConnection(e){this.rejectConnecting?.(e),this.clearConnecting()}clearConnecting(){this.connecting=void 0,this.resolveConnecting=void 0,this.rejectConnecting=void 0}emitError(e){for(const t of this.errorListeners)t(e)}}class F{constructor(e){this.frameListeners=new Set,this.connectionListeners=new Set,this.connected=!1,this.manuallyClosed=!1,this.everConnected=!1,this.reconnectAttempt=0,this.rendezvousUrl=e.rendezvousUrl,this.backendId=e.backendId,this.deviceIdentity=e.deviceIdentity,this.authorize=e.authorize,this.iceTransportPolicy=e.iceTransportPolicy??"all",this.createPeerConnection=e.createPeerConnection??(t=>new RTCPeerConnection(t)),this.createRendezvousClient=e.createRendezvousClient??(t=>new V({url:this.rendezvousUrl,backendId:this.backendId,ticket:t})),this.reconnectDelayMs=e.reconnectDelayMs??(t=>Math.min(15e3,500*2**Math.min(t,5))),this.schedule=e.schedule??((t,i)=>setTimeout(t,i))}get isConnected(){return this.connected&&this.channel?.readyState==="open"}get isReconnecting(){return this.reconnectTimer!==void 0}onFrame(e){return this.frameListeners.add(e),()=>this.frameListeners.delete(e)}onConnectionChange(e){return this.connectionListeners.add(e),()=>this.connectionListeners.delete(e)}async connect(e){if(this.isConnected)return;this.manuallyClosed=!1;const t=await this.authorize(),i=J(t.ticket);if(i.backendId!==this.backendId||i.deviceId!==this.deviceIdentity.deviceId)throw new Error("Connection ticket does not match this browser and backend");const s=this.createRendezvousClient(t.ticket),r=this.createPeerConnection({iceServers:t.iceServers,iceTransportPolicy:this.iceTransportPolicy}),u=r.createDataChannel(L,{ordered:!0,protocol:_});this.rendezvous=s,this.peer=r,this.channel=u,await new Promise(async(y,E)=>{let g=!1,p="",k="",w,f,m=!1;const C=[],d=o=>{g||(g=!0,this.closeInternal(),E(o instanceof Error?o:new Error(String(o))))},v=async()=>{if(!(!w||!f||m)){await z(f,{backendId:this.backendId,connectionId:p,offerSdp:k,answerSdp:w,expiresAt:i.expiresAt}),await r.setRemoteDescription({type:"answer",sdp:w}),m=!0;for(const o of C.splice(0))await r.addIceCandidate(o)}};r.onicecandidate=o=>{if(!o.candidate||!p)return;const h=o.candidate.toJSON();s.sendSignal({kind:"candidate",candidate:h.candidate??"",sdpMid:h.sdpMid??null,sdpMLineIndex:h.sdpMLineIndex??null})},r.onconnectionstatechange=()=>{(r.connectionState==="failed"||r.connectionState==="closed")&&(g?this.handleDisconnected():d(new Error(`WebRTC connection ${r.connectionState}`)))},u.onerror=()=>d(new Error("WebRTC DataChannel failed")),u.onclose=()=>{g?this.handleDisconnected():d(new Error("WebRTC DataChannel closed before authentication"))},u.onopen=()=>{R(this.deviceIdentity,t.ticket,f?.signature??"").then(o=>{if(!f)throw new Error("Backend identity binding is missing");u.send(JSON.stringify({protocolVersion:S,type:"authenticate",ticket:t.ticket,bindingSignature:f.signature,deviceSignature:o,pairingSecret:t.pairingSecret}))}).catch(d)},u.onmessage=o=>{const h=String(o.data);if(!this.connected){let l;try{l=JSON.parse(h)}catch{d(new Error("Backend returned an invalid authentication frame"));return}if(l?.protocolVersion!==S||l?.type!=="authenticated"){d(new Error(l?.message||"Backend rejected DataChannel authentication"));return}if(l.deviceId!==this.deviceIdentity.deviceId){d(new Error("Backend authenticated an unexpected browser device"));return}this.connected=!0,this.reconnectAttempt=0,g=!0,this.emitConnectionChange({connected:!0,reconnected:this.everConnected}),this.everConnected=!0,y();return}for(const l of this.frameListeners)l(h)},s.onSignal(o=>{(async()=>{if(o.kind==="description"){if(o.type!=="answer")throw new Error("Browser expected an SDP answer");w=o.sdp,await v();return}const h={candidate:o.candidate,sdpMid:o.sdpMid,sdpMLineIndex:o.sdpMLineIndex};m?await r.addIceCandidate(h):C.push(h)})().catch(d)}),s.onIdentityBinding(o=>{f=o,v().catch(d)}),s.onConnectionClosed(o=>d(new Error(o))),s.onError(o=>d(o instanceof Error?o:new Error(o.message)));try{if(p=await s.connect(),p!==i.connectionId)throw new Error("Rendezvous route does not match the connection ticket");const o=await r.createOffer();if(k=o.sdp??"",!k)throw new Error("Browser WebRTC offer is empty");await r.setLocalDescription(o),s.sendSignal({kind:"description",type:"offer",sdp:k})}catch(o){d(o)}})}send(e){if(!this.isConnected||!this.channel)throw new Error("Backend transport is not connected");this.channel.send(e)}close(e=1e3,t="Client closed"){this.manuallyClosed=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0,this.rendezvous?.close(t),this.closeInternal()}closeInternal(){const e=this.connected;this.connected=!1,this.channel?.close(),this.peer?.close(),this.rendezvous?.close(),this.channel=void 0,this.peer=void 0,this.rendezvous=void 0,e&&this.emitConnectionChange({connected:!1,reconnected:!1})}handleDisconnected(){this.manuallyClosed||!this.connected||(this.closeInternal(),this.scheduleReconnect())}scheduleReconnect(){if(this.manuallyClosed||this.reconnectTimer)return;const e=this.reconnectAttempt++;this.reconnectTimer=this.schedule(()=>{this.reconnectTimer=void 0,this.connect("webrtc").catch(()=>this.scheduleReconnect())},this.reconnectDelayMs(e))}emitConnectionChange(e){for(const t of this.connectionListeners)t(e)}}function J(n){const[e]=n.split(".");if(!e)throw new Error("Connection ticket is malformed");try{const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),i=T(JSON.parse(atob(t)));if(!i)throw new Error("Connection ticket claims are invalid");return i}catch{throw new Error("Connection ticket claims are malformed")}}export{F as W};
@@ -0,0 +1,6 @@
1
+ import{_ as ie}from"./index-DwbBcYUf.js";import{i as oe}from"./__vite-browser-external-DtLbhLGx.js";function ae(i){const e=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],s=(S,f)=>S>>>f|S<<32-f,t=new TextEncoder().encode(i),n=t.length*8,o=new Uint8Array(Math.ceil((t.length+9)/64)*64);o.set(t),o[t.length]=128;const a=new DataView(o.buffer);a.setUint32(o.length-4,n,!1),n>4294967295&&a.setUint32(o.length-8,Math.floor(n/4294967296),!1);let[r,h,u,_,y,v,w,c]=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];const g=new Int32Array(64);for(let S=0;S<o.length;S+=64){for(let d=0;d<16;d++)g[d]=a.getInt32(S+d*4,!1);for(let d=16;d<64;d++){const U=s(g[d-15],7)^s(g[d-15],18)^g[d-15]>>>3,q=s(g[d-2],17)^s(g[d-2],19)^g[d-2]>>>10;g[d]=g[d-16]+U+g[d-7]+q|0}let[f,$,L,N,P,A,F,R]=[r,h,u,_,y,v,w,c];for(let d=0;d<64;d++){const U=s(P,6)^s(P,11)^s(P,25),q=P&A^~P&F,V=R+U+q+e[d]+g[d]|0,se=s(f,2)^s(f,13)^s(f,22),te=f&$^f&L^$&L,ne=se+te|0;R=F,F=A,A=P,P=N+V|0,N=L,L=$,$=f,f=V+ne|0}r=r+f|0,h=h+$|0,u=u+L|0,_=_+N|0,y=y+P|0,v=v+A|0,w=w+F|0,c=c+R|0}return[r,h,u,_,y,v,w,c].map(S=>(S>>>0).toString(16).padStart(8,"0")).join("")}async function re(i){if(typeof globalThis.crypto?.subtle?.digest=="function"){const e=new TextEncoder().encode(i),s=await globalThis.crypto.subtle.digest("SHA-256",e),t=new Uint8Array(s);return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}if(typeof globalThis.process<"u"){const{createHash:e}=await ie(async()=>{const{createHash:s}=await import("./__vite-browser-external-DtLbhLGx.js").then(t=>t._);return{createHash:s}},[]);return e("sha256").update(i,"utf8").digest("hex")}return ae(i)}function ce(i,e){let s=i;for(const t of e)s=s.slice(0,t.offset)+t.insert+s.slice(t.offset+t.deleteCount);return s}async function le(i,e,s){if(s.length===0)return{data:i,hash:e};let t=i,n=e,o;for(const r of s){if(o=r,r.op==="full"){t=r.data,n=r.hash;continue}if(r.baseHash!==n)return console.warn("[jsonl-sync] Base hash mismatch, need full sync",{expected:r.baseHash,actual:n}),null;t=ce(t,r.patches),n=r.hash}const a=await re(t);if(a!==n){const r=o?.op==="full"?"[jsonl-sync] Full sync hash mismatch":"[jsonl-sync] Post-patch hash mismatch";return console.error(r,{expected:n,actual:a}),null}return{data:t,hash:n}}const he=10*6e4,de=he+9e4,Q=1;class D extends Error{constructor(e,s,t){super(`${s}: ${t}`),this.code=e}}function p(i,e,s="invalid_message"){throw new D(s,i,e)}function K(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function m(i,e){return K(i)||p(e,"expected an object"),i}function l(i,e,s=!0){return(typeof i!="string"||!s&&i.length===0)&&p(e,s?"expected a string":"expected a non-empty string"),i}function k(i,e){return i===void 0?void 0:l(i,e)}function b(i,e){return typeof i!="boolean"&&p(e,"expected a boolean"),i}function C(i,e){return(!Number.isSafeInteger(i)||i<0)&&p(e,"expected a non-negative safe integer"),i}function M(i,e){return(typeof i!="number"||!Number.isFinite(i))&&p(e,"expected a finite number"),i}function T(i,e){return Array.isArray(i)||p(e,"expected an array"),i}function H(i,e){return T(i,e).map((s,t)=>l(s,`${e}[${t}]`))}function O(i,e){const s=m(i,e);for(const[t,n]of Object.entries(s))l(n,`${e}.${t}`);return s}function Y(i,e){const s=m(i,e);for(const[t,n]of Object.entries(s))n!=="running"&&n!=="done"&&p(`${e}.${t}`,"expected 'running' or 'done'");return s}function ue(i,e){const s=m(i,e);for(const[t,n]of Object.entries(s))H(n,`${e}.${t}`);return s}function B(i,e){return["off","minimal","low","medium","high","xhigh","max"].includes(String(i))||p(e,"expected a supported thinking level"),i}function ge(i,e){const s=m(i,e);return l(s.provider,`${e}.provider`,!1),l(s.modelId,`${e}.modelId`,!1),s}function W(i,e){const s=m(i,e);l(s.provider,`${e}.provider`,!1);const t=k(s.id,`${e}.id`),n=k(s.modelId,`${e}.modelId`);return!t&&!n&&p(e,"expected id or modelId"),s}function pe(i,e){if(i.protocolVersion!==Q){const s=i.protocolVersion===void 0?"missing":JSON.stringify(i.protocolVersion);p(`${e}.protocolVersion`,`unsupported protocol version ${s}; expected ${Q}`,"unsupported_version")}}function X(i){try{return{ok:!0,value:JSON.parse(i)}}catch(e){return{ok:!1,error:{code:"invalid_json",message:`Invalid JSON: ${e instanceof Error?e.message:String(e)}`,requestId:null,command:"parse"}}}}function Z(i,e,s){const t=K(i)?i:void 0,n=typeof t?.id=="string"?t.id:null,o=typeof t?.type=="string"?t.type:s,a=e instanceof D?e:new D("invalid_message","$",e instanceof Error?e.message:String(e));return{ok:!1,error:{code:a.code,message:a.message,requestId:n,command:o}}}function me(i,e){T(i,e).forEach((s,t)=>{const n=m(s,`${e}[${t}]`);l(n.name,`${e}[${t}].name`,!1),k(n.description,`${e}[${t}].description`),["extension","prompt","skill"].includes(String(n.source))||p(`${e}[${t}].source`,"expected extension, prompt, or skill"),n.sourceInfo!==void 0&&m(n.sourceInfo,`${e}[${t}].sourceInfo`),k(n.location,`${e}[${t}].location`),k(n.path,`${e}[${t}].path`)})}function fe(i,e){const s=m(i,e);l(s.sessionFile,`${e}.sessionFile`,!1),l(s.sessionId,`${e}.sessionId`,!1);for(const n of["userMessages","assistantMessages","toolCalls","toolResults","totalMessages"])C(s[n],`${e}.${n}`);const t=m(s.tokens,`${e}.tokens`);for(const n of["input","output","cacheRead","cacheWrite","total"])C(t[n],`${e}.tokens.${n}`);if(M(s.cost,`${e}.cost`)<0&&p(`${e}.cost`,"expected a non-negative number"),s.contextUsage!==void 0){const n=m(s.contextUsage,`${e}.contextUsage`);n.tokens!==null&&C(n.tokens,`${e}.contextUsage.tokens`),C(n.contextWindow,`${e}.contextUsage.contextWindow`),n.percent!==null&&M(n.percent,`${e}.contextUsage.percent`)<0&&p(`${e}.contextUsage.percent`,"expected a non-negative number or null")}}function _e(i,e,s){const t=m(e,s);switch(i){case"install_pi":case"subscribe_session":case"steer":case"remove_steering":case"abort":case"set_session_name":break;case"prompt":case"fork_prompt":l(t.newSessionPath,`${s}.newSessionPath`,!1);break;case"hard_kill":b(t.killed,`${s}.killed`),t.reason!==void 0&&t.reason!=="signal_failed"&&t.reason!=="not_attached"&&p(`${s}.reason`,"expected signal_failed or not_attached");break;case"compact":break;case"get_available_models":T(t.models,`${s}.models`).forEach((n,o)=>W(n,`${s}.models[${o}]`));break;case"get_default_model":t.model!==null&&W(t.model,`${s}.model`),B(t.thinkingLevel,`${s}.thinkingLevel`);break;case"get_session_statuses":Y(t.statuses,`${s}.statuses`);break;case"get_session_stats":fe(t,s);break;case"fork":l(t.text,`${s}.text`),b(t.cancelled,`${s}.cancelled`),t.newSessionPath!==null&&l(t.newSessionPath,`${s}.newSessionPath`,!1);break;case"get_commands":me(t.commands,`${s}.commands`);break;case"reload_processes":C(t.killed,`${s}.killed`),C(t.draining,`${s}.draining`);break}}const Se=new Set(["install_pi","subscribe_session","prompt","steer","remove_steering","abort","hard_kill","compact","get_available_models","get_default_model","get_session_statuses","get_session_stats","fork","fork_prompt","set_session_name","get_commands","reload_processes"]);function ye(i,e){const s=l(i,e,!1);return Se.has(s)||p(e,`unknown response command '${s}'`,"unknown_message"),s}function ve(i,e){T(i,e).forEach((s,t)=>{const n=m(s,`${e}[${t}]`);C(n.offset,`${e}[${t}].offset`),C(n.deleteCount,`${e}[${t}].deleteCount`),l(n.insert,`${e}[${t}].insert`)})}function we(i){const e=X(i);if(!e.ok)return e;const s=e.value;try{const t=m(s,"$message");pe(t,"$message");const n=l(t.type,"$message.type",!1);switch(n){case"response":{if(b(t.success,"$message.success")){l(t.id,"$message.id",!1);const a=ye(t.command,"$message.command");_e(a,t.data,"$message.data")}else t.id!==null&&l(t.id,"$message.id",!1),l(t.command,"$message.command",!1),l(t.error,"$message.error",!1),["invalid_json","invalid_message","unsupported_version","unknown_command","unknown_message","command_failed"].includes(String(t.code))||p("$message.code","expected a protocol error code");break}case"init":Y(t.sessionStatuses,"$message.sessionStatuses"),ue(t.steeringQueues,"$message.steeringQueues"),O(t.providerUsageStatuses,"$message.providerUsageStatuses");break;case"pi_install_required":l(t.command,"$message.command",!1),b(t.installable,"$message.installable"),b(t.installing,"$message.installing"),l(t.message,"$message.message",!1);break;case"session_status_change":l(t.sessionPath,"$message.sessionPath",!1),t.status!=="running"&&t.status!=="done"&&p("$message.status","expected running or done");break;case"provider_usage":O(t.statuses,"$message.statuses");break;case"extension_status":l(t.sessionPath,"$message.sessionPath",!1),O(t.statuses,"$message.statuses");break;case"session_sync":l(t.sessionPath,"$message.sessionPath",!1),C(t.revision,"$message.revision"),l(t.hash,"$message.hash",!1),t.op==="full"?l(t.data,"$message.data"):t.op==="delta"?(l(t.baseHash,"$message.baseHash",!1),ve(t.patches,"$message.patches")):p("$message.op","expected full or delta");break;case"control_state":l(t.sessionPath,"$message.sessionPath",!1),t.controlRevision!==void 0&&C(t.controlRevision,"$message.controlRevision"),W(t.model,"$message.model"),B(t.thinkingLevel,"$message.thinkingLevel");break;case"session_attached":l(t.sessionPath,"$message.sessionPath",!1),k(t.cwd,"$message.cwd"),k(t.firstMessage,"$message.firstMessage");break;case"sessions_changed":l(t.file,"$message.file");break;default:p("$message.type",`unknown server message '${n}'`,"unknown_message")}return{ok:!0,value:t}}catch(t){return Z(s,t,"unknown")}}function Ce(i){const e=X(i);if(!e.ok)return e;const s=e.value;try{const t=m(s,"$session");T(t.messages,"$session.messages").forEach((o,a)=>{const r=m(o,`$session.messages[${a}]`);l(r.role,`$session.messages[${a}].role`,!1)}),b(t.isStreaming,"$session.isStreaming"),H(t.pendingToolCalls,"$session.pendingToolCalls");const n=m(t.toolCallTimings,"$session.toolCallTimings");for(const[o,a]of Object.entries(n)){const r=m(a,`$session.toolCallTimings.${o}`);M(r.startedAt,`$session.toolCallTimings.${o}.startedAt`),r.completedAt!==void 0&&M(r.completedAt,`$session.toolCallTimings.${o}.completedAt`)}return t.model!==null&&ge(t.model,"$session.model"),B(t.thinkingLevel,"$session.thinkingLevel"),H(t.steeringQueue,"$session.steeringQueue"),k(t.error,"$session.error"),{ok:!0,value:t}}catch(t){return Z(s,t,"session_sync")}}function $e(i,e){return JSON.stringify({protocolVersion:Q,id:e,...i})}function Pe(i){throw new Error(`Unhandled protocol variant: ${JSON.stringify(i)}`)}const x=["off","minimal","low","medium","high","xhigh","max"];function E(i){return i?.id??i?.modelId}function j(i,e){const s=E(i),t=E(e);return!!i&&!!e&&!!s&&!!t&&i.provider===e.provider&&s===t}function J(i){const e=E(i);if(!(!i.provider||!e))return{provider:i.provider,modelId:e}}function ke(i){if(!i)return!1;if(typeof i.reasoning=="boolean")return i.reasoning;if(i.thinkingLevelMap)return!0;const e=String(i.provider??"").toLowerCase(),s=String(E(i)??"").toLowerCase();return!!(e==="openai-codex"||e==="openai"&&s.startsWith("gpt-5"))}function be(i){if(!ke(i))return["off"];const e=i?.thinkingLevelMap;return x.filter(s=>{const t=e?.[s];return t===null?!1:s==="xhigh"||s==="max"?t!==void 0:!0})}function G(i,e){const s=be(i);if(s.includes(e))return e;const t=x.indexOf(e);if(t===-1)return s[0]??"off";for(let n=t;n<x.length;n++){const o=x[n];if(s.includes(o))return o}for(let n=t-1;n>=0;n--){const o=x[n];if(s.includes(o))return o}return s[0]??"off"}class Le extends Error{constructor(e,s,t){super(e),this.status=s,this.details=t,this.name="BackendApiError"}}class xe{constructor(e={}){this.fetch=e.fetch??globalThis.fetch.bind(globalThis)}listSessions(){return this.requestJson("/api/sessions")}async deleteSession(e){await this.requestJson("/api/sessions",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})})}async listForkMessages(e){return(await this.requestJson(`/api/sessions/fork-messages?path=${encodeURIComponent(e)}`)).messages??[]}browseDirectory(e){return this.requestJson(`/api/browse?path=${encodeURIComponent(e)}`)}createDirectory(e,s){return this.requestJson("/api/directories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parentPath:e,name:s})})}async getRawSession(e){const s=await this.fetch(`/api/sessions/raw?path=${encodeURIComponent(e)}`);if(!s.ok)throw await this.toError(s,"Failed to load raw session");return s.text()}getFileContent(e,s){const t=new URLSearchParams({sessionPath:e,path:s});return this.requestJson(`/api/files/content?${t}`,{cache:"no-store"})}createFileUpload(e){return this.requestJson("/api/files/uploads",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}appendFileUpload(e){return this.requestJson(`/api/files/uploads/${encodeURIComponent(e.uploadId)}/chunks`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({offset:e.offset,data:e.data})})}completeFileUpload(e){return this.requestJson(`/api/files/uploads/${encodeURIComponent(e)}/complete`,{method:"POST"})}getLocalSettings(){return this.requestJson("/api/settings/local")}validateLocalSettings(e){return this.requestValidation("/api/settings/local/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:e})})}patchLocalSettings(e){return this.requestValidation("/api/settings/local",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}saveLocalSettings(e){return this.requestValidation("/api/settings/local",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:e})})}getUpdates(){return this.requestJson("/api/updates",{cache:"no-store"})}runUpdate(e){return this.requestJson(`/api/updates/${e}`,{method:"POST",headers:{"X-Pipane-Action":"update"}})}async requestValidation(e,s){const t=await this.fetch(e,s),n=await this.readJson(t);if(!t.ok&&typeof n?.valid!="boolean")throw this.errorFromPayload(t,n,"Settings request failed");return n}async requestJson(e,s){const t=s?await this.fetch(e,s):await this.fetch(e),n=await this.readJson(t);if(!t.ok)throw this.errorFromPayload(t,n,`Backend request failed (${t.status})`);return n}async readJson(e){return e.json().catch(()=>({}))}async toError(e,s){const t=await this.readJson(e);return this.errorFromPayload(e,t,s)}errorFromPayload(e,s,t){const n=Array.isArray(s?.errors)?s.errors.filter(a=>typeof a=="string"):[],o=typeof s?.error=="string"?s.error:n.length>0?n.join(`
2
+ `):t;return new Le(o,e.status,s)}}const ee=[{name:"help",description:"Show this help",source:"builtin"},{name:"new",description:"Start a new session",source:"builtin"},{name:"session",description:"Show session file, messages, tokens, and cost",source:"builtin"},{name:"fork",description:"Fork session from a previous message",source:"builtin"},{name:"compact",description:"Compact conversation history",source:"builtin",argumentHint:"[instructions]",acceptsArguments:!0},{name:"name",description:"Set session display name",source:"builtin",argumentHint:"<name>",acceptsArguments:!0},{name:"reload",description:"Restart all pooled pi RPC processes",source:"builtin"}];function Re(i){const e=ee.map(t=>({...t})),s=new Set(e.map(t=>t.name.toLocaleLowerCase()));for(const t of i){const n=t.name.toLocaleLowerCase();s.has(n)||(s.add(n),e.push({name:t.name,description:t.description??"",source:t.source,acceptsArguments:!0}))}return e}function Te(i,e){const s=i.toLocaleLowerCase(),t=e.toLocaleLowerCase();if(!t)return 0;if(s===t)return 1e5;let n=s.startsWith(t)?5e4:0,o=0,a=-2,r=-1;for(const h of t){const u=s.indexOf(h,o);if(u===-1)return;r===-1&&(r=u);const _=u>0?s[u-1]:"";u===0||_==="-"||_===":"||_==="_"?n+=18:n+=4,u===a+1&&(n+=12),a=u,o=u+1}return n-=r*3,n-=s.length-t.length,n}function Ue(i,e){return i.map((s,t)=>({command:s,index:t,score:Te(s.name,e)})).filter(s=>s.score!==void 0).sort((s,t)=>t.score-s.score||s.index-t.index).map(s=>s.command)}function qe(i){switch(i){case"builtin":return"Built-in";case"extension":return"Extension";case"prompt":return"Prompt";case"skill":return"Skill"}}const z=1,Ae=1e4;class Fe{constructor(e={}){this.socket=null,this.reconnecting=!1,this.reconnectAttempt=0,this.manuallyClosed=!1,this.frameListeners=new Set,this.connectionListeners=new Set,this.createWebSocket=e.createWebSocket??(s=>new WebSocket(s)),this.schedule=e.schedule??globalThis.setTimeout.bind(globalThis),this.cancelSchedule=e.cancelSchedule??globalThis.clearTimeout.bind(globalThis),e.socket&&(this.socket=e.socket,this.attachFrameHandler(e.socket))}get isConnected(){return this.socket?.readyState===z}get isReconnecting(){return this.reconnecting}onFrame(e){return this.frameListeners.add(e),()=>this.frameListeners.delete(e)}onConnectionChange(e){return this.connectionListeners.add(e),()=>this.connectionListeners.delete(e)}async connect(e){this.isConnected||(this.endpoint=e,this.manuallyClosed=!1,await this.openSocket(!1))}send(e){if(!this.socket||this.socket.readyState!==z)throw new Error("Backend transport is not connected");this.socket.send(e)}close(e=1e3,s="Client closed"){this.manuallyClosed=!0,this.reconnecting=!1,this.reconnectTimer&&(this.cancelSchedule(this.reconnectTimer),this.reconnectTimer=void 0),this.socket?.close(e,s)}attachFrameHandler(e){e.onmessage=s=>{const t=String(s.data);for(const n of this.frameListeners)n(t)}}emitConnectionChange(e){for(const s of this.connectionListeners)s(e)}openSocket(e){const s=this.endpoint;return s?new Promise((t,n)=>{const o=this.createWebSocket(s);let a=!1,r=!1;this.socket=o,this.attachFrameHandler(o),o.onopen=()=>{this.socket===o&&(a=!0,r=!0,this.reconnecting=!1,this.reconnectAttempt=0,this.emitConnectionChange({connected:!0,reconnected:e}),t())},o.onerror=()=>{!e&&!r&&(r=!0,n(new Error("WebSocket connection failed")))},o.onclose=()=>{if(this.socket===o&&(this.socket=null),r||(r=!0,n(new Error("WebSocket closed before connecting"))),this.manuallyClosed){a&&this.emitConnectionChange({connected:!1,reconnected:!1});return}(a||e)&&(this.scheduleReconnect(),a&&this.emitConnectionChange({connected:!1,reconnected:!1}))}}):Promise.reject(new Error("Backend transport endpoint is missing"))}scheduleReconnect(){if(this.reconnectTimer||this.manuallyClosed)return;this.reconnecting=!0,this.reconnectAttempt++;const e=Math.min(500*2**(this.reconnectAttempt-1),Ae);this.reconnectTimer=this.schedule(()=>{this.reconnectTimer=void 0,this.openSocket(!0).catch(()=>{})},e)}}const Ie="provider-usage";function Me(i){const e=typeof i?.provider=="string"?i.provider.toLowerCase():"";if(e.includes("codex"))return"codex";if(e.includes("anthropic"))return"anthropic"}class Oe{constructor(e={}){this.sessionsChangedListeners=new Set,this.piInstallRequiredListeners=new Set,this.pendingRequests=new Map,this.requestId=0,this._connectionListeners=new Set,this._state={model:void 0,thinkingLevel:"off",messages:[],isStreaming:!1,error:void 0},this._pendingToolCallIds=new Set,this._toolCallTimings={},this._steeringQueues=new Map,this._steeringQueueListeners=new Set,this._extensionStatuses=new Map,this._providerUsageStatuses=new Map,this._extensionStatusListeners=new Set,this._controlRevision=0,this._availableModels=null,this._sessionId="",this._sessionStatus="virtual",this._localAssistantMessages=[],this._optimisticSessions=new Map,this._globalSessionStatus=new Map,this._globalStatusListeners=new Set,this._sessionNonce=0,this._pendingNewPrompt=!1,this._startingPrompts=new Map,this._syncJson="",this._syncHash="",this._pendingSessionSyncs=[],this._sessionSyncFlushScheduled=!1,this._sessionSyncFlushInProgress=!1,this._sessionListeners=new Set,this._contentListeners=new Set,this._statusListeners=new Set,this.transport=e.transport??new Fe({socket:e.socket,createWebSocket:e.createWebSocket}),this.api=e.api??new xe({fetch:e.fetch}),this.requestFrame=e.requestFrame??(s=>requestAnimationFrame(s)),this.transport.onFrame(s=>this.handleMessage(s)),this.transport.onConnectionChange(s=>this.handleTransportConnectionChange(s.connected,s.reconnected))}get state(){return this._state}get sessionId(){return this._sessionId}get sessionFile(){return this._sessionPath}get sessionName(){return this._sessionName}get sessionStatus(){return this._sessionStatus}get isConnected(){return this.transport.isConnected}get isReconnecting(){return this.transport.isReconnecting}onConnectionChange(e){return this._connectionListeners.add(e),()=>this._connectionListeners.delete(e)}emitConnectionChange(e){for(const s of this._connectionListeners)s(e)}get pendingToolCallIds(){return this._pendingToolCallIds}get toolCallTimings(){return this._toolCallTimings}get steeringQueue(){return this._sessionPath?this._steeringQueues.get(this._sessionPath)??[]:[]}get extensionStatuses(){const e=new Map(this._extensionStatuses),s=Me(this._state.model),t=s?this._providerUsageStatuses.get(s):this._providerUsageStatuses.size===1?this._providerUsageStatuses.values().next().value:void 0;return t&&e.set(Ie,t),e}onExtensionStatusChange(e){return this._extensionStatusListeners.add(e),()=>this._extensionStatusListeners.delete(e)}replaceExtensionStatuses(e){const s=new Map;if(e&&typeof e=="object"&&!Array.isArray(e))for(const[t,n]of Object.entries(e))typeof n=="string"&&s.set(t,n);if(!(s.size===this._extensionStatuses.size&&[...s].every(([t,n])=>this._extensionStatuses.get(t)===n))){this._extensionStatuses=s;for(const t of this._extensionStatusListeners)t()}}replaceProviderUsageStatuses(e){const s=new Map;if(e&&typeof e=="object"&&!Array.isArray(e))for(const[t,n]of Object.entries(e))typeof n=="string"&&s.set(t,n);if(!(s.size===this._providerUsageStatuses.size&&[...s].every(([t,n])=>this._providerUsageStatuses.get(t)===n))){this._providerUsageStatuses=s;for(const t of this._extensionStatusListeners)t()}}clearExtensionStatuses(){this.replaceExtensionStatuses({})}getSessionStatus(e){return this._globalSessionStatus.get(e)}onGlobalStatusChange(e){return this._globalStatusListeners.add(e),()=>this._globalStatusListeners.delete(e)}emitGlobalStatusChange(){for(const e of this._globalStatusListeners)e()}setGlobalSessionStatus(e,s){this._globalSessionStatus.set(e,s),s==="running"&&this._startingPrompts.get(e)?.resolveReady(e),this.emitGlobalStatusChange()}setAllSessionStatuses(e){this._globalSessionStatus.clear();for(const[s,t]of Object.entries(e))this._globalSessionStatus.set(s,t);this.emitGlobalStatusChange()}onSteeringQueueChange(e){return this._steeringQueueListeners.add(e),()=>this._steeringQueueListeners.delete(e)}emitSteeringQueueChange(){for(const e of this._steeringQueueListeners)e()}enqueueSteering(e,s){const t=this._steeringQueues.get(e)??[];this._steeringQueues.set(e,[...t,s]),this.emitSteeringQueueChange()}onSessionChange(e){return this._sessionListeners.add(e),()=>this._sessionListeners.delete(e)}emitSessionChange(){for(const e of this._sessionListeners)e()}onContentChange(e){return this._contentListeners.add(e),()=>this._contentListeners.delete(e)}emitContentChange(){for(const e of this._contentListeners)e()}onStatusChange(e){return this._statusListeners.add(e),()=>this._statusListeners.delete(e)}emitStatusChange(){for(const e of this._statusListeners)e()}onSessionsChanged(e){return this.sessionsChangedListeners.add(e),()=>this.sessionsChangedListeners.delete(e)}onPiInstallRequired(e){return this.piInstallRequiredListeners.add(e),()=>this.piInstallRequiredListeners.delete(e)}emitPiInstallRequired(e){for(const s of this.piInstallRequiredListeners)s(e)}toErrorMessage(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}reportError(e,s="Request failed"){const t=this.toErrorMessage(e);this._state.error=t,this._state.messages=[...this._state.messages,{role:"assistant",content:[{type:"text",text:`⚠️ ${s}: ${t}`}],timestamp:Date.now()}],this.emitStatusChange(),this.emitContentChange()}async connect(e){await this.transport.connect(e),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.syncStateOnFocus()})}disconnect(){this.transport.close()}handleTransportConnectionChange(e,s){e?s?this.onReconnected():this._sessionStatus="virtual":this.handleTransportDisconnected(),this.emitConnectionChange(e)}handleTransportDisconnected(){for(const e of this.pendingRequests.values())e.reject(new Error("Backend transport disconnected"));this.pendingRequests.clear(),this._pendingControl?.phase==="sent"?this.rollbackSentControl(this._pendingControl.revision):this._pendingControl?.phase==="acknowledged"&&(this._pendingControl=void 0)}async onReconnected(){this._sessionPath&&this._sessionStatus!=="virtual"&&(this._awaitingFullSync=void 0,this.requestFullSessionSync(this._sessionPath)),this.refreshSessionStatuses()}async syncStateOnFocus(){this.refreshSessionStatuses(),this._sessionPath&&this._sessionStatus!=="virtual"&&this.subscribeToSession(this._sessionPath),this._sessionStatus==="detached"&&this._state.isStreaming&&(console.log("[ws-adapter] Tab regained focus: clearing stale streaming state"),this._state.isStreaming=!1,this._pendingToolCallIds.clear(),this.emitStatusChange())}async refreshSessionStatuses(){try{const e=await this.send({type:"get_session_statuses"});e?.statuses&&this.setAllSessionStatuses(e.statuses)}catch(e){console.error("Failed to refresh session statuses:",e)}}async subscribeToSession(e){try{await this.send({type:"subscribe_session",sessionPath:e??""})}catch(s){console.error("Failed to subscribe to session:",s)}}async requestFullSessionSync(e){const s={sessionPath:e,sessionNonce:this._sessionNonce};this._awaitingFullSync?.sessionPath===s.sessionPath&&this._awaitingFullSync.sessionNonce===s.sessionNonce||(this._awaitingFullSync=s,this._syncJson="",this._syncHash="",this._syncRevision=void 0,this.clearSessionSyncQueue(),await this.subscribeToSession(e))}handleProtocolError(e){const s=`Protocol error: ${e.message}`;console.error(`[ws-adapter] ${s}`),this._state.error=s,this.emitStatusChange(),e.code==="unsupported_version"&&this.transport.close(1002,"Unsupported protocol version")}handleMessage(e){if(oe(e))return;const s=we(e);if(!s.ok){this.handleProtocolError(s.error);return}const t=s.value;switch(t.type){case"response":{if(!t.success&&t.id===null){this._state.error=t.error,this.emitStatusChange();return}if(t.id===null)return;const n=this.pendingRequests.get(t.id);if(!n)return;if(this.pendingRequests.delete(t.id),t.command!==n.command){n.reject(new Error(`Mismatched response for ${n.command}: received ${t.command}`));return}t.success?n.resolve(t.data):(this._state.error=t.error,this.emitStatusChange(),n.reject(new Error(t.error)));return}case"pi_install_required":this.emitPiInstallRequired({command:t.command,installable:t.installable,installing:t.installing,message:t.message});return;case"init":this.setAllSessionStatuses(t.sessionStatuses),this.replaceProviderUsageStatuses(t.providerUsageStatuses),this._steeringQueues.clear();for(const[n,o]of Object.entries(t.steeringQueues))o.length>0&&this._steeringQueues.set(n,[...o]);this.emitSteeringQueueChange();return;case"session_status_change":this.setGlobalSessionStatus(t.sessionPath,t.status);return;case"provider_usage":this.replaceProviderUsageStatuses(t.statuses);return;case"extension_status":t.sessionPath===this._sessionPath&&this.replaceExtensionStatuses(t.statuses);return;case"session_sync":if(t.sessionPath!==this._sessionPath)return;this.enqueueSessionSync({...t,__sessionPath:t.sessionPath,__sessionNonce:this._sessionNonce});return;case"control_state":{if(t.sessionPath!==this._sessionPath)return;this.applyAuthoritativeControlState(t.model,t.thinkingLevel,t.controlRevision)&&this.emitContentChange();return}case"session_attached":{this.setGlobalSessionStatus(t.sessionPath,"running"),t.cwd&&(this._pendingCwd=t.cwd);const n=t.sessionPath===this._sessionPath||this._sessionStatus==="virtual"&&this._pendingNewPrompt;if(n){if(this._sessionStatus==="virtual"){this._sessionPath=t.sessionPath;const a=I.basename(t.sessionPath,".jsonl"),r=a.split("_");this._sessionId=r.length>1?r.slice(1).join("_"):a,this._startingPrompts.get(`virtual:${this._sessionNonce}`)?.resolveReady(t.sessionPath)}this._sessionStatus="attached",this._state.isStreaming=!0,this.requestFullSessionSync(t.sessionPath),this.emitStatusChange()}if(!this._optimisticSessions.has(t.sessionPath)){const o=new Date().toISOString(),a=I.basename(t.sessionPath,".jsonl"),r=a.split("_"),h=r.length>1?r.slice(1).join("_"):a;this._optimisticSessions.set(t.sessionPath,{id:h,path:t.sessionPath,cwd:t.cwd??"",created:o,modified:o,lastUserPromptTime:o,messageCount:1,firstMessage:t.firstMessage??"(new session)"})}n&&this.emitSessionChange();return}case"sessions_changed":for(const n of this.sessionsChangedListeners)n(t.file);return;default:Pe(t)}}enqueueSessionSync(e){const s=this._awaitingFullSync!==void 0&&this._awaitingFullSync.sessionPath===e.__sessionPath&&this._awaitingFullSync.sessionNonce===e.__sessionNonce;if(e.op==="full")s&&(this._awaitingFullSync=void 0),this._pendingSessionSyncs=[e];else{if(s)return;this._pendingSessionSyncs.push(e)}this._sessionSyncFlushScheduled||this._sessionSyncFlushInProgress||(this._sessionSyncFlushScheduled=!0,this.requestFrame(()=>{this._sessionSyncFlushScheduled=!1,this.flushSessionSyncQueue()}))}clearSessionSyncQueue(){this._pendingSessionSyncs=[],this._sessionSyncFlushScheduled=!1}async flushSessionSyncQueue(){if(this._sessionSyncFlushInProgress)return;this._sessionSyncFlushInProgress=!0;const e=this._pendingSessionSyncs.splice(0);try{const s=await this.applySessionSyncBatch(e);s&&this.emitSessionSyncChanges(s)}finally{this._sessionSyncFlushInProgress=!1,this._pendingSessionSyncs.length>0&&!this._sessionSyncFlushScheduled&&(this._sessionSyncFlushScheduled=!0,this.requestFrame(()=>{this._sessionSyncFlushScheduled=!1,this.flushSessionSyncQueue()}))}}emitSessionSyncChanges(e){e.steering&&this.emitSteeringQueueChange(),e.content&&this.emitContentChange(),e.status&&this.emitStatusChange()}async applySessionSyncBatch(e){const s=this._sessionPath,t=this._sessionNonce;if(!s||e.length===0||e.some(c=>c.__sessionPath!==s||c.__sessionNonce!==t))return;let n=this._syncRevision;for(const c of e){if(c.op==="full"){n=c.revision;continue}if(n===void 0||c.revision!==n+1){console.error("[ws-adapter] Session revision gap, re-subscribing",{expected:n===void 0?"full snapshot":n+1,actual:c.revision}),this.requestFullSessionSync(s);return}n=c.revision}const o=e.map(c=>c.op==="full"?{op:"full",data:c.data,hash:c.hash}:{op:"delta",patches:c.patches,hash:c.hash,baseHash:c.baseHash});if(o[0]?.op==="delta"&&!this._syncHash){console.warn("[ws-adapter] Ignoring delta while awaiting full sync");return}const a=await le(this._syncJson,this._syncHash,o);if(s!==this._sessionPath||t!==this._sessionNonce)return;if(!a){console.error("[ws-adapter] Sync verification failed, re-subscribing"),this.requestFullSessionSync(s);return}const r=Ce(a.data);if(!r.ok){this.handleProtocolError(r.error);return}const h=r.value;this._syncJson=a.data,this._syncHash=a.hash,this._syncRevision=n;const u=this._state.isStreaming,_=this._sessionStatus,y=this._state.error,v=[...this._steeringQueues.get(s)??[]];this._state.messages=[...h.messages??[],...this._localAssistantMessages],this._state.isStreaming=h.isStreaming??!1,this._sessionStatus!=="virtual"&&(this._sessionStatus=this._state.isStreaming?"attached":"detached"),this._pendingToolCallIds=new Set(h.pendingToolCalls??[]),this._toolCallTimings=h.toolCallTimings??{},this.applyAuthoritativeControlState(h.model,h.thinkingLevel),Array.isArray(h.steeringQueue)&&(h.steeringQueue.length>0?this._steeringQueues.set(s,[...h.steeringQueue]):this._steeringQueues.delete(s)),this._state.error=h.error||void 0;const w=this._steeringQueues.get(s)??[];return{content:!0,status:u!==this._state.isStreaming||_!==this._sessionStatus||y!==this._state.error,steering:v.length!==w.length||v.some((c,g)=>c!==w[g])}}send(e){if(!this.transport.isConnected)return Promise.reject(new Error("Backend transport is not connected"));const s=`req_${++this.requestId}`;return new Promise((t,n)=>{const o=e.type==="compact"?de:e.type==="prompt"||e.type==="fork_prompt"?9e4:3e4,a=setTimeout(()=>{this.pendingRequests.delete(s),n(new Error(`Timeout waiting for response to ${e.type}`))},o);this.pendingRequests.set(s,{command:e.type,resolve:r=>{clearTimeout(a),t(r)},reject:r=>{clearTimeout(a),n(r)}}),this.transport.send($e(e,s))})}async fetchAvailableModels(){const s=(await this.send({type:"get_available_models"}))?.models??[];this._availableModels=s;const t=this.resolveModel(this._state.model);return t&&(this._state.model=t),s}resolveModel(e){if(!e)return;const s=this._availableModels?.find(n=>j(n,e));if(s)return s;const t=J(e);if(t)return{...e,provider:t.provider,id:t.modelId}}markControlPending(){const e=++this._controlRevision;return this._pendingControl={revision:e,sessionNonce:this._sessionNonce,phase:"local"},e}markControlSent(e){this._pendingControl?.revision===e&&this._pendingControl.sessionNonce===this._sessionNonce&&(this._pendingControl.phase="sent")}rollbackSentControl(e){const s=this._pendingControl;if(!s||s.revision!==e||s.phase!=="sent")return;this._pendingControl=void 0;const t=this._lastAuthoritativeControl;t?.sessionNonce===this._sessionNonce&&(this._state.model=t.model,this._state.thinkingLevel=t.thinkingLevel,this.emitContentChange())}rememberAuthoritativeControl(e,s){this._lastAuthoritativeControl={sessionNonce:this._sessionNonce,model:e,thinkingLevel:s}}applyAuthoritativeControlState(e,s,t){const n=this.resolveModel(e),o=s,a=this._pendingControl;if(t!==void 0){if(a){if(a.sessionNonce!==this._sessionNonce||a.revision!==t)return!1;a.phase="acknowledged",a.model=n,a.thinkingLevel=o}return n&&(this._state.model=n),o&&(this._state.thinkingLevel=o),n&&o&&this.rememberAuthoritativeControl(n,o),!!n||!!o}if(a){if(!(a.phase==="acknowledged"&&!!a.model&&j(e,a.model)&&o===a.thinkingLevel))return!1;this._pendingControl=void 0}return n&&(this._state.model=n),o&&(this._state.thinkingLevel=o),n&&o&&this.rememberAuthoritativeControl(n,o),!!n||!!o}async installPi(){await this.send({type:"install_pi"})}async loadDefaultModel(){if(this._state.model)return;const e=await this.send({type:"get_default_model"});this.applyAuthoritativeControlState(e?.model,e?.thinkingLevel)}setCwd(e){this._pendingCwd=e}get cwd(){return this._pendingCwd}createStartingPrompt(e){let s,t;const n={ready:new Promise(o=>{s=o}),resolveReady:o=>s(o),finished:new Promise(o=>{t=o}),resolveFinished:()=>t()};return this._startingPrompts.set(e,n),n}finishStartingPrompt(e,s,t){s.resolveReady(t),s.resolveFinished(),this._startingPrompts.get(e)===s&&this._startingPrompts.delete(e)}async prompt(e,s){let t;if(typeof e=="string"?t=e:Array.isArray(e)?t=e.map(c=>this.extractText(c)).join(`
3
+ `):t=this.extractText(e),this.clearLocalAssistantMessages(),await this.handleSlashCommand(t))return;const o=this._sessionStatus==="virtual"?`virtual:${this._sessionNonce}`:this._sessionPath,a=o?this._startingPrompts.get(o):void 0;if(a){const c=await a.ready;if(c&&this._globalSessionStatus.get(c)==="running"){this.enqueueSteering(c,t),await this.send({type:"steer",sessionPath:c,message:t});return}if(await a.finished,!c)throw new Error("The session failed to start before the queued prompt could be sent");return this.prompt(e,s)}if((this._sessionPath?this._globalSessionStatus.get(this._sessionPath)==="running":!1)&&this._sessionPath){this.enqueueSteering(this._sessionPath,t),await this.send({type:"steer",sessionPath:this._sessionPath,message:t});return}const h=this._state.model;if(!h)throw new Error(`BUG: effective model is undefined when sending prompt. sessionStatus=${this._sessionStatus}, sessionPath=${this._sessionPath}`);const u=J(h);if(!u)throw new Error("BUG: active model has no provider/model ID");const _=this._state.thinkingLevel,y=this._pendingControl?.revision??this._controlRevision;this.markControlSent(y);const v=o??`virtual:${this._sessionNonce}`,w=this.createStartingPrompt(v);if(this._sessionStatus==="virtual"){const c=this._sessionNonce;this._pendingNewPrompt=!0;try{const g=await this.send({type:"prompt",sessionPath:"__new__",cwd:this._pendingCwd,message:t,model:u,thinkingLevel:_,controlRevision:y,images:s});if(this._sessionNonce!==c){console.log("[ws-adapter] Discarding stale prompt response (session changed during await)");return}const S=g?.newSessionPath;if(S&&!this._sessionPath){this._sessionPath=S;const f=I.basename(S,".jsonl"),$=f.split("_");this._sessionId=$.length>1?$.slice(1).join("_"):f,this._sessionStatus="attached",this.requestFullSessionSync(S),this.emitSessionChange(),this.emitStatusChange()}}catch(g){throw this.rollbackSentControl(y),g}finally{this._pendingNewPrompt=!1;const g=this._sessionNonce===c?this._sessionPath:void 0;this.finishStartingPrompt(v,w,g)}return}if(!this._sessionPath)throw new Error("No session loaded");try{await this.send({type:"prompt",sessionPath:this._sessionPath,message:t,model:u,thinkingLevel:_,controlRevision:y,images:s})}catch(c){throw this.rollbackSentControl(y),c}finally{this.finishStartingPrompt(v,w,this._sessionPath)}}extractText(e){if("content"in e){if(typeof e.content=="string")return e.content;if(Array.isArray(e.content))return e.content.filter(s=>s.type==="text").map(s=>s.text).join(`
4
+ `)}return""}async fetchCommands(){try{const e=this._sessionPath?{sessionPath:this._sessionPath}:{cwd:this._pendingCwd};return(await this.send({type:"get_commands",...e}))?.commands??[]}catch{return[]}}clearLocalAssistantMessages(){if(this._localAssistantMessages.length===0)return;const e=new Set(this._localAssistantMessages);this._localAssistantMessages=[],this._state.messages=this._state.messages.filter(s=>!e.has(s)),this.emitContentChange()}appendLocalAssistantMessage(e){const s={role:"assistant",content:[{type:"text",text:e}]};this._localAssistantMessages.push(s),this._state.messages=[...this._state.messages,s],this.emitContentChange()}formatSessionStats(e){const s=o=>o.toLocaleString("en-US"),t=`$${e.cost.toFixed(e.cost<.01?4:e.cost<1?3:2)}`,n=["**Session information**","",`- **File:** \`${e.sessionFile}\``,`- **ID:** \`${e.sessionId}\``,`- **Messages:** ${s(e.totalMessages)} total (${s(e.userMessages)} user, ${s(e.assistantMessages)} assistant)`,`- **Tools:** ${s(e.toolCalls)} calls, ${s(e.toolResults)} results`,`- **Tokens:** ${s(e.tokens.total)} total (${s(e.tokens.input)} input, ${s(e.tokens.output)} output, ${s(e.tokens.cacheRead)} cache read, ${s(e.tokens.cacheWrite)} cache write)`,`- **Cost:** ${t}`];if(e.contextUsage){const o=e.contextUsage.tokens===null?`unknown / ${s(e.contextUsage.contextWindow)}`:`${s(e.contextUsage.tokens)} / ${s(e.contextUsage.contextWindow)}${e.contextUsage.percent===null?"":` (${e.contextUsage.percent}%)`}`;n.push(`- **Context:** ${o}`)}return n.join(`
5
+ `)}async showSessionMessage(){if(!this._sessionPath){this.appendLocalAssistantMessage("No active session yet. Send a message first to create one.");return}const e=await this.send({type:"get_session_stats",sessionPath:this._sessionPath});this.appendLocalAssistantMessage(this.formatSessionStats(e))}async showHelpMessage(){const e=["**Built-in commands:**","","| Command | Description |","|---------|-------------|",...ee.map(a=>{const r=a.argumentHint?` ${a.argumentHint}`:"";return`| \`/${a.name}${r}\` | ${a.description} |`})],s=await this.fetchCommands(),t=s.filter(a=>a.source==="extension"),n=s.filter(a=>a.source==="prompt"),o=s.filter(a=>a.source==="skill");if(t.length>0){e.push("","**Extension commands:**","","| Command | Description |","|---------|-------------|");for(const a of t)e.push(`| \`/${a.name}\` | ${a.description||""} |`)}if(n.length>0){e.push("","**Prompt templates:**","","| Command | Description |","|---------|-------------|");for(const a of n){const r=a.location?` *(${a.location})*`:"";e.push(`| \`/${a.name}\` | ${a.description||""}${r} |`)}}if(o.length>0){e.push("","**Skills:**","","| Command | Description |","|---------|-------------|");for(const a of o){const r=a.location?` *(${a.location})*`:"";e.push(`| \`/${a.name}\` | ${a.description||""}${r} |`)}}e.push("","**Keyboard shortcuts:**","","| Shortcut | Action |","|----------|--------|","| `Enter` | Send message (also works during streaming to steer) |","| `Cmd+Enter` | Fork session and send message in the fork |","| `Shift+Enter` | New line |","| `Escape` | Abort current turn |"),this.appendLocalAssistantMessage(e.join(`
6
+ `))}async handleSlashCommand(e){const s=e.trim();if(!s.startsWith("/"))return!1;if(s==="/help")return await this.showHelpMessage(),!0;if(s==="/new")return await this.newSession(),!0;if(s==="/session")return await this.showSessionMessage(),!0;if(s==="/fork")return window.dispatchEvent(new CustomEvent("pi-fork-request")),!0;if(s==="/compact"||s.startsWith("/compact ")){if(!this._sessionPath)return!0;const t=s.startsWith("/compact ")?s.slice(9).trim():void 0,n={role:"compactionSummary",summary:"",tokensBefore:0,timestamp:Date.now(),_compacting:!0};this._state.isStreaming=!0,this._state.messages=[...this._state.messages,n],this.emitStatusChange(),this.emitContentChange();try{await this.send({type:"compact",sessionPath:this._sessionPath,customInstructions:t})}catch(o){throw this._state.messages=this._state.messages.filter(a=>a!==n),this.emitContentChange(),o}finally{this._state.isStreaming=!1,this.emitStatusChange()}return await this.subscribeToSession(this._sessionPath),!0}if(s.startsWith("/name ")){const t=s.slice(6).trim();if(!t)return!0;if(!this._sessionPath)return this.appendLocalAssistantMessage("Cannot set name: no active session. Send a message first."),!0;try{await this.send({type:"set_session_name",sessionPath:this._sessionPath,name:t}),this._sessionName=t,this.appendLocalAssistantMessage(`Session renamed to **${t}**`),this.emitSessionChange()}catch(n){this.appendLocalAssistantMessage(`Failed to rename session: ${n?.message||"unknown error"}`)}return!0}if(s==="/reload"){try{const t=await this.send({type:"reload_processes"}),n=t?.killed??0,o=t?.draining??0;this.appendLocalAssistantMessage(`Reload requested: killed ${n} idle process(es), draining ${o} running process(es).`)}catch(t){this.appendLocalAssistantMessage(`Failed to reload pi processes: ${t?.message||"unknown error"}`)}return!0}return!1}abort(){this._sessionPath&&this.send({type:"abort",sessionPath:this._sessionPath}).catch(()=>{})}hardKill(){this._sessionPath&&this.send({type:"hard_kill",sessionPath:this._sessionPath}).catch(()=>{})}steer(e){const s=this.extractText(e);!s||!this._sessionPath||!(this._globalSessionStatus.get(this._sessionPath)==="running")||(this.enqueueSteering(this._sessionPath,s),this.send({type:"steer",sessionPath:this._sessionPath,message:s}).catch(console.error))}removeSteering(e){this._sessionPath&&this.send({type:"remove_steering",sessionPath:this._sessionPath,index:e}).catch(console.error)}setModel(e){const s=this.resolveModel(e)??e,t=j(this._state.model,s),n=G(s,this._state.thinkingLevel);t&&n===this._state.thinkingLevel||(this._state.model=s,this._state.thinkingLevel=n,this.markControlPending(),this.emitContentChange())}setThinkingLevel(e){const s=G(this._state.model,e);s!==this._state.thinkingLevel&&(this._state.thinkingLevel=s,this.markControlPending(),this.emitContentChange())}async getForkMessages(){return this._sessionPath?this.listForkMessages(this._sessionPath):[]}listForkMessages(e){return this.api.listForkMessages(e)}browseDirectory(e){return this.api.browseDirectory(e)}createDirectory(e,s){return this.api.createDirectory(e,s)}getRawSession(e){return this.api.getRawSession(e)}getFileContent(e,s){return this.api.getFileContent(e,s)}createFileUpload(e){return this.api.createFileUpload(e)}appendFileUpload(e){return this.api.appendFileUpload(e)}completeFileUpload(e){return this.api.completeFileUpload(e)}getLocalSettings(){return this.api.getLocalSettings()}validateLocalSettings(e){return this.api.validateLocalSettings(e)}patchLocalSettings(e){return this.api.patchLocalSettings(e)}saveLocalSettings(e){return this.api.saveLocalSettings(e)}getUpdates(){return this.api.getUpdates()}runUpdate(e){return this.api.runUpdate(e)}async fork(e){if(!this._sessionPath)throw new Error("No session loaded");const s=await this.send({type:"fork",sessionPath:this._sessionPath,entryId:e});return{text:s?.text??"",cancelled:s?.cancelled??!1,newSessionPath:s?.newSessionPath??null}}async forkAndPrompt(e,s){if(!this._sessionPath||this._sessionStatus==="virtual"){await this.prompt(e,s);return}if(!this._state.model)throw new Error(`BUG: _state.model is undefined when sending fork_prompt. sessionPath=${this._sessionPath}`);const t=J(this._state.model);if(!t)throw new Error("BUG: active model has no provider/model ID");const n=this._pendingControl?.revision??this._controlRevision;this.markControlSent(n);const o=this._sessionNonce;let a;try{a=await this.send({type:"fork_prompt",sessionPath:this._sessionPath,message:e,model:t,thinkingLevel:this._state.thinkingLevel,controlRevision:n,images:s})}catch(r){throw this.rollbackSentControl(n),r}if(this._sessionNonce!==o){console.log("[ws-adapter] Discarding stale fork_prompt response (session changed during await)");return}a?.newSessionPath&&await this.switchSession(a.newSessionPath)}async listSessions(){const e=await this.api.listSessions(),s=new Set(e.map(n=>n.path));for(const[n,o]of this._optimisticSessions)if(s.has(n)){const a=e.find(r=>r.path===n);a&&!a.cwd&&o.cwd?a.cwd=o.cwd:this._optimisticSessions.delete(n)}else e.push(o);const t=this.virtualSessionInfo;return t&&!s.has(t.path)&&e.push(t),e}get optimisticSessions(){return Array.from(this._optimisticSessions.values())}async deleteSession(e){await this.api.deleteSession(e)}async switchSession(e,s){const t=++this._sessionNonce;s!==void 0&&(this._pendingCwd=s),this._pendingNewPrompt=!1,this._pendingControl=void 0,this._lastAuthoritativeControl=void 0,this._sessionPath=e,this._localAssistantMessages=[],this.clearExtensionStatuses();const n=I.basename(e,".jsonl"),o=n.split("_");this._sessionId=o.length>1?o.slice(1).join("_"):n,this._sessionStatus="detached",this._state.messages=[],this._state.isStreaming=!1,this._pendingToolCallIds.clear(),this._toolCallTimings={},this._awaitingFullSync=void 0,this._state.error=void 0,await this.requestFullSessionSync(e),!(t!==this._sessionNonce||e!==this._sessionPath)&&(this._globalSessionStatus.get(e)==="running"&&(this._sessionStatus="attached",this._state.isStreaming=!0),this.emitSessionChange(),this.emitStatusChange())}async newSession(e){this._sessionNonce++,this._pendingNewPrompt=!1,this._pendingControl=void 0,this._sessionId=typeof crypto.randomUUID=="function"?crypto.randomUUID():Array.from(crypto.getRandomValues(new Uint8Array(16))).map(s=>s.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5"),this._sessionPath=void 0,this._sessionName=void 0,this._localAssistantMessages=[],this.clearExtensionStatuses(),this._sessionStatus="virtual",this._pendingCwd=e,this._state.model?this.rememberAuthoritativeControl(this._state.model,this._state.thinkingLevel):this._lastAuthoritativeControl=void 0,this._state.messages=[],this._state.isStreaming=!1,this._pendingToolCallIds.clear(),this._toolCallTimings={},this._syncJson="",this._syncHash="",this._syncRevision=void 0,this._awaitingFullSync=void 0,this.clearSessionSyncQueue(),this._state.error=void 0,this.subscribeToSession(void 0),this.emitSessionChange(),this.emitStatusChange()}get virtualSessionInfo(){if(this._sessionStatus!=="virtual"||!this._pendingCwd)return;const e=new Date().toISOString();return{id:this._sessionId,path:`__virtual__${this._sessionId}`,cwd:this._pendingCwd,created:e,modified:e,lastUserPromptTime:e,messageCount:0,firstMessage:"(new session)"}}}const I={basename(i,e){const s=i.split("/").pop()||i;return e&&s.endsWith(e)?s.slice(0,-e.length):s}};export{Oe as W,G as c,Ue as f,be as g,Re as m,qe as s};
@@ -17,8 +17,8 @@
17
17
  if (colorTheme && colorTheme !== "default") root.setAttribute("data-color-theme", colorTheme);
18
18
  })();
19
19
  </script>
20
- <script type="module" crossorigin src="/assets/index-XEVKscP-.js"></script>
21
- <link rel="stylesheet" crossorigin href="/assets/index-BtDAXAo1.css">
20
+ <script type="module" crossorigin src="/assets/index-DwbBcYUf.js"></script>
21
+ <link rel="stylesheet" crossorigin href="/assets/index-iblQYBAl.css">
22
22
  </head>
23
23
  <body>
24
24
  <div id="app">