UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

3 lines (2 loc) • 38.7 kB
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } } import{Check,build_default}from"./chunk-MIKPY3E7.js";var ServerError=class extends Error{constructor(error){super(error.message),this.name="ServerError",this.code=error.code}},DisconnectedError=class extends Error{constructor(message="Client is disconnected",cause){super(message,cause===void 0?void 0:{cause}),this.name="DisconnectedError"}},ClientDisposedError=class extends Error{constructor(){super("Client is disposed"),this.name="ClientDisposedError"}};function toError(error){return error instanceof Error?error:new Error(String(error))}function toDisconnectedError(error){let cause=toError(error);return cause instanceof DisconnectedError?cause:new DisconnectedError(cause.message,cause)}import{createServiceCatalogueCall,createServiceStateDecoder,createServiceSubscribeCall,createServiceUnsubscribeCall,parseServiceCall,parseServiceCatalogue,parseWireServiceProviderUpdate,parseWireServiceSubscriptionSnapshot}from"@earendil-works/chord";import{BACKGROUND_CONTEXT}from"@earendil-works/chord/context";var CborError=class extends Error{constructor(message){super(message),this.name="CborError"}},textEncoder=new TextEncoder,textDecoder=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});function resolveLimit(name,value,maximum){if(!Number.isSafeInteger(value)||value<0||value>maximum)throw new RangeError(`${name} must be an integer between 0 and ${maximum}`);return value}function resolveOptions(options){return{maxByteLength:resolveLimit("maxByteLength",options?.maxByteLength??16777216,4294967295),maxContainerLength:resolveLimit("maxContainerLength",options?.maxContainerLength??1e6,4294967295),maxDepth:resolveLimit("maxDepth",options?.maxDepth??64,512)}}var CborReader=class{constructor(bytes,options){this.offset=0,this.bytes=bytes,this.options=options}decode(){let value=this.readItem(0);if(this.offset!==this.bytes.byteLength)throw new CborError("CBOR payload contains trailing data");return value}readItem(depth){if(depth>this.options.maxDepth)throw new CborError(`CBOR nesting depth exceeds configured limit of ${this.options.maxDepth}`);let initial=this.readByte(),majorType=initial>>>5,additionalInformation=initial&31;switch(majorType){case 0:return this.readArgument(additionalInformation);case 1:{let value=-1-this.readArgument(additionalInformation);if(!Number.isSafeInteger(value))throw new CborError("Decoded CBOR integer is outside the safe range");return value}case 2:{let length=this.readLength(additionalInformation,"byte string",this.options.maxByteLength);return new Uint8Array(this.readBytes(length))}case 3:{let length=this.readLength(additionalInformation,"text string",this.options.maxByteLength),bytes=this.readBytes(length);try{return textDecoder.decode(bytes)}catch{throw new CborError("CBOR text string contains invalid UTF-8")}}case 4:{let length=this.readLength(additionalInformation,"array",this.options.maxContainerLength),result=[];for(let index=0;index<length;index++)result.push(this.readItem(depth+1));return result}case 5:{let length=this.readLength(additionalInformation,"map",this.options.maxContainerLength),result={},keys=new Set;for(let index=0;index<length;index++){let key=this.readItem(depth+1);if(typeof key!="string")throw new CborError("CBOR map keys must be strings");if(keys.has(key))throw new CborError("CBOR map contains a duplicate key");keys.add(key),Object.defineProperty(result,key,{configurable:!0,enumerable:!0,value:this.readItem(depth+1),writable:!0})}return result}case 6:throw new CborError("CBOR tags are not supported");case 7:return this.readSimple(additionalInformation);default:throw new CborError("Malformed CBOR major type")}}readSimple(additionalInformation){switch(additionalInformation){case 20:return!1;case 21:return!0;case 22:return null;case 27:{let bytes=this.readBytes(8),value=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength).getFloat64(0,!1);if(!Number.isFinite(value))throw new CborError("Decoded CBOR number must be finite");if(Number.isInteger(value)&&!Number.isSafeInteger(value))throw new CborError("Decoded CBOR integer is outside the safe range");return value}case 31:throw new CborError("CBOR break marker is not supported");default:throw new CborError("Unsupported CBOR simple value or floating-point width")}}readLength(additionalInformation,kind,limit){if(additionalInformation===31)throw new CborError(`Indefinite-length CBOR ${kind}s are not supported`);let length=this.readArgument(additionalInformation);if(length>limit)throw new CborError(`CBOR ${kind} length exceeds configured limit of ${limit}`);return length}readArgument(additionalInformation){if(additionalInformation<24)return additionalInformation;switch(additionalInformation){case 24:return this.readByte();case 25:{let bytes=this.readBytes(2);return bytes[0]*256+bytes[1]}case 26:{let bytes=this.readBytes(4);return bytes[0]*16777216+bytes[1]*65536+bytes[2]*256+bytes[3]}case 27:{let high=this.readArgument(26),low=this.readArgument(26);if(high>2097151)throw new CborError("Decoded CBOR integer or length is outside the safe range");return high*4294967296+low}case 31:throw new CborError("Indefinite-length CBOR items are not supported");default:throw new CborError("Malformed CBOR additional information")}}readByte(){if(this.offset>=this.bytes.byteLength)throw new CborError("Truncated CBOR payload");let value=this.bytes[this.offset];return this.offset++,value}readBytes(length){if(length>this.bytes.byteLength-this.offset)throw new CborError("Truncated CBOR payload");let value=this.bytes.subarray(this.offset,this.offset+length);return this.offset+=length,value}};function decodeCbor(bytes,options){if(!(bytes instanceof Uint8Array))throw new TypeError("CBOR input must be a Uint8Array");let resolved=resolveOptions(options);if(bytes.byteLength>resolved.maxByteLength)throw new CborError(`CBOR byte length exceeds configured limit of ${resolved.maxByteLength}`);return new CborReader(bytes,resolved).decode()}var CborWriter=class{constructor(maxByteLength){this.offset=0,this.maxByteLength=maxByteLength,this.buffer=new Uint8Array(Math.min(256,maxByteLength))}writeByte(value){this.ensureCapacity(1),this.buffer[this.offset]=value,this.offset++}writeBytes(bytes){this.ensureCapacity(bytes.byteLength),this.buffer.set(bytes,this.offset),this.offset+=bytes.byteLength}writeUint16(value){this.ensureCapacity(2),this.buffer[this.offset]=value>>>8,this.buffer[this.offset+1]=value,this.offset+=2}writeUint32(value){this.ensureCapacity(4),this.buffer[this.offset]=value>>>24,this.buffer[this.offset+1]=value>>>16,this.buffer[this.offset+2]=value>>>8,this.buffer[this.offset+3]=value,this.offset+=4}writeUint64(value){let high=Math.floor(value/4294967296),low=value-high*4294967296;this.writeUint32(high),this.writeUint32(low)}writeFloat64(value){this.ensureCapacity(9),this.buffer[this.offset]=251,new DataView(this.buffer.buffer).setFloat64(this.offset+1,value,!1),this.offset+=9}finish(){return this.buffer.slice(0,this.offset)}ensureCapacity(additionalBytes){let required=this.offset+additionalBytes;if(required>this.maxByteLength)throw new CborError(`CBOR byte length exceeds configured limit of ${this.maxByteLength}`);if(required<=this.buffer.byteLength)return;let capacity=Math.max(1,this.buffer.byteLength);for(;capacity<required;)capacity=Math.min(this.maxByteLength,Math.max(required,capacity*2));let expanded=new Uint8Array(capacity);expanded.set(this.buffer),this.buffer=expanded}};function writeArgument(writer,majorType,value){let prefix=majorType<<5;value<24?writer.writeByte(prefix|value):value<=255?(writer.writeByte(prefix|24),writer.writeByte(value)):value<=65535?(writer.writeByte(prefix|25),writer.writeUint16(value)):value<=4294967295?(writer.writeByte(prefix|26),writer.writeUint32(value)):(writer.writeByte(prefix|27),writer.writeUint64(value))}function isPlainObject(value){if(typeof value!="object"||value===null)return!1;let prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function encodeText(writer,value,options){let bytes=textEncoder.encode(value);if(bytes.byteLength>options.maxByteLength)throw new CborError(`CBOR text string length exceeds configured limit of ${options.maxByteLength}`);if(textDecoder.decode(bytes)!==value)throw new CborError("CBOR text strings must contain valid Unicode scalar values");writeArgument(writer,3,bytes.byteLength),writer.writeBytes(bytes)}function encodeValue(writer,value,options,depth,ancestors){if(depth>options.maxDepth)throw new CborError(`CBOR nesting depth exceeds configured limit of ${options.maxDepth}`);if(value===null){writer.writeByte(246);return}if(typeof value=="boolean"){writer.writeByte(value?245:244);return}if(typeof value=="number"){if(!Number.isFinite(value))throw new CborError("CBOR numbers must be finite");if(Number.isInteger(value)&&!Object.is(value,-0)){if(!Number.isSafeInteger(value))throw new CborError("CBOR integers must be safe JavaScript integers");value>=0?writeArgument(writer,0,value):writeArgument(writer,1,-1-value)}else writer.writeFloat64(value);return}if(typeof value=="string"){encodeText(writer,value,options);return}if(value instanceof Uint8Array){if(value.byteLength>options.maxByteLength)throw new CborError(`CBOR byte string length exceeds configured limit of ${options.maxByteLength}`);writeArgument(writer,2,value.byteLength),writer.writeBytes(value);return}if(Array.isArray(value)){if(ancestors.has(value))throw new CborError("CBOR values must not contain cycles");if(value.length>options.maxContainerLength)throw new CborError(`CBOR array length exceeds configured limit of ${options.maxContainerLength}`);ancestors.add(value);try{writeArgument(writer,4,value.length);for(let index=0;index<value.length;index++){if(!Object.hasOwn(value,index)||value[index]===void 0)throw new CborError("CBOR arrays must not contain holes or undefined values");encodeValue(writer,value[index],options,depth+1,ancestors)}}finally{ancestors.delete(value)}return}if(isPlainObject(value)){if(ancestors.has(value))throw new CborError("CBOR values must not contain cycles");for(let symbol of Object.getOwnPropertySymbols(value))if(Object.prototype.propertyIsEnumerable.call(value,symbol))throw new CborError("CBOR map keys must be strings");let entries=[];for(let key of Object.keys(value)){let entryValue=value[key];entryValue!==void 0&&entries.push([key,entryValue])}if(entries.length>options.maxContainerLength)throw new CborError(`CBOR map length exceeds configured limit of ${options.maxContainerLength}`);ancestors.add(value);try{writeArgument(writer,5,entries.length);for(let[key,entryValue]of entries)encodeText(writer,key,options),encodeValue(writer,entryValue,options,depth+1,ancestors)}finally{ancestors.delete(value)}return}throw new CborError(`Unsupported CBOR value type: ${typeof value}`)}function encodeCbor(value,options){let resolved=resolveOptions(options),writer=new CborWriter(resolved.maxByteLength);return encodeValue(writer,value,resolved,0,new Set),writer.finish()}import{isJsonValue}from"@earendil-works/chord";var FrameError=class extends Error{constructor(message){super(message),this.name="FrameError"}};function resolveMaxFrameLength(options){let value=options?.maxFrameLength??16777216;if(!Number.isSafeInteger(value)||value<0||value>4294967295)throw new RangeError(`maxFrameLength must be an integer between 0 and ${4294967295}`);return value}function encodeFrame(payload){if(!(payload instanceof Uint8Array))throw new TypeError("Frame payload must be a Uint8Array");if(payload.byteLength>4294967295)throw new RangeError("Frame payload exceeds the unsigned 32-bit length limit");let frame=new Uint8Array(4+payload.byteLength),length=payload.byteLength;return frame[0]=length>>>24,frame[1]=length>>>16,frame[2]=length>>>8,frame[3]=length,frame.set(payload,4),frame}var FrameDecoder=class{constructor(options){this.header=new Uint8Array(4),this.headerLength=0,this.payloadBlocks=[],this.currentPayloadBlockLength=0,this.payloadLength=0,this.state="open",this.maxFrameLength=resolveMaxFrameLength(options)}push(chunk){if(this.state==="ended")throw new FrameError("Frame decoder has ended");if(this.state==="failed")throw new FrameError("Frame decoder has failed");if(!(chunk instanceof Uint8Array))throw new TypeError("Frame chunk must be a Uint8Array");let frames=[],chunkOffset=0;for(;chunkOffset<chunk.byteLength;){if(this.expectedPayloadLength===void 0){let headerBytes=Math.min(4-this.headerLength,chunk.byteLength-chunkOffset);if(this.header.set(chunk.subarray(chunkOffset,chunkOffset+headerBytes),this.headerLength),this.headerLength+=headerBytes,chunkOffset+=headerBytes,this.headerLength<4)continue;let frameLength=this.header[0]*16777216+this.header[1]*65536+this.header[2]*256+this.header[3];if(this.headerLength=0,frameLength>this.maxFrameLength&&this.fail(`Frame length ${frameLength} exceeds configured limit of ${this.maxFrameLength}`),frameLength===0){frames.push(new Uint8Array);continue}this.expectedPayloadLength=frameLength,this.payloadBlocks=[],this.currentPayloadBlock=void 0,this.currentPayloadBlockLength=0,this.payloadLength=0}let expectedPayloadLength=this.expectedPayloadLength;if(expectedPayloadLength!==void 0){for(;chunkOffset<chunk.byteLength&&this.payloadLength<expectedPayloadLength;){let block=this.currentPayloadBlock;(!block||this.currentPayloadBlockLength===block.byteLength)&&(block=new Uint8Array(Math.min(65536,expectedPayloadLength-this.payloadLength)),this.payloadBlocks.push(block),this.currentPayloadBlock=block,this.currentPayloadBlockLength=0);let payloadBytes=Math.min(block.byteLength-this.currentPayloadBlockLength,chunk.byteLength-chunkOffset);block.set(chunk.subarray(chunkOffset,chunkOffset+payloadBytes),this.currentPayloadBlockLength),this.currentPayloadBlockLength+=payloadBytes,this.payloadLength+=payloadBytes,chunkOffset+=payloadBytes}if(this.payloadLength===expectedPayloadLength){if(this.payloadBlocks.length===1)frames.push(this.payloadBlocks[0]);else{let payload=new Uint8Array(expectedPayloadLength),offset=0;for(let payloadBlock of this.payloadBlocks)payload.set(payloadBlock,offset),offset+=payloadBlock.byteLength;frames.push(payload)}this.payloadBlocks=[],this.currentPayloadBlock=void 0,this.currentPayloadBlockLength=0,this.expectedPayloadLength=void 0,this.payloadLength=0}}}return frames}end(){if(this.state==="ended")throw new FrameError("Frame decoder has ended");if(this.state==="failed")throw new FrameError("Frame decoder has failed");(this.headerLength!==0||this.expectedPayloadLength!==void 0)&&this.fail("Truncated frame at end of stream"),this.state="ended"}fail(message){throw this.state="failed",this.headerLength=0,this.payloadBlocks=[],this.currentPayloadBlock=void 0,this.currentPayloadBlockLength=0,this.expectedPayloadLength=void 0,this.payloadLength=0,new FrameError(message)}};var PROTOCOL_VERSION=8,IdSchema=build_default.String({minLength:1}),OpaqueJsonValueSchema=build_default.Unsafe(build_default.Unknown()),StrictObject=properties=>build_default.Object(properties,{additionalProperties:!1}),ServerIdSchema=build_default.String({pattern:"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"});function isServerId(value){return Check(ServerIdSchema,value)}var ProtocolErrorSchema=StrictObject({code:IdSchema,message:build_default.String()}),ClientHelloSchema=StrictObject({type:build_default.Literal("hello"),version:build_default.Integer({minimum:0})}),ServerTargetSchema=StrictObject({serverId:ServerIdSchema}),SessionTargetSchema=StrictObject({serverId:ServerIdSchema,sessionId:IdSchema,attachmentId:IdSchema}),RpcTargetSchema=build_default.Union([ServerTargetSchema,SessionTargetSchema]),RequestEnvelopeSchema=StrictObject({type:build_default.Literal("request"),id:IdSchema,target:RpcTargetSchema,call:OpaqueJsonValueSchema}),CancelEnvelopeSchema=StrictObject({type:build_default.Literal("cancel"),id:IdSchema,target:RpcTargetSchema}),ClientMessageSchema=build_default.Union([ClientHelloSchema,RequestEnvelopeSchema,CancelEnvelopeSchema]),ServerHelloSchema=StrictObject({type:build_default.Literal("hello"),version:build_default.Literal(PROTOCOL_VERSION),serverId:ServerIdSchema}),ServerHelloErrorSchema=StrictObject({type:build_default.Literal("hello_error"),error:ProtocolErrorSchema}),ResponseEnvelopeSchema=build_default.Union([StrictObject({type:build_default.Literal("response"),id:IdSchema,ok:build_default.Literal(!0),result:build_default.Optional(OpaqueJsonValueSchema)}),StrictObject({type:build_default.Literal("response"),id:IdSchema,ok:build_default.Literal(!1),error:ProtocolErrorSchema})]),ServiceEventEnvelopeSchema=StrictObject({type:build_default.Literal("service_update"),subscriptionId:IdSchema,update:OpaqueJsonValueSchema}),AttachmentEnvelopeSchema=StrictObject({type:build_default.Literal("attachment"),attachment:build_default.Union([SessionTargetSchema,build_default.Null()])}),ServerMessageSchema=build_default.Union([ServerHelloSchema,ServerHelloErrorSchema,ResponseEnvelopeSchema,ServiceEventEnvelopeSchema,AttachmentEnvelopeSchema]);var ProtocolValidationError=class extends Error{constructor(message){super(message),this.name="ProtocolValidationError"}};function parseClientMessage(value){if(!Check(ClientMessageSchema,value)||!isJsonValue(value))throw new ProtocolValidationError("Invalid client protocol message");return value}function parseServerMessage(value){if(!Check(ServerMessageSchema,value)||!isJsonValue(value))throw new ProtocolValidationError("Invalid server protocol message");return value}function boundedErrorMessage(error){return error instanceof Error?error.message.length<=500?error.message:`${error.message.slice(0,497)}...`:"Unknown codec error"}function encodeProtocolMessage(value,parse,kind,options){let validated=parse(value);try{let maxFrameLength=options?.maxFrameLength??16777216;return encodeFrame(encodeCbor(validated,{maxByteLength:maxFrameLength}))}catch(error){throw error instanceof ProtocolValidationError?error:new ProtocolValidationError(`Unable to encode ${kind} protocol message: ${boundedErrorMessage(error)}`)}}function encodeClientMessage(message,options){return encodeProtocolMessage(message,parseClientMessage,"client",options)}var ValidatedMessageDecoder=class{constructor(kind,parse,options){this.failed=!1,this.frames=new FrameDecoder(options),this.kind=kind,this.maxFrameLength=options?.maxFrameLength??16777216,this.parse=parse}push(chunk){if(this.failed)throw new ProtocolValidationError(`${this.kind} message decoder has failed`);try{let messages=[];for(let frame of this.frames.push(chunk))messages.push(this.parse(decodeCbor(frame,{maxByteLength:this.maxFrameLength})));return messages}catch(error){throw this.failed=!0,error instanceof ProtocolValidationError?error:new ProtocolValidationError(`Invalid ${this.kind} protocol frame: ${boundedErrorMessage(error)}`)}}end(){if(this.failed)throw new ProtocolValidationError(`${this.kind} message decoder has failed`);try{this.frames.end()}catch(error){throw this.failed=!0,new ProtocolValidationError(`Invalid ${this.kind} protocol framing: ${boundedErrorMessage(error)}`)}}};var ServerMessageDecoder=class{constructor(options){this.decoder=new ValidatedMessageDecoder("server",parseServerMessage,options)}push(chunk){return this.decoder.push(chunk)}end(){this.decoder.end()}};var RecoveryRepairAdviceSchema=build_default.Object({state:build_default.Union([build_default.Literal("ok"),build_default.Literal("repair_needed"),build_default.Literal("storage_unavailable")]),healthRevision:build_default.Union([build_default.String({pattern:"^(0|[1-9][0-9]*)$"}),build_default.Null()]),source:build_default.Union([build_default.Object({sessionEpoch:build_default.String({minLength:1}),sequence:build_default.Integer({minimum:0})},{additionalProperties:!1}),build_default.Null()]),hint:build_default.Literal("restart_from_catalog"),retryAfterMs:build_default.Integer({minimum:0,maximum:2e3})},{additionalProperties:!1});function isRecoveryRepairAdvice(value){return Check(RecoveryRepairAdviceSchema,value)}function createPromiseResolvers(){let resolve,reject;return{promise:new Promise((resolvePromise,rejectPromise)=>{resolve=resolvePromise,reject=rejectPromise}),resolve,reject}}var MAX_UINT322=4294967295,Connection=class{#options;#maxFrameLength;#lifecycle={state:"disconnected"};#sequence=0;constructor(options){if(this.#options=options,this.#maxFrameLength=options.maxFrameLength??16777216,!Number.isSafeInteger(this.#maxFrameLength)||this.#maxFrameLength<=0||this.#maxFrameLength>MAX_UINT322)throw new TypeError(`Client maxFrameLength must be an integer between 1 and ${MAX_UINT322}`)}get state(){return this.#lifecycle.state}get maxFrameLength(){return this.#maxFrameLength}connect(){if(this.#lifecycle.state!=="disconnected")return Promise.reject(new DisconnectedError(`Client is already ${this.#lifecycle.state}`));let id2=++this.#sequence,handshake=createPromiseResolvers();this.#lifecycle={state:"connecting",id:id2,decoder:new ServerMessageDecoder({maxFrameLength:this.#maxFrameLength}),handshake},this.#options.onStateChange({state:"connecting"});let handlers={onData:chunk=>this.#handleData(id2,chunk),onClose:()=>{this.#isCurrent(id2)&&this.#handleClose()},onError:error=>{this.#isCurrent(id2)&&this.#failAndClose(toDisconnectedError(error))}};return this.#openTransport(id2,handlers),handshake.promise}disconnect(reason="Client disconnected"){this.#lifecycle.state!=="disconnected"&&this.#failAndClose(typeof reason=="string"?new DisconnectedError(reason):reason)}fail(error){this.#failAndClose(error)}send(frame){let lifecycle=this.#lifecycle;if(lifecycle.state!=="connected")throw new DisconnectedError;let sending;try{sending=lifecycle.transport.send(frame)}catch(error){this.#failAndClose(toDisconnectedError(error));return}sending.catch(error=>{let current=this.#lifecycle;current.state!=="disconnected"&&current.transport===lifecycle.transport&&this.#failAndClose(toDisconnectedError(error))})}async#openTransport(id2,handlers){let transport;try{transport=await this.#options.transportFactory(handlers)}catch(error){this.#isCurrent(id2)&&this.#fail(toDisconnectedError(error));return}let lifecycle=this.#lifecycle;if(lifecycle.state!=="connecting"||lifecycle.id!==id2){transport.close();return}this.#lifecycle={...lifecycle,transport};try{await transport.send(encodeClientMessage({type:"hello",version:PROTOCOL_VERSION},{maxFrameLength:this.#maxFrameLength}))}catch(error){this.#isCurrent(id2)&&this.#failAndClose(toDisconnectedError(error))}}#handleData(id2,chunk){let lifecycle=this.#lifecycle;if(lifecycle.state==="disconnected"||lifecycle.id!==id2)return;if(lifecycle.state==="connecting"&&!lifecycle.transport){this.#failAndClose(new ProtocolValidationError("Received server data before the client hello was sent"));return}let messages;try{messages=lifecycle.decoder.push(chunk)}catch(error){this.#failAndClose(toError(error));return}for(let message of messages){if(this.#lifecycle.state==="disconnected")return;this.#handleMessage(message)}}#handleMessage(message){let lifecycle=this.#lifecycle;if(lifecycle.state==="connecting"){if(message.type==="hello_error"){this.#failAndClose(new ServerError(message.error));return}if(message.type!=="hello"){this.#failAndClose(new ProtocolValidationError("Expected server hello as first message"));return}if(message.serverId!==this.#options.serverId){this.#failAndClose(new ProtocolValidationError(`Connected server ${JSON.stringify(message.serverId)} does not match ${JSON.stringify(this.#options.serverId)}`));return}if(!lifecycle.transport){this.#failAndClose(new ProtocolValidationError("Received server hello before the client hello was sent"));return}let connected={state:"connected",id:lifecycle.id,decoder:lifecycle.decoder,transport:lifecycle.transport,handshake:lifecycle.handshake};this.#lifecycle=connected;try{this.#options.onHandshake(message)}catch(error){this.#lifecycle===connected&&this.#failAndClose(toError(error));return}if(this.#lifecycle!==connected||(this.#options.onStateChange({state:"connected"}),this.#lifecycle!==connected))return;this.#lifecycle={...connected,handshake:void 0},lifecycle.handshake.resolve(message);return}if(lifecycle.state==="connected"){if(message.type==="hello"||message.type==="hello_error"){this.#failAndClose(new ProtocolValidationError("Unexpected handshake message"));return}this.#options.onMessage(message)}}#handleClose(){let lifecycle=this.#lifecycle;if(lifecycle.state==="disconnected")return;let error=new DisconnectedError("Byte transport closed");try{lifecycle.decoder.end()}catch(decoderError){error=toError(decoderError)}this.#fail(error)}#failAndClose(error){let lifecycle=this.#lifecycle,transport=lifecycle.state==="disconnected"?void 0:lifecycle.transport;this.#fail(error),transport?.close()}#fail(error){let lifecycle=this.#lifecycle;lifecycle.state!=="disconnected"&&(this.#lifecycle={state:"disconnected"},lifecycle.handshake?.reject(error),this.#options.onStateChange({state:"disconnected",error}))}#isCurrent(id2){return this.#lifecycle.state!=="disconnected"&&this.#lifecycle.id===id2}};var Client=class _Client{#options;#connection;#pendingRequests=new Map;#connectionStateListeners=new Set;#attachmentListeners=new Set;#serviceListeners=new Map;#requestSequence=0;#serviceSubscriptionSequence=0;#hello;#attachment;#disposed=!1;#disposePromise;constructor(options){if(!isServerId(options.serverId))throw new TypeError("serverId must be a canonical lowercase UUIDv4");this.#options=options,this.#connection=new Connection({transportFactory:options.transportFactory,serverId:options.serverId,maxFrameLength:options.maxFrameLength,onHandshake:hello=>{this.#hello=hello},onMessage:message=>this.#handleMessage(message),onStateChange:change=>this.#handleConnectionStateChange(change)})}get disposed(){return this.#disposed}get connectionState(){return this.#connection.state}get connected(){return this.#connection.state==="connected"}get serverId(){return this.#options.serverId}get hello(){return this.#hello}get attachment(){return this.#attachment}static async connect(options){let client=new _Client(options);try{return await client.connect(),client}catch(error){throw await client.dispose(),error}}connect(){return this.#disposed?Promise.reject(new ClientDisposedError):(this.#hello=void 0,this.#connection.connect())}reconnect(){return this.connect()}disconnect(reason="Client disconnected"){this.#connection.disconnect(reason)}onConnectionStateChange(listener){return this.#assertNotDisposed(),this.#connectionStateListeners.add(listener),()=>this.#connectionStateListeners.delete(listener)}onAttachmentChange(listener){return this.#assertNotDisposed(),this.#attachmentListeners.add(listener),()=>this.#attachmentListeners.delete(listener)}request(target,call,signal){return this.#request(target,call,signal)}async serviceCatalogue(target,signal){let result=await this.#request(target,createServiceCatalogueCall(),signal);try{return parseServiceCatalogue(result)}catch(error){let validationError=new ProtocolValidationError(error instanceof Error?error.message:"Invalid service catalogue");throw this.#connection.fail(validationError),validationError}}async subscribeService(target,serviceId,mode,listener,signal){let subscriptionId=`service-${++this.#serviceSubscriptionSequence}`,active={target,listener,decoder:createServiceStateDecoder(),queuedWireUpdates:[],queued:[],deliveryTail:Promise.resolve(),hydrated:!1,ready:!1};this.#serviceListeners.set(subscriptionId,active);let snapshot;try{snapshot=await this.#request(target,createServiceSubscribeCall(subscriptionId,serviceId,mode),signal,result=>{let decoded=active.decoder.decodeSnapshot(parseWireServiceSubscriptionSnapshot(result));active.hydrated=!0;for(let update of active.queuedWireUpdates.splice(0))active.queued.push(active.decoder.decodeUpdate(parseWireServiceProviderUpdate(update)));return decoded})}catch(error){throw this.#serviceListeners.get(subscriptionId)===active&&this.#serviceListeners.delete(subscriptionId),error}if(this.#serviceListeners.get(subscriptionId)!==active)throw new DisconnectedError;let disposed=!1;return{id:subscriptionId,target,snapshot,start:()=>{if(!(disposed||active.ready)){active.ready=!0;for(let update of active.queued.splice(0))this.#deliverServiceUpdate(active,update)}},dispose:async()=>{if(!disposed){disposed=!0,this.#serviceListeners.get(subscriptionId)===active&&this.#serviceListeners.delete(subscriptionId);try{this.connected&&this.#targetIsCurrent(target)&&await this.#request(target,createServiceUnsubscribeCall(subscriptionId)),await active.deliveryTail}finally{active.queuedWireUpdates.length=0,active.queued.length=0}}}}}#request(target,call,signal,transform){if(this.#disposed)return Promise.reject(new ClientDisposedError);if(!this.connected)return Promise.reject(new DisconnectedError);if(signal?.aborted)return Promise.reject(abortError(signal));let id2=`request-${++this.#requestSequence}`,{promise,resolve,reject}=createPromiseResolvers(),sent=!1,aborted=!1,onAbort,sendCancel=()=>{if(!(!sent||!this.connected))try{this.#connection.send(encodeClientMessage({type:"cancel",id:id2,target},{maxFrameLength:this.#connection.maxFrameLength}))}catch(error){this.#connection.fail(toError(error))}};signal!==void 0&&(onAbort=()=>{aborted||(aborted=!0,reject(abortError(signal)),sendCancel())},signal.addEventListener("abort",onAbort,{once:!0})),this.#pendingRequests.set(id2,{resolve:result=>{try{resolve(transform===void 0?result:transform(result))}catch(error){let validationError=new ProtocolValidationError(error instanceof Error?error.message:"Invalid service operation stream");this.#connection.fail(validationError),reject(validationError)}},reject,cleanup:()=>{signal!==void 0&&onAbort!==void 0&&signal.removeEventListener("abort",onAbort)}});let frame;try{frame=encodeClientMessage({type:"request",id:id2,target,call:parseServiceCall(call)},{maxFrameLength:this.#connection.maxFrameLength})}catch(error){return this.#takePendingRequest(id2)?.reject(toError(error)),promise}return this.#connection.send(frame),sent=!0,aborted&&sendCancel(),promise}#handleMessage(message){if(message.type==="attachment"){if(message.attachment!==null&&message.attachment.serverId!==this.#options.serverId){this.#connection.fail(new ProtocolValidationError("Attachment update belongs to another server"));return}this.#setAttachment(message.attachment??void 0);return}if(message.type==="service_update"){let active=this.#serviceListeners.get(message.subscriptionId);if(active===void 0)return;if(!active.hydrated){active.queuedWireUpdates.push(message.update);return}let update;try{update=active.decoder.decodeUpdate(parseWireServiceProviderUpdate(message.update))}catch(error){this.#connection.fail(new ProtocolValidationError(error instanceof Error?error.message:"Invalid service operation stream"));return}active.ready?this.#deliverServiceUpdate(active,update):active.queued.push(update);return}let pending=this.#takePendingRequest(message.id);if(!pending){this.#connection.fail(new ProtocolValidationError("Response has no matching request"));return}if(!message.ok){pending.reject(new ServerError(message.error));return}pending.resolve(message.result)}#handleConnectionStateChange(change){change.state==="disconnected"&&(this.#hello=void 0,this.#setAttachment(void 0),this.#rejectPendingRequests(change.error??new DisconnectedError),this.#serviceListeners.clear());for(let listener of this.#connectionStateListeners)try{listener(change)}catch(error){this.#reportListenerError(error)}}#takePendingRequest(id2){let request=this.#pendingRequests.get(id2);return request&&(this.#pendingRequests.delete(id2),request.cleanup()),request}#rejectPendingRequests(error){let requests=[...this.#pendingRequests.values()];this.#pendingRequests.clear();for(let request of requests)request.cleanup(),request.reject(error)}dispose(){if(this.#disposePromise)return this.#disposePromise;this.#disposed=!0,this.#disposePromise=Promise.resolve();let error=new ClientDisposedError;return this.#rejectPendingRequests(error),this.#connection.disconnect(error),this.#hello=void 0,this.#setAttachment(void 0),this.#connectionStateListeners.clear(),this.#attachmentListeners.clear(),this.#serviceListeners.clear(),this.#disposePromise}[Symbol.asyncDispose](){return this.dispose()}#setAttachment(attachment){let previous=this.#attachment;if(!(previous?.serverId===attachment?.serverId&&previous?.sessionId===attachment?.sessionId&&previous?.attachmentId===attachment?.attachmentId)){this.#attachment=attachment;for(let listener of this.#attachmentListeners)try{listener(attachment)}catch(error){this.#reportListenerError(error)}}}#deliverServiceUpdate(active,update){active.deliveryTail=active.deliveryTail.then(()=>active.listener(update)).catch(error=>this.#reportListenerError(error))}#targetIsCurrent(target){if(!("sessionId"in target))return this.#hello?.serverId===target.serverId;let attachment=this.#attachment;return attachment?.serverId===target.serverId&&attachment.sessionId===target.sessionId&&attachment.attachmentId===target.attachmentId}#assertNotDisposed(){if(this.#disposed)throw new ClientDisposedError}#reportListenerError(error){if(this.#options.onListenerError)try{this.#options.onListenerError(toError(error))}catch{}}};function createClientServiceTransport(client,getTarget){let target=()=>{let resolved=getTarget();if(resolved===void 0)throw new Error("Remote service target is unavailable");return resolved};return{invoke:async(call,context)=>client.request(target(),call,context.abortSignal),async subscribe(serviceId,mode,listener,context){let subscription=await client.subscribeService(target(),serviceId,mode,update=>listener(update,BACKGROUND_CONTEXT),context.abortSignal);return{snapshot:subscription.snapshot,activate:()=>subscription.start(),close:()=>subscription.dispose()}}}}function abortError(signal){let reason=signal.reason;return reason instanceof Error?reason:new DOMException("The operation was aborted","AbortError")}var MaterializerRefusal=class extends Error{constructor(code){super(`materializer refused: ${code}`),this.name="MaterializerRefusal",this.code=code}},MaterializerConsumer=class{constructor(adapter){this.adapter=adapter}reset(identity){return this.adapter.reset(identity)}async accept(unit){if(unit.kind==="control")throw new MaterializerRefusal("stray_control");if(!Number.isSafeInteger(unit.sequence)||unit.sequence<1||!Array.isArray(unit.controls))throw new MaterializerRefusal("invalid_unit");return this.deliver(unit,async()=>unit)}acceptEnvelope(envelope,load){return this.deliver(envelope,async()=>({...envelope,kind:"unit",record:await load()}))}async deliver(unit,load){if(await this.adapter.reset(unit),unit.sequence<=await this.adapter.frontier(unit))return"duplicate";let transaction=await this.adapter.begin(unit);try{return await transaction.apply(await load()),await transaction.commit(unit.sequence)}catch(cause){throw await transaction.abort(),cause}}};var object=v=>typeof v=="object"&&v!==null&&!Array.isArray(v),count=v=>typeof v=="number"&&Number.isSafeInteger(v)&&v>=0,id=v=>typeof v=="string"&&/^[A-Za-z0-9][A-Za-z0-9:_-]{0,127}$/.test(v),invalid=()=>{throw new MaterializerRefusal("invalid_unit")};function parseMaterializerFrame(input){if(!object(input))return invalid();if(input.type==="materializer_control")throw new MaterializerRefusal("stray_control");if(input.materializer===void 0)return{kind:"legacy",frame:input};if(!id(input.sessionId)||!id(input.admissionId)||!count(input.generation))return invalid();let m=input.materializer;if(!object(m)||!id(m.sessionEpoch)||!count(m.sequence)||m.sequence===0||m.generation!==input.generation||!Array.isArray(m.controls)||m.controls.length>1)return invalid();let controls=[];for(let c of m.controls){if(!object(c)||c.kind!=="seed"||!id(c.token)||!count(c.sequence)||c.sequence>=m.sequence)return invalid();controls.push({kind:"seed",token:c.token,sequence:c.sequence})}let p=m.payload;return!object(p)||p.kind!=="event"||!id(p.id)||!id(p.admissionId)||p.sessionEpoch!==m.sessionEpoch||p.sequence!==m.sequence||!id(p.componentRef)||!count(p.length)||typeof p.digest!="string"||!/^[0-9a-f]{64}$/.test(p.digest)?invalid():{kind:"unit",envelope:{sessionId:input.sessionId,sessionEpoch:m.sessionEpoch,generation:input.generation,sequence:m.sequence,controls,payload:{kind:"event",id:p.id,admissionId:p.admissionId,sessionEpoch:m.sessionEpoch,sequence:m.sequence,componentRef:p.componentRef,length:p.length,digest:p.digest}}}}var RecoveryRepairAdviceError=class extends Error{constructor(){super("invalid recovery repair advice"),this.name="RecoveryRepairAdviceError"}},RecoveryRepairController=class{constructor(){this.consecutiveGone=!1,this.restartedTokens=new Set}rememberRestart(token){if(this.restartedTokens.add(token),this.restartedTokens.size>64){let oldest=this.restartedTokens.values().next();oldest.done||this.restartedTokens.delete(oldest.value)}}observe(input,now,context){if(!isRecoveryRepairAdvice(input))throw new RecoveryRepairAdviceError;if(input.state==="repair_needed"&&context&&(context.reason==="unknown_token"||context.reason==="released")){let delay=Math.max(100,input.retryAfterMs);return this.blocked=void 0,this.restartedTokens.has(context.token)?{action:"wait",retryAfterMs:delay}:this.consecutiveGone?(this.goneWait?.token!==context.token&&(this.goneWait={token:context.token,until:now+delay}),now>=this.goneWait.until?(this.rememberRestart(context.token),this.goneWait=void 0,{action:"restart_from_catalog"}):{action:"wait",retryAfterMs:Math.max(100,this.goneWait.until-now)}):(this.consecutiveGone=!0,this.rememberRestart(context.token),{action:"restart_from_catalog"})}input.state==="ok"&&(this.consecutiveGone=!1,this.goneWait=void 0);let blocked=this.blocked;if(blocked){let before=blocked.advice;return(input.healthRevision!==null&&input.healthRevision!==before.healthRevision||input.source!==null&&(input.source.sessionEpoch!==before.source?.sessionEpoch||input.source.sequence!==before.source.sequence))&&now>=blocked.until?(this.blocked=void 0,{action:"restart_from_catalog"}):{action:"wait",retryAfterMs:Math.max(100,blocked.until-now)}}switch(input.state){case"ok":return{action:"ready"};case"repair_needed":case"storage_unavailable":return this.blocked={advice:input,until:now+Math.max(100,input.retryAfterMs)},{action:"wait",retryAfterMs:Math.max(100,input.retryAfterMs)}}}};export{ServerError,DisconnectedError,ClientDisposedError,Client,createClientServiceTransport,MaterializerRefusal,MaterializerConsumer,parseMaterializerFrame,RecoveryRepairAdviceError,RecoveryRepairController};