pipane 0.1.8 → 0.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/build-info.json +2 -2
- package/dist/client/assets/__vite-browser-external-DGfF_P2w.js +1 -0
- package/dist/client/assets/backend-landing-page-CF2aHs0U.js +1 -0
- package/dist/client/assets/{__vite-browser-external-DtLbhLGx.js → backend-protocol-BvNAsFvb.js} +1 -1
- package/dist/client/assets/device-identity-C_w2NbSk.js +4 -0
- package/dist/client/assets/index-DtrSEX3O.css +1 -0
- package/dist/client/assets/index-bOr1Y6MY.js +2 -0
- package/dist/client/assets/{main-DEfSB8wO.js → main-CQj3ADar.js} +531 -427
- package/dist/client/assets/pairing-page-CiEb8c3R.js +1 -0
- package/dist/client/assets/remote-backend-manager-Bbt7CXRP.js +1 -0
- package/dist/client/assets/rendezvous-trust-api-xLnrhe-v.js +1 -0
- package/dist/client/assets/webrtc-frame-transport-Drpqhhdy.js +1 -0
- package/dist/client/assets/workspace-backend-client-kUrfC0HS.js +1 -0
- package/dist/client/assets/ws-agent-adapter-Cauprivt.js +6 -0
- package/dist/client/index.html +5 -17
- package/dist/server/server/backend-registration-config.js +7 -0
- package/dist/server/server/frame-connection.js +157 -40
- package/dist/server/server/frame-router.js +2 -1
- package/dist/server/server/server.js +16 -12
- package/dist/server/server/ws-handler.js +44 -23
- package/dist/server/shared/data-channel-framing.js +31 -1
- package/docs/protocol.md +5 -3
- package/package.json +1 -1
- package/dist/client/assets/backend-landing-page-B7SbyIXQ.js +0 -1
- package/dist/client/assets/index-C7_1ODks.js +0 -2
- package/dist/client/assets/index-DgI_gkjg.css +0 -1
- package/dist/client/assets/pairing-page-C0YByC2D.js +0 -1
- package/dist/client/assets/remote-backend-manager-DCSdS38m.js +0 -1
- package/dist/client/assets/rendezvous-trust-api-C2Zob5i4.js +0 -4
- package/dist/client/assets/webrtc-frame-transport-DGX5EO_A.js +0 -1
- package/dist/client/assets/ws-agent-adapter-DpkkZGPl.js +0 -6
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{l as y}from"./device-identity-C_w2NbSk.js";import{R as f,p as h}from"./rendezvous-trust-api-xLnrhe-v.js";import{W as x}from"./webrtc-frame-transport-Drpqhhdy.js";import"./__vite-browser-external-DGfF_P2w.js";const w={loadIdentity:()=>y(),createTrustApi:()=>new f(window.location.origin),createTransport:i=>new x(i)};async function E(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{E as initializePairingPage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{B as c,e as f,i as w,d as m}from"./backend-protocol-BvNAsFvb.js";import{l as y}from"./device-identity-C_w2NbSk.js";import{R as g}from"./rendezvous-trust-api-xLnrhe-v.js";import{W as v}from"./webrtc-frame-transport-Drpqhhdy.js";import{W as k}from"./ws-agent-adapter-Cauprivt.js";import"./__vite-browser-external-DGfF_P2w.js";import"./index-bOr1Y6MY.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=m(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 R{constructor(e,t={loadIdentity:()=>y(),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{R as RemoteBackendManager};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{s as c}from"./device-identity-C_w2NbSk.js";class d{constructor(e,n=globalThis.fetch.bind(globalThis)){const t=new URL(e);t.pathname="/",t.search="",t.hash="",this.baseUrl=t.toString(),this.fetch=n}async createPairingTicket(e,n,t=`c_${crypto.randomUUID()}`){const r=await this.createChallenge({purpose:"pair",deviceId:e.deviceId,devicePublicKey:e.publicKey,backendId:n.backendId,connectionId:t,pairId:n.pairId});return this.completeTicket(`v1/pairings/${encodeURIComponent(n.pairId)}/tickets`,e,r)}async createConnectionTicket(e,n,t=`c_${crypto.randomUUID()}`){const r=await this.createChallenge({purpose:"connect",deviceId:e.deviceId,backendId:n,connectionId:t});return this.completeTicket("v1/connections/tickets",e,r)}async listAuthorizedBackends(e){const n=await this.createChallenge({purpose:"discover",deviceId:e.deviceId}),t=await this.completeSignedRequest("v1/accounts/backends",e,n);if(!Array.isArray(t.backends)||!t.backends.every(o))throw new Error("Rendezvous returned an invalid backend list");return t.backends}async revokeDevice(e,n,t){const r=await this.createChallenge({purpose:"revoke_device",deviceId:e.deviceId,backendId:n,targetDeviceId:t});await this.completeMutation("v1/revocations/devices",e,r)}async revokeBackend(e,n){const t=await this.createChallenge({purpose:"revoke_backend",deviceId:e.deviceId,backendId:n});await this.completeMutation("v1/revocations/backends",e,t)}async createChallenge(e){return this.requestJson("v1/auth/challenges",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})}async completeTicket(e,n,t){const r=await c(n,t),a=await this.requestJson(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({challengeId:t.challengeId,signature:r})});if(!a||typeof a.ticket!="string"||!Array.isArray(a.iceServers))throw new Error("Rendezvous returned an invalid connection ticket");return a}async completeMutation(e,n,t){await this.completeSignedRequest(e,n,t)}async completeSignedRequest(e,n,t){const r=await c(n,t);return this.requestJson(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({challengeId:t.challengeId,signature:r})})}async requestJson(e,n){const t=await this.fetch(new URL(e,this.baseUrl),n),r=await t.json().catch(()=>{});if(!t.ok)throw new Error(typeof r?.error=="string"?r.error:`Rendezvous request failed (${t.status})`);return r}}function o(s){if(!s||typeof s!="object"||Array.isArray(s))return!1;const e=s;return typeof e.backendId=="string"&&e.backendId.length>0&&(e.name===void 0||typeof e.name=="string")&&(e.softwareVersion===void 0||typeof e.softwareVersion=="string")&&Array.isArray(e.protocolVersions)&&e.protocolVersions.every(n=>Number.isSafeInteger(n)&&n>0)&&typeof e.online=="boolean"}function l(s){const e=new URL(s),n=/^\/pair\/([^/]+)$/u.exec(e.pathname),t=new URLSearchParams(e.hash.replace(/^#/u,"")),r=t.get("backend"),a=t.get("secret");if(!n?.[1]||!r||!a)throw new Error("Pairing URL is malformed");return{pairId:decodeURIComponent(n[1]),backendId:r,secret:a}}export{d as R,l as p};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{P as z,b as A,c as P,T as L,v as M,p as B}from"./device-identity-C_w2NbSk.js";import{D,a as O,e as N,M as x,b as U}from"./__vite-browser-external-DGfF_P2w.js";const v=2;function T(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${v}/rendezvous/${e}`,t.search="",t.hash="",t.toString()}function W(n){return JSON.stringify(n)}function F(n){return V(n)}function V(n,e){const t=j(n);if(!t.ok)return t;const i=t.value;switch(i.type){case"challenge":return u("invalid backend challenge");case"registered":return u("invalid backend registration");case"pairing_opened":return u("invalid pairing acknowledgement");case"pairing_confirmed":return u("invalid pairing confirmation");case"connection_request":return u("invalid connection request");case"backend_connected":if(!c(i.backendId)||!c(i.connectionId))return u("invalid browser connection acknowledgement");break;case"signal":if(!c(i.connectionId)||!q(i.signal))return u("invalid ICE signal");break;case"connection_binding":if(!c(i.connectionId)||!H(i.binding))return u("invalid backend identity binding");break;case"connection_closed":if(!c(i.connectionId)||!c(i.reason))return u("invalid connection closure");break;case"authorization_revoked":return u("invalid authorization revocation");case"error":if(!J(i.code)||!c(i.message)||!G(i.connectionId))return u("invalid rendezvous error");break;default:return $(i.type)}return{ok:!0,value:i}}function j(n){let e;try{e=JSON.parse(n)}catch{return{ok:!1,error:{code:"invalid_json",message:"Message is not valid JSON"}}}return!y(e)||!c(e.type)?u("Message must be an object with a type"):e.protocolVersion!==v?{ok:!1,error:{code:"unsupported_version",message:`Unsupported rendezvous protocol version: ${String(e.protocolVersion)}`}}:{ok:!0,value:e}}function q(n){return!y(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 H(n){return y(n)&&n.version===1&&c(n.backendId)&&c(n.publicKey)&&c(n.connectionId)&&c(n.offerSha256)&&c(n.answerSha256)&&c(n.dtlsFingerprint)&&Y(n.expiresAt)&&c(n.signature)}function J(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 u(n){return{ok:!1,error:{code:"invalid_message",message:n}}}function $(n){return{ok:!1,error:{code:"unknown_message",message:`Unknown rendezvous message: ${String(n)}`}}}function y(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}function c(n){return typeof n=="string"&&n.length>0}function G(n){return n===void 0||c(n)}function Y(n){return Number.isSafeInteger(n)&&n>0}class K{constructor(e){this.signalListeners=new Set,this.bindingListeners=new Set,this.closedListeners=new Set,this.errorListeners=new Set,this.socket=null,this.endpoint=T(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 r of this.closedListeners)r(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=F(t);if(!i.ok){const o=new Error(i.error.message);this.emitError(o),this.failConnection(o),e.close(1002,"Invalid rendezvous message");return}const r=i.value;switch(r.type){case"backend_connected":if(r.backendId!==this.backendId){const o=new Error("Rendezvous connected an unexpected backend");this.emitError(o),this.failConnection(o),e.close(1002,"Backend identity mismatch");return}this.connectionId=r.connectionId,this.resolveConnecting?.(r.connectionId),this.clearConnecting();break;case"signal":if(r.connectionId!==this.connectionId)return;for(const o of this.signalListeners)o(r.signal);break;case"connection_binding":if(r.connectionId!==this.connectionId)return;for(const o of this.bindingListeners)o(r.binding);break;case"connection_closed":if(r.connectionId!==this.connectionId)return;this.connectionId=void 0;for(const o of this.closedListeners)o(r.reason);break;case"error":this.emitError(r),this.connectionId||this.failConnection(new Error(r.message));break}}sendRaw(e){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw new Error("Rendezvous WebSocket is not connected");this.socket.send(W({protocolVersion:v,...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 re{constructor(e){this.frameListeners=new Set,this.connectionListeners=new Set,this.decoder=new D,this.outgoing=[],this.connected=!1,this.manuallyClosed=!1,this.everConnected=!1,this.reconnectAttempt=0,this.nextFrameId=0,this.queuedBytes=0,this.flushing=!1,this.iceServerUrls=[],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 K({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=ie(t.ticket);if(this.iceServerUrls=X(t.iceServers),i.backendId!==this.backendId||i.deviceId!==this.deviceIdentity.deviceId)throw new Error("Connection ticket does not match this browser and backend");const r=this.createRendezvousClient(t.ticket),o=this.createPeerConnection({iceServers:t.iceServers,iceTransportPolicy:this.iceTransportPolicy}),a=o.createDataChannel(z,{ordered:!0,protocol:A});a.bufferedAmountLowThreshold=O,a.onbufferedamountlow=()=>this.flushOutgoing(),this.rendezvous=r,this.peer=o,this.channel=a,await new Promise(async(S,I)=>{let k=!1,g="",d="",w,b,C=!1;const E=[],l=s=>{k||(k=!0,this.closeInternal(),I(s instanceof Error?s:new Error(String(s))))},_=async()=>{if(!(!w||!b||C)){await M(b,{backendId:this.backendId,connectionId:g,offerSdp:d,answerSdp:w,expiresAt:i.expiresAt}),await o.setRemoteDescription({type:"answer",sdp:w}),C=!0;for(const s of E.splice(0))await o.addIceCandidate(s)}};o.onicecandidate=s=>{if(!s.candidate||!g)return;const p=s.candidate.toJSON();r.sendSignal({kind:"candidate",candidate:p.candidate??"",sdpMid:p.sdpMid??null,sdpMLineIndex:p.sdpMLineIndex??null})},o.onconnectionstatechange=()=>{(o.connectionState==="failed"||o.connectionState==="closed")&&(k?this.handleDisconnected():l(new Error(`WebRTC connection ${o.connectionState}`)))},a.onerror=()=>l(new Error("WebRTC DataChannel failed")),a.onclose=()=>{k?this.handleDisconnected():l(new Error("WebRTC DataChannel closed before authentication"))},a.onopen=()=>{P(this.deviceIdentity,t.ticket,b?.signature??"").then(s=>{if(!b)throw new Error("Backend identity binding is missing");a.send(JSON.stringify({protocolVersion:L,type:"authenticate",ticket:t.ticket,bindingSignature:b.signature,deviceSignature:s,pairingSecret:t.pairingSecret}))}).catch(l)},a.onmessage=s=>{const p=String(s.data);if(!this.connected){let m;try{m=JSON.parse(p)}catch{l(new Error("Backend returned an invalid authentication frame"));return}if(m?.protocolVersion!==L||m?.type!=="authenticated"){l(new Error(m?.message||"Backend rejected DataChannel authentication"));return}if(m.deviceId!==this.deviceIdentity.deviceId){l(new Error("Backend authenticated an unexpected browser device"));return}this.connected=!0,this.reconnectAttempt=0,k=!0,this.emitConnectionChange({connected:!0,reconnected:this.everConnected}),this.everConnected=!0,S();return}try{const m=this.decoder.accept(p);if(m===void 0)return;for(const R of this.frameListeners)R(m)}catch{this.handleDisconnected()}},r.onSignal(s=>{(async()=>{if(s.kind==="description"){if(s.type!=="answer")throw new Error("Browser expected an SDP answer");w=s.sdp,await _();return}const p={candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex};C?await o.addIceCandidate(p):E.push(p)})().catch(l)}),r.onIdentityBinding(s=>{b=s,_().catch(l)}),r.onConnectionClosed(s=>l(new Error(s))),r.onError(s=>l(s instanceof Error?s:new Error(s.message)));try{if(g=await r.connect(),g!==i.connectionId)throw new Error("Rendezvous route does not match the connection ticket");const s=await o.createOffer();if(d=s.sdp??"",!d)throw new Error("Browser WebRTC offer is empty");await o.setLocalDescription(s),r.sendSignal({kind:"description",type:"offer",sdp:d})}catch(s){l(s)}})}send(e){if(!this.isConnected||!this.channel)throw new Error("Backend transport is not connected");const i=N(e,`b${(++this.nextFrameId).toString(36)}`).map(o=>({message:o,byteLength:Q.encode(o).byteLength})),r=i.reduce((o,a)=>o+a.byteLength,0);if(this.queuedBytes+r>x)throw new Error("DataChannel outgoing frame queue exceeds its limit");this.outgoing.push(...i),this.queuedBytes+=r,this.flushOutgoing()}async getConnectionDiagnostics(){const e=this.peer,t=this.channel;let i=[];if(e)try{(await e.getStats()).forEach(w=>i.push(w))}catch{i=[]}const r=i.filter(d=>d.type==="local-candidate"||d.type==="remote-candidate").map(d=>ee(d,d.type==="local-candidate"?"local":"remote")),o=Z(i),a=o?r.find(d=>d.id===o.localCandidateId):void 0,S=o?r.find(d=>d.id===o.remoteCandidateId):void 0,I=o?ne(o,a,S):void 0,k=i.find(d=>d.type==="transport"),g=i.find(d=>d.type==="data-channel");return{collectedAt:new Date().toISOString(),carrier:"webrtc",backendId:this.backendId,rendezvousUrl:this.rendezvousUrl,signalingUrl:T(this.rendezvousUrl,"browser"),connectionState:e?.connectionState,iceConnectionState:e?.iceConnectionState,iceGatheringState:e?.iceGatheringState,signalingState:e?.signalingState,dtlsState:e?.sctp?.transport.state??f(k?.dtlsState),icePath:te(a,S),iceServerUrls:[...this.iceServerUrls],...I?{selectedPair:I}:{},candidates:r,dataChannel:{state:t?.readyState,label:t?.label,protocol:t?.protocol,ordered:t?.ordered,bufferedAmount:t?.bufferedAmount,maxMessageSize:e?.sctp?.maxMessageSize,messagesSent:h(g?.messagesSent),messagesReceived:h(g?.messagesReceived),bytesSent:h(g?.bytesSent),bytesReceived:h(g?.bytesReceived)}}}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.outgoing.length=0,this.queuedBytes=0,this.decoder.reset(),this.rendezvous?.close(),this.channel=void 0,this.peer=void 0,this.rendezvous=void 0,e&&this.emitConnectionChange({connected:!1,reconnected:!1})}flushOutgoing(){const e=this.channel;if(!(this.flushing||!e||!this.isConnected)){this.flushing=!0;try{for(;this.outgoing.length>0&&e.bufferedAmount<U;){const t=this.outgoing[0];e.send(t.message),this.outgoing.shift(),this.queuedBytes-=t.byteLength}}catch{this.handleDisconnected()}finally{this.flushing=!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)}}const Q=new TextEncoder;function X(n){return[...new Set(n.flatMap(e=>typeof e.urls=="string"?[e.urls]:[...e.urls]))]}function Z(n){const e=n.find(t=>t.type==="transport")?.selectedCandidatePairId;if(typeof e=="string"){const t=n.find(i=>i.id===e&&i.type==="candidate-pair");if(t)return t}return n.find(t=>t.type==="candidate-pair"&&t.selected===!0)??n.find(t=>t.type==="candidate-pair"&&t.nominated===!0&&t.state==="succeeded")}function ee(n,e){return{id:String(n.id),scope:e,address:f(n.address)??f(n.ip),port:h(n.port),protocol:f(n.protocol),candidateType:f(n.candidateType),networkType:f(n.networkType),tcpType:f(n.tcpType),relayProtocol:f(n.relayProtocol),relatedAddress:f(n.relatedAddress),relatedPort:h(n.relatedPort),url:f(n.url),priority:h(n.priority)}}function ne(n,e,t){const i=h(n.currentRoundTripTime);return{state:f(n.state),nominated:typeof n.nominated=="boolean"?n.nominated:void 0,currentRoundTripTimeMs:i===void 0?void 0:i*1e3,availableOutgoingBitrate:h(n.availableOutgoingBitrate),bytesSent:h(n.bytesSent),bytesReceived:h(n.bytesReceived),packetsSent:h(n.packetsSent),packetsReceived:h(n.packetsReceived),...e?{local:e}:{},...t?{remote:t}:{}}}function te(n,e){const t=[n?.candidateType,e?.candidateType];return t.includes("relay")?"turn-relay":t.includes("srflx")||t.includes("prflx")?"direct-stun":t.includes("host")?"direct-host":"unknown"}function f(n){return typeof n=="string"&&n.length>0?n:void 0}function h(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ie(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=B(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{re as W};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{B as a}from"./backend-protocol-BvNAsFvb.js";const u={model:void 0,thinkingLevel:"off",messages:[],isStreaming:!1};class C{constructor(e,t,i){if(this.manager=t,this.contexts=new Map,this.endpoint="webrtc",this.connectedOnce=!1,this.connectionListeners=new Set,this.extensionStatusListeners=new Set,this.globalStatusListeners=new Set,this.steeringQueueListeners=new Set,this.sessionListeners=new Set,this.contentListeners=new Set,this.statusListeners=new Set,this.sessionsChangedListeners=new Set,this.piInstallRequiredListeners=new Set,this.workspaceListeners=new Set,e.length===0)throw new Error("No authorized backends are available");for(const s of e)this.contexts.set(s.backendId,{descriptor:{...s,protocolVersions:[...s.protocolVersions]},sessions:[],...this.isCompatible(s)?{}:{error:`Update required for semantic protocol v${a}`},initialized:!1,unsubscribers:[]});this.activeId=this.chooseInitialBackend(i),this.ensureClient(this.requireContext(this.activeId))}get state(){return this.activeClient?.state??u}get sessionId(){return this.activeClient?.sessionId??""}get sessionFile(){return this.activeClient?.sessionFile}get sessionName(){return this.activeClient?.sessionName}get sessionStatus(){return this.activeClient?.sessionStatus??"virtual"}get isConnected(){return this.activeClient?.isConnected??!1}get isReconnecting(){return this.activeClient?.isReconnecting??!1}get pendingToolCallIds(){return this.activeClient?.pendingToolCallIds??new Set}get toolCallTimings(){return this.activeClient?.toolCallTimings??{}}get steeringQueue(){return this.activeClient?.steeringQueue??[]}get extensionStatuses(){return this.activeClient?.extensionStatuses??new Map}get cwd(){return this.activeClient?.cwd}get activeBackendId(){return this.activeId}get workspaceBackends(){return[...this.contexts.values()].map(e=>({...e.descriptor,protocolVersions:[...e.descriptor.protocolVersions],connected:e.client?.isConnected??!1,reconnecting:e.client?.isReconnecting??!1,...e.error?{error:e.error}:{}}))}get optimisticSessions(){return[...this.contexts.entries()].flatMap(([e,t])=>(t.client?.optimisticSessions??[]).map(i=>({...i,backendId:e})))}get virtualSessionInfo(){const e=this.activeClient?.virtualSessionInfo;return e?{...e,backendId:this.activeId}:void 0}async connect(e){this.endpoint=e;const t=[...this.contexts.values()].filter(n=>n.descriptor.online&&this.isCompatible(n.descriptor)),s=(await Promise.allSettled(t.map(async n=>{const l=this.ensureClient(n);try{return await l.connect(e),n.error=void 0,await this.refreshContextSessions(n),n}catch(h){throw n.error=c(h),h}}))).flatMap(n=>n.status==="fulfilled"?[n.value]:[]);if(s.length===0)throw this.emitWorkspaceChange(),new Error(t.length===0?"All authorized backends are offline":"Could not connect to any authorized backend");this.connectedOnce=!0,this.activeClient?.isConnected||this.setActiveBackend(s[0].descriptor.backendId),this.emitWorkspaceChange()}disconnect(){for(const e of this.contexts.values())e.client?.disconnect()}onConnectionChange(e){return r(this.connectionListeners,e)}onExtensionStatusChange(e){return r(this.extensionStatusListeners,e)}onGlobalStatusChange(e){return r(this.globalStatusListeners,e)}onSteeringQueueChange(e){return r(this.steeringQueueListeners,e)}onSessionChange(e){return r(this.sessionListeners,e)}onContentChange(e){return r(this.contentListeners,e)}onStatusChange(e){return r(this.statusListeners,e)}onSessionsChanged(e){return r(this.sessionsChangedListeners,e)}onPiInstallRequired(e){return r(this.piInstallRequiredListeners,e)}onWorkspaceChange(e){return r(this.workspaceListeners,e)}getSessionStatus(e,t=this.activeId){return this.contexts.get(t)?.client?.getSessionStatus(e)}reportError(e,t){this.requireActiveClient().reportError(e,t)}fetchAvailableModels(){return this.requireActiveClient().fetchAvailableModels()}installPi(){return this.requireActiveClient().installPi()}async loadDefaultModel(){await this.requireActiveClient().loadDefaultModel(),this.requireContext(this.activeId).initialized=!0}setCwd(e){this.requireActiveClient().setCwd(e)}prompt(e,t){return this.requireActiveClient().prompt(e,t)}fetchCommands(){return this.requireActiveClient().fetchCommands()}abort(){this.requireActiveClient().abort()}hardKill(){this.requireActiveClient().hardKill()}steer(e){this.requireActiveClient().steer(e)}removeSteering(e){this.requireActiveClient().removeSteering(e)}setModel(e){this.requireActiveClient().setModel(e)}setThinkingLevel(e){this.requireActiveClient().setThinkingLevel(e)}getForkMessages(){return this.requireActiveClient().getForkMessages()}fork(e){return this.requireActiveClient().fork(e)}forkAndPrompt(e,t){return this.requireActiveClient().forkAndPrompt(e,t)}async switchSession(e,t,i=this.activeId){const s=await this.activateContext(i,!1);await this.ensureConversationInitialized(s),await this.requireContextClient(s).switchSession(e,t)}async newSession(e,t=this.activeId){const i=await this.activateContext(t,!1);await this.ensureConversationInitialized(i),await this.requireContextClient(i).newSession(e)}async activateBackend(e){const t=await this.activateContext(e);await this.ensureConversationInitialized(t)}async removeBackend(e){const t=this.requireContext(e);await this.manager.revokeBackend(e);for(const i of t.unsubscribers)i();if(t.client?.disconnect(),this.contexts.delete(e),this.contexts.size===0){this.emitWorkspaceChange();return}if(this.activeId===e){const i=[...this.contexts.values()].find(s=>s.client?.isConnected)??[...this.contexts.values()].find(s=>s.descriptor.online)??[...this.contexts.values()][0];this.setActiveBackend(i.descriptor.backendId)}this.emitWorkspaceChange()}getConnectionDiagnostics(){return this.requireActiveClient().getConnectionDiagnostics?.()??Promise.resolve(void 0)}getBackendConnectionDiagnostics(e){const t=this.requireContext(e);return this.ensureClient(t).getConnectionDiagnostics?.()??Promise.resolve(void 0)}async listSessions(){return[...this.contexts.entries()].flatMap(([e,t])=>t.sessions.map(i=>({...i,backendId:e})))}async deleteSession(e,t=this.activeId){const i=this.requireContext(t),s=this.ensureClient(i);s.isConnected||await this.connectContext(i),await s.deleteSession(e),i.sessions=i.sessions.filter(n=>n.path!==e),this.emitSessionsChanged(t,"")}async browseDirectory(e,t=this.activeId){return this.connectedClient(t).then(i=>i.browseDirectory(e))}async createDirectory(e,t,i=this.activeId){return this.connectedClient(i).then(s=>s.createDirectory(e,t))}listForkMessages(e){return this.requireActiveClient().listForkMessages(e)}getRawSession(e){return this.requireActiveClient().getRawSession(e)}getFileContent(e,t){return this.requireActiveClient().getFileContent(e,t)}createFileUpload(e){return this.requireActiveClient().createFileUpload(e)}appendFileUpload(e){return this.requireActiveClient().appendFileUpload(e)}completeFileUpload(e){return this.requireActiveClient().completeFileUpload(e)}getLocalSettings(){return this.requireActiveClient().getLocalSettings()}validateLocalSettings(e){return this.requireActiveClient().validateLocalSettings(e)}patchLocalSettings(e){return this.requireActiveClient().patchLocalSettings(e)}saveLocalSettings(e){return this.requireActiveClient().saveLocalSettings(e)}getUpdates(){return this.requireActiveClient().getUpdates()}runUpdate(e){return this.requireActiveClient().runUpdate(e)}getCapabilities(){return this.requireActiveClient().getCapabilities?.()??Promise.reject(new Error("Backend capabilities are unavailable"))}get activeClient(){return this.contexts.get(this.activeId)?.client}chooseInitialBackend(e){const t=[...this.contexts.values()].filter(i=>this.isCompatible(i.descriptor));if(t.length===0)throw new Error(`No authorized backend supports semantic protocol v${a}`);return e&&t.some(i=>i.descriptor.backendId===e)?e:t.find(i=>i.descriptor.online)?.descriptor.backendId??t[0].descriptor.backendId}isCompatible(e){return e.protocolVersions.includes(a)}requireContext(e){const t=this.contexts.get(e);if(!t)throw new Error("This browser is not authorized for the requested backend");return t}requireActiveClient(){const e=this.activeClient;if(!e)throw new Error("No active backend is available");return e}requireContextClient(e){return e.client??this.ensureClient(e)}ensureClient(e){if(!this.isCompatible(e.descriptor))throw new Error(e.error||"Backend update required");if(e.client)return e.client;const t=e.descriptor.backendId,i=this.manager.getClient(t);return e.client=i,e.unsubscribers.push(i.onConnectionChange(s=>{e.error=s?void 0:e.error,s&&this.connectedOnce&&this.refreshContextSessions(e),this.emitWorkspaceChange(),this.activeId===t&&this.emit(this.connectionListeners,s)}),i.onExtensionStatusChange(()=>{this.activeId===t&&this.emit(this.extensionStatusListeners)}),i.onGlobalStatusChange(()=>{this.emit(this.globalStatusListeners),this.emitWorkspaceChange()}),i.onSteeringQueueChange(()=>{this.activeId===t&&this.emit(this.steeringQueueListeners)}),i.onSessionChange(()=>{this.refreshContextSessions(e),this.activeId===t&&this.emit(this.sessionListeners)}),i.onContentChange(()=>{this.activeId===t&&this.emit(this.contentListeners)}),i.onStatusChange(()=>{this.activeId===t&&this.emit(this.statusListeners)}),i.onSessionsChanged(s=>{this.refreshContextSessions(e).finally(()=>this.emitSessionsChanged(t,s))}),i.onPiInstallRequired(s=>{this.activeId===t&&this.emit(this.piInstallRequiredListeners,s)})),i}async activateContext(e,t=!0){const i=this.requireContext(e),s=this.ensureClient(i);return s.isConnected||await this.connectContext(i),this.activeId!==e&&(await this.activeClient?.setSessionSubscriptionActive?.(!1),this.setActiveBackend(e),t&&await s.setSessionSubscriptionActive?.(!0)),i}async connectContext(e){const t=this.ensureClient(e);try{await t.connect(this.endpoint),e.error=void 0,await this.refreshContextSessions(e)}catch(i){throw e.error=c(i),this.emitWorkspaceChange(),i}}async connectedClient(e){const t=this.requireContext(e),i=this.ensureClient(t);return i.isConnected||await this.connectContext(t),i}async ensureConversationInitialized(e){if(e.initialized)return;if(e.initializing)return e.initializing;const t=this.requireContextClient(e);return e.initializing=(async()=>{try{await t.fetchAvailableModels()}catch{}await t.loadDefaultModel(),e.initialized=!0})().finally(()=>{e.initializing=void 0}),e.initializing}async refreshContextSessions(e){const t=e.client;if(t?.isConnected)try{e.sessions=await t.listSessions(),e.error=void 0,this.emitWorkspaceChange()}catch(i){e.error=c(i),this.emitWorkspaceChange()}}setActiveBackend(e){this.activeId=e,this.connectedOnce&&window.location.pathname.startsWith("/backend/")&&window.history.replaceState(null,"","/"),this.emitWorkspaceChange(),this.emit(this.connectionListeners,this.isConnected),this.emit(this.sessionListeners),this.emit(this.contentListeners),this.emit(this.statusListeners),this.emit(this.extensionStatusListeners),this.emit(this.steeringQueueListeners),this.emit(this.sessionsChangedListeners,"__local_settings__")}emitSessionsChanged(e,t){this.emit(this.sessionsChangedListeners,t),this.emitWorkspaceChange()}emitWorkspaceChange(){this.emit(this.workspaceListeners)}emit(e,...t){for(const i of e)i(...t)}}function r(o,e){return o.add(e),()=>o.delete(e)}function c(o){return o instanceof Error?o.message:String(o)}export{C as WorkspaceBackendClient};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{_ as ie}from"./index-bOr1Y6MY.js";import{i as oe}from"./backend-protocol-BvNAsFvb.js";import{D as ae}from"./__vite-browser-external-DGfF_P2w.js";function re(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,l,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,T,F,R]=[r,l,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&T^~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=T,T=P,P=N+V|0,N=L,L=$,$=f,f=V+ne|0}r=r+f|0,l=l+$|0,u=u+L|0,_=_+N|0,y=y+P|0,v=v+T|0,w=w+F|0,c=c+R|0}return[r,l,u,_,y,v,w,c].map(S=>(S>>>0).toString(16).padStart(8,"0")).join("")}async function ce(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-DGfF_P2w.js").then(t=>t._);return{createHash:s}},[]);return e("sha256").update(i,"utf8").digest("hex")}return re(i)}function he(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=he(t,r.patches),n=r.hash}const a=await ce(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 de=10*6e4,ue=de+9e4,J=1;class Q extends Error{constructor(e,s,t){super(`${s}: ${t}`),this.code=e}}function p(i,e,s="invalid_message"){throw new Q(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 h(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:h(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 A(i,e){return Array.isArray(i)||p(e,"expected an array"),i}function H(i,e){return A(i,e).map((s,t)=>h(s,`${e}[${t}]`))}function O(i,e){const s=m(i,e);for(const[t,n]of Object.entries(s))h(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 ge(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 pe(i,e){const s=m(i,e);return h(s.provider,`${e}.provider`,!1),h(s.modelId,`${e}.modelId`,!1),s}function W(i,e){const s=m(i,e);h(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 me(i,e){if(i.protocolVersion!==J){const s=i.protocolVersion===void 0?"missing":JSON.stringify(i.protocolVersion);p(`${e}.protocolVersion`,`unsupported protocol version ${s}; expected ${J}`,"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 Q?e:new Q("invalid_message","$",e instanceof Error?e.message:String(e));return{ok:!1,error:{code:a.code,message:a.message,requestId:n,command:o}}}function fe(i,e){A(i,e).forEach((s,t)=>{const n=m(s,`${e}[${t}]`);h(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 _e(i,e){const s=m(i,e);h(s.sessionFile,`${e}.sessionFile`,!1),h(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 Se(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":h(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":A(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":_e(t,s);break;case"fork":h(t.text,`${s}.text`),b(t.cancelled,`${s}.cancelled`),t.newSessionPath!==null&&h(t.newSessionPath,`${s}.newSessionPath`,!1);break;case"get_commands":fe(t.commands,`${s}.commands`);break;case"reload_processes":C(t.killed,`${s}.killed`),C(t.draining,`${s}.draining`);break}}const ye=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 ve(i,e){const s=h(i,e,!1);return ye.has(s)||p(e,`unknown response command '${s}'`,"unknown_message"),s}function we(i,e){A(i,e).forEach((s,t)=>{const n=m(s,`${e}[${t}]`);C(n.offset,`${e}[${t}].offset`),C(n.deleteCount,`${e}[${t}].deleteCount`),h(n.insert,`${e}[${t}].insert`)})}function Ce(i){const e=X(i);if(!e.ok)return e;const s=e.value;try{const t=m(s,"$message");me(t,"$message");const n=h(t.type,"$message.type",!1);switch(n){case"response":{if(b(t.success,"$message.success")){h(t.id,"$message.id",!1);const a=ve(t.command,"$message.command");Se(a,t.data,"$message.data")}else t.id!==null&&h(t.id,"$message.id",!1),h(t.command,"$message.command",!1),h(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"),ge(t.steeringQueues,"$message.steeringQueues"),O(t.providerUsageStatuses,"$message.providerUsageStatuses");break;case"pi_install_required":h(t.command,"$message.command",!1),b(t.installable,"$message.installable"),b(t.installing,"$message.installing"),h(t.message,"$message.message",!1);break;case"session_status_change":h(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":h(t.sessionPath,"$message.sessionPath",!1),O(t.statuses,"$message.statuses");break;case"session_sync":h(t.sessionPath,"$message.sessionPath",!1),C(t.revision,"$message.revision"),h(t.hash,"$message.hash",!1),t.op==="full"?h(t.data,"$message.data"):t.op==="delta"?(h(t.baseHash,"$message.baseHash",!1),we(t.patches,"$message.patches")):p("$message.op","expected full or delta");break;case"control_state":h(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":h(t.sessionPath,"$message.sessionPath",!1),k(t.cwd,"$message.cwd"),k(t.firstMessage,"$message.firstMessage");break;case"sessions_changed":h(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 $e(i){const e=X(i);if(!e.ok)return e;const s=e.value;try{const t=m(s,"$session");A(t.messages,"$session.messages").forEach((o,a)=>{const r=m(o,`$session.messages[${a}]`);h(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&&pe(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 Pe(i,e){return JSON.stringify({protocolVersion:J,id:e,...i})}function ke(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 D(i){const e=E(i);if(!(!i.provider||!e))return{provider:i.provider,modelId:e}}function be(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 Le(i){if(!be(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=Le(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 xe extends Error{constructor(e,s,t){super(e),this.status=s,this.details=t,this.name="BackendApiError"}}class Ae{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 xe(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 qe(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 l of t){const u=s.indexOf(l,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 Oe(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 je(i){switch(i){case"builtin":return"Built-in";case"extension":return"Extension";case"prompt":return"Prompt";case"skill":return"Skill"}}const z=1,Fe=1e4;class Ie{constructor(e={}){this.socket=null,this.reconnecting=!1,this.reconnectAttempt=0,this.manuallyClosed=!1,this.decoder=new ae,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.decoder.reset(),this.socket?.close(e,s)}attachFrameHandler(e){e.onmessage=s=>{try{const t=this.decoder.accept(String(s.data));if(t===void 0)return;for(const n of this.frameListeners)n(t)}catch{e.close(1002,"Invalid carrier frame")}}}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),this.decoder.reset(),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),Fe);this.reconnectTimer=this.schedule(()=>{this.reconnectTimer=void 0,this.openSocket(!0).catch(()=>{})},e)}}const Me="provider-usage";function Ee(i){const e=typeof i?.provider=="string"?i.provider.toLowerCase():"";if(e.includes("codex"))return"codex";if(e.includes("anthropic"))return"anthropic"}class De{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._sessionSubscriptionActive=!0,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 Ie({socket:e.socket,createWebSocket:e.createWebSocket}),this.api=e.api??new Ae({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=Ee(this._state.model),t=s?this._providerUsageStatuses.get(s):this._providerUsageStatuses.size===1?this._providerUsageStatuses.values().next().value:void 0;return t&&e.set(Me,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()}async setSessionSubscriptionActive(e){if(e!==this._sessionSubscriptionActive){if(this._sessionSubscriptionActive=e,this._sessionNonce++,this._awaitingFullSync=void 0,this.clearSessionSyncQueue(),!e){await this.subscribeToSession(void 0);return}this._sessionPath&&this._sessionStatus!=="virtual"&&await this.requestFullSessionSync(this._sessionPath)}}getConnectionDiagnostics(){return this.transport.getConnectionDiagnostics?.()??Promise.resolve(void 0)}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._sessionSubscriptionActive&&this._sessionPath&&this._sessionStatus!=="virtual"&&(this._awaitingFullSync=void 0,this.requestFullSessionSync(this._sessionPath)),this.refreshSessionStatuses()}async syncStateOnFocus(){this.refreshSessionStatuses(),this._sessionSubscriptionActive&&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=Ce(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("_"),l=r.length>1?r.slice(1).join("_"):a;this._optimisticSessions.set(t.sessionPath,{id:l,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:ke(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=$e(a.data);if(!r.ok){this.handleProtocolError(r.error);return}const l=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=[...l.messages??[],...this._localAssistantMessages],this._state.isStreaming=l.isStreaming??!1,this._sessionStatus!=="virtual"&&(this._sessionStatus=this._state.isStreaming?"attached":"detached"),this._pendingToolCallIds=new Set(l.pendingToolCalls??[]),this._toolCallTimings=l.toolCallTimings??{},this.applyAuthoritativeControlState(l.model,l.thinkingLevel),Array.isArray(l.steeringQueue)&&(l.steeringQueue.length>0?this._steeringQueues.set(s,[...l.steeringQueue]):this._steeringQueues.delete(s)),this._state.error=l.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"?ue: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(Pe(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=D(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 l=this._state.model;if(!l)throw new Error(`BUG: effective model is undefined when sending prompt. sessionStatus=${this._sessionStatus}, sessionPath=${this._sessionPath}`);const u=D(l);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=D(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){this._sessionSubscriptionActive=!0;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._sessionSubscriptionActive=!0,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{De as W,G as c,Oe as f,Le as g,qe as m,je as s};
|
package/dist/client/index.html
CHANGED
|
@@ -17,33 +17,21 @@
|
|
|
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-
|
|
21
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
20
|
+
<script type="module" crossorigin src="/assets/index-bOr1Y6MY.js"></script>
|
|
21
|
+
<link rel="stylesheet" crossorigin href="/assets/index-DtrSEX3O.css">
|
|
22
22
|
</head>
|
|
23
23
|
<body>
|
|
24
24
|
<div id="app">
|
|
25
25
|
<!-- Static skeleton shell: visible until JS renders the real app.
|
|
26
26
|
Uses only inline styles so it works before any CSS loads. -->
|
|
27
27
|
<div id="skeleton-shell" style="display:flex;flex-direction:column;width:100%;height:100vh;font-family:ui-sans-serif,system-ui,-apple-system,sans-serif;background:var(--sk-background, #ffffff);color:var(--sk-muted-foreground, #6b7280);">
|
|
28
|
-
<!--
|
|
29
|
-
<div style="display:flex;align-items:center;justify-content:space-between;padding:0.5rem 1rem;border-bottom:1px solid var(--sk-border, #e5e7eb);flex-shrink:0;">
|
|
30
|
-
<div style="display:flex;align-items:center;gap:0.5rem;">
|
|
31
|
-
<div class="skeleton-bar" style="width:18px;height:18px;border-radius:4px;"></div>
|
|
32
|
-
<div class="skeleton-bar" style="width:56px;height:14px;border-radius:4px;"></div>
|
|
33
|
-
</div>
|
|
34
|
-
<div style="display:flex;gap:0.35rem;">
|
|
35
|
-
<div class="skeleton-bar" style="width:18px;height:18px;border-radius:4px;"></div>
|
|
36
|
-
<div class="skeleton-bar" style="width:18px;height:18px;border-radius:4px;"></div>
|
|
37
|
-
<div class="skeleton-bar" style="width:18px;height:18px;border-radius:4px;"></div>
|
|
38
|
-
</div>
|
|
39
|
-
</div>
|
|
40
|
-
<!-- Body: sidebar + content -->
|
|
28
|
+
<!-- Body: sidebar + content. Navigation chrome stays inside the sidebar. -->
|
|
41
29
|
<div style="display:flex;flex:1;overflow:hidden;">
|
|
42
30
|
<!-- Sidebar skeleton -->
|
|
43
31
|
<div style="width:280px;flex-shrink:0;border-right:1px solid var(--sk-border, #e5e7eb);padding:0;">
|
|
44
|
-
<!--
|
|
32
|
+
<!-- Pipane sidebar header -->
|
|
45
33
|
<div style="display:flex;align-items:center;justify-content:space-between;padding:0.5rem 0.75rem;border-bottom:1px solid var(--sk-border, #e5e7eb);">
|
|
46
|
-
<div class="skeleton-bar" style="width:
|
|
34
|
+
<div class="skeleton-bar" style="width:54px;height:12px;border-radius:3px;"></div>
|
|
47
35
|
<div class="skeleton-bar" style="width:44px;height:20px;border-radius:4px;"></div>
|
|
48
36
|
</div>
|
|
49
37
|
<!-- Search bar -->
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export const DEFAULT_RENDEZVOUS_URL = "https://pipane.dev";
|
|
2
|
+
export function resolveRendezvousUrl(configuredUrl) {
|
|
3
|
+
return configuredUrl ?? DEFAULT_RENDEZVOUS_URL;
|
|
4
|
+
}
|
|
5
|
+
export function resolveBackendName(configuredName, systemHostname) {
|
|
6
|
+
return configuredName || systemHostname.split(".", 1)[0] || systemHostname;
|
|
7
|
+
}
|
|
@@ -1,22 +1,123 @@
|
|
|
1
|
-
import { DATA_CHANNEL_BUFFER_HIGH_WATER_BYTES, DATA_CHANNEL_BUFFER_LOW_WATER_BYTES, DataChannelFrameDecoder, MAX_DATA_CHANNEL_QUEUED_BYTES, encodeDataChannelFrame, } from "../shared/data-channel-framing.js";
|
|
1
|
+
import { DATA_CHANNEL_BUFFER_HIGH_WATER_BYTES, DATA_CHANNEL_BUFFER_LOW_WATER_BYTES, DataChannelFrameDecoder, MAX_DATA_CHANNEL_QUEUED_BYTES, encodeDataChannelFrame, encodeDataChannelFrameCancellation, } from "../shared/data-channel-framing.js";
|
|
2
2
|
export const FRAME_CONNECTION_OPEN = 1;
|
|
3
3
|
export const FRAME_CONNECTION_CLOSED = 3;
|
|
4
|
+
/**
|
|
5
|
+
* Bounded two-lane scheduler shared by server WebSocket and DataChannel carriers.
|
|
6
|
+
* Control frames may overtake queued bulk chunks, while each logical frame keeps
|
|
7
|
+
* its own ordered chunk sequence.
|
|
8
|
+
*/
|
|
9
|
+
class PrioritizedFrameQueue {
|
|
10
|
+
idPrefix;
|
|
11
|
+
canWrite;
|
|
12
|
+
write;
|
|
13
|
+
onFailure;
|
|
14
|
+
control = [];
|
|
15
|
+
bulk = [];
|
|
16
|
+
nextFrameId = 0;
|
|
17
|
+
queuedBytes = 0;
|
|
18
|
+
flushing = false;
|
|
19
|
+
constructor(idPrefix, canWrite, write, onFailure) {
|
|
20
|
+
this.idPrefix = idPrefix;
|
|
21
|
+
this.canWrite = canWrite;
|
|
22
|
+
this.write = write;
|
|
23
|
+
this.onFailure = onFailure;
|
|
24
|
+
}
|
|
25
|
+
enqueue(frame, options = {}) {
|
|
26
|
+
const id = `${this.idPrefix}${(++this.nextFrameId).toString(36)}`;
|
|
27
|
+
const messages = encodeDataChannelFrame(frame, id).map((value) => ({
|
|
28
|
+
value,
|
|
29
|
+
byteLength: Buffer.byteLength(value),
|
|
30
|
+
}));
|
|
31
|
+
const addedBytes = messages.reduce((total, message) => total + message.byteLength, 0);
|
|
32
|
+
if (this.queuedBytes + addedBytes > MAX_DATA_CHANNEL_QUEUED_BYTES) {
|
|
33
|
+
this.onFailure();
|
|
34
|
+
throw new Error("Carrier outgoing frame queue exceeds its limit");
|
|
35
|
+
}
|
|
36
|
+
const outgoing = {
|
|
37
|
+
id,
|
|
38
|
+
messages,
|
|
39
|
+
nextIndex: 0,
|
|
40
|
+
...(options.transferKey ? { transferKey: options.transferKey } : {}),
|
|
41
|
+
};
|
|
42
|
+
(options.priority === "bulk" ? this.bulk : this.control).push(outgoing);
|
|
43
|
+
this.queuedBytes += addedBytes;
|
|
44
|
+
this.flush();
|
|
45
|
+
}
|
|
46
|
+
cancelTransfer(transferKey) {
|
|
47
|
+
const cancellationIds = [];
|
|
48
|
+
for (const queue of [this.control, this.bulk]) {
|
|
49
|
+
for (let index = queue.length - 1; index >= 0; index--) {
|
|
50
|
+
const frame = queue[index];
|
|
51
|
+
if (frame.transferKey !== transferKey)
|
|
52
|
+
continue;
|
|
53
|
+
for (let messageIndex = frame.nextIndex; messageIndex < frame.messages.length; messageIndex++) {
|
|
54
|
+
this.queuedBytes -= frame.messages[messageIndex].byteLength;
|
|
55
|
+
}
|
|
56
|
+
if (frame.nextIndex > 0 && frame.nextIndex < frame.messages.length) {
|
|
57
|
+
cancellationIds.push(frame.id);
|
|
58
|
+
}
|
|
59
|
+
queue.splice(index, 1);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const cancellations = cancellationIds.map((id) => {
|
|
63
|
+
const value = encodeDataChannelFrameCancellation(id);
|
|
64
|
+
const message = { value, byteLength: Buffer.byteLength(value) };
|
|
65
|
+
this.queuedBytes += message.byteLength;
|
|
66
|
+
return { id: `${this.idPrefix}c${id}`, messages: [message], nextIndex: 0 };
|
|
67
|
+
});
|
|
68
|
+
this.control.unshift(...cancellations);
|
|
69
|
+
this.flush();
|
|
70
|
+
}
|
|
71
|
+
flush() {
|
|
72
|
+
if (this.flushing)
|
|
73
|
+
return;
|
|
74
|
+
this.flushing = true;
|
|
75
|
+
try {
|
|
76
|
+
while (this.canWrite()) {
|
|
77
|
+
const queue = this.control.length > 0 ? this.control : this.bulk;
|
|
78
|
+
const frame = queue[0];
|
|
79
|
+
if (!frame)
|
|
80
|
+
break;
|
|
81
|
+
const message = frame.messages[frame.nextIndex];
|
|
82
|
+
this.write(message.value);
|
|
83
|
+
frame.nextIndex++;
|
|
84
|
+
this.queuedBytes -= message.byteLength;
|
|
85
|
+
if (frame.nextIndex === frame.messages.length)
|
|
86
|
+
queue.shift();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
this.onFailure();
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
this.flushing = false;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
clear() {
|
|
97
|
+
this.control.length = 0;
|
|
98
|
+
this.bulk.length = 0;
|
|
99
|
+
this.queuedBytes = 0;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
4
102
|
/** Adapts an authenticated reliable DataChannel to the server's logical frame connection contract. */
|
|
5
103
|
export class DataChannelFrameConnection {
|
|
6
104
|
channel;
|
|
7
105
|
messageListeners = new Set();
|
|
8
106
|
closeListeners = new Set();
|
|
9
107
|
decoder = new DataChannelFrameDecoder();
|
|
10
|
-
outgoing
|
|
108
|
+
outgoing;
|
|
11
109
|
state = FRAME_CONNECTION_OPEN;
|
|
12
|
-
nextFrameId = 0;
|
|
13
|
-
queuedBytes = 0;
|
|
14
|
-
flushing = false;
|
|
15
110
|
closeEmitted = false;
|
|
16
111
|
constructor(channel) {
|
|
17
112
|
this.channel = channel;
|
|
113
|
+
this.outgoing = new PrioritizedFrameQueue("s", () => this.readyState === FRAME_CONNECTION_OPEN
|
|
114
|
+
&& channel.bufferedAmount() < DATA_CHANNEL_BUFFER_HIGH_WATER_BYTES, (message) => {
|
|
115
|
+
// A false result means libdatachannel accepted the message into
|
|
116
|
+
// native buffering. bufferedAmount, not the result, controls flow.
|
|
117
|
+
channel.sendMessage(message);
|
|
118
|
+
}, () => this.close());
|
|
18
119
|
channel.setBufferedAmountLowThreshold(DATA_CHANNEL_BUFFER_LOW_WATER_BYTES);
|
|
19
|
-
channel.onBufferedAmountLow(() => this.
|
|
120
|
+
channel.onBufferedAmountLow(() => this.outgoing.flush());
|
|
20
121
|
channel.onMessage((message) => {
|
|
21
122
|
try {
|
|
22
123
|
const decoded = this.decoder.accept(message.toString());
|
|
@@ -37,19 +138,13 @@ export class DataChannelFrameConnection {
|
|
|
37
138
|
? FRAME_CONNECTION_OPEN
|
|
38
139
|
: FRAME_CONNECTION_CLOSED;
|
|
39
140
|
}
|
|
40
|
-
send(frame) {
|
|
141
|
+
send(frame, options) {
|
|
41
142
|
if (this.readyState !== FRAME_CONNECTION_OPEN)
|
|
42
143
|
throw new Error("DataChannel frame connection is closed");
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
this.close();
|
|
48
|
-
throw new Error("DataChannel outgoing frame queue exceeds its limit");
|
|
49
|
-
}
|
|
50
|
-
this.outgoing.push(...additions);
|
|
51
|
-
this.queuedBytes += addedBytes;
|
|
52
|
-
this.flushOutgoing();
|
|
144
|
+
this.outgoing.enqueue(frame, options);
|
|
145
|
+
}
|
|
146
|
+
cancelTransfer(transferKey) {
|
|
147
|
+
this.outgoing.cancelTransfer(transferKey);
|
|
53
148
|
}
|
|
54
149
|
close() {
|
|
55
150
|
if (this.state === FRAME_CONNECTION_CLOSED)
|
|
@@ -69,34 +164,12 @@ export class DataChannelFrameConnection {
|
|
|
69
164
|
this.closeListeners.add(listener);
|
|
70
165
|
return this;
|
|
71
166
|
}
|
|
72
|
-
flushOutgoing() {
|
|
73
|
-
if (this.flushing || this.readyState !== FRAME_CONNECTION_OPEN)
|
|
74
|
-
return;
|
|
75
|
-
this.flushing = true;
|
|
76
|
-
try {
|
|
77
|
-
while (this.outgoing.length > 0 && this.channel.bufferedAmount() < DATA_CHANNEL_BUFFER_HIGH_WATER_BYTES) {
|
|
78
|
-
const next = this.outgoing[0];
|
|
79
|
-
// A false result means libdatachannel accepted the message into
|
|
80
|
-
// native buffering. bufferedAmount, not the result, controls flow.
|
|
81
|
-
this.channel.sendMessage(next.message);
|
|
82
|
-
this.outgoing.shift();
|
|
83
|
-
this.queuedBytes -= next.byteLength;
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
catch {
|
|
87
|
-
this.close();
|
|
88
|
-
}
|
|
89
|
-
finally {
|
|
90
|
-
this.flushing = false;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
167
|
finishClose() {
|
|
94
168
|
if (this.closeEmitted)
|
|
95
169
|
return;
|
|
96
170
|
this.closeEmitted = true;
|
|
97
171
|
this.state = FRAME_CONNECTION_CLOSED;
|
|
98
|
-
this.outgoing.
|
|
99
|
-
this.queuedBytes = 0;
|
|
172
|
+
this.outgoing.clear();
|
|
100
173
|
this.decoder.reset();
|
|
101
174
|
const listeners = [...this.closeListeners];
|
|
102
175
|
this.closeListeners.clear();
|
|
@@ -104,3 +177,47 @@ export class DataChannelFrameConnection {
|
|
|
104
177
|
listener();
|
|
105
178
|
}
|
|
106
179
|
}
|
|
180
|
+
/**
|
|
181
|
+
* Adds the same bounded, prioritised carrier scheduler to local WebSockets.
|
|
182
|
+
* Incoming browser commands remain ordinary WebSocket text frames; large
|
|
183
|
+
* server responses use the shared transparent carrier envelopes.
|
|
184
|
+
*/
|
|
185
|
+
export class WebSocketFrameConnection {
|
|
186
|
+
socket;
|
|
187
|
+
outgoing;
|
|
188
|
+
constructor(socket) {
|
|
189
|
+
this.socket = socket;
|
|
190
|
+
this.outgoing = new PrioritizedFrameQueue("w", () => this.readyState === FRAME_CONNECTION_OPEN
|
|
191
|
+
&& socket.bufferedAmount < DATA_CHANNEL_BUFFER_HIGH_WATER_BYTES, (message) => socket.send(message, (error) => {
|
|
192
|
+
if (error)
|
|
193
|
+
this.close(1011, "WebSocket send failed");
|
|
194
|
+
else
|
|
195
|
+
this.outgoing.flush();
|
|
196
|
+
}), () => this.close(1011, "WebSocket frame queue failed"));
|
|
197
|
+
socket.on("close", () => this.outgoing.clear());
|
|
198
|
+
}
|
|
199
|
+
get readyState() {
|
|
200
|
+
return this.socket.readyState;
|
|
201
|
+
}
|
|
202
|
+
send(frame, options) {
|
|
203
|
+
if (this.readyState !== FRAME_CONNECTION_OPEN)
|
|
204
|
+
throw new Error("WebSocket frame connection is closed");
|
|
205
|
+
this.outgoing.enqueue(frame, options);
|
|
206
|
+
}
|
|
207
|
+
cancelTransfer(transferKey) {
|
|
208
|
+
this.outgoing.cancelTransfer(transferKey);
|
|
209
|
+
}
|
|
210
|
+
close(code, reason) {
|
|
211
|
+
this.outgoing.clear();
|
|
212
|
+
this.socket.close(code, reason);
|
|
213
|
+
}
|
|
214
|
+
on(event, listener) {
|
|
215
|
+
if (event === "message") {
|
|
216
|
+
this.socket.on("message", (data) => listener(data));
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
this.socket.on("close", listener);
|
|
220
|
+
}
|
|
221
|
+
return this;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
@@ -7,7 +7,8 @@ class RoutedFrameConnection {
|
|
|
7
7
|
this.connection = connection;
|
|
8
8
|
}
|
|
9
9
|
get readyState() { return this.connection.readyState; }
|
|
10
|
-
send(frame) { return this.connection.send(frame); }
|
|
10
|
+
send(frame, options) { return this.connection.send(frame, options); }
|
|
11
|
+
cancelTransfer(transferKey) { this.connection.cancelTransfer?.(transferKey); }
|
|
11
12
|
close(code, reason) { return this.connection.close(code, reason); }
|
|
12
13
|
on(event, listener) {
|
|
13
14
|
if (event === "message")
|
|
@@ -46,6 +46,7 @@ import { DataChannelFrameConnection } from "./frame-connection.js";
|
|
|
46
46
|
import { routeFrameConnection } from "./frame-router.js";
|
|
47
47
|
import { BackendProtocolHandler } from "./backend-protocol-handler.js";
|
|
48
48
|
import { LocalBackendApi } from "./local-backend-api.js";
|
|
49
|
+
import { resolveBackendName, resolveRendezvousUrl } from "./backend-registration-config.js";
|
|
49
50
|
import qrcode from "qrcode-terminal";
|
|
50
51
|
const DEFAULT_PORT = process.env.NODE_ENV === "production" ? "8222" : "18111";
|
|
51
52
|
const REQUESTED_PORT = parseInt(process.env.PORT || DEFAULT_PORT, 10);
|
|
@@ -74,7 +75,7 @@ const PI_AVAILABLE = checkCommandAvailable(PI_LAUNCH.command);
|
|
|
74
75
|
const PI_MAX_PROCESSES = parseInt(process.env.PI_MAX_PROCESSES || "24", 10);
|
|
75
76
|
const PI_PREWARM_COUNT = parseInt(process.env.PI_PREWARM_COUNT || "2", 10);
|
|
76
77
|
const USAGE_EXTENSION_ENABLED = process.env.PIPANE_USAGE_EXTENSION !== "0";
|
|
77
|
-
const RENDEZVOUS_URL = process.env.PIPANE_RENDEZVOUS_URL;
|
|
78
|
+
const RENDEZVOUS_URL = resolveRendezvousUrl(process.env.PIPANE_RENDEZVOUS_URL);
|
|
78
79
|
let rendezvousPairingRuntime;
|
|
79
80
|
let registeredBackendId;
|
|
80
81
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
@@ -101,7 +102,7 @@ async function startRendezvousRegistration() {
|
|
|
101
102
|
url: RENDEZVOUS_URL,
|
|
102
103
|
identity,
|
|
103
104
|
metadata: {
|
|
104
|
-
name: process.env.PIPANE_BACKEND_NAME
|
|
105
|
+
name: resolveBackendName(process.env.PIPANE_BACKEND_NAME, hostname()),
|
|
105
106
|
softwareVersion: PKG_VERSION,
|
|
106
107
|
protocolVersions: [WS_PROTOCOL_VERSION, BACKEND_PROTOCOL_VERSION],
|
|
107
108
|
},
|
|
@@ -357,21 +358,24 @@ function startSessionsWatcher() {
|
|
|
357
358
|
console.log(`Sessions dir does not exist yet: ${SESSIONS_DIR}`);
|
|
358
359
|
return null;
|
|
359
360
|
}
|
|
360
|
-
|
|
361
|
-
let lastChangedFile = null;
|
|
361
|
+
const sessionListTimers = new Map();
|
|
362
362
|
const watcher = watch(SESSIONS_DIR, { recursive: true }, (_event, filename) => {
|
|
363
363
|
if (!filename || !filename.endsWith(".jsonl"))
|
|
364
364
|
return;
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
365
|
+
const fullPath = path.join(SESSIONS_DIR, filename);
|
|
366
|
+
// WsHandler coalesces detached state per file on a short trailing edge.
|
|
367
|
+
wsHandler.notifySessionFileChanged(fullPath);
|
|
368
|
+
// Sidebar notifications remain less frequent, but no longer let a change
|
|
369
|
+
// in one session overwrite another session's pending watcher event.
|
|
370
|
+
const pending = sessionListTimers.get(fullPath);
|
|
371
|
+
if (pending)
|
|
372
|
+
clearTimeout(pending);
|
|
373
|
+
const timer = setTimeout(() => {
|
|
374
|
+
sessionListTimers.delete(fullPath);
|
|
373
375
|
wsHandler.notifySessionsChanged(fullPath);
|
|
374
376
|
}, 300);
|
|
377
|
+
timer.unref?.();
|
|
378
|
+
sessionListTimers.set(fullPath, timer);
|
|
375
379
|
});
|
|
376
380
|
console.log(`Watching sessions directory: ${SESSIONS_DIR}`);
|
|
377
381
|
return watcher;
|