char-slop/berry
multipurpose self-modifiable agentic harness
git clone https://git.t4t.associates/char-slop/berry
6334b24
main
1// A channel over a websocket: the first message authorizes it and carries its arguments; after that, text frames are 2// JSON and binary frames bytes, each way. 3 4import type { Channel , ChannelMessage , JsonValue } from "@berry/api" ; 5 6const AUTH_TIMEOUT_MS = 10_000 ; 7 8/** Why the server closed a channel it could not open, for the frontend's `messages` to fail with. */ 9export const REFUSED = 4400 ; 10const UNAUTHORIZED = 4001 ; 11 12export type ChannelOptions = { 13authorize ( token :string ) :boolean ; 14/** Hand the channel to whoever opens it; a rejection closes it with the message. */ 15open ( args :JsonValue | undefined , channel :Channel , signal :AbortSignal ) :Promise < void >; 16}; 17 18export function serveChannel ( socket :WebSocket , { authorize, open} :ChannelOptions ) :void { 19socket . binaryType = "arraybuffer" ; 20const closed = new AbortController (); 21let incoming ! :ReadableStreamDefaultController < ChannelMessage >; 22const messages = new ReadableStream < ChannelMessage >({ 23start :( controller ) => void ( incoming = controller ), 24}); 25const channel :Channel = { 26send ( message ) { 27if ( socket . readyState !== WebSocket . OPEN ) return ; 28socket . send ( message instanceof Uint8Array ?message :JSON . stringify ( message )); 29}, 30 messages, 31close :() => socket . close ( 1000 ), 32}; 33let authorized = false ; 34const timeout = setTimeout (() => socket . close ( UNAUTHORIZED , "unauthorized" ), AUTH_TIMEOUT_MS ); 35socket . addEventListener ( "message" , ( event ) => { 36if ( closed . signal . aborted ) return ; 37let message :ChannelMessage ; 38try { 39message = typeof event . data === "string" 40 ?JSON . parse ( event . data ) 41 :new Uint8Array ( event . data as ArrayBuffer ); 42} catch { 43return socket . close ( REFUSED , "malformed message" ); 44} 45if ( authorized ) return incoming . enqueue ( message ); 46clearTimeout ( timeout ); 47const { token, args} = ( message ?? {}) as { token ?:unknown ; args ?:JsonValue }; 48if ( typeof token !== "string" || ! authorize ( token )) { 49return socket . close ( UNAUTHORIZED , "unauthorized" ); 50} 51authorized = true ; 52open ( args , channel , closed . signal ). catch (( error ) => { 53const reason = error instanceof Error ?error . message :String ( error ); 54// a close reason is at most 123 bytes 55const short = new TextDecoder (). decode ( new TextEncoder (). encode ( reason ). slice ( 0 , 120 )); 56socket . close ( REFUSED , short . replace ( / \uFFFD$ / , "" )); 57}); 58}); 59socket . addEventListener ( "close" , () => { 60clearTimeout ( timeout ); 61closed . abort (); 62try { 63incoming . close (); 64} catch { 65// already ended 66} 67}); 68}