okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bf63faab2
main
1/** 2* A client for the Harness Gateway (the `dsh web` HTTP + WebSocket surface). 3* 4* Two carriers, both authenticated by the cookie the launch URL's token buys: 5* - HTTP unary RPC: POST /api/<method> with the gateway's envelope 6* - WebSocket mux: /api/remote.mux carrying many independent logical streams 7* 8* The streams used here are `$events` (Host notifications and the approval waterfall) and 9* `session/follow` (a session's durable event log plus live assistant frames). 10* 11* Node 24's global WebSocket accepts a `headers` option, which is how the cookie reaches the upgrade. 12* No dependency is added to the host. 13*/ 14 15export class GatewayError extends Error { 16constructor ( message , { code= 'gateway/error' , details} = {}) { 17super ( message ); 18this . name = 'GatewayError' ; 19this . code = code ; 20this . details = details ; 21} 22} 23 24export class GatewayClient { 25 #base; #token; #cookie= null ; #rpcId= 0 ; #ws= null ; #wsReady= null ; #streams= new Map (); #nextStream= 0 ; 26 #closed= false ; #reconnectTimer= null ; #onState; 27 28/** 29* @param { {baseUrl: string, token: string, onState?: (state: 'open'|'closed') => void} } options 30*/ 31constructor ({ baseUrl, token, onState= () => {} }) { 32this . #base= baseUrl . replace ( / \/ + $ / , '' ); 33this . #token= token ; 34this . #onState= onState ; 35} 36 37/** Exchange the launch token for the API cookie. */ 38async connect () { 39const res = await fetch ( ` ${ this . #base } /?token= ${ encodeURIComponent ( this . #token )} ` , { redirect :'manual' }); 40const cookie = ( res . headers . get ( 'set-cookie' ) ?? '' ). split ( ';' )[ 0 ]; 41if ( ! cookie . startsWith ( 'dsh-auth-' )) throw new GatewayError ( `the agent refused the launch token (HTTP ${ res . status } )` , { code :'gateway/auth' }); 42this . #cookie= cookie ; 43} 44 45/** One unary call. Resolves with the value, rejects with a GatewayError carrying the gateway's code. */ 46async rpc ( method , args = {}, { signal} = {}) { 47if ( ! this . #cookie) throw new GatewayError ( 'not connected' , { code :'gateway/not-connected' }); 48const rpcId = `h ${ ++ this . #rpcId } ` ; 49const res = await fetch ( ` ${ this . #base } /api/ ${ method } ` , { 50method :'POST' , 51headers :{ 'content-type' :'application/json' , cookie :this . #cookie}, 52body :JSON . stringify ({ type :'client-request' , rpcId, method, payload :{ args} }), 53 signal, 54}); 55let body ; 56try { body = await res . json (); } catch { throw new GatewayError ( ` ${ method } : the agent returned a non-JSON answer (HTTP ${ res . status } )` , { code :'gateway/bad-response' }); } 57const result = body ?. result ; 58if ( ! result ?. ok ) { 59const e = result ?. error ?? {}; 60throw new GatewayError ( ` ${ method } : ${ e . message ?? `HTTP ${ res . status } ` } ` , { code :e . code ?? 'gateway/error' , details :e . details }); 61} 62return result . value ; 63} 64 65/** 66* Open a logical stream on the mux. Handlers: `onItem(value)`, `onEnd()`, `onError(error)`. 67* The stream is re-opened after a socket reconnect and `onItem` receives it from the start again 68* (a `session/follow` opens with a fresh snapshot, so callers de-duplicate by sequence number). 69*/ 70openStream ( endpoint , args , handlers ) { 71const streamId = `s ${ ++ this . #nextStream } ` ; 72const entry = { streamId, endpoint, args, ...handlers , closed :false }; 73this . #streams. set ( streamId , entry ); 74void this . #ensureSocket(). then (() => this . #sendOpen( entry ), () => {}); 75return { 76 streamId, 77close :() => { 78entry . closed = true ; 79this . #streams. delete ( streamId ); 80if ( this . #ws?. readyState === 1 ) { 81try { this . #ws. send ( JSON . stringify ({ type :'cancel' , streamId})); } catch { /* socket going away */ } 82} 83}, 84}; 85} 86 87/** Answer one forwarded approval waterfall. `outcome` is `allowed-once`, `rejected`, or `next`. */ 88async answerEvent ({ clientId, eventId, outcome}) { 89const wire = outcome === 'next' ?{ kind :'next' } :{ kind :'result' , value :outcome }; 90return this . rpc ( '$events/result' , { clientId, eventId, outcome :wire }); 91} 92 93close () { 94this . #closed= true ; 95clearTimeout ( this . #reconnectTimer); 96for ( const s of this . #streams. values ()) s . closed = true ; 97this . #streams. clear (); 98try { this . #ws?. close (); } catch { /* already closed */ } 99this . #ws= null ; 100} 101 102// -- socket --------------------------------------------------------------------------------------- 103 104 #ensureSocket() { 105if ( this . #closed) return Promise . reject ( new GatewayError ( 'closed' , { code :'gateway/closed' })); 106if ( this . #ws&& this . #ws. readyState === 1 ) return Promise . resolve (); 107if ( this . #wsReady) return this . #wsReady; 108this . #wsReady= new Promise (( resolve , reject ) => { 109const url = ` ${ this . #base . replace ( / ^http / , 'ws' )} /api/remote.mux` ; 110const ws = new WebSocket ( url , { headers :{ cookie :this . #cookie} }); 111this . #ws= ws ; 112ws . onopen = () => { this . #wsReady= null ; this . #onState( 'open' ); resolve (); }; 113ws . onmessage = e => this . #onMessage( String ( e . data )); 114ws . onerror = () => { /* the close handler reports it */ }; 115ws . onclose = () => { 116const wasReady = this . #wsReady; 117this . #wsReady= null ; 118if ( this . #ws=== ws ) this . #ws= null ; 119this . #onState( 'closed' ); 120if ( wasReady ) reject ( new GatewayError ( 'the agent socket closed before it opened' , { code :'gateway/socket' })); 121if ( this . #closed) return ; 122// Streams are re-opened by a new socket; a dropped socket must not strand a follower. 123clearTimeout ( this . #reconnectTimer); 124if ( this . #streams. size ) this . #reconnectTimer= setTimeout (() => { 125this . #ensureSocket(). then (() => { for ( const s of this . #streams. values ()) this . #sendOpen( s ); }). catch (() => { 126for ( const s of [ ...this . #streams. values ()]) s . onError ?.( new GatewayError ( 'the agent socket could not be re-opened' , { code :'gateway/socket' })); 127}); 128}, 500 ); 129}; 130}); 131return this . #wsReady; 132} 133 134 #sendOpen( entry ) { 135if ( entry . closed || this . #ws?. readyState !== 1 ) return ; 136this . #ws. send ( JSON . stringify ({ type :'open' , streamId :entry . streamId , endpoint :entry . endpoint , payload :{ args :entry . args } })); 137} 138 139 #onMessage( text ) { 140let m ; try { m = JSON . parse ( text ); } catch { return ; } 141const s = this . #streams. get ( m . streamId ); 142if ( ! s ) return ; 143if ( m . type === 'item' ) s . onItem ?.( m . value ); 144else if ( m . type === 'end' ) { this . #streams. delete ( s . streamId ); s . onEnd ?.(); } 145else if ( m . type === 'error' ) s . onError ?.( new GatewayError ( m . error ?. message ?? 'stream failed' , { code :m . error ?. code , details :m . error ?. details })); 146} 147}