char-slop/berry
multipurpose self-modifiable agentic harness
git clone https://git.t4t.associates/char-slop/berry
6334b24
main
1import type { Channel , ChannelMessage , JsonValue } from "@berry/api" ; 2import { token } from "./client.ts" ; 3 4/** Open a channel to `path`: its first message authorizes it and carries `args`; what `send` is given before then waits. */ 5export function openChannel ( path :string , args :JsonValue | undefined ) :Channel { 6const scheme = location . protocol === "https:" ?"wss:" :"ws:" ; 7const socket = new WebSocket ( ` ${ scheme } // ${ location . host } ${ path } ` ); 8socket . binaryType = "arraybuffer" ; 9const waiting :ChannelMessage [] = []; 10const encode = ( message :ChannelMessage ) => 11message instanceof Uint8Array ?message :JSON . stringify ( message ); 12let incoming ! :ReadableStreamDefaultController < ChannelMessage >; 13const messages = new ReadableStream < ChannelMessage >({ 14start :( controller ) => void ( incoming = controller ), 15cancel :() => socket . close ( 1000 ), 16}); 17socket . addEventListener ( "open" , () => { 18socket . send ( JSON . stringify ({ token :token . get (), args :args ?? {} })); 19for ( const message of waiting . splice ( 0 )) socket . send ( encode ( message )); 20}); 21socket . addEventListener ( "message" , ( event ) => { 22incoming . enqueue ( 23typeof event . data === "string" ?JSON . parse ( event . data ) :new Uint8Array ( event . data ), 24); 25}); 26socket . addEventListener ( "close" , ({ code, reason}) => { 27try { 28// closed as asked, by either end; anything else is a failure, such as a restart or a refusal 29if ( code === 1000 ) incoming . close (); 30else incoming . error ( new Error ( reason || `the channel closed ( ${ code } )` )); 31} catch { 32// already ended 33} 34}); 35return { 36send ( message ) { 37if ( socket . readyState === WebSocket . CONNECTING ) waiting . push ( message ); 38else if ( socket . readyState === WebSocket . OPEN ) socket . send ( encode ( message )); 39}, 40 messages, 41close :() => socket . close ( 1000 ), 42}; 43}