@cotal-ai/connector-claude-code 0.163.2 → 0.163.3
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/dist/docs-bundle.bin +0 -0
- package/dist/docs-index.bin +0 -0
- package/dist/mcp.cjs +2 -2
- package/package.json +3 -3
package/dist/mcp.cjs
CHANGED
|
@@ -113,7 +113,7 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
|
|
|
113
113
|
]))`;continue}}if(flags.s&&source[i]==="."){pattern+=inCharGroup?`${source[i]}\r
|
|
114
114
|
`:`[${source[i]}\r
|
|
115
115
|
]`;continue}pattern+=source[i];if(source[i]==="\\"){isEscaped=true}else if(inCharGroup&&source[i]==="]"){inCharGroup=false}else if(!inCharGroup&&source[i]==="["){inCharGroup=true}}try{new RegExp(pattern)}catch{console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);return regex.source}return pattern}function parseRecordDef(def,refs){if(refs.target==="openAi"){console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.")}if(refs.target==="openApi3"&&def.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum){return{type:"object",required:def.keyType._def.values,properties:def.keyType._def.values.reduce((acc,key)=>({...acc,[key]:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"properties",key]})??parseAnyDef(refs)}),{}),additionalProperties:refs.rejectedAdditionalProperties}}const schema={type:"object",additionalProperties:parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"additionalProperties"]})??refs.allowedAdditionalProperties};if(refs.target==="openApi3"){return schema}if(def.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodString&&def.keyType._def.checks?.length){const{type,...keyType}=parseStringDef(def.keyType._def,refs);return{...schema,propertyNames:keyType}}else if(def.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum){return{...schema,propertyNames:{enum:def.keyType._def.values}}}else if(def.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodBranded&&def.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&def.keyType._def.type._def.checks?.length){const{type,...keyType}=parseBrandedDef(def.keyType._def,refs);return{...schema,propertyNames:keyType}}return schema}function parseMapDef(def,refs){if(refs.mapStrategy==="record"){return parseRecordDef(def,refs)}const keys=parseDef(def.keyType._def,{...refs,currentPath:[...refs.currentPath,"items","items","0"]})||parseAnyDef(refs);const values=parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"items","items","1"]})||parseAnyDef(refs);return{type:"array",maxItems:125,items:{type:"array",items:[keys,values],minItems:2,maxItems:2}}}function parseNativeEnumDef(def){const object3=def.values;const actualKeys=Object.keys(def.values).filter(key=>{return typeof object3[object3[key]]!=="number"});const actualValues=actualKeys.map(key=>object3[key]);const parsedTypes=Array.from(new Set(actualValues.map(values=>typeof values)));return{type:parsedTypes.length===1?parsedTypes[0]==="string"?"string":"number":["string","number"],enum:actualValues}}function parseNeverDef(refs){return refs.target==="openAi"?void 0:{not:parseAnyDef({...refs,currentPath:[...refs.currentPath,"not"]})}}function parseNullDef(refs){return refs.target==="openApi3"?{enum:["null"],nullable:true}:{type:"null"}}var primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef(def,refs){if(refs.target==="openApi3")return asAnyOf(def,refs);const options=def.options instanceof Map?Array.from(def.options.values()):def.options;if(options.every(x=>x._def.typeName in primitiveMappings&&(!x._def.checks||!x._def.checks.length))){const types=options.reduce((types2,x)=>{const type=primitiveMappings[x._def.typeName];return type&&!types2.includes(type)?[...types2,type]:types2},[]);return{type:types.length>1?types:types[0]}}else if(options.every(x=>x._def.typeName==="ZodLiteral"&&!x.description)){const types=options.reduce((acc,x)=>{const type=typeof x._def.value;switch(type){case"string":case"number":case"boolean":return[...acc,type];case"bigint":return[...acc,"integer"];case"object":if(x._def.value===null)return[...acc,"null"];case"symbol":case"undefined":case"function":default:return acc}},[]);if(types.length===options.length){const uniqueTypes=types.filter((x,i,a)=>a.indexOf(x)===i);return{type:uniqueTypes.length>1?uniqueTypes:uniqueTypes[0],enum:options.reduce((acc,x)=>{return acc.includes(x._def.value)?acc:[...acc,x._def.value]},[])}}}else if(options.every(x=>x._def.typeName==="ZodEnum")){return{type:"string",enum:options.reduce((acc,x)=>[...acc,...x._def.values.filter(x2=>!acc.includes(x2))],[])}}return asAnyOf(def,refs)}var asAnyOf=(def,refs)=>{const anyOf=(def.options instanceof Map?Array.from(def.options.values()):def.options).map((x,i)=>parseDef(x._def,{...refs,currentPath:[...refs.currentPath,"anyOf",`${i}`]})).filter(x=>!!x&&(!refs.strictUnions||typeof x==="object"&&Object.keys(x).length>0));return anyOf.length?{anyOf}:void 0};function parseNullableDef(def,refs){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(def.innerType._def.typeName)&&(!def.innerType._def.checks||!def.innerType._def.checks.length)){if(refs.target==="openApi3"){return{type:primitiveMappings[def.innerType._def.typeName],nullable:true}}return{type:[primitiveMappings[def.innerType._def.typeName],"null"]}}if(refs.target==="openApi3"){const base2=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath]});if(base2&&"$ref"in base2)return{allOf:[base2],nullable:true};return base2&&{...base2,nullable:true}}const base=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath,"anyOf","0"]});return base&&{anyOf:[base,{type:"null"}]}}function parseNumberDef(def,refs){const res={type:"number"};if(!def.checks)return res;for(const check2 of def.checks){switch(check2.kind){case"int":res.type="integer";addErrorMessage(res,"type",check2.message,refs);break;case"min":if(refs.target==="jsonSchema7"){if(check2.inclusive){setResponseValueAndErrors(res,"minimum",check2.value,check2.message,refs)}else{setResponseValueAndErrors(res,"exclusiveMinimum",check2.value,check2.message,refs)}}else{if(!check2.inclusive){res.exclusiveMinimum=true}setResponseValueAndErrors(res,"minimum",check2.value,check2.message,refs)}break;case"max":if(refs.target==="jsonSchema7"){if(check2.inclusive){setResponseValueAndErrors(res,"maximum",check2.value,check2.message,refs)}else{setResponseValueAndErrors(res,"exclusiveMaximum",check2.value,check2.message,refs)}}else{if(!check2.inclusive){res.exclusiveMaximum=true}setResponseValueAndErrors(res,"maximum",check2.value,check2.message,refs)}break;case"multipleOf":setResponseValueAndErrors(res,"multipleOf",check2.value,check2.message,refs);break}}return res}function parseObjectDef(def,refs){const forceOptionalIntoNullable=refs.target==="openAi";const result={type:"object",properties:{}};const required2=[];const shape=def.shape();for(const propName in shape){let propDef=shape[propName];if(propDef===void 0||propDef._def===void 0){continue}let propOptional=safeIsOptional(propDef);if(propOptional&&forceOptionalIntoNullable){if(propDef._def.typeName==="ZodOptional"){propDef=propDef._def.innerType}if(!propDef.isNullable()){propDef=propDef.nullable()}propOptional=false}const parsedDef=parseDef(propDef._def,{...refs,currentPath:[...refs.currentPath,"properties",propName],propertyPath:[...refs.currentPath,"properties",propName]});if(parsedDef===void 0){continue}result.properties[propName]=parsedDef;if(!propOptional){required2.push(propName)}}if(required2.length){result.required=required2}const additionalProperties=decideAdditionalProperties(def,refs);if(additionalProperties!==void 0){result.additionalProperties=additionalProperties}return result}function decideAdditionalProperties(def,refs){if(def.catchall._def.typeName!=="ZodNever"){return parseDef(def.catchall._def,{...refs,currentPath:[...refs.currentPath,"additionalProperties"]})}switch(def.unknownKeys){case"passthrough":return refs.allowedAdditionalProperties;case"strict":return refs.rejectedAdditionalProperties;case"strip":return refs.removeAdditionalStrategy==="strict"?refs.allowedAdditionalProperties:refs.rejectedAdditionalProperties}}function safeIsOptional(schema){try{return schema.isOptional()}catch{return true}}var parseOptionalDef=(def,refs)=>{if(refs.currentPath.toString()===refs.propertyPath?.toString()){return parseDef(def.innerType._def,refs)}const innerSchema=parseDef(def.innerType._def,{...refs,currentPath:[...refs.currentPath,"anyOf","1"]});return innerSchema?{anyOf:[{not:parseAnyDef(refs)},innerSchema]}:parseAnyDef(refs)};var parsePipelineDef=(def,refs)=>{if(refs.pipeStrategy==="input"){return parseDef(def.in._def,refs)}else if(refs.pipeStrategy==="output"){return parseDef(def.out._def,refs)}const a=parseDef(def.in._def,{...refs,currentPath:[...refs.currentPath,"allOf","0"]});const b=parseDef(def.out._def,{...refs,currentPath:[...refs.currentPath,"allOf",a?"1":"0"]});return{allOf:[a,b].filter(x=>x!==void 0)}};function parsePromiseDef(def,refs){return parseDef(def.type._def,refs)}function parseSetDef(def,refs){const items=parseDef(def.valueType._def,{...refs,currentPath:[...refs.currentPath,"items"]});const schema={type:"array",uniqueItems:true,items};if(def.minSize){setResponseValueAndErrors(schema,"minItems",def.minSize.value,def.minSize.message,refs)}if(def.maxSize){setResponseValueAndErrors(schema,"maxItems",def.maxSize.value,def.maxSize.message,refs)}return schema}function parseTupleDef(def,refs){if(def.rest){return{type:"array",minItems:def.items.length,items:def.items.map((x,i)=>parseDef(x._def,{...refs,currentPath:[...refs.currentPath,"items",`${i}`]})).reduce((acc,x)=>x===void 0?acc:[...acc,x],[]),additionalItems:parseDef(def.rest._def,{...refs,currentPath:[...refs.currentPath,"additionalItems"]})}}else{return{type:"array",minItems:def.items.length,maxItems:def.items.length,items:def.items.map((x,i)=>parseDef(x._def,{...refs,currentPath:[...refs.currentPath,"items",`${i}`]})).reduce((acc,x)=>x===void 0?acc:[...acc,x],[])}}}function parseUndefinedDef(refs){return{not:parseAnyDef(refs)}}function parseUnknownDef(refs){return parseAnyDef(refs)}var parseReadonlyDef=(def,refs)=>{return parseDef(def.innerType._def,refs)};var selectParser=(def,typeName,refs)=>{switch(typeName){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(def,refs);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(def,refs);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(def,refs);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(def,refs);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(def,refs);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef(refs);case ZodFirstPartyTypeKind.ZodNull:return parseNullDef(refs);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(def,refs);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(def,refs);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(def,refs);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(def,refs);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(def,refs);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(def,refs);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef(def);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(def);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(def,refs);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(def,refs);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(def,refs);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(def,refs);case ZodFirstPartyTypeKind.ZodLazy:return()=>def.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(def,refs);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef(refs);case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(def,refs);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef(refs);case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef(refs);case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(def,refs);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(def,refs);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(def,refs);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef(def,refs);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(def,refs);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:return void 0;default:return(_=>void 0)(typeName)}};function parseDef(def,refs,forceResolution=false){const seenItem=refs.seen.get(def);if(refs.override){const overrideResult=refs.override?.(def,refs,seenItem,forceResolution);if(overrideResult!==ignoreOverride){return overrideResult}}if(seenItem&&!forceResolution){const seenSchema=get$ref(seenItem,refs);if(seenSchema!==void 0){return seenSchema}}const newItem={def,path:refs.currentPath,jsonSchema:void 0};refs.seen.set(def,newItem);const jsonSchemaOrGetter=selectParser(def,def.typeName,refs);const jsonSchema=typeof jsonSchemaOrGetter==="function"?parseDef(jsonSchemaOrGetter(),refs):jsonSchemaOrGetter;if(jsonSchema){addMeta(def,refs,jsonSchema)}if(refs.postProcess){const postProcessResult=refs.postProcess(jsonSchema,def,refs);newItem.jsonSchema=jsonSchema;return postProcessResult}newItem.jsonSchema=jsonSchema;return jsonSchema}var get$ref=(item,refs)=>{switch(refs.$refStrategy){case"root":return{$ref:item.path.join("/")};case"relative":return{$ref:getRelativePath(refs.currentPath,item.path)};case"none":case"seen":{if(item.path.length<refs.currentPath.length&&item.path.every((value,index2)=>refs.currentPath[index2]===value)){console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);return parseAnyDef(refs)}return refs.$refStrategy==="seen"?parseAnyDef(refs):void 0}}};var addMeta=(def,refs,jsonSchema)=>{if(def.description){jsonSchema.description=def.description;if(refs.markdownDescription){jsonSchema.markdownDescription=def.description}}return jsonSchema};var zodToJsonSchema=(schema,options)=>{const refs=getRefs(options);let definitions=typeof options==="object"&&options.definitions?Object.entries(options.definitions).reduce((acc,[name2,schema2])=>({...acc,[name2]:parseDef(schema2._def,{...refs,currentPath:[...refs.basePath,refs.definitionPath,name2]},true)??parseAnyDef(refs)}),{}):void 0;const name=typeof options==="string"?options:options?.nameStrategy==="title"?void 0:options?.name;const main2=parseDef(schema._def,name===void 0?refs:{...refs,currentPath:[...refs.basePath,refs.definitionPath,name]},false)??parseAnyDef(refs);const title=typeof options==="object"&&options.name!==void 0&&options.nameStrategy==="title"?options.name:void 0;if(title!==void 0){main2.title=title}if(refs.flags.hasReferencedOpenAiAnyType){if(!definitions){definitions={}}if(!definitions[refs.openAiAnyTypeName]){definitions[refs.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:refs.$refStrategy==="relative"?"1":[...refs.basePath,refs.definitionPath,refs.openAiAnyTypeName].join("/")}}}}const combined=name===void 0?definitions?{...main2,[refs.definitionPath]:definitions}:main2:{$ref:[...refs.$refStrategy==="relative"?[]:refs.basePath,refs.definitionPath,name].join("/"),[refs.definitionPath]:{...definitions,[name]:main2}};if(refs.target==="jsonSchema7"){combined.$schema="http://json-schema.org/draft-07/schema#"}else if(refs.target==="jsonSchema2019-09"||refs.target==="openAi"){combined.$schema="https://json-schema.org/draft/2019-09/schema#"}if(refs.target==="openAi"&&("anyOf"in combined||"oneOf"in combined||"allOf"in combined||"type"in combined&&Array.isArray(combined.type))){console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.")}return combined};function mapMiniTarget(t){if(!t)return"draft-7";if(t==="jsonSchema7"||t==="draft-7")return"draft-7";if(t==="jsonSchema2019-09"||t==="draft-2020-12")return"draft-2020-12";return"draft-7"}function toJsonSchemaCompat(schema,opts){if(isZ4Schema(schema)){return toJSONSchema(schema,{target:mapMiniTarget(opts?.target),io:opts?.pipeStrategy??"input"})}return zodToJsonSchema(schema,{strictUnions:opts?.strictUnions??true,pipeStrategy:opts?.pipeStrategy??"input"})}function getMethodLiteral(schema){const shape=getObjectShape(schema);const methodSchema=shape?.method;if(!methodSchema){throw new Error("Schema is missing a method literal")}const value=getLiteralValue(methodSchema);if(typeof value!=="string"){throw new Error("Schema method literal must be a string")}return value}function parseWithCompat(schema,data){const result=safeParse2(schema,data);if(!result.success){throw result.error}return result.data}var DEFAULT_REQUEST_TIMEOUT_MSEC=6e4;var Protocol=class{constructor(_options){this._options=_options;this._requestMessageId=0;this._requestHandlers=new Map;this._requestHandlerAbortControllers=new Map;this._notificationHandlers=new Map;this._responseHandlers=new Map;this._progressHandlers=new Map;this._timeoutInfo=new Map;this._pendingDebouncedNotifications=new Set;this._taskProgressTokens=new Map;this._requestResolvers=new Map;this.setNotificationHandler(CancelledNotificationSchema,notification=>{this._oncancel(notification)});this.setNotificationHandler(ProgressNotificationSchema,notification=>{this._onprogress(notification)});this.setRequestHandler(PingRequestSchema,_request=>({}));this._taskStore=_options?.taskStore;this._taskMessageQueue=_options?.taskMessageQueue;if(this._taskStore){this.setRequestHandler(GetTaskRequestSchema,async(request,extra)=>{const task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task){throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found")}return{...task}});this.setRequestHandler(GetTaskPayloadRequestSchema,async(request,extra)=>{const handleTaskResult=async()=>{const taskId=request.params.taskId;if(this._taskMessageQueue){let queuedMessage;while(queuedMessage=await this._taskMessageQueue.dequeue(taskId,extra.sessionId)){if(queuedMessage.type==="response"||queuedMessage.type==="error"){const message=queuedMessage.message;const requestId=message.id;const resolver=this._requestResolvers.get(requestId);if(resolver){this._requestResolvers.delete(requestId);if(queuedMessage.type==="response"){resolver(message)}else{const errorMessage=message;const error51=new McpError(errorMessage.error.code,errorMessage.error.message,errorMessage.error.data);resolver(error51)}}else{const messageType=queuedMessage.type==="response"?"Response":"Error";this._onerror(new Error(`${messageType} handler missing for request ${requestId}`))}continue}await this._transport?.send(queuedMessage.message,{relatedRequestId:extra.requestId})}}const task=await this._taskStore.getTask(taskId,extra.sessionId);if(!task){throw new McpError(ErrorCode.InvalidParams,`Task not found: ${taskId}`)}if(!isTerminal(task.status)){await this._waitForTaskUpdate(taskId,extra.signal);return await handleTaskResult()}if(isTerminal(task.status)){const result=await this._taskStore.getTaskResult(taskId,extra.sessionId);this._clearTaskQueue(taskId);return{...result,_meta:{...result._meta,[RELATED_TASK_META_KEY]:{taskId}}}}return await handleTaskResult()};return await handleTaskResult()});this.setRequestHandler(ListTasksRequestSchema,async(request,extra)=>{try{const{tasks,nextCursor}=await this._taskStore.listTasks(request.params?.cursor,extra.sessionId);return{tasks,nextCursor,_meta:{}}}catch(error51){throw new McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${error51 instanceof Error?error51.message:String(error51)}`)}});this.setRequestHandler(CancelTaskRequestSchema,async(request,extra)=>{try{const task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task){throw new McpError(ErrorCode.InvalidParams,`Task not found: ${request.params.taskId}`)}if(isTerminal(task.status)){throw new McpError(ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${task.status}`)}await this._taskStore.updateTaskStatus(request.params.taskId,"cancelled","Client cancelled task execution.",extra.sessionId);this._clearTaskQueue(request.params.taskId);const cancelledTask=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!cancelledTask){throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${request.params.taskId}`)}return{_meta:{},...cancelledTask}}catch(error51){if(error51 instanceof McpError){throw error51}throw new McpError(ErrorCode.InvalidRequest,`Failed to cancel task: ${error51 instanceof Error?error51.message:String(error51)}`)}})}}async _oncancel(notification){if(!notification.params.requestId){return}const controller=this._requestHandlerAbortControllers.get(notification.params.requestId);controller?.abort(notification.params.reason)}_setupTimeout(messageId,timeout,maxTotalTimeout,onTimeout,resetTimeoutOnProgress=false){this._timeoutInfo.set(messageId,{timeoutId:setTimeout(onTimeout,timeout),startTime:Date.now(),timeout,maxTotalTimeout,resetTimeoutOnProgress,onTimeout})}_resetTimeout(messageId){const info=this._timeoutInfo.get(messageId);if(!info)return false;const totalElapsed=Date.now()-info.startTime;if(info.maxTotalTimeout&&totalElapsed>=info.maxTotalTimeout){this._timeoutInfo.delete(messageId);throw McpError.fromError(ErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:info.maxTotalTimeout,totalElapsed})}clearTimeout(info.timeoutId);info.timeoutId=setTimeout(info.onTimeout,info.timeout);return true}_cleanupTimeout(messageId){const info=this._timeoutInfo.get(messageId);if(info){clearTimeout(info.timeoutId);this._timeoutInfo.delete(messageId)}}async connect(transport){if(this._transport){throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.")}this._transport=transport;const _onclose=this.transport?.onclose;this._transport.onclose=()=>{_onclose?.();this._onclose()};const _onerror=this.transport?.onerror;this._transport.onerror=error51=>{_onerror?.(error51);this._onerror(error51)};const _onmessage=this._transport?.onmessage;this._transport.onmessage=(message,extra)=>{_onmessage?.(message,extra);if(isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)){this._onresponse(message)}else if(isJSONRPCRequest(message)){this._onrequest(message,extra)}else if(isJSONRPCNotification(message)){this._onnotification(message)}else{this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`))}};await this._transport.start()}_onclose(){const responseHandlers=this._responseHandlers;this._responseHandlers=new Map;this._progressHandlers.clear();this._taskProgressTokens.clear();this._pendingDebouncedNotifications.clear();for(const info of this._timeoutInfo.values()){clearTimeout(info.timeoutId)}this._timeoutInfo.clear();for(const controller of this._requestHandlerAbortControllers.values()){controller.abort()}this._requestHandlerAbortControllers.clear();const error51=McpError.fromError(ErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0;this.onclose?.();for(const handler of responseHandlers.values()){handler(error51)}}_onerror(error51){this.onerror?.(error51)}_onnotification(notification){const handler=this._notificationHandlers.get(notification.method)??this.fallbackNotificationHandler;if(handler===void 0){return}Promise.resolve().then(()=>handler(notification)).catch(error51=>this._onerror(new Error(`Uncaught error in notification handler: ${error51}`)))}_onrequest(request,extra){const handler=this._requestHandlers.get(request.method)??this.fallbackRequestHandler;const capturedTransport=this._transport;const relatedTaskId=request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;if(handler===void 0){const errorResponse={jsonrpc:"2.0",id:request.id,error:{code:ErrorCode.MethodNotFound,message:"Method not found"}};if(relatedTaskId&&this._taskMessageQueue){this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId).catch(error51=>this._onerror(new Error(`Failed to enqueue error response: ${error51}`)))}else{capturedTransport?.send(errorResponse).catch(error51=>this._onerror(new Error(`Failed to send an error response: ${error51}`)))}return}const abortController=new AbortController;this._requestHandlerAbortControllers.set(request.id,abortController);const taskCreationParams=isTaskAugmentedRequestParams(request.params)?request.params.task:void 0;const taskStore=this._taskStore?this.requestTaskStore(request,capturedTransport?.sessionId):void 0;const fullExtra={signal:abortController.signal,sessionId:capturedTransport?.sessionId,_meta:request.params?._meta,sendNotification:async notification=>{if(abortController.signal.aborted)return;const notificationOptions={relatedRequestId:request.id};if(relatedTaskId){notificationOptions.relatedTask={taskId:relatedTaskId}}await this.notification(notification,notificationOptions)},sendRequest:async(r,resultSchema,options)=>{if(abortController.signal.aborted){throw new McpError(ErrorCode.ConnectionClosed,"Request was cancelled")}const requestOptions={...options,relatedRequestId:request.id};if(relatedTaskId&&!requestOptions.relatedTask){requestOptions.relatedTask={taskId:relatedTaskId}}const effectiveTaskId=requestOptions.relatedTask?.taskId??relatedTaskId;if(effectiveTaskId&&taskStore){await taskStore.updateTaskStatus(effectiveTaskId,"input_required")}return await this.request(r,resultSchema,requestOptions)},authInfo:extra?.authInfo,requestId:request.id,requestInfo:extra?.requestInfo,taskId:relatedTaskId,taskStore,taskRequestedTtl:taskCreationParams?.ttl,closeSSEStream:extra?.closeSSEStream,closeStandaloneSSEStream:extra?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(taskCreationParams){this.assertTaskHandlerCapability(request.method)}}).then(()=>handler(request,fullExtra)).then(async result=>{if(abortController.signal.aborted){return}const response={result,jsonrpc:"2.0",id:request.id};if(relatedTaskId&&this._taskMessageQueue){await this._enqueueTaskMessage(relatedTaskId,{type:"response",message:response,timestamp:Date.now()},capturedTransport?.sessionId)}else{await capturedTransport?.send(response)}},async error51=>{if(abortController.signal.aborted){return}const errorResponse={jsonrpc:"2.0",id:request.id,error:{code:Number.isSafeInteger(error51["code"])?error51["code"]:ErrorCode.InternalError,message:error51.message??"Internal error",...error51["data"]!==void 0&&{data:error51["data"]}}};if(relatedTaskId&&this._taskMessageQueue){await this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId)}else{await capturedTransport?.send(errorResponse)}}).catch(error51=>this._onerror(new Error(`Failed to send response: ${error51}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(request.id)===abortController){this._requestHandlerAbortControllers.delete(request.id)}})}_onprogress(notification){const{progressToken,...params}=notification.params;const messageId=Number(progressToken);const handler=this._progressHandlers.get(messageId);if(!handler){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));return}const responseHandler=this._responseHandlers.get(messageId);const timeoutInfo=this._timeoutInfo.get(messageId);if(timeoutInfo&&responseHandler&&timeoutInfo.resetTimeoutOnProgress){try{this._resetTimeout(messageId)}catch(error51){this._responseHandlers.delete(messageId);this._progressHandlers.delete(messageId);this._cleanupTimeout(messageId);responseHandler(error51);return}}handler(params)}_onresponse(response){const messageId=Number(response.id);const resolver=this._requestResolvers.get(messageId);if(resolver){this._requestResolvers.delete(messageId);if(isJSONRPCResultResponse(response)){resolver(response)}else{const error51=new McpError(response.error.code,response.error.message,response.error.data);resolver(error51)}return}const handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}this._responseHandlers.delete(messageId);this._cleanupTimeout(messageId);let isTaskResponse=false;if(isJSONRPCResultResponse(response)&&response.result&&typeof response.result==="object"){const result=response.result;if(result.task&&typeof result.task==="object"){const task=result.task;if(typeof task.taskId==="string"){isTaskResponse=true;this._taskProgressTokens.set(task.taskId,messageId)}}}if(!isTaskResponse){this._progressHandlers.delete(messageId)}if(isJSONRPCResultResponse(response)){handler(response)}else{const error51=McpError.fromError(response.error.code,response.error.message,response.error.data);handler(error51)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(request,resultSchema,options){const{task}=options??{};if(!task){try{const result=await this.request(request,resultSchema,options);yield{type:"result",result}}catch(error51){yield{type:"error",error:error51 instanceof McpError?error51:new McpError(ErrorCode.InternalError,String(error51))}}return}let taskId;try{const createResult=await this.request(request,CreateTaskResultSchema,options);if(createResult.task){taskId=createResult.task.taskId;yield{type:"taskCreated",task:createResult.task}}else{throw new McpError(ErrorCode.InternalError,"Task creation did not return a task")}while(true){const task2=await this.getTask({taskId},options);yield{type:"taskStatus",task:task2};if(isTerminal(task2.status)){if(task2.status==="completed"){const result=await this.getTaskResult({taskId},resultSchema,options);yield{type:"result",result}}else if(task2.status==="failed"){yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} failed`)}}else if(task2.status==="cancelled"){yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} was cancelled`)}}return}if(task2.status==="input_required"){const result=await this.getTaskResult({taskId},resultSchema,options);yield{type:"result",result};return}const pollInterval=task2.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(resolve=>setTimeout(resolve,pollInterval));options?.signal?.throwIfAborted()}}catch(error51){yield{type:"error",error:error51 instanceof McpError?error51:new McpError(ErrorCode.InternalError,String(error51))}}}request(request,resultSchema,options){const{relatedRequestId,resumptionToken,onresumptiontoken,task,relatedTask}=options??{};return new Promise((resolve,reject)=>{const earlyReject=error51=>{reject(error51)};if(!this._transport){earlyReject(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===true){try{this.assertCapabilityForMethod(request.method);if(task){this.assertTaskCapability(request.method)}}catch(e){earlyReject(e);return}}options?.signal?.throwIfAborted();const messageId=this._requestMessageId++;const jsonrpcRequest={...request,jsonrpc:"2.0",id:messageId};if(options?.onprogress){this._progressHandlers.set(messageId,options.onprogress);jsonrpcRequest.params={...request.params,_meta:{...request.params?._meta||{},progressToken:messageId}}}if(task){jsonrpcRequest.params={...jsonrpcRequest.params,task}}if(relatedTask){jsonrpcRequest.params={...jsonrpcRequest.params,_meta:{...jsonrpcRequest.params?._meta||{},[RELATED_TASK_META_KEY]:relatedTask}}}const cancel=reason2=>{this._responseHandlers.delete(messageId);this._progressHandlers.delete(messageId);this._cleanupTimeout(messageId);this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason2)}},{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error52=>this._onerror(new Error(`Failed to send cancellation: ${error52}`)));const error51=reason2 instanceof McpError?reason2:new McpError(ErrorCode.RequestTimeout,String(reason2));reject(error51)};this._responseHandlers.set(messageId,response=>{if(options?.signal?.aborted){return}if(response instanceof Error){return reject(response)}try{const parseResult=safeParse2(resultSchema,response.result);if(!parseResult.success){reject(parseResult.error)}else{resolve(parseResult.data)}}catch(error51){reject(error51)}});options?.signal?.addEventListener("abort",()=>{cancel(options?.signal?.reason)});const timeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC;const timeoutHandler=()=>cancel(McpError.fromError(ErrorCode.RequestTimeout,"Request timed out",{timeout}));this._setupTimeout(messageId,timeout,options?.maxTotalTimeout,timeoutHandler,options?.resetTimeoutOnProgress??false);const relatedTaskId=relatedTask?.taskId;if(relatedTaskId){const responseResolver=response=>{const handler=this._responseHandlers.get(messageId);if(handler){handler(response)}else{this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`))}};this._requestResolvers.set(messageId,responseResolver);this._enqueueTaskMessage(relatedTaskId,{type:"request",message:jsonrpcRequest,timestamp:Date.now()}).catch(error51=>{this._cleanupTimeout(messageId);reject(error51)})}else{this._transport.send(jsonrpcRequest,{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error51=>{this._cleanupTimeout(messageId);reject(error51)})}})}async getTask(params,options){return this.request({method:"tasks/get",params},GetTaskResultSchema,options)}async getTaskResult(params,resultSchema,options){return this.request({method:"tasks/result",params},resultSchema,options)}async listTasks(params,options){return this.request({method:"tasks/list",params},ListTasksResultSchema,options)}async cancelTask(params,options){return this.request({method:"tasks/cancel",params},CancelTaskResultSchema,options)}async notification(notification,options){if(!this._transport){throw new Error("Not connected")}this.assertNotificationCapability(notification.method);const relatedTaskId=options?.relatedTask?.taskId;if(relatedTaskId){const jsonrpcNotification2={...notification,jsonrpc:"2.0",params:{...notification.params,_meta:{...notification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}};await this._enqueueTaskMessage(relatedTaskId,{type:"notification",message:jsonrpcNotification2,timestamp:Date.now()});return}const debouncedMethods=this._options?.debouncedNotificationMethods??[];const canDebounce=debouncedMethods.includes(notification.method)&&!notification.params&&!options?.relatedRequestId&&!options?.relatedTask;if(canDebounce){if(this._pendingDebouncedNotifications.has(notification.method)){return}this._pendingDebouncedNotifications.add(notification.method);Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(notification.method);if(!this._transport){return}let jsonrpcNotification2={...notification,jsonrpc:"2.0"};if(options?.relatedTask){jsonrpcNotification2={...jsonrpcNotification2,params:{...jsonrpcNotification2.params,_meta:{...jsonrpcNotification2.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}}this._transport?.send(jsonrpcNotification2,options).catch(error51=>this._onerror(error51))});return}let jsonrpcNotification={...notification,jsonrpc:"2.0"};if(options?.relatedTask){jsonrpcNotification={...jsonrpcNotification,params:{...jsonrpcNotification.params,_meta:{...jsonrpcNotification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}}await this._transport.send(jsonrpcNotification,options)}setRequestHandler(requestSchema,handler){const method=getMethodLiteral(requestSchema);this.assertRequestHandlerCapability(method);this._requestHandlers.set(method,(request,extra)=>{const parsed=parseWithCompat(requestSchema,request);return Promise.resolve(handler(parsed,extra))})}removeRequestHandler(method){this._requestHandlers.delete(method)}assertCanSetRequestHandler(method){if(this._requestHandlers.has(method)){throw new Error(`A request handler for ${method} already exists, which would be overridden`)}}setNotificationHandler(notificationSchema,handler){const method=getMethodLiteral(notificationSchema);this._notificationHandlers.set(method,notification=>{const parsed=parseWithCompat(notificationSchema,notification);return Promise.resolve(handler(parsed))})}removeNotificationHandler(method){this._notificationHandlers.delete(method)}_cleanupTaskProgressHandler(taskId){const progressToken=this._taskProgressTokens.get(taskId);if(progressToken!==void 0){this._progressHandlers.delete(progressToken);this._taskProgressTokens.delete(taskId)}}async _enqueueTaskMessage(taskId,message,sessionId){if(!this._taskStore||!this._taskMessageQueue){throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured")}const maxQueueSize=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(taskId,message,sessionId,maxQueueSize)}async _clearTaskQueue(taskId,sessionId){if(this._taskMessageQueue){const messages=await this._taskMessageQueue.dequeueAll(taskId,sessionId);for(const message of messages){if(message.type==="request"&&isJSONRPCRequest(message.message)){const requestId=message.message.id;const resolver=this._requestResolvers.get(requestId);if(resolver){resolver(new McpError(ErrorCode.InternalError,"Task cancelled or completed"));this._requestResolvers.delete(requestId)}else{this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`))}}}}}async _waitForTaskUpdate(taskId,signal){let interval=this._options?.defaultTaskPollInterval??1e3;try{const task=await this._taskStore?.getTask(taskId);if(task?.pollInterval){interval=task.pollInterval}}catch{}return new Promise((resolve,reject)=>{if(signal.aborted){reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"));return}const timeoutId=setTimeout(resolve,interval);signal.addEventListener("abort",()=>{clearTimeout(timeoutId);reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"))},{once:true})})}requestTaskStore(request,sessionId){const taskStore=this._taskStore;if(!taskStore){throw new Error("No task store configured")}return{createTask:async taskParams=>{if(!request){throw new Error("No request provided")}return await taskStore.createTask(taskParams,request.id,{method:request.method,params:request.params},sessionId)},getTask:async taskId=>{const task=await taskStore.getTask(taskId,sessionId);if(!task){throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found")}return task},storeTaskResult:async(taskId,status2,result)=>{await taskStore.storeTaskResult(taskId,status2,result,sessionId);const task=await taskStore.getTask(taskId,sessionId);if(task){const notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:task});await this.notification(notification);if(isTerminal(task.status)){this._cleanupTaskProgressHandler(taskId)}}},getTaskResult:taskId=>{return taskStore.getTaskResult(taskId,sessionId)},updateTaskStatus:async(taskId,status2,statusMessage)=>{const task=await taskStore.getTask(taskId,sessionId);if(!task){throw new McpError(ErrorCode.InvalidParams,`Task "${taskId}" not found - it may have been cleaned up`)}if(isTerminal(task.status)){throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${taskId}" from terminal status "${task.status}" to "${status2}". Terminal states (completed, failed, cancelled) cannot transition to other states.`)}await taskStore.updateTaskStatus(taskId,status2,statusMessage,sessionId);const updatedTask=await taskStore.getTask(taskId,sessionId);if(updatedTask){const notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:updatedTask});await this.notification(notification);if(isTerminal(updatedTask.status)){this._cleanupTaskProgressHandler(taskId)}}},listTasks:cursor=>{return taskStore.listTasks(cursor,sessionId)}}}};function isPlainObject2(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function mergeCapabilities(base,additional){const result={...base};for(const key in additional){const k=key;const addValue=additional[k];if(addValue===void 0)continue;const baseValue=result[k];if(isPlainObject2(baseValue)&&isPlainObject2(addValue)){result[k]={...baseValue,...addValue}}else{result[k]=addValue}}return result}init_types();var import_ajv=__toESM(require_ajv(),1);var import_ajv_formats=__toESM(require_dist(),1);function createDefaultAjvInstance(){const ajv=new import_ajv.default({strict:false,validateFormats:true,validateSchema:false,allErrors:true});const addFormats=import_ajv_formats.default;addFormats(ajv);return ajv}var AjvJsonSchemaValidator=class{constructor(ajv){this._ajv=ajv??createDefaultAjvInstance()}getValidator(schema){const ajvValidator="$id"in schema&&typeof schema.$id==="string"?this._ajv.getSchema(schema.$id)??this._ajv.compile(schema):this._ajv.compile(schema);return input=>{const valid=ajvValidator(input);if(valid){return{valid:true,data:input,errorMessage:void 0}}else{return{valid:false,data:void 0,errorMessage:this._ajv.errorsText(ajvValidator.errors)}}}}};init_types();var ExperimentalServerTasks=class{constructor(_server){this._server=_server}requestStream(request,resultSchema,options){return this._server.requestStream(request,resultSchema,options)}createMessageStream(params,options){const clientCapabilities=this._server.getClientCapabilities();if((params.tools||params.toolChoice)&&!clientCapabilities?.sampling?.tools){throw new Error("Client does not support sampling tools capability.")}if(params.messages.length>0){const lastMessage=params.messages[params.messages.length-1];const lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content];const hasToolResults=lastContent.some(c=>c.type==="tool_result");const previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0;const previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[];const hasPreviousToolUse=previousContent.some(c=>c.type==="tool_use");if(hasToolResults){if(lastContent.some(c=>c.type!=="tool_result")){throw new Error("The last message must contain only tool_result content if any is present")}if(!hasPreviousToolUse){throw new Error("tool_result blocks are not matching any tool_use from the previous message")}}if(hasPreviousToolUse){const toolUseIds=new Set(previousContent.filter(c=>c.type==="tool_use").map(c=>c.id));const toolResultIds=new Set(lastContent.filter(c=>c.type==="tool_result").map(c=>c.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id2=>toolResultIds.has(id2))){throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}}return this.requestStream({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}elicitInputStream(params,options){const clientCapabilities=this._server.getClientCapabilities();const mode=params.mode??"form";switch(mode){case"url":{if(!clientCapabilities?.elicitation?.url){throw new Error("Client does not support url elicitation.")}break}case"form":{if(!clientCapabilities?.elicitation?.form){throw new Error("Client does not support form elicitation.")}break}}const normalizedParams=mode==="form"&¶ms.mode===void 0?{...params,mode:"form"}:params;return this.requestStream({method:"elicitation/create",params:normalizedParams},ElicitResultSchema,options)}async getTask(taskId,options){return this._server.getTask({taskId},options)}async getTaskResult(taskId,resultSchema,options){return this._server.getTaskResult({taskId},resultSchema,options)}async listTasks(cursor,options){return this._server.listTasks(cursor?{cursor}:void 0,options)}async cancelTask(taskId,options){return this._server.cancelTask({taskId},options)}};function assertToolsCallTaskCapability(requests,method,entityName){if(!requests){throw new Error(`${entityName} does not support task creation (required for ${method})`)}switch(method){case"tools/call":if(!requests.tools?.call){throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`)}break;default:break}}function assertClientRequestTaskCapability(requests,method,entityName){if(!requests){throw new Error(`${entityName} does not support task creation (required for ${method})`)}switch(method){case"sampling/createMessage":if(!requests.sampling?.createMessage){throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`)}break;case"elicitation/create":if(!requests.elicitation?.create){throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`)}break;default:break}}var Server=class extends Protocol{constructor(_serverInfo,options){super(options);this._serverInfo=_serverInfo;this._loggingLevels=new Map;this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((level,index2)=>[level,index2]));this.isMessageIgnored=(level,sessionId)=>{const currentLevel=this._loggingLevels.get(sessionId);return currentLevel?this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(currentLevel):false};this._capabilities=options?.capabilities??{};this._instructions=options?.instructions;this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator;this.setRequestHandler(InitializeRequestSchema,request=>this._oninitialize(request));this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.());if(this._capabilities.logging){this.setRequestHandler(SetLevelRequestSchema,async(request,extra)=>{const transportSessionId=extra.sessionId||extra.requestInfo?.headers["mcp-session-id"]||void 0;const{level}=request.params;const parseResult=LoggingLevelSchema.safeParse(level);if(parseResult.success){this._loggingLevels.set(transportSessionId,parseResult.data)}return{}})}}get experimental(){if(!this._experimental){this._experimental={tasks:new ExperimentalServerTasks(this)}}return this._experimental}registerCapabilities(capabilities){if(this.transport){throw new Error("Cannot register capabilities after connecting to transport")}this._capabilities=mergeCapabilities(this._capabilities,capabilities)}setRequestHandler(requestSchema,handler){const shape=getObjectShape(requestSchema);const methodSchema=shape?.method;if(!methodSchema){throw new Error("Schema is missing a method literal")}let methodValue;if(isZ4Schema(methodSchema)){const v4Schema=methodSchema;const v4Def=v4Schema._zod?.def;methodValue=v4Def?.value??v4Schema.value}else{const v3Schema=methodSchema;const legacyDef=v3Schema._def;methodValue=legacyDef?.value??v3Schema.value}if(typeof methodValue!=="string"){throw new Error("Schema method literal must be a string")}const method=methodValue;if(method==="tools/call"){const wrappedHandler=async(request,extra)=>{const validatedRequest=safeParse2(CallToolRequestSchema,request);if(!validatedRequest.success){const errorMessage=validatedRequest.error instanceof Error?validatedRequest.error.message:String(validatedRequest.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${errorMessage}`)}const{params}=validatedRequest.data;const result=await Promise.resolve(handler(request,extra));if(params.task){const taskValidationResult=safeParse2(CreateTaskResultSchema,result);if(!taskValidationResult.success){const errorMessage=taskValidationResult.error instanceof Error?taskValidationResult.error.message:String(taskValidationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${errorMessage}`)}return taskValidationResult.data}const validationResult=safeParse2(CallToolResultSchema,result);if(!validationResult.success){const errorMessage=validationResult.error instanceof Error?validationResult.error.message:String(validationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${errorMessage}`)}return validationResult.data};return super.setRequestHandler(requestSchema,wrappedHandler)}return super.setRequestHandler(requestSchema,handler)}assertCapabilityForMethod(method){switch(method){case"sampling/createMessage":if(!this._clientCapabilities?.sampling){throw new Error(`Client does not support sampling (required for ${method})`)}break;case"elicitation/create":if(!this._clientCapabilities?.elicitation){throw new Error(`Client does not support elicitation (required for ${method})`)}break;case"roots/list":if(!this._clientCapabilities?.roots){throw new Error(`Client does not support listing roots (required for ${method})`)}break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/message":if(!this._capabilities.logging){throw new Error(`Server does not support logging (required for ${method})`)}break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources){throw new Error(`Server does not support notifying about resources (required for ${method})`)}break;case"notifications/tools/list_changed":if(!this._capabilities.tools){throw new Error(`Server does not support notifying of tool list changes (required for ${method})`)}break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts){throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`)}break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url){throw new Error(`Client does not support URL elicitation (required for ${method})`)}break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){if(!this._capabilities){return}switch(method){case"completion/complete":if(!this._capabilities.completions){throw new Error(`Server does not support completions (required for ${method})`)}break;case"logging/setLevel":if(!this._capabilities.logging){throw new Error(`Server does not support logging (required for ${method})`)}break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts){throw new Error(`Server does not support prompts (required for ${method})`)}break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources){throw new Error(`Server does not support resources (required for ${method})`)}break;case"tools/call":case"tools/list":if(!this._capabilities.tools){throw new Error(`Server does not support tools (required for ${method})`)}break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks){throw new Error(`Server does not support tasks capability (required for ${method})`)}break;case"ping":case"initialize":break}}assertTaskCapability(method){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,method,"Client")}assertTaskHandlerCapability(method){if(!this._capabilities){return}assertToolsCallTaskCapability(this._capabilities.tasks?.requests,method,"Server")}async _oninitialize(request){const requestedVersion=request.params.protocolVersion;this._clientCapabilities=request.params.capabilities;this._clientVersion=request.params.clientInfo;const protocolVersion=SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)?requestedVersion:LATEST_PROTOCOL_VERSION;return{protocolVersion,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},EmptyResultSchema)}async createMessage(params,options){if(params.tools||params.toolChoice){if(!this._clientCapabilities?.sampling?.tools){throw new Error("Client does not support sampling tools capability.")}}if(params.messages.length>0){const lastMessage=params.messages[params.messages.length-1];const lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content];const hasToolResults=lastContent.some(c=>c.type==="tool_result");const previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0;const previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[];const hasPreviousToolUse=previousContent.some(c=>c.type==="tool_use");if(hasToolResults){if(lastContent.some(c=>c.type!=="tool_result")){throw new Error("The last message must contain only tool_result content if any is present")}if(!hasPreviousToolUse){throw new Error("tool_result blocks are not matching any tool_use from the previous message")}}if(hasPreviousToolUse){const toolUseIds=new Set(previousContent.filter(c=>c.type==="tool_use").map(c=>c.id));const toolResultIds=new Set(lastContent.filter(c=>c.type==="tool_result").map(c=>c.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id2=>toolResultIds.has(id2))){throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}}if(params.tools){return this.request({method:"sampling/createMessage",params},CreateMessageResultWithToolsSchema,options)}return this.request({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}async elicitInput(params,options){const mode=params.mode??"form";switch(mode){case"url":{if(!this._clientCapabilities?.elicitation?.url){throw new Error("Client does not support url elicitation.")}const urlParams=params;return this.request({method:"elicitation/create",params:urlParams},ElicitResultSchema,options)}case"form":{if(!this._clientCapabilities?.elicitation?.form){throw new Error("Client does not support form elicitation.")}const formParams=params.mode==="form"?params:{...params,mode:"form"};const result=await this.request({method:"elicitation/create",params:formParams},ElicitResultSchema,options);if(result.action==="accept"&&result.content&&formParams.requestedSchema){try{const validator=this._jsonSchemaValidator.getValidator(formParams.requestedSchema);const validationResult=validator(result.content);if(!validationResult.valid){throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${validationResult.errorMessage}`)}}catch(error51){if(error51 instanceof McpError){throw error51}throw new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${error51 instanceof Error?error51.message:String(error51)}`)}}return result}}}createElicitationCompletionNotifier(elicitationId,options){if(!this._clientCapabilities?.elicitation?.url){throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)")}return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId}},options)}async listRoots(params,options){return this.request({method:"roots/list",params},ListRootsResultSchema,options)}async sendLoggingMessage(params,sessionId){if(this._capabilities.logging){if(!this.isMessageIgnored(params.level,sessionId)){return this.notification({method:"notifications/message",params})}}}async sendResourceUpdated(params){return this.notification({method:"notifications/resources/updated",params})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};init_types();var COMPLETABLE_SYMBOL=Symbol.for("mcp.completable");function isCompletable(schema){return!!schema&&typeof schema==="object"&&COMPLETABLE_SYMBOL in schema}function getCompleter(schema){const meta3=schema[COMPLETABLE_SYMBOL];return meta3?.complete}var McpZodTypeKind;(function(McpZodTypeKind2){McpZodTypeKind2["Completable"]="McpCompletable"})(McpZodTypeKind||(McpZodTypeKind={}));var TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;function validateToolName(name){const warnings=[];if(name.length===0){return{isValid:false,warnings:["Tool name cannot be empty"]}}if(name.length>128){return{isValid:false,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]}}if(name.includes(" ")){warnings.push("Tool name contains spaces, which may cause parsing issues")}if(name.includes(",")){warnings.push("Tool name contains commas, which may cause parsing issues")}if(name.startsWith("-")||name.endsWith("-")){warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts")}if(name.startsWith(".")||name.endsWith(".")){warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts")}if(!TOOL_NAME_REGEX.test(name)){const invalidChars=name.split("").filter(char=>!/[A-Za-z0-9._-]/.test(char)).filter((char,index2,arr)=>arr.indexOf(char)===index2);warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c=>`"${c}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)");return{isValid:false,warnings}}return{isValid:true,warnings}}function issueToolNameWarning(name,warnings){if(warnings.length>0){console.warn(`Tool name validation warning for "${name}":`);for(const warning of warnings){console.warn(` - ${warning}`)}console.warn("Tool registration will proceed, but this may cause compatibility issues.");console.warn("Consider updating the tool name to conform to the MCP tool naming standard.");console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function validateAndWarnToolName(name){const result=validateToolName(name);issueToolNameWarning(name,result.warnings);return result.isValid}var ExperimentalMcpServerTasks=class{constructor(_mcpServer){this._mcpServer=_mcpServer}registerToolTask(name,config2,handler){const execution={taskSupport:"required",...config2.execution};if(execution.taskSupport==="forbidden"){throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`)}const mcpServerInternal=this._mcpServer;return mcpServerInternal._createRegisteredTool(name,config2.title,config2.description,config2.inputSchema,config2.outputSchema,config2.annotations,execution,config2._meta,handler)}};init_external();init_external();var McpServer=class{constructor(serverInfo,options){this._registeredResources={};this._registeredResourceTemplates={};this._registeredTools={};this._registeredPrompts={};this._toolHandlersInitialized=false;this._completionHandlerInitialized=false;this._resourceHandlersInitialized=false;this._promptHandlersInitialized=false;this.server=new Server(serverInfo,options)}get experimental(){if(!this._experimental){this._experimental={tasks:new ExperimentalMcpServerTasks(this)}}return this._experimental}async connect(transport){return await this.server.connect(transport)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized){return}this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema));this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema));this.server.registerCapabilities({tools:{listChanged:true}});this.server.setRequestHandler(ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,tool])=>tool.enabled).map(([name,tool])=>{const toolDefinition={name,title:tool.title,description:tool.description,inputSchema:(()=>{const obj=normalizeObjectSchema(tool.inputSchema);return obj?toJsonSchemaCompat(obj,{strictUnions:true,pipeStrategy:"input"}):EMPTY_OBJECT_JSON_SCHEMA})(),annotations:tool.annotations,execution:tool.execution,_meta:tool._meta};if(tool.outputSchema){const obj=normalizeObjectSchema(tool.outputSchema);if(obj){toolDefinition.outputSchema=toJsonSchemaCompat(obj,{strictUnions:true,pipeStrategy:"output"})}}return toolDefinition})}));this.server.setRequestHandler(CallToolRequestSchema,async(request,extra)=>{try{const tool=this._registeredTools[request.params.name];if(!tool){throw new McpError(ErrorCode.InvalidParams,`Tool ${request.params.name} not found`)}if(!tool.enabled){throw new McpError(ErrorCode.InvalidParams,`Tool ${request.params.name} disabled`)}const isTaskRequest=!!request.params.task;const taskSupport=tool.execution?.taskSupport;const isTaskHandler="createTask"in tool.handler;if((taskSupport==="required"||taskSupport==="optional")&&!isTaskHandler){throw new McpError(ErrorCode.InternalError,`Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`)}if(taskSupport==="required"&&!isTaskRequest){throw new McpError(ErrorCode.MethodNotFound,`Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`)}if(taskSupport==="optional"&&!isTaskRequest&&isTaskHandler){return await this.handleAutomaticTaskPolling(tool,request,extra)}const args=await this.validateToolInput(tool,request.params.arguments,request.params.name);const result=await this.executeToolHandler(tool,args,extra);if(isTaskRequest){return result}await this.validateToolOutput(tool,result,request.params.name);return result}catch(error51){if(error51 instanceof McpError){if(error51.code===ErrorCode.UrlElicitationRequired){throw error51}}return this.createToolError(error51 instanceof Error?error51.message:String(error51))}});this._toolHandlersInitialized=true}createToolError(errorMessage){return{content:[{type:"text",text:errorMessage}],isError:true}}async validateToolInput(tool,args,toolName){if(!tool.inputSchema){return void 0}const inputObj=normalizeObjectSchema(tool.inputSchema);const schemaToParse=inputObj??tool.inputSchema;const parseResult=await safeParseAsync2(schemaToParse,args);if(!parseResult.success){const error51="error"in parseResult?parseResult.error:"Unknown error";const errorMessage=getParseErrorMessage(error51);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`)}return parseResult.data}async validateToolOutput(tool,result,toolName){if(!tool.outputSchema){return}if(!("content"in result)){return}if(result.isError){return}if(!result.structuredContent){throw new McpError(ErrorCode.InvalidParams,`Output validation error: Tool ${toolName} has an output schema but no structured content was provided`)}const outputObj=normalizeObjectSchema(tool.outputSchema);const parseResult=await safeParseAsync2(outputObj,result.structuredContent);if(!parseResult.success){const error51="error"in parseResult?parseResult.error:"Unknown error";const errorMessage=getParseErrorMessage(error51);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`)}}async executeToolHandler(tool,args,extra){const handler=tool.handler;const isTaskHandler="createTask"in handler;if(isTaskHandler){if(!extra.taskStore){throw new Error("No task store provided.")}const taskExtra={...extra,taskStore:extra.taskStore};if(tool.inputSchema){const typedHandler=handler;return await Promise.resolve(typedHandler.createTask(args,taskExtra))}else{const typedHandler=handler;return await Promise.resolve(typedHandler.createTask(taskExtra))}}if(tool.inputSchema){const typedHandler=handler;return await Promise.resolve(typedHandler(args,extra))}else{const typedHandler=handler;return await Promise.resolve(typedHandler(extra))}}async handleAutomaticTaskPolling(tool,request,extra){if(!extra.taskStore){throw new Error("No task store provided for task-capable tool.")}const args=await this.validateToolInput(tool,request.params.arguments,request.params.name);const handler=tool.handler;const taskExtra={...extra,taskStore:extra.taskStore};const createTaskResult=args?await Promise.resolve(handler.createTask(args,taskExtra)):await Promise.resolve(handler.createTask(taskExtra));const taskId=createTaskResult.task.taskId;let task=createTaskResult.task;const pollInterval=task.pollInterval??5e3;while(task.status!=="completed"&&task.status!=="failed"&&task.status!=="cancelled"){await new Promise(resolve=>setTimeout(resolve,pollInterval));const updatedTask=await extra.taskStore.getTask(taskId);if(!updatedTask){throw new McpError(ErrorCode.InternalError,`Task ${taskId} not found during polling`)}task=updatedTask}return await extra.taskStore.getTaskResult(taskId)}setCompletionRequestHandler(){if(this._completionHandlerInitialized){return}this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema));this.server.registerCapabilities({completions:{}});this.server.setRequestHandler(CompleteRequestSchema,async request=>{switch(request.params.ref.type){case"ref/prompt":assertCompleteRequestPrompt(request);return this.handlePromptCompletion(request,request.params.ref);case"ref/resource":assertCompleteRequestResourceTemplate(request);return this.handleResourceCompletion(request,request.params.ref);default:throw new McpError(ErrorCode.InvalidParams,`Invalid completion reference: ${request.params.ref}`)}});this._completionHandlerInitialized=true}async handlePromptCompletion(request,ref){const prompt=this._registeredPrompts[ref.name];if(!prompt){throw new McpError(ErrorCode.InvalidParams,`Prompt ${ref.name} not found`)}if(!prompt.enabled){throw new McpError(ErrorCode.InvalidParams,`Prompt ${ref.name} disabled`)}if(!prompt.argsSchema){return EMPTY_COMPLETION_RESULT}const promptShape=getObjectShape(prompt.argsSchema);const field=promptShape?.[request.params.argument.name];if(!isCompletable(field)){return EMPTY_COMPLETION_RESULT}const completer=getCompleter(field);if(!completer){return EMPTY_COMPLETION_RESULT}const suggestions=await completer(request.params.argument.value,request.params.context);return createCompletionResult(suggestions)}async handleResourceCompletion(request,ref){const template=Object.values(this._registeredResourceTemplates).find(t=>t.resourceTemplate.uriTemplate.toString()===ref.uri);if(!template){if(this._registeredResources[ref.uri]){return EMPTY_COMPLETION_RESULT}throw new McpError(ErrorCode.InvalidParams,`Resource template ${request.params.ref.uri} not found`)}const completer=template.resourceTemplate.completeCallback(request.params.argument.name);if(!completer){return EMPTY_COMPLETION_RESULT}const suggestions=await completer(request.params.argument.value,request.params.context);return createCompletionResult(suggestions)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized){return}this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema));this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema));this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema));this.server.registerCapabilities({resources:{listChanged:true}});this.server.setRequestHandler(ListResourcesRequestSchema,async(request,extra)=>{const resources2=Object.entries(this._registeredResources).filter(([_,resource])=>resource.enabled).map(([uri,resource])=>({uri,name:resource.name,...resource.metadata}));const templateResources=[];for(const template of Object.values(this._registeredResourceTemplates)){if(!template.resourceTemplate.listCallback){continue}const result=await template.resourceTemplate.listCallback(extra);for(const resource of result.resources){templateResources.push({...template.metadata,...resource})}}return{resources:[...resources2,...templateResources]}});this.server.setRequestHandler(ListResourceTemplatesRequestSchema,async()=>{const resourceTemplates=Object.entries(this._registeredResourceTemplates).map(([name,template])=>({name,uriTemplate:template.resourceTemplate.uriTemplate.toString(),...template.metadata}));return{resourceTemplates}});this.server.setRequestHandler(ReadResourceRequestSchema,async(request,extra)=>{const uri=new URL(request.params.uri);const resource=this._registeredResources[uri.toString()];if(resource){if(!resource.enabled){throw new McpError(ErrorCode.InvalidParams,`Resource ${uri} disabled`)}return resource.readCallback(uri,extra)}for(const template of Object.values(this._registeredResourceTemplates)){const variables=template.resourceTemplate.uriTemplate.match(uri.toString());if(variables){return template.readCallback(uri,variables,extra)}}throw new McpError(ErrorCode.InvalidParams,`Resource ${uri} not found`)});this._resourceHandlersInitialized=true}setPromptRequestHandlers(){if(this._promptHandlersInitialized){return}this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema));this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema));this.server.registerCapabilities({prompts:{listChanged:true}});this.server.setRequestHandler(ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,prompt])=>prompt.enabled).map(([name,prompt])=>{return{name,title:prompt.title,description:prompt.description,arguments:prompt.argsSchema?promptArgumentsFromSchema(prompt.argsSchema):void 0}})}));this.server.setRequestHandler(GetPromptRequestSchema,async(request,extra)=>{const prompt=this._registeredPrompts[request.params.name];if(!prompt){throw new McpError(ErrorCode.InvalidParams,`Prompt ${request.params.name} not found`)}if(!prompt.enabled){throw new McpError(ErrorCode.InvalidParams,`Prompt ${request.params.name} disabled`)}if(prompt.argsSchema){const argsObj=normalizeObjectSchema(prompt.argsSchema);const parseResult=await safeParseAsync2(argsObj,request.params.arguments);if(!parseResult.success){const error51="error"in parseResult?parseResult.error:"Unknown error";const errorMessage=getParseErrorMessage(error51);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${request.params.name}: ${errorMessage}`)}const args=parseResult.data;const cb=prompt.callback;return await Promise.resolve(cb(args,extra))}else{const cb=prompt.callback;return await Promise.resolve(cb(extra))}});this._promptHandlersInitialized=true}resource(name,uriOrTemplate,...rest){let metadata2;if(typeof rest[0]==="object"){metadata2=rest.shift()}const readCallback=rest[0];if(typeof uriOrTemplate==="string"){if(this._registeredResources[uriOrTemplate]){throw new Error(`Resource ${uriOrTemplate} is already registered`)}const registeredResource=this._createRegisteredResource(name,void 0,uriOrTemplate,metadata2,readCallback);this.setResourceRequestHandlers();this.sendResourceListChanged();return registeredResource}else{if(this._registeredResourceTemplates[name]){throw new Error(`Resource template ${name} is already registered`)}const registeredResourceTemplate=this._createRegisteredResourceTemplate(name,void 0,uriOrTemplate,metadata2,readCallback);this.setResourceRequestHandlers();this.sendResourceListChanged();return registeredResourceTemplate}}registerResource(name,uriOrTemplate,config2,readCallback){if(typeof uriOrTemplate==="string"){if(this._registeredResources[uriOrTemplate]){throw new Error(`Resource ${uriOrTemplate} is already registered`)}const registeredResource=this._createRegisteredResource(name,config2.title,uriOrTemplate,config2,readCallback);this.setResourceRequestHandlers();this.sendResourceListChanged();return registeredResource}else{if(this._registeredResourceTemplates[name]){throw new Error(`Resource template ${name} is already registered`)}const registeredResourceTemplate=this._createRegisteredResourceTemplate(name,config2.title,uriOrTemplate,config2,readCallback);this.setResourceRequestHandlers();this.sendResourceListChanged();return registeredResourceTemplate}}_createRegisteredResource(name,title,uri,metadata2,readCallback){const registeredResource={name,title,metadata:metadata2,readCallback,enabled:true,disable:()=>registeredResource.update({enabled:false}),enable:()=>registeredResource.update({enabled:true}),remove:()=>registeredResource.update({uri:null}),update:updates=>{if(typeof updates.uri!=="undefined"&&updates.uri!==uri){delete this._registeredResources[uri];if(updates.uri)this._registeredResources[updates.uri]=registeredResource}if(typeof updates.name!=="undefined")registeredResource.name=updates.name;if(typeof updates.title!=="undefined")registeredResource.title=updates.title;if(typeof updates.metadata!=="undefined")registeredResource.metadata=updates.metadata;if(typeof updates.callback!=="undefined")registeredResource.readCallback=updates.callback;if(typeof updates.enabled!=="undefined")registeredResource.enabled=updates.enabled;this.sendResourceListChanged()}};this._registeredResources[uri]=registeredResource;return registeredResource}_createRegisteredResourceTemplate(name,title,template,metadata2,readCallback){const registeredResourceTemplate={resourceTemplate:template,title,metadata:metadata2,readCallback,enabled:true,disable:()=>registeredResourceTemplate.update({enabled:false}),enable:()=>registeredResourceTemplate.update({enabled:true}),remove:()=>registeredResourceTemplate.update({name:null}),update:updates=>{if(typeof updates.name!=="undefined"&&updates.name!==name){delete this._registeredResourceTemplates[name];if(updates.name)this._registeredResourceTemplates[updates.name]=registeredResourceTemplate}if(typeof updates.title!=="undefined")registeredResourceTemplate.title=updates.title;if(typeof updates.template!=="undefined")registeredResourceTemplate.resourceTemplate=updates.template;if(typeof updates.metadata!=="undefined")registeredResourceTemplate.metadata=updates.metadata;if(typeof updates.callback!=="undefined")registeredResourceTemplate.readCallback=updates.callback;if(typeof updates.enabled!=="undefined")registeredResourceTemplate.enabled=updates.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[name]=registeredResourceTemplate;const variableNames=template.uriTemplate.variableNames;const hasCompleter=Array.isArray(variableNames)&&variableNames.some(v=>!!template.completeCallback(v));if(hasCompleter){this.setCompletionRequestHandler()}return registeredResourceTemplate}_createRegisteredPrompt(name,title,description,argsSchema,callback){const registeredPrompt={title,description,argsSchema:argsSchema===void 0?void 0:objectFromShape(argsSchema),callback,enabled:true,disable:()=>registeredPrompt.update({enabled:false}),enable:()=>registeredPrompt.update({enabled:true}),remove:()=>registeredPrompt.update({name:null}),update:updates=>{if(typeof updates.name!=="undefined"&&updates.name!==name){delete this._registeredPrompts[name];if(updates.name)this._registeredPrompts[updates.name]=registeredPrompt}if(typeof updates.title!=="undefined")registeredPrompt.title=updates.title;if(typeof updates.description!=="undefined")registeredPrompt.description=updates.description;if(typeof updates.argsSchema!=="undefined")registeredPrompt.argsSchema=objectFromShape(updates.argsSchema);if(typeof updates.callback!=="undefined")registeredPrompt.callback=updates.callback;if(typeof updates.enabled!=="undefined")registeredPrompt.enabled=updates.enabled;this.sendPromptListChanged()}};this._registeredPrompts[name]=registeredPrompt;if(argsSchema){const hasCompletable=Object.values(argsSchema).some(field=>{const inner=field instanceof ZodOptional2?field._def?.innerType:field;return isCompletable(inner)});if(hasCompletable){this.setCompletionRequestHandler()}}return registeredPrompt}_createRegisteredTool(name,title,description,inputSchema,outputSchema,annotations,execution,_meta,handler){validateAndWarnToolName(name);const registeredTool={title,description,inputSchema:getZodSchemaObject(inputSchema),outputSchema:getZodSchemaObject(outputSchema),annotations,execution,_meta,handler,enabled:true,disable:()=>registeredTool.update({enabled:false}),enable:()=>registeredTool.update({enabled:true}),remove:()=>registeredTool.update({name:null}),update:updates=>{if(typeof updates.name!=="undefined"&&updates.name!==name){if(typeof updates.name==="string"){validateAndWarnToolName(updates.name)}delete this._registeredTools[name];if(updates.name)this._registeredTools[updates.name]=registeredTool}if(typeof updates.title!=="undefined")registeredTool.title=updates.title;if(typeof updates.description!=="undefined")registeredTool.description=updates.description;if(typeof updates.paramsSchema!=="undefined")registeredTool.inputSchema=objectFromShape(updates.paramsSchema);if(typeof updates.outputSchema!=="undefined")registeredTool.outputSchema=objectFromShape(updates.outputSchema);if(typeof updates.callback!=="undefined")registeredTool.handler=updates.callback;if(typeof updates.annotations!=="undefined")registeredTool.annotations=updates.annotations;if(typeof updates._meta!=="undefined")registeredTool._meta=updates._meta;if(typeof updates.enabled!=="undefined")registeredTool.enabled=updates.enabled;this.sendToolListChanged()}};this._registeredTools[name]=registeredTool;this.setToolRequestHandlers();this.sendToolListChanged();return registeredTool}tool(name,...rest){if(this._registeredTools[name]){throw new Error(`Tool ${name} is already registered`)}let description;let inputSchema;let outputSchema;let annotations;if(typeof rest[0]==="string"){description=rest.shift()}if(rest.length>1){const firstArg=rest[0];if(isZodRawShapeCompat(firstArg)){inputSchema=rest.shift();if(rest.length>1&&typeof rest[0]==="object"&&rest[0]!==null&&!isZodRawShapeCompat(rest[0])){annotations=rest.shift()}}else if(typeof firstArg==="object"&&firstArg!==null){if(Object.values(firstArg).some(v=>typeof v==="object"&&v!==null)){throw new Error(`Tool ${name} expected a Zod schema or ToolAnnotations, but received an unrecognized object`)}annotations=rest.shift()}}const callback=rest[0];return this._createRegisteredTool(name,void 0,description,inputSchema,outputSchema,annotations,{taskSupport:"forbidden"},void 0,callback)}registerTool(name,config2,cb){if(this._registeredTools[name]){throw new Error(`Tool ${name} is already registered`)}const{title,description,inputSchema,outputSchema,annotations,_meta}=config2;return this._createRegisteredTool(name,title,description,inputSchema,outputSchema,annotations,{taskSupport:"forbidden"},_meta,cb)}prompt(name,...rest){if(this._registeredPrompts[name]){throw new Error(`Prompt ${name} is already registered`)}let description;if(typeof rest[0]==="string"){description=rest.shift()}let argsSchema;if(rest.length>1){argsSchema=rest.shift()}const cb=rest[0];const registeredPrompt=this._createRegisteredPrompt(name,void 0,description,argsSchema,cb);this.setPromptRequestHandlers();this.sendPromptListChanged();return registeredPrompt}registerPrompt(name,config2,cb){if(this._registeredPrompts[name]){throw new Error(`Prompt ${name} is already registered`)}const{title,description,argsSchema}=config2;const registeredPrompt=this._createRegisteredPrompt(name,title,description,argsSchema,cb);this.setPromptRequestHandlers();this.sendPromptListChanged();return registeredPrompt}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(params,sessionId){return this.server.sendLoggingMessage(params,sessionId)}sendResourceListChanged(){if(this.isConnected()){this.server.sendResourceListChanged()}}sendToolListChanged(){if(this.isConnected()){this.server.sendToolListChanged()}}sendPromptListChanged(){if(this.isConnected()){this.server.sendPromptListChanged()}}};var EMPTY_OBJECT_JSON_SCHEMA={type:"object",properties:{}};function isZodTypeLike(value){return value!==null&&typeof value==="object"&&"parse"in value&&typeof value.parse==="function"&&"safeParse"in value&&typeof value.safeParse==="function"}function isZodSchemaInstance(obj){return"_def"in obj||"_zod"in obj||isZodTypeLike(obj)}function isZodRawShapeCompat(obj){if(typeof obj!=="object"||obj===null){return false}if(isZodSchemaInstance(obj)){return false}if(Object.keys(obj).length===0){return true}return Object.values(obj).some(isZodTypeLike)}function getZodSchemaObject(schema){if(!schema){return void 0}if(isZodRawShapeCompat(schema)){return objectFromShape(schema)}if(!isZodSchemaInstance(schema)){throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object")}return schema}function promptArgumentsFromSchema(schema){const shape=getObjectShape(schema);if(!shape)return[];return Object.entries(shape).map(([name,field])=>{const description=getSchemaDescription(field);const isOptional=isSchemaOptional(field);return{name,description,required:!isOptional}})}function getMethodValue(schema){const shape=getObjectShape(schema);const methodSchema=shape?.method;if(!methodSchema){throw new Error("Schema is missing a method literal")}const value=getLiteralValue(methodSchema);if(typeof value==="string"){return value}throw new Error("Schema method literal must be a string")}function createCompletionResult(suggestions){return{completion:{values:suggestions.slice(0,100),total:suggestions.length,hasMore:suggestions.length>100}}}var EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:false}};var import_node_process=__toESM(require("node:process"),1);init_types();var ReadBuffer=class{append(chunk){this._buffer=this._buffer?Buffer.concat([this._buffer,chunk]):chunk}readMessage(){if(!this._buffer){return null}const index2=this._buffer.indexOf("\n");if(index2===-1){return null}const line=this._buffer.toString("utf8",0,index2).replace(/\r$/,"");this._buffer=this._buffer.subarray(index2+1);return deserializeMessage(line)}clear(){this._buffer=void 0}};function deserializeMessage(line){return JSONRPCMessageSchema.parse(JSON.parse(line))}function serializeMessage(message){return JSON.stringify(message)+"\n"}var StdioServerTransport=class{constructor(_stdin=import_node_process.default.stdin,_stdout=import_node_process.default.stdout){this._stdin=_stdin;this._stdout=_stdout;this._readBuffer=new ReadBuffer;this._started=false;this._ondata=chunk=>{this._readBuffer.append(chunk);this.processReadBuffer()};this._onerror=error51=>{this.onerror?.(error51)}}async start(){if(this._started){throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.")}this._started=true;this._stdin.on("data",this._ondata);this._stdin.on("error",this._onerror)}processReadBuffer(){while(true){try{const message=this._readBuffer.readMessage();if(message===null){break}this.onmessage?.(message)}catch(error51){this.onerror?.(error51)}}}async close(){this._stdin.off("data",this._ondata);this._stdin.off("error",this._onerror);const remainingDataListeners=this._stdin.listenerCount("data");if(remainingDataListeners===0){this._stdin.pause()}this._readBuffer.clear();this.onclose?.()}send(message){return new Promise(resolve=>{const json2=serializeMessage(message);if(this._stdout.write(json2)){resolve()}else{this._stdout.once("drain",resolve)}})}};var import_node_fs7=require("node:fs");var import_node_os2=require("node:os");var reconnects=new WeakMap;function requestSafeReconnect(nc,additionalPending=()=>0){const active=reconnects.get(nc);if(active)return active;const refresh=reconnectOnce(nc,additionalPending).finally(()=>{reconnects.delete(nc)});reconnects.set(nc,refresh);return refresh}async function reconnectOnce(nc,additionalPending){const deadline=Date.now()+5e3;for(;;){if(nc.isClosed())throw new Error("credential reconnect: connection already closed");const mux=nc.protocol?.muxSubscriptions;if(typeof mux?.size!=="function")throw new Error("credential reconnect: native request multiplexer unavailable; connection retained");if(mux.size()+additionalPending()===0)break;if(Date.now()>=deadline)throw new Error("credential reconnect: outgoing requests remained busy for 5000ms; connection retained, refresh must be retried");await new Promise(resolve=>setTimeout(resolve,10))}const original=nc.request;const statuses=nc.status()[Symbol.asyncIterator]();let ready;let failed;const gate=new Promise((resolve,reject)=>{ready=resolve;failed=reject});void gate.catch(()=>{});const timer=setTimeout(()=>failed(new Error("credential reconnect: native readiness exceeded 5000ms; new requests were not sent")),5e3);const gated=async(subject,data,opts)=>{const start=Date.now();const budget=opts?.timeout||1e3;let timeout;try{await Promise.race([gate,new Promise((_resolve,reject)=>{timeout=setTimeout(()=>reject(new Error("credential reconnect: request deadline elapsed before initial send")),budget)})]);const remaining=budget-(Date.now()-start);if(remaining<=0)throw new Error("credential reconnect: request deadline elapsed before initial send");return await original.call(nc,subject,data,{...opts,timeout:remaining})}finally{clearTimeout(timeout)}};nc.request=gated;const watch=(async()=>{for(;;){const next=await statuses.next();if(next.done)break;if(next.value.type==="reconnect"){ready();return}}failed(new Error("credential reconnect: connection closed before native readiness"))})();void watch.catch(error51=>failed(error51 instanceof Error?error51:new Error(String(error51))));try{await nc.reconnect();await gate}catch(error51){failed(error51 instanceof Error?error51:new Error(String(error51)));throw error51}finally{clearTimeout(timer);if(nc.request===gated)nc.request=original;await statuses.return?.()}}var import_node_crypto=require("node:crypto");var import_nkeys=__toESM(require_mod(),1);var import_codec=__toESM(require_codec(),1);var ED25519_PKCS8=Buffer.from("302e020100300506032b657004220420","hex");var ED25519_SPKI=Buffer.from("302a300506032b6570032100","hex");function nativeNkeySigner(seed){const encodedSeed=Uint8Array.from(seed);const decoded=import_codec.Codec.decodeSeed(encodedSeed);if(decoded.buf.byteLength!==32){decoded.buf.fill(0);encodedSeed.fill(0);throw new import_nkeys.NKeysError(import_nkeys.NKeysErrorCode.InvalidSeedLen)}if(decoded.prefix===import_nkeys.Prefix.Curve){decoded.buf.fill(0);encodedSeed.fill(0);throw new import_nkeys.NKeysError(import_nkeys.NKeysErrorCode.InvalidCurveOperation)}const der=Buffer.concat([ED25519_PKCS8,decoded.buf]);let privateKey;let publicKey;let publicBytes;let publicNkey;try{privateKey=(0,import_node_crypto.createPrivateKey)({key:der,format:"der",type:"pkcs8"});publicKey=(0,import_node_crypto.createPublicKey)(privateKey);const jwk=publicKey.export({format:"jwk"});if(jwk.crv!=="Ed25519"||typeof jwk.x!=="string")throw new Error("native nkey signer did not derive an Ed25519 public key");publicBytes=Buffer.from(jwk.x,"base64url");publicNkey=new TextDecoder().decode(import_codec.Codec.encode(decoded.prefix,publicBytes))}catch(error51){encodedSeed.fill(0);throw error51}finally{decoded.buf.fill(0);der.fill(0)}const active=()=>{if(!privateKey)throw new import_nkeys.NKeysError(import_nkeys.NKeysErrorCode.ClearedPair);return privateKey};return{getPublicKey(){active();return publicNkey},getSeed(){active();return encodedSeed.slice()},getPrivateKey(){active();const raw=import_codec.Codec.decodeSeed(encodedSeed).buf;const secret=Buffer.concat([raw,publicBytes]);try{return import_codec.Codec.encode(import_nkeys.Prefix.Private,secret)}finally{raw.fill(0);secret.fill(0)}},sign(input){return(0,import_node_crypto.sign)(null,input,active())},verify(input,signature){active();return(0,import_node_crypto.verify)(null,input,publicKey,signature)},clear(){encodedSeed.fill(0);privateKey=void 0},seal(){throw new import_nkeys.NKeysError(import_nkeys.NKeysErrorCode.InvalidNKeyOperation)},open(){throw new import_nkeys.NKeysError(import_nkeys.NKeysErrorCode.InvalidNKeyOperation)}}}var import_node_child_process=require("node:child_process");var import_node_fs2=require("node:fs");var import_node_crypto2=require("node:crypto");var import_node_path=require("node:path");var import_node_fs=require("node:fs");var isWin=process.platform==="win32";function notPrivate(path,why){const refused=new Error(`refusing to write "${path}": it ${why}; it was left unchanged`);refused.code="EPERM";return refused}function openPrivate(path,flags){if(isWin){const fd2=(0,import_node_fs.openSync)(path,flags,384);try{(0,import_node_fs.fchmodSync)(fd2,384)}catch(e){(0,import_node_fs.closeSync)(fd2);throw e}return fd2}let fd;try{fd=(0,import_node_fs.openSync)(path,flags|import_node_fs.constants.O_NOFOLLOW|import_node_fs.constants.O_NONBLOCK,384)}catch(e){if(e.code==="ELOOP")throw notPrivate(path,"is a symlink");throw e}try{const info=(0,import_node_fs.fstatSync)(fd);if(!info.isFile())throw notPrivate(path,"is not a regular file");if(info.uid!==process.getuid())throw notPrivate(path,`is owned by uid ${info.uid}, not this user`);(0,import_node_fs.fchmodSync)(fd,384);return fd}catch(e){(0,import_node_fs.closeSync)(fd);throw e}}function createPrivateRecord(path,data){writeBytes(path,data,true)}function writeBytes(path,data,exclusive){const fd=openPrivate(path,import_node_fs.constants.O_WRONLY|import_node_fs.constants.O_CREAT|(exclusive?import_node_fs.constants.O_EXCL:0));try{try{(0,import_node_fs.ftruncateSync)(fd);(0,import_node_fs.writeFileSync)(fd,data)}finally{(0,import_node_fs.closeSync)(fd)}}catch(e){if(exclusive){try{(0,import_node_fs.unlinkSync)(path)}catch{}}throw e}}function processStatFields(pid){try{const stat=(0,import_node_fs2.readFileSync)(`/proc/${pid}/stat`,"utf8");const after=stat.lastIndexOf(") ");if(after<0||stat.slice(0,stat.indexOf(" "))!==String(pid))return void 0;return stat.slice(after+2).trim().split(/\s+/)}catch{return void 0}}function processStartToken(pid){if(process.platform==="win32")return void 0;if(process.platform==="linux")return processStatFields(pid)?.[19];try{const out=(0,import_node_child_process.execFileSync)("ps",["-o","lstart=","-p",String(pid)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return out||void 0}catch{return void 0}}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function pidAlive(pid){try{process.kill(pid,0);return true}catch(e){const code=e.code;if(code==="ESRCH")return false;if(code==="EPERM")return true;throw e}}function readOwner(path){let raw;try{raw=(0,import_node_fs2.readFileSync)(path,"utf8")}catch(e){const code=e.code;if(code==="ENOENT")return void 0;if(code==="EISDIR"||code==="EACCES"||code==="EPERM")throw new Error(`advisory lock path ${path} is unreadable (${code}) - remove the stray file or directory there and retry`);throw e}let ino;try{ino=(0,import_node_fs2.statSync)(path).ino}catch{}try{return{owner:JSON.parse(raw),ino}}catch{return{ino}}}function inspectLock(path){const inspection=inspectLockSnapshot(path);return inspection.state==="active"?{state:"active",owner:inspection.owner}:{state:inspection.state}}function inspectLockSnapshot(path){const found=readOwner(path);if(found===void 0)return{state:"absent"};const{owner:owner2,ino}=found;if(!owner2||typeof owner2.pid!=="number"||!Number.isInteger(owner2.pid)||owner2.pid<=0||typeof owner2.nonce!=="string"){return{state:"stale",ino}}if(!pidAlive(owner2.pid))return{state:"stale",ino};if(owner2.start!==void 0){const fields=process.platform==="linux"?processStatFields(owner2.pid):void 0;const now=process.platform==="linux"?fields?.[19]:processStartToken(owner2.pid);if(now===owner2.start&&fields?.[0]==="Z")return{state:"stale",ino};if(now!==void 0&&now!==owner2.start)return{state:"stale",ino}}return{state:"active",owner:owner2,ino}}function publishAtomic(path,content){const tmp=`${path}.${(0,import_node_crypto2.randomBytes)(8).toString("hex")}.tmp`;createPrivateRecord(tmp,content);try{(0,import_node_fs2.linkSync)(tmp,path);return true}catch(e){if(e.code==="EEXIST")return false;throw e}finally{try{(0,import_node_fs2.unlinkSync)(tmp)}catch{}}}function reclaimStale(path,inspectedIno){const sentinel=`${path}.reclaim`;const mine=JSON.stringify({pid:process.pid,start:processStartToken(process.pid),nonce:(0,import_node_crypto2.randomBytes)(8).toString("hex"),ts:Date.now()});if(!publishAtomic(sentinel,mine)){const reclaimer=inspectLock(sentinel);if(reclaimer.state==="stale")throw new Error(`a lock reclaim was interrupted and its sentinel remains (${sentinel}) - if no cotal process is running, remove it and retry`);return reclaimer.state==="active"?reclaimer.owner:void 0}try{const inspection=inspectLockSnapshot(path);if(inspection.state!=="stale")return;if(inspectedIno!==void 0&&inspection.ino!==void 0&&inspection.ino!==inspectedIno)return;(0,import_node_fs2.unlinkSync)(path)}catch(e){if(e.code!=="ENOENT")throw e}finally{try{(0,import_node_fs2.unlinkSync)(sentinel)}catch{}}}function newAttempt(path,opts){(0,import_node_fs2.mkdirSync)((0,import_node_path.dirname)(path),{recursive:true,mode:448});const nonce3=(0,import_node_crypto2.randomBytes)(12).toString("hex");const owner2={pid:process.pid,start:processStartToken(process.pid),nonce:nonce3,ts:Date.now(),...opts.label?{label:opts.label}:{}};return{path,nonce:nonce3,content:`${JSON.stringify(owner2)}
|
|
116
|
-
`}}function tryAcquireOnce({path,nonce:nonce3,content}){if(publishAtomic(path,content)){let released=false;return{kind:"acquired",held:{nonce:nonce3,release(){if(released)return;released=true;const found=readOwner(path);if(found?.owner?.nonce===nonce3){try{(0,import_node_fs2.unlinkSync)(path)}catch{}}}}}}const inspection=inspectLockSnapshot(path);if(inspection.state==="absent")return{kind:"retry"};if(inspection.state==="stale"){const reclaimer=reclaimStale(path,inspection.ino);return reclaimer?{kind:"reclaiming",owner:reclaimer}:{kind:"retry"}}return{kind:"held",owner:inspection.owner}}function reclaimPollMs(pollMs){return Math.min(pollMs,50)}function acquireLock(path,opts={}){const waitMs=opts.waitMs??3e5;const pollMs=opts.pollMs??200;const attempt=newAttempt(path,opts);const deadline=Date.now()+waitMs;for(;;){const result=tryAcquireOnce(attempt);if(result.kind==="acquired")return result.held;if(result.kind==="retry")continue;const left=deadline-Date.now();if(left<=0)throw lockTimeoutError(path,opts,result.owner,waitMs);sleepSync(Math.min(result.kind==="reclaiming"?reclaimPollMs(pollMs):pollMs,left))}}function lockTimeoutError(path,opts,owner2,waitMs){return opts.onTimeout?.(owner2)??new Error(`${opts.label??"a lock"} is held by a live process (pid ${owner2.pid}) and did not release within ${Math.round(waitMs/1e3)}s - retry, or if it is wedged, remove ${path}`)}var import_node_crypto3=require("node:crypto");var import_node_fs3=require("node:fs");var import_node_os=require("node:os");var import_node_path2=require("node:path");var LocalConsumerHeldError=class extends Error{};function localConsumerClaimPath(servers,space2,owner2,actor2,lifecycleUid){const user=(0,import_node_os.userInfo)();const root=process.platform==="linux"?`/tmp/cotal-consumers-${user.uid}`:(0,import_node_path2.join)(user.homedir,".cotal-consumers");(0,import_node_fs3.mkdirSync)(root,{recursive:true,mode:448});const st=(0,import_node_fs3.lstatSync)(root);if(!st.isDirectory()||st.isSymbolicLink()||process.platform!=="win32"&&(st.uid!==user.uid||(st.mode&63)!==0))throw new Error("local consumer custody directory is not private to this OS user");const targets=[...new Set(servers.split(",").map(s=>{const u=new URL(s.trim().includes("://")?s.trim():`nats://${s.trim()}`);u.username="";u.password="";if(!u.port)u.port=u.protocol==="nats:"?"4222":u.protocol==="wss:"?"443":"80";return u.href}))].sort();const key=(0,import_node_crypto3.createHash)("sha256").update(JSON.stringify([targets,space2,owner2,actor2,lifecycleUid])).digest("hex");const path=(0,import_node_path2.join)(root,`${key}.lock`);try{const file2=(0,import_node_fs3.lstatSync)(path);if(!file2.isFile()||file2.isSymbolicLink()||process.platform!=="win32"&&(file2.uid!==user.uid||(file2.mode&63)!==0))throw new Error("local consumer custody file is not private to this OS user")}catch(error51){if(error51.code!=="ENOENT")throw error51}return path}function acquireLocalConsumer(servers,space2,owner2,actor2,lifecycleUid){return acquireLock(localConsumerClaimPath(servers,space2,owner2,actor2,lifecycleUid),{waitMs:0,label:"local inbox consumer",onTimeout:()=>new LocalConsumerHeldError(`local inbox already has a consuming session for ${owner2}.${actor2} in space "${space2}"; preserve that session and choose a distinct actor for a new launch`)})}var import_nkeys2=__toESM(require_mod(),1);var ILLEGAL=/[^A-Za-z0-9_-]/g;function token(s){const t=s.trim().replace(ILLEGAL,"_");return t.length>0?t:"_"}var ROOT="cotal";function spacePrefix(space2){return`${ROOT}.${token(space2)}`}function normalizeMentions(mentions){if(!mentions?.length)return void 0;const out=[...new Set(mentions.map(m=>m.trim().toLowerCase()).filter(m=>m.length>0))];return out.length?out:void 0}function channelPath(channel){const segs=channel.split(".").map(s=>s.trim()).filter(s=>s.length>0);if(segs.length===0)return"_";return segs.map((s,i)=>{if(s===">"){if(i!==segs.length-1)throw new Error(`channel "${channel}": '>' is only valid as the last segment`);return">"}return s==="*"?"*":token(s)}).join(".")}function assertValidRole(role){if(typeof role!=="string"||!/^[A-Za-z0-9_-]+$/.test(role))throw new Error(`invalid role "${role}": must be a single NATS-safe token ([A-Za-z0-9_-]) - a role is an address, so it is rejected rather than silently rewritten`);return role}function routeToken(s){return s==="*"?"*":assertValidRole(s)}function ownerToken(s){return s==="*"?"*":assertValidOwnerToken(s)}function chatSubject(space2,owner2,actor2,channel){return`${spacePrefix(space2)}.chat.${ownerToken(owner2)}.${ownerToken(actor2)}.${channelPath(channel)}`}function isConcreteChannel(channel){return!channel.split(".").some(s=>s.trim()==="*"||s.trim()===">")}function isChannelFamily(channel){const segs=channel.split(".");return channel.length<=MAX_CHANNEL_LENGTH&&segs.length>=2&&segs[segs.length-1]===">"&&segs.slice(0,-1).every(s=>/^[A-Za-z0-9_-]+$/.test(s))}function familiesCovering(channel){const segs=channel.split(".");return segs.slice(1).map((_,i)=>`${segs.slice(0,i+1).join(".")}.>`)}function subjectMatches(pattern,subject){const p=pattern.split(".");const s=subject.split(".");for(let i=0;i<p.length;i++){if(p[i]===">")return i<s.length;if(i>=s.length)return false;if(p[i]==="*")continue;if(p[i]!==s[i])return false}return p.length===s.length}function assertValidChannel(channel){if(channel.length>MAX_CHANNEL_LENGTH)throw new Error(`invalid channel "${channel.slice(0,32)}\u2026": ${channel.length} characters exceeds the ${MAX_CHANNEL_LENGTH}-character limit (every grant line a channel mints rides the CONNECT line)`);const segs=channel.split(".");if(!channel.length||segs.some(s=>s.length===0))throw new Error(`invalid channel "${channel}": empty segment (no leading/trailing/double dots)`);segs.forEach((s,i)=>{if(s===">"){if(i!==segs.length-1)throw new Error(`invalid channel "${channel}": '>' is only valid as the last segment`);return}if(s==="*")return;if(!/^[A-Za-z0-9_-]+$/.test(s))throw new Error(`invalid channel "${channel}": segment "${s}" must be a NATS-safe token ([A-Za-z0-9_-])${/[*>]/.test(s)?", '*', or '>'":""} - policy channel names can't contain characters the wire layer would rewrite`)});return channel}var MAX_CHANNEL_LENGTH=4096;function assertValidOwnerToken(owner2){if(typeof owner2!=="string"||!/^[A-Za-z0-9_]+$/.test(owner2))throw new Error(`invalid owner/actor token "${owner2}": must be a single NATS-safe token ([A-Za-z0-9_]) - no dots, '*', '>', or '-'. A separator or wildcard in an id is lane breakout or aliasing, and '-' is reserved as the principal name-form separator, so it is rejected rather than silently rewritten.`);return owner2}function principalKey(owner2,actor2){assertValidOwnerToken(owner2);assertValidOwnerToken(actor2);return{key:`${owner2}.${actor2}`,name:`${owner2}-${actor2}`}}var LIFECYCLE_TOKEN=/^[a-z0-9]{26,32}$/;function assertLifecycleToken(v,what="lifecycleUid"){if(!LIFECYCLE_TOKEN.test(v))throw new Error(`${what} "${v}" is not a valid lifecycle token ([a-z0-9]{26,32})`);return v}function mintLifecycleUid(){return assertLifecycleToken(BigInt(`0x${Array.from(globalThis.crypto.getRandomValues(new Uint8Array(20)),b=>b.toString(16).padStart(2,"0")).join("")}`).toString(36).padStart(26,"0"))}function lifecycleNameKey(owner2,actor2,lifecycleUid){return`${principalKey(owner2,actor2).name}-${assertLifecycleToken(lifecycleUid)}`}function parseLifecycleSubjectKey(key){if(typeof key!=="string")return null;const parts=key.split(".");if(parts.length!==3)return null;const[owner2,actor2,uid2]=parts;if(!/^[A-Za-z0-9_]+$/.test(owner2)||!/^[A-Za-z0-9_]+$/.test(actor2)||!LIFECYCLE_TOKEN.test(uid2))return null;return{owner:owner2,actor:actor2,lifecycleUid:uid2}}function parsePrincipalKey(key){if(typeof key!=="string")return null;const dot=key.indexOf(".");if(dot<=0||dot>=key.length-1)return null;const owner2=key.slice(0,dot);const actor2=key.slice(dot+1);if(!/^[A-Za-z0-9_]+$/.test(owner2)||!/^[A-Za-z0-9_]+$/.test(actor2))return null;return{owner:owner2,actor:actor2}}function assertInboxConnId(connId){if(typeof connId!=="string"||!/^[A-Za-z0-9_-]{8,120}$/.test(connId))throw new Error(`invalid connId/inbox nonce ${JSON.stringify(connId)} - must match [A-Za-z0-9_-]{8,120} (no subject metacharacters; guards the _INBOX_<connId>.> grant against wildcard escalation)`);return connId}var DEV_OWNER="local";var DERIVED_OWNER_PREFIX="u_";function assertDerivedOwnerToken(owner2){if(typeof owner2!=="string"||!/^u_[a-z2-7]{26}$/.test(owner2))throw new Error(`invalid derived owner token "${owner2}": expected "${DERIVED_OWNER_PREFIX}" + 26 lowercase base32 chars ([a-z2-7]). Owner tokens are derived server-side at the auth callout and are structurally disjoint from nkeys; anything else at an owner boundary is rejected, not rewritten.`);return owner2}function assertPrincipalOwnerToken(owner2,opts={}){if(opts.allowLocal&&owner2===DEV_OWNER)return owner2;if(opts.allowPlatform&&/^p_[a-z2-7]{26}$/.test(owner2))return owner2;try{return assertDerivedOwnerToken(owner2)}catch{throw new Error(`invalid principal owner "${owner2}" at a trust boundary: expected a derived owner (u_\u2026)${opts.allowLocal?` or the reserved dev owner "${DEV_OWNER}"`:""}${opts.allowPlatform?" or a platform owner (p_\u2026)":""} - an nkey-shaped or arbitrary token is not a real owner (flip criterion 2: owners are nkey-disjoint).`)}}function isPrincipalOwnerToken(owner2,opts={allowLocal:true}){try{assertPrincipalOwnerToken(owner2,{allowLocal:opts.allowLocal??true,allowPlatform:opts.allowPlatform??false});return true}catch{return false}}function channelInAllow(allow,channel){return allow.some(a=>subjectMatches(a,channel))}function resolveReadAcl(subscribe,allowSubscribe){const allow=allowSubscribe?.length?allowSubscribe:subscribe;for(const ch of subscribe)if(!(isConcreteChannel(ch)?channelInAllow:patternInAllow)(allow,ch))throw new Error(`subscribe "${ch}" is not within allowSubscribe [${allow.join(", ")}]`);return allow}function patternCovers(cap,pattern){const c=cap.split(".");const p=pattern.split(".");if(c.slice(0,-1).includes(">")||p.slice(0,-1).includes(">"))return false;for(let i=0;i<c.length;i++){if(c[i]===">")return p.length>i;if(i>=p.length)return false;if(p[i]===">")return false;if(c[i]==="*")continue;if(p[i]==="*")return false;if(c[i]!==p[i])return false}return c.length===p.length}function patternInAllow(allow,pattern){return allow.some(a=>patternCovers(a,pattern))}function membershipInAllow(allow,channel){return isChannelFamily(channel)?patternInAllow(allow,channel):channelInAllow(allow,channel)}function unicastSubject(space2,recipOwner,recipActor,sndOwner,sndActor){return`${spacePrefix(space2)}.inst.${ownerToken(recipOwner)}.${ownerToken(recipActor)}.${ownerToken(sndOwner)}.${ownerToken(sndActor)}`}function unicastRecvFilter(space2,owner2,actor2){return`${spacePrefix(space2)}.inst.${ownerToken(owner2)}.${ownerToken(actor2)}.>`}function anycastSubject(space2,service,owner2,actor2){return`${spacePrefix(space2)}.svc.${routeToken(service)}.${ownerToken(owner2)}.${ownerToken(actor2)}`}function anycastServeFilter(space2,service){return`${spacePrefix(space2)}.svc.${routeToken(service)}.>`}var TAKE_ROUTE="take";function takeSubject(space2,role,owner2,actor2){return`${spacePrefix(space2)}.${TAKE_ROUTE}.${routeToken(role)}.${ownerToken(owner2)}.${ownerToken(actor2)}`}function takeServeFilter(space2){return`${spacePrefix(space2)}.${TAKE_ROUTE}.*.*.*`}function parseTakeSubject(subject){const parts=subject.split(".");if(parts.length!==6||parts[0]!==ROOT||parts[2]!==TAKE_ROUTE)return null;return{role:parts[3],owner:parts[4],actor:parts[5],sender:`${parts[4]}.${parts[5]}`}}function controlServiceSubject(space2,service,owner2,actor2){return`${spacePrefix(space2)}.ctl.${routeToken(service)}.${ownerToken(owner2)}.${ownerToken(actor2)}`}var CONTROL_DELIVERY="delivery";var CONTROL_DELIVERY_ADMIN="delivery-admin";var LIVENESS_ROUTE="live";function livenessSubject(space2,plane,owner2,actor2){return`${spacePrefix(space2)}.${LIVENESS_ROUTE}.${routeToken(plane)}.${ownerToken(owner2)}.${ownerToken(actor2)}`}function livenessServeFilter(space2,plane){return`${spacePrefix(space2)}.${LIVENESS_ROUTE}.${routeToken(plane)}.*.*`}function spaceWildcard(space2){return`${spacePrefix(space2)}.>`}function chatWildcard(space2){return`${spacePrefix(space2)}.chat.>`}function parseSubject(subject){const parts=subject.split(".");if(parts[0]!==ROOT)return null;const kind=parts[2];const mk=(kind2,owner2,actor2,rest)=>({kind:kind2,owner:owner2,actor:actor2,sender:`${owner2}.${actor2}`,rest});if(kind==="chat"){if(parts.length<6)return null;return mk(kind,parts[3],parts[4],parts.slice(5).join("."))}if(kind==="inst"){if(parts.length!==7)return null;return mk(kind,parts[5],parts[6],`${parts[3]}.${parts[4]}`)}if(kind==="svc"||kind==="ctl"){if(parts.length!==6)return null;return mk(kind,parts[4],parts[5],parts[3])}return null}function presenceBucket(space2){return`cotal_presence_${token(space2)}`}var PRESENCE_STATUSES={idle:true,waiting:true,working:true,offline:true};function presenceRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function presenceOptionalString(value){return value===void 0||typeof value==="string"}function isPresenceRow(value,key){return presenceRowProblem(value,key)===void 0}function presenceRowProblem(value,key){if(!presenceRecord(value))return"row";if(!presenceRecord(value.card))return"card";const card=value.card;if(typeof card.id!=="string"||card.id.length===0||card.id!==key)return"card.id";if(typeof card.name!=="string")return"card.name";if(!presenceOptionalString(card.role))return"card.role";if(typeof value.status!=="string"||!Object.hasOwn(PRESENCE_STATUSES,value.status))return"status";if(typeof value.ts!=="number"||!Number.isFinite(value.ts))return"ts";if(!presenceOptionalString(value.activity))return"activity";if(!presenceOptionalString(value.attention))return"attention";if(value.condition!==void 0){if(!presenceRecord(value.condition))return"condition";if(typeof value.condition.code!=="string")return"condition.code"}return void 0}function assertPresenceRow(value,key){const field=presenceRowProblem(value,key);if(field!==void 0)throw new TypeError(`invalid presence ${field}`)}function channelBucket(space2){return`cotal_channels_${token(space2)}`}var CHANNEL_DEFAULTS_KEY="=defaults";function membersBucket(space2){return`cotal_members_${token(space2)}`}function memberKey(channel,principal,lifecycleUid){const family=isChannelFamily(channel);if(!family&&!isConcreteChannel(assertValidChannel(channel)))throw new Error(`member key: "${channel}" must be a concrete channel or a family such as review.>`);return`${family?`${channel.slice(0,-1)}=`:channel}/${principal}.${assertLifecycleToken(lifecycleUid)}`}function parseMemberKey(key){const i=key.indexOf("/");if(i<=0||i>=key.length-1)return null;let channel=key.slice(0,i);const eq=channel.indexOf("=");if(eq!==-1){if(eq!==channel.length-1||!channel.endsWith(".="))return null;channel=`${channel.slice(0,-1)}>`}const tail=key.slice(i+1);const dot=tail.lastIndexOf(".");if(dot<=0||dot>=tail.length-1)return null;const principal=tail.slice(0,dot);const uid2=tail.slice(dot+1);if(!LIFECYCLE_TOKEN.test(uid2)||parsePrincipalKey(principal)===null)return null;return{channel,principal,lifecycleUid:uid2}}function aclBucket(space2){return`cotal_acl_${token(space2)}`}function aclKey(principal,lifecycleUid){return`${principal}.${assertLifecycleToken(lifecycleUid)}`}function aclAliasFilter(principal){return`${principal}.*`}function membershipBucket(space2){return`cotal_membership_${token(space2)}`}var MEMBERSHIP_FEED_KEY="=feed";function deliveryBucket(space2){return`cotal_delivery_${token(space2)}`}function anycastBucket(space2){return`cotal_anycast_${token(space2)}`}function leaseKey(shardIndex){return`lease.${shardIndex}`}function managerBucket(space2){return`cotal_manager_${token(space2)}`}var MANAGER_LEASE_KEY="lease";function managerLeaseKey(instanceId){return`${MANAGER_LEASE_KEY}.${instanceId}`}var MANAGER_RENEWAL_LEASE_KEY="renewal";function chatStream(space2){return`CHAT_${token(space2)}`}function dmStream(space2){return`DM_${token(space2)}`}function taskStream(space2){return`TASK_${token(space2)}`}function inboxStream(space2){return`INBOX_${token(space2)}`}function dlvStream(space2){return`DLV_${token(space2)}`}function dinboxSubject(space2,owner2,actor2,lifecycleUid){return`${spacePrefix(space2)}.dinbox.${ownerToken(owner2)}.${ownerToken(actor2)}.${assertLifecycleToken(lifecycleUid)}`}function dlvSubject(space2,owner2,actor2,lifecycleUid){return`${spacePrefix(space2)}.dlv.${ownerToken(owner2)}.${ownerToken(actor2)}.${assertLifecycleToken(lifecycleUid)}`}function parseDinboxPrincipal(subject){const parts=subject.split(".");return parts.length===6&&parts[0]===ROOT&&parts[2]==="dinbox"&&LIFECYCLE_TOKEN.test(parts[5])?{owner:parts[3],actor:parts[4],lifecycleUid:parts[5]}:null}function dlvDurable(owner2,actor2,lifecycleUid){return`dlv_${lifecycleNameKey(owner2,actor2,lifecycleUid)}`}var FANOUT_DURABLE="fanout";var INBOX_READER_DURABLE="reader";function fanoutDurable(shard=0,shards=1){return shards<=1?FANOUT_DURABLE:`${FANOUT_DURABLE}_${shard}`}function readerDurable(shard=0,shards=1){return shards<=1?INBOX_READER_DURABLE:`${INBOX_READER_DURABLE}_${shard}`}function chatHistDurable(owner2,actor2,lifecycleUid){return`chathist_${lifecycleNameKey(owner2,actor2,lifecycleUid)}`}var HISTORY_READERS=8;function historyReaderConsumer(readerId,slot){if(typeof readerId!=="string"||!/^[A-Za-z0-9_-]{1,120}$/.test(readerId))throw new Error(`history reader id ${JSON.stringify(readerId)} must match [A-Za-z0-9_-]{1,120}`);if(!Number.isInteger(slot)||slot<0||slot>=HISTORY_READERS)throw new Error(`history reader slot must be an integer in [0, ${HISTORY_READERS}), received ${slot}`);return`hist_${readerId}_${slot}`}function calloutReaderId(serverId,clientId){if(typeof serverId!=="string"||!/^N[A-Z2-7]{55}$/.test(serverId))throw new Error(`history reader server id ${JSON.stringify(serverId)} is not a server public key`);if(!Number.isSafeInteger(clientId)||clientId<1)throw new Error(`history reader client id must be a positive integer, received ${JSON.stringify(clientId)}`);return`${serverId}_${clientId}`}function dmDurable(owner2,actor2,lifecycleUid){return`dm_${lifecycleNameKey(owner2,actor2,lifecycleUid)}`}function taskDurable(service){return`svc_${assertValidRole(service)}`}var RESERVED_COMMANDS=Object.freeze(["describe","cancel"]);var ENDPOINT_LABEL=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;var COMMAND=/^[a-z0-9-]{1,32}$/;var NONCE=/^[A-Za-z0-9_-]{22,64}$/;var ID=/^[A-Za-z0-9_-]{1,64}$/;var DIGEST_HEX=/^[a-f0-9]{64}$/;var EPOCH=/^(0|[1-9][0-9]*)$/;var GENERATION=/^[a-f0-9]{32}$/;function assertGeneration(generation,what="generation"){if(typeof generation!=="string"||!GENERATION.test(generation))throw new Error(`${what} is not an issued generation (32 lowercase hex characters)`);return generation}var MAX_EP_SUBJECT_BYTES=1024;function endpointToken(name){const labels=name.split(".");for(const l of labels){if(!ENDPOINT_LABEL.test(l))throw new Error(`endpoint name label "${l}" in "${name}" is not DNS-shaped ([a-z0-9]([a-z0-9-]*[a-z0-9])?)`)}const tok=labels.join("_");if(tok.length>64)throw new Error(`endpoint name token "${tok}" exceeds 64 characters`);return tok}function endpointNameOf(token2){return token2.split("_").join(".")}function assertCommandToken(command){if(!COMMAND.test(command))throw new Error(`command "${command}" is not a valid command token ([a-z0-9-]{1,32})`);return command}function assertNonce(nonce3){if(!NONCE.test(nonce3))throw new Error(`nonce is not a valid nonce token ([A-Za-z0-9_-]{22,64}; >=128 bits of CSPRNG entropy)`);return nonce3}function assertIdToken(v,what="id"){if(!ID.test(v))throw new Error(`${what} "${v}" is not a valid id token ([A-Za-z0-9_-]{1,64})`);return v}function assertPoolToken(pool){if(!COMMAND.test(pool))throw new Error(`pool "${pool}" is not a valid pool token ([a-z0-9-]{1,32})`);return pool}function assertBoundedOwner(v,what){assertValidOwnerToken(v);if(v.length>64)throw new Error(`${what} "${v}" exceeds 64 characters`);return v}function assertSized(subject){if(new TextEncoder().encode(subject).length>MAX_EP_SUBJECT_BYTES)throw new Error(`subject exceeds ${MAX_EP_SUBJECT_BYTES} bytes: ${subject.slice(0,80)}\u2026`);return subject}var EP_AUTHZ_MODES=Object.freeze(["self","owner","any","child","ledger","handle","exact"]);var AUTHZ_SET=new Set(EP_AUTHZ_MODES);function isEpAuthzMode(m){return AUTHZ_SET.has(m)}var TARGET_ARITY={self:0,owner:1,any:1,child:1,ledger:1,handle:3,exact:3};function targetTokens(target2){if(target2.mode==="self")return["self"];if(target2.mode==="handle"||target2.mode==="exact")return[target2.mode,assertBoundedOwner(target2.tOwner,"target owner"),assertBoundedOwner(target2.tActor,"target actor"),assertLifecycleToken(target2.tUid,"target lifecycleUid")];return[target2.mode,assertBoundedOwner(target2.tOwner,"target owner")]}function callerTokens(caller){return[assertBoundedOwner(caller.owner,"caller owner"),assertBoundedOwner(caller.actor,"caller actor"),assertLifecycleToken(caller.uid,"caller lifecycleUid")]}function epGoalProgressGrantRow(space2,endpoint,caller){return`${spacePrefix(space2)}.epe.${endpointToken(endpoint)}.*.*.goal.${callerTokens(caller).join(".")}.>`}function isIssuedCaller(caller){return typeof caller.generation==="string"}function callerRailTokens(caller){return isIssuedCaller(caller)?[...callerTokens(caller),assertGeneration(caller.generation,"caller generation")]:callerTokens(caller)}function epPlaneTokens(caller){return isIssuedCaller(caller)?["ep",EP_RAIL_V1]:["ep"]}var EP_RAIL_V1="v1";function requestHead(space2,plane,route,endpoint,command){const parts=[spacePrefix(space2),...plane,route.mode,endpointToken(endpoint)];if(route.mode==="inst")parts.push(route.instanceId);parts.push(assertCommandToken(command));return parts}function epRequestSubject(space2,req){const route=req.route.mode==="inst"?{mode:"inst",instanceId:assertLifecycleToken(req.route.instanceId,"instanceId")}:req.route;const parts=requestHead(space2,epPlaneTokens(req.caller),route,req.endpoint,req.command);if(req.target)parts.push(...targetTokens(req.target));parts.push(...callerRailTokens(req.caller),assertNonce(req.nonce));return assertSized(parts.join("."))}function epCallerReplyFilter(space2,caller){return`${spacePrefix(space2)}.${epPlaneTokens(caller).join(".")}.reply.*.*.*.${callerRailTokens(caller).join(".")}.*`}function epcSubject(space2,digestHex){if(!DIGEST_HEX.test(digestHex))throw new Error(`contract digest "${digestHex}" is not 64 lowercase hex chars`);return`${spacePrefix(space2)}.epc.${digestHex}`}function parseTail(parts,i,withNonce,issued=false){let target2=null;const disc=parts[i];if(disc!==void 0&&AUTHZ_SET.has(disc)){const mode=disc;const arity=TARGET_ARITY[mode];const t=parts.slice(i+1,i+1+arity);if(t.length!==arity)return null;target2=mode==="self"?{mode}:mode==="handle"||mode==="exact"?{mode,tOwner:t[0],tActor:t[1],tUid:t[2]}:{mode,tOwner:t[0]};i+=1+arity}const want=i+3+(issued?1:0)+(withNonce?1:0);if(parts.length!==want)return null;let caller={owner:parts[i],actor:parts[i+1],uid:parts[i+2]};if(issued){const generation=parts[i+3];try{assertGeneration(generation)}catch{return null}caller={...caller,generation};i+=1}return withNonce?{target:target2,caller,nonce:parts[i+3]}:{target:target2,caller}}function parseEpoch(tok){if(!EPOCH.test(tok))return null;const n=Number(tok);return Number.isSafeInteger(n)?n:null}function parseEpSubject(subject){if(new TextEncoder().encode(subject).length>MAX_EP_SUBJECT_BYTES)return null;const parts=subject.split(".");if(parts[0]!==ROOT||parts.length<4)return null;const plane=parts[2];if(plane==="ep"){const issued=parts[3]===EP_RAIL_V1;const o=issued?1:0;const route=parts[3+o];const rail=issued?{rail:EP_RAIL_V1}:{};if(route==="one"||route==="all"){if(parts.length<10+o)return null;const tail=parseTail(parts,6+o,true,issued);if(!tail)return null;return{plane:"request",...rail,route,endpoint:endpointNameOf(parts[4+o]),command:parts[5+o],target:tail.target,caller:tail.caller,nonce:tail.nonce}}if(route==="inst"){if(parts.length<11+o)return null;const tail=parseTail(parts,7+o,true,issued);if(!tail)return null;return{plane:"request",...rail,route,endpoint:endpointNameOf(parts[4+o]),instanceId:parts[5+o],command:parts[6+o],target:tail.target,caller:tail.caller,nonce:tail.nonce}}if(route==="reply"){if(parts.length!==11+2*o)return null;const epoch=parseEpoch(parts[6+o]);if(epoch===null)return null;const triple={owner:parts[7+o],actor:parts[8+o],uid:parts[9+o]};if(!issued)return{plane:"reply",endpoint:endpointNameOf(parts[4]),instanceId:parts[5],epoch,caller:triple,nonce:parts[10]};const generation=parts[11];try{assertGeneration(generation)}catch{return null}return{plane:"reply",rail:EP_RAIL_V1,endpoint:endpointNameOf(parts[5]),instanceId:parts[6],epoch,caller:{...triple,generation},nonce:parts[12]}}return null}if(plane==="epe"){if(parts.length<7)return null;const epoch=parseEpoch(parts[5]);if(epoch===null)return null;return{plane:"event",endpoint:endpointNameOf(parts[3]),instanceId:parts[4],epoch,topic:parts.slice(6)}}if(plane==="epf"){if(parts.length<5)return null;return{plane:"fact",endpoint:endpointNameOf(parts[3]),topic:parts.slice(4)}}if(plane==="epj"){if(parts.length<8)return null;const tail=parseTail(parts,5,false);if(!tail)return null;return{plane:"journal",endpoint:endpointNameOf(parts[3]),command:parts[4],target:tail.target,caller:tail.caller}}if(plane==="ept"){if(parts.length!==8)return null;const epoch=parseEpoch(parts[5]);const phase=parts[7];if(epoch===null||phase!=="schedule"&&phase!=="armed"&&phase!=="fire")return null;return{plane:"timer",endpoint:endpointNameOf(parts[3]),instanceId:parts[4],epoch,timerId:parts[6],phase}}if(plane==="epr"){if(parts.length<7)return null;const epoch=parseEpoch(parts[5]);if(epoch===null)return null;return{plane:"record",endpoint:endpointNameOf(parts[3]),instanceId:parts[4],epoch,kind:parts[6],qualifier:parts.slice(7)}}if(plane==="epc"){if(parts.length!==4||!DIGEST_HEX.test(parts[3]))return null;return{plane:"contract",digestHex:parts[3]}}if(plane==="epw"){if(parts.length!==9)return null;return{plane:"work",endpoint:endpointNameOf(parts[3]),pool:parts[4],acceptance:{owner:parts[5],actor:parts[6],uid:parts[7],id:parts[8]}}}if(plane==="eps"){if(parts.length!==7)return null;const epoch=parseEpoch(parts[5]);const dir=parts[6];if(epoch===null||dir!=="in"&&dir!=="out")return null;return{plane:"session",endpoint:endpointNameOf(parts[3]),sessionId:parts[4],epoch,dir}}return null}var import_node_crypto4=require("node:crypto");var import_json_canonicalize=__toESM(require_index_umd(),1);var DIGEST_PREFIX="sha256:";var DIGEST_RE=/^sha256:[0-9a-f]{64}$/;function isContractDigest(v){return typeof v==="string"&&DIGEST_RE.test(v)}function isWellFormedUnicode(s){return!hasLoneSurrogate(s)}function hasLoneSurrogate(s){for(let i=0;i<s.length;i++){const c=s.charCodeAt(i);if(c>=55296&&c<=56319){const n=s.charCodeAt(i+1);if(!(n>=56320&&n<=57343))return true;i++}else if(c>=56320&&c<=57343){return true}}return false}function interchangeableCopy(v,path){if(v===null)return null;switch(typeof v){case"string":if(hasLoneSurrogate(v))throw new Error(`canonicalJson: lone surrogate in string at ${path} (I-JSON violation)`);return v;case"number":if(!Number.isFinite(v))throw new Error(`canonicalJson: non-finite number at ${path}`);return v;case"boolean":return v;case"undefined":throw new Error(`canonicalJson: undefined at ${path} (strict mode never coerces to null)`);case"object":{if(Array.isArray(v)){if(Object.getPrototypeOf(v)!==Array.prototype)throw new Error(`canonicalJson: non-ordinary array at ${path} (a subclassed/exotic array canonicalizes through projections)`);const length=Object.getOwnPropertyDescriptor(v,"length")?.value;if(typeof length!=="number"||!Number.isInteger(length)||length<0)throw new Error(`canonicalJson: invalid array length at ${path} (refusing the projection)`);for(const k of Reflect.ownKeys(v)){if(typeof k!=="string")throw new Error(`canonicalJson: symbol-keyed own property on array at ${path} (invisible to canonicalization; refusing the projection)`);if(k==="length")continue;if(!/^(0|[1-9][0-9]*)$/.test(k)||Number(k)>=length)throw new Error(`canonicalJson: non-index own property "${k}" on array at ${path} (invisible to canonicalization; refusing the projection)`)}const copy2=[];for(let i=0;i<length;i++){const d=Object.getOwnPropertyDescriptor(v,i);if(d===void 0)throw new Error(`canonicalJson: hole at ${path}[${i}] (a hole would be coerced to null; refusing the projection)`);if(!d.enumerable||d.get!==void 0||d.set!==void 0)throw new Error(`canonicalJson: non-enumerable or accessor element at ${path}[${i}] (refusing the projection)`);copy2.push(interchangeableCopy(d.value,`${path}[${i}]`))}return copy2}const proto=Object.getPrototypeOf(v);if(proto!==Object.prototype&&proto!==null)throw new Error(`canonicalJson: non-plain object at ${path} (a class/exotic instance canonicalizes through projections like toJSON; only plain data objects are interchangeable)`);const copy=Object.create(null);for(const k of Reflect.ownKeys(v)){if(typeof k!=="string")throw new Error(`canonicalJson: symbol-keyed own property at ${path} (invisible to canonicalization; refusing the projection)`);if(hasLoneSurrogate(k))throw new Error(`canonicalJson: lone surrogate in key at ${path}.${k}`);const d=Object.getOwnPropertyDescriptor(v,k);if(!d.enumerable)throw new Error(`canonicalJson: non-enumerable own property "${k}" at ${path} (invisible to canonicalization; refusing the projection)`);if(d.get!==void 0||d.set!==void 0)throw new Error(`canonicalJson: accessor property "${k}" at ${path} (a getter is code, not data; refusing the projection)`);copy[k]=interchangeableCopy(d.value,`${path}.${k}`)}return copy}default:throw new Error(`canonicalJson: unsupported ${typeof v} at ${path}`)}}function canonicalJson(value){return(0,import_json_canonicalize.canonicalizeEx)(interchangeableCopy(value,"$"),{undefinedInArrayToNull:false})}function contractDigest(value){return DIGEST_PREFIX+(0,import_node_crypto4.createHash)("sha256").update(canonicalJson(value),"utf8").digest("hex")}var EP_ERROR_CODES=Object.freeze(["bad-request","unsupported-version","op-mismatch","class-mismatch","target-mismatch","sender-mismatch","unauthenticated","permission-denied","not-found","already-exists","conflict","contract-mismatch","contract-invalid","failed-precondition","deadline-exceeded","cancelled","expired","unavailable","unimplemented","resource-exhausted","internal"]);var EP_UNBOUND_RESPONDER="ai.cotal.ep.unbound-responder";function respondedButUnbound(e){return e instanceof EpEnvelopeError&&(e.details??[]).some(d=>d.kind===EP_UNBOUND_RESPONDER)}var EP_UNANSWERED="ai.cotal.ep.unanswered";function unansweredRequest(e){return e instanceof EpEnvelopeError&&(e.details??[]).some(d=>d.kind===EP_UNANSWERED)}var EP_UNDECLARED_ARG="ai.cotal.ep.undeclared-arg";var EP_BIND_REFUSED="ai.cotal.ep.bind-refused";function bindRefusalMarked(e){return(e?.details??[]).some(d=>d.kind===EP_BIND_REFUSED)}function replyRefusedBeforeEffect(e){if(!bindRefusalMarked(e))return false;return e?.outcome==="not-executed"}var EP_TARGET_UNMAPPED="ai.cotal.ep.target-unmapped";function replyTargetUnmapped(e){return e?.outcome==="not-executed"&&(e.details??[]).some(d=>d.kind===EP_TARGET_UNMAPPED)}var EP_LIFECYCLE_BLOCKED="ai.cotal.ep.lifecycle-blocked";function detailsOf(source){if(source instanceof EpEnvelopeError)return source.details;if(source&&typeof source==="object"&&Array.isArray(source.details))return source.details;return void 0}function lifecycleBlockedFrom(source){return detailsOf(source)?.find(d=>d.kind===EP_LIFECYCLE_BLOCKED)}function renderLifecycleBlocked(message,source){const d=lifecycleBlockedFrom(source);if(!d)return message;const parts=[`blockedOp=${d.blockedOp}`];for(const k of["headState","gateState","opId","remedy"]){const v=d[k];if(typeof v==="string"&&v.length>0)parts.push(`${k}=${v}`)}const suffix=`[lifecycle ${parts.join(" ")}]`;return message.includes(suffix)?message:`${message} ${suffix}`}var EpEnvelopeError=class extends Error{code;details;outcome;constructor(code,message,details,outcome){super(message);this.code=code;this.details=details;this.outcome=outcome;this.name="EpEnvelopeError"}toEpError(){return{code:this.code,message:this.message,...this.details?{details:this.details}:{},...this.outcome?{outcome:this.outcome}:{}}}};var import_jetstream2=__toESM(require_mod4(),1);var import_transport_node2=__toESM(require_transport_node(),1);var import_kv=__toESM(require_mod6(),1);var SCHEMA_PROFILE=Object.freeze({maxDocumentBytes:256*1024,maxClosureBytes:1024*1024,maxDepth:32,maxRefChain:32,compileBudgetMs:100,maxPatternChars:256,validateBudgetMs:10,compiledCacheEntries:256});var EP_ENVELOPE_V=1;var EP_ERROR_SET=new Set(EP_ERROR_CODES);var UTF8=new TextEncoder;var utf8Bytes=s=>UTF8.encode(s).length;var LABEL="[a-z0-9]([a-z0-9-]*[a-z0-9])?";var EXTENSION_CODE=new RegExp(`^${LABEL}(\\.${LABEL}){2,}$`);function isEpErrorCode(code){if(typeof code!=="string"||utf8Bytes(code)>64)return false;return EP_ERROR_SET.has(code)||EXTENSION_CODE.test(code)}function fail(code,message,outcome){throw new EpEnvelopeError(code,message,void 0,outcome)}function controlReplyFrom(reply){if(reply.ok)return{ok:true,...reply.data!==void 0?{data:reply.data}:{}};const{error:error51}=reply;return{ok:false,error:renderLifecycleBlocked(error51.message,error51),code:error51.code,...reply.data!==void 0?{data:reply.data}:{},...error51.details?{details:error51.details}:{},...error51.outcome!==void 0?{outcome:error51.outcome}:{}}}function controlReplyFromThrown(e,message){return{ok:false,error:renderLifecycleBlocked(message,e),code:e.code,...e.details?{details:e.details}:{},...e.outcome!==void 0?{outcome:e.outcome}:{}}}function asRecord(v,what){if(v===null||typeof v!=="object"||Array.isArray(v))fail("bad-request",`${what} is not a JSON object`);return v}function asString(v,what){if(typeof v!=="string"||v.length===0)fail("bad-request",`${what} is not a non-empty string`);return v}function grammar(fn){try{return fn()}catch(e){fail("bad-request",e.message)}}function assertVersion(o,what){if(o.v!==EP_ENVELOPE_V)fail("unsupported-version",`${what} envelope version ${JSON.stringify(o.v)} is not ${EP_ENVELOPE_V}`)}function pickError(v){const e=asRecord(v,"error");const code=asString(e.code,"error.code");if(!isEpErrorCode(code))fail("bad-request",`error.code ${JSON.stringify(code)} is neither a catalog token nor a reverse-DNS extension token within 64 bytes`);const message=typeof e.message==="string"?e.message:fail("bad-request","error.message is not a string");let details;if(e.details!==void 0){if(!Array.isArray(e.details))fail("bad-request","error.details is not an array");details=e.details.map((d,i)=>{const o=asRecord(d,`error.details[${i}]`);const kind=asString(o.kind,`error.details[${i}].kind`);if(!EXTENSION_CODE.test(kind))fail("bad-request",`error.details[${i}].kind "${kind}" is not reverse-DNS namespaced`);return o})}let outcome;if(e.outcome!==void 0){if(e.outcome!=="executed"&&e.outcome!=="not-executed"&&e.outcome!=="unknown")fail("bad-request",`error.outcome ${JSON.stringify(e.outcome)} is not one of executed, not-executed, unknown (SPEC 13.3)`);outcome=e.outcome}return{code,message,...details?{details}:{},...outcome?{outcome}:{}}}function parseEndpointReply(raw){const o=asRecord(raw,"reply");assertVersion(o,"reply");const id2=grammar(()=>assertIdToken(asString(o.id,"id"),"id"));if(typeof o.ok!=="boolean")fail("bad-request","ok is not a boolean");if(o.ok&&o.error!==void 0)fail("bad-request","an ok reply must not carry an error");if(!o.ok&&o.data!==void 0)fail("bad-request","a failed reply must not carry data");const reply=o.ok?{v:EP_ENVELOPE_V,id:id2,ok:true,...o.data!==void 0?{data:o.data}:{}}:{v:EP_ENVELOPE_V,id:id2,ok:false,error:pickError(o.error)};const receipt2=o.receipt===void 0?void 0:asString(o.receipt,"receipt");return{...reply,...receipt2!==void 0?{receipt:receipt2}:{}}}var cpuNow=()=>typeof process==="undefined"?void 0:process.cpuUsage();function reportValidateBudget(what,startedCpu,startedMs){if(startedCpu===void 0)return;const cpu=process.cpuUsage(startedCpu);const cpuMs=Math.round((cpu.user+cpu.system)/1e3);if(cpuMs<=SCHEMA_PROFILE.validateBudgetMs)return;console.error(`! schema: ${what} validation took ~${cpuMs}ms of process CPU (\xA713.8 reference budget ${SCHEMA_PROFILE.validateBudgetMs}ms; ${Date.now()-startedMs}ms elapsed). Approximate - process-wide CPU includes JIT/Worker threads. Not a refusal - and note that refusing HERE would not have helped: this fires after validate() completed, so the cost is already paid. Validation cost on this path is bounded by nothing pre-emptively; a byte/item bound before validate is owed.`)}function firstErrorDetail(first){if(!first)return"";const extra=typeof first.params?.additionalProperty==="string"?`: ${JSON.stringify(first.params.additionalProperty)}`:"";return`: ${first.instancePath||"/"} ${first.message??""}${extra}`}function assertArgsValid(validate2,args){const value=args===void 0?null:args;const startedCpu=cpuNow();const started=Date.now();const okValid=validate2(value);reportValidateBudget("args",startedCpu,started);if(!okValid){const first=validate2.errors?.[0];fail("bad-request",`args do not validate against the input schema${firstErrorDetail(first)}`,"not-executed")}return value}function assertOutputValid(validate2,data){const value=data===void 0?null:data;const startedCpu=cpuNow();const started=Date.now();const okValid=validate2(value);reportValidateBudget("output",startedCpu,started);if(!okValid){const first=validate2.errors?.[0];fail("internal",`output does not validate against the pinned output schema; an invalid reply is a responder bug, never success (SPEC 13.7)${firstErrorDetail(first)}`)}}function recordsBucket(space2){return`cotal_records_${token(space2)}`}var qEndpoint={name:"endpoint",assert:v=>endpointToken(v)};var qOwner=name=>({name,assert:v=>assertBoundedOwner(v,name)});var qUid=name=>({name,assert:v=>assertLifecycleToken(v,name)});var qId=name=>({name,assert:v=>assertIdToken(v,name)});var LIFECYCLE_HEAD={kind:"lifecycle",qualifiers:[qOwner("owner"),qOwner("actor")],split:false,writers:{spec:"minting-manager-commit",status:"minting-manager-commit"},mediation:"mediated"};var UID_RESERVATION={kind:"uid",qualifiers:[qUid("lifecycleUid")],split:false,writers:{spec:"minting-authority",status:"minting-authority"},mediation:"mediated"};var OBLIGATION_EP_SENTINEL="ep";var OBLIGATION={kind:"oblig",qualifiers:[{name:"targetUid",assert:v=>v===OBLIGATION_EP_SENTINEL?v:assertLifecycleToken(v,"targetUid")},qEndpoint,qOwner("cOwner"),qOwner("cActor"),qUid("cUid"),qId("id")],split:false,writers:{spec:"admission-mediator",status:"admission-mediator"},mediation:"mediated"};var POLICY_VERSION={kind:"policy",qualifiers:[qEndpoint,{name:"digestHex",assert:v=>{if(!/^[0-9a-f]{64}$/.test(v))throw new Error(`policy digest ${JSON.stringify(v)} is not 64 lowercase hex chars (SPEC 13.7)`);return v}}],split:false,writers:{spec:"provisioner-registration",status:"provisioner-registration"},mediation:"mediated"};var RETIREMENT_FRONTIER={kind:"frontier",qualifiers:[qUid("lifecycleUid")],split:false,writers:{spec:"minting-authority",status:"minting-authority"},mediation:"mediated"};var GOVERN_HEAD={kind:"govern",qualifiers:[qEndpoint],split:false,writers:{spec:"provisioner-registration",status:"provisioner-registration"},mediation:"mediated"};var RECORD_KINDS={svc:{kind:"svc",qualifiers:[qEndpoint,qUid("instanceId")],split:true,writers:{spec:"provisioner-registration",status:"instance-commit-epoch-fenced"},mediation:"mediated"},signer:{kind:"signer",qualifiers:[qId("keyId")],split:true,writers:{spec:"operator-registry",status:"operator-registry"},mediation:"mediated"},handle:{kind:"handle",qualifiers:[qId("issuerKeyId"),qId("id")],split:true,writers:{spec:"issuer-create-only",status:"issuer-or-operator-monotonic"},mediation:"mediated"},contracts:{kind:"contracts",qualifiers:[qEndpoint],split:true,writers:{spec:"instance",status:"instance"},mediation:"direct"},goal:{kind:"goal",qualifiers:[qEndpoint,qOwner("cOwner"),qOwner("cActor"),qUid("cUid"),qId("goalId")],split:true,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},goalidx:{kind:"goalidx",qualifiers:[qEndpoint,qOwner("cOwner"),qOwner("cActor"),qUid("cUid"),qId("goalId")],split:false,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},goaleff:{kind:"goaleff",qualifiers:[qEndpoint,qOwner("cOwner"),qOwner("cActor"),qUid("cUid"),qId("goalId"),qId("gen")],split:false,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},epname:{kind:"epname",qualifiers:[qEndpoint,qId("nameToken")],split:false,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},epmig:{kind:"epmig",qualifiers:[qEndpoint],split:false,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},cp:{kind:"cp",qualifiers:[qEndpoint,qId("token")],split:true,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},lease:{kind:"lease",qualifiers:[qEndpoint,{name:"pool",assert:assertPoolToken},qOwner("cOwner"),qOwner("cActor"),qUid("cUid"),qId("id")],split:true,writers:{spec:"pool-owner-lease-command",status:"pool-owner-lease-command"},mediation:"mediated"},run:{kind:"run",qualifiers:[qEndpoint,qId("runId")],split:true,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},answer:{kind:"answer",qualifiers:[qEndpoint,qId("token"),qId("answerId")],split:false,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},notice:{kind:"notice",qualifiers:[qEndpoint,qId("runId"),qId("addresseeId"),qId("noticeId")],split:true,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},program:{kind:"program",qualifiers:[qEndpoint,qId("runId")],split:false,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},migration:{kind:"migration",qualifiers:[qEndpoint,qId("runId"),qId("migrationId")],split:true,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},lifecycle:{kind:"lifecycle",qualifiers:[qOwner("owner"),qOwner("actor"),qUid("lifecycleUid")],split:true,writers:{spec:"minting-manager-commit",status:"minting-manager-commit"},mediation:"mediated"}};var AUTHORITY_KIND_DEFS=[LIFECYCLE_HEAD,UID_RESERVATION,GOVERN_HEAD,OBLIGATION,POLICY_VERSION,RETIREMENT_FRONTIER];function freezeDef(def){for(const q of def.qualifiers)Object.freeze(q);Object.freeze(def.qualifiers);Object.freeze(def.writers);return Object.freeze(def)}var registry2=new Map;for(const def of[...Object.values(RECORD_KINDS),...AUTHORITY_KIND_DEFS]){freezeDef(def);const list2=registry2.get(def.kind)??[];list2.push(def);registry2.set(def.kind,list2)}Object.freeze(AUTHORITY_KIND_DEFS);Object.freeze(RECORD_KINDS);var AUTHORITY_DEF_SET=new Set(AUTHORITY_KIND_DEFS);function isCasLoss(e){const code=e?.code;return code===10071||code===10164}var import_transport_node=__toESM(require_transport_node(),1);var IDEMPOTENCY_HORIZON_MS_DEFAULT=24*60*60*1e3;var RESULT_RETENTION_MS_DEFAULT=24*60*60*1e3;var RECEIPT_RETENTION_MS_DEFAULT=90*24*60*60*1e3;var import_node_crypto5=require("node:crypto");var import_jetstream=__toESM(require_mod4(),1);var dec=new TextDecoder("utf-8",{fatal:true});function assertIssuedSpace(space2){if(typeof space2!=="string"||space2.length===0||token(space2)!==space2)throw new Error("issued space must be a nonempty canonical subject token ([A-Za-z0-9_-])")}function refSnapshot(value){closed(value,["space","owner","actor","uid","generation"],"issued reference");assertIssuedSpace(value.space);callerTokens(value);assertGeneration(value.generation);return Object.freeze({space:value.space,owner:value.owner,actor:value.actor,uid:value.uid,generation:value.generation})}function closed(value,keys,label){if(value===null||typeof value!=="object"||Array.isArray(value)||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null)throw new Error(`${label} must be a plain record`);for(const key of Reflect.ownKeys(value)){if(typeof key!=="string"||!keys.includes(key))throw new Error(`${label} carries an unsupported field ${String(key)}`);if(!Object.hasOwn(Object.getOwnPropertyDescriptor(value,key),"value"))throw new Error(`${label} cannot carry accessors`)}return value}function acceptedBucket(space2){return`cotal_accepted_${token(space2)}`}function acceptedKey(acceptedToken){return`accepted.v1.${assertGeneration(acceptedToken,"accepted token")}`}async function readAcceptedRow(nc,space2,acceptedToken,timeoutMs=3e3){const bucket=acceptedBucket(space2);const response=await nc.request(`$JS.API.DIRECT.GET.KV_${bucket}.$KV.${bucket}.${acceptedKey(acceptedToken)}`,new Uint8Array(0),{timeout:timeoutMs});const status2=response.headers?.get("Status");if(status2)throw new EpEnvelopeError("permission-denied",`no accepted row for this token (${status2}); the connection holds no issued authority (SPEC 13.15)`);const row=closed(JSON.parse(dec.decode(response.data)),["version","ref"],"accepted row");if(row.version!==1)throw new Error("unsupported accepted-row version");const ref=refSnapshot(row.ref);if(ref.space!==space2)throw new EpEnvelopeError("permission-denied","the accepted row names a foreign space");return ref}async function issuedCallerOfToken(nc,space2,acceptedToken,expected){const ref=await readAcceptedRow(nc,space2,acceptedToken);if(ref.owner!==expected.owner||ref.actor!==expected.actor||ref.uid!==expected.uid)throw new EpEnvelopeError("permission-denied",`this connection's accepted row names ${ref.owner}.${ref.actor}/${ref.uid}, not the caller ${expected.owner}.${expected.actor}/${expected.uid}; refused (SPEC 13.15)`);return{owner:ref.owner,actor:ref.actor,uid:ref.uid,generation:ref.generation}}var STATIC_GENERATION_HORIZON_SEC=30*24*60*60;function subjectToken(value,pattern){if(typeof value!=="string"||value.length===0||/\s/u.test(value)||[...value].some(ch=>ch.charCodeAt(0)<32||ch.charCodeAt(0)===127))throw new Error("a subject must be nonempty without whitespace or control characters; queue-qualified forms are not a ceiling entry");const parts=value.split(".");for(let i=0;i<parts.length;i++){const part=parts[i];if(!part||part.includes("*")&&(!pattern||part!=="*")||part.includes(">")&&(!pattern||part!==">"||i!==parts.length-1))throw new Error(`subject "${value}" has an invalid token or wildcard`)}return value}function patterns(value){if(!Array.isArray(value))throw new Error("subject patterns must be an explicit array");return Object.freeze(value.map(entry=>subjectToken(entry,true)))}function permission(allow,deny){return Object.freeze({allow:Object.freeze(allow),deny})}function readIssuedSubjectPermission(value){const raw=closed(value,["allow","deny"],"subject permission");const allow=closed(raw.allow,["mode","patterns"],"subject allow");const deny=patterns(raw.deny);if(allow.mode==="all"||allow.mode==="none"){if(Object.hasOwn(allow,"patterns"))throw new Error("only patterns mode carries a patterns field");return permission({mode:allow.mode},deny)}if(allow.mode!=="patterns")throw new Error("unsupported subject allow mode");const listed=patterns(allow.patterns);if(listed.length===0)throw new Error("patterns mode requires a nonempty list");return permission({mode:"patterns",patterns:listed},deny)}function importNativeSubjectPermissions(value){const raw=closed(value,["pub","sub"],"native permissions");const direction=v=>{if(v===void 0)return permission({mode:"all"},Object.freeze([]));const r=closed(v,["allow","deny"],"native subject permission");const allow=Object.hasOwn(r,"allow")?patterns(r.allow):Object.freeze([]);const deny=Object.hasOwn(r,"deny")?patterns(r.deny):Object.freeze([]);return permission(allow.length?{mode:"patterns",patterns:allow}:{mode:"all"},deny)};for(const key of["pub","sub"])if(Object.hasOwn(raw,key)&&raw[key]===void 0)throw new Error("an explicit native direction must not be undefined");return Object.freeze({publish:direction(raw.pub),subscribe:direction(raw.sub)})}function issuedPermitsSubject(value,concrete){const parsed=readIssuedSubjectPermission(value);subjectToken(concrete,false);if(parsed.deny.some(pattern=>subjectMatches(pattern,concrete)))return false;if(parsed.allow.mode==="none")return false;return parsed.allow.mode==="all"||parsed.allow.patterns.some(pattern=>subjectMatches(pattern,concrete))}var AUTHORITY_STORE_IMMUTABLE_FLAGS=Object.freeze({allow_rollup_hdrs:false,deny_delete:true,deny_purge:true});var WRITE_ONCE_PER_KEY=Object.freeze({max_msgs_per_subject:1,discard:import_jetstream.DiscardPolicy.New,discard_new_per_subject:true});var APPEND_ONLY_PER_KEY=Object.freeze({max_msgs_per_subject:-1});var ROW_TTL_RETENTION=Object.freeze({allow_msg_ttl:true});var enc=new TextEncoder;function connectionAcceptedToken(connId){if(typeof connId!=="string"||connId.length===0)throw new Error("connectionAcceptedToken: a connection nonce is required");return(0,import_node_crypto5.createHash)("sha256").update(`cotal.accepted.v1\0${connId}`).digest("hex").slice(0,32)}function listingAcceptedToken(connId,horizon){if(typeof connId!=="string"||connId.length===0)throw new Error("listingAcceptedToken: a connection id is required");if(!Number.isSafeInteger(horizon)||horizon<=0)throw new Error("listingAcceptedToken: the horizon must be a positive unix-seconds integer");return(0,import_node_crypto5.createHash)("sha256").update(`cotal.listing.v1\0${connId}\0${horizon}`).digest("hex").slice(0,32)}async function issuedUserCaller(nc,space2,connId,expected){return issuedCallerOfToken(nc,space2,connectionAcceptedToken(connId),expected)}function admissionBucket(space2){return`cotal_admission_${token(space2)}`}var enc2=new TextEncoder;var dec2=new TextDecoder("utf-8",{fatal:true});function admissionStoreDefinition(space2){return{bucket:admissionBucket(space2),createOptions:{allow_direct:false},hardenAfterCreate:{...AUTHORITY_STORE_IMMUTABLE_FLAGS,...WRITE_ONCE_PER_KEY}}}function epcStreamName(space2){return`EPC_${token(space2)}`}function wfjStreamName(space2){return`WFJ_${token(space2)}`}function epAuthBucket(space2){return`cotal_auth_${token(space2)}`}var EP_SUBMISSION_MAX_AGE_MS=24*60*60*1e3;var EP_EVENT_MAX_AGE_MS=24*60*60*1e3;var EP_INGRESS_MAX_AGE_MS=24*60*60*1e3;var EP_TIMER_MAX_AGE_MS=31*24*60*60*1e3;var EP_AUTH_MARKER_TTL_MS=60*60*1e3;function endpointAuthorityStoreDefinitions(space2){return{records:{bucket:recordsBucket(space2),createOptions:{allow_direct:true},hardenAfterCreate:AUTHORITY_STORE_IMMUTABLE_FLAGS},auth:{bucket:epAuthBucket(space2),createOptions:{allow_direct:false,markerTTL:EP_AUTH_MARKER_TTL_MS}}}}var AUTHORITY_HEAD_ARITY=new Map(AUTHORITY_KIND_DEFS.map(d=>[d.kind,1+d.qualifiers.length]));function recordsKvStreamName(space2){return`KV_${recordsBucket(space2)}`}var BASELINE_DELIVERY_ENDPOINT="delivery";var BASELINE_DELIVERY_COMMANDS=Object.freeze(["join","leave","list"]);var BASELINE_LIFECYCLE_ENDPOINT="manager";var BASELINE_SELF_LIFECYCLE_COMMANDS=Object.freeze(["stop","turn-participate","turn-pending","turn-yield","turn-unconfirmed","run-answer"]);var SPAWN_CREATE_COMMANDS=Object.freeze(["spawn","resolve-agent"]);var SPAWN_OWNER_LIFECYCLE_COMMANDS=Object.freeze(["despawn","attach"]);var OPERATOR_SEAT_COMMANDS=Object.freeze(["input","turn"]);var SPAWN_SERVICE_COMMANDS=Object.freeze(["define-persona","remove-persona","inspect","list-personas","show-persona","goal-result"]);var RUN_WRITE_COMMANDS=Object.freeze(["run-start","run-resume","run-start-keyed","run-submission-status","run-cancel"]);var RUN_READ_COMMANDS=Object.freeze(["run-status","run-ps"]);var CHAT_SESSION_COMMANDS=Object.freeze(["chat-session-open","chat-session-retire"]);var MANAGER_READ_COMMANDS=Object.freeze(["status","ps","slots","inspect","models","list-personas","show-persona","goal-result"]);var MANAGER_ADMIN_COMMANDS=Object.freeze(["purge","launch","resume-preserved","commit-resume","finalize-resume","prepare-preservation","commit-preservation","abort-preservation","transcript-receive"]);var GOAL_BEARING_COMMANDS=Object.freeze(["spawn","launch"]);var GOAL_BEARING_SET=new Set(GOAL_BEARING_COMMANDS);var REPEAT_SAFE_COMMANDS=Object.freeze({[BASELINE_LIFECYCLE_ENDPOINT]:Object.freeze(["status","ps","slots","inspect","list-personas","show-persona","run-status","run-ps","goal-result"]),[BASELINE_DELIVERY_ENDPOINT]:Object.freeze(["list"])});var REPEAT_SAFE_ANY_ENDPOINT="describe";var REPEAT_SAFE_SNAP=new Map(Object.entries(REPEAT_SAFE_COMMANDS).map(([endpoint,commands])=>[endpoint,new Set(commands)]));function isRepeatSafeCommand(endpoint,command){if(command===REPEAT_SAFE_ANY_ENDPOINT)return true;return REPEAT_SAFE_SNAP.get(endpoint)?.has(command)===true}var DELIVERY_COMMANDS_SNAP=Object.freeze([...BASELINE_DELIVERY_COMMANDS]);var SELF_LIFECYCLE_SNAP=Object.freeze([...BASELINE_SELF_LIFECYCLE_COMMANDS]);var SPAWN_CREATE_SNAP=Object.freeze([...SPAWN_CREATE_COMMANDS]);var SPAWN_OWNER_SNAP=Object.freeze([...SPAWN_OWNER_LIFECYCLE_COMMANDS]);var OPERATOR_SEAT_SNAP=Object.freeze([...OPERATOR_SEAT_COMMANDS]);var SPAWN_SERVICE_SNAP=Object.freeze([...SPAWN_SERVICE_COMMANDS]);var RUN_WRITE_SNAP=Object.freeze([...RUN_WRITE_COMMANDS]);var RUN_READ_SNAP=Object.freeze([...RUN_READ_COMMANDS]);var CHAT_SESSION_SNAP=Object.freeze([...CHAT_SESSION_COMMANDS]);var MANAGER_READ_SNAP=Object.freeze([...MANAGER_READ_COMMANDS]);var MANAGER_ADMIN_SNAP=Object.freeze([...MANAGER_ADMIN_COMMANDS]);var HEX64=/^[0-9a-f]{64}$/;function contractRefToHex(ref){const hex3=ref.startsWith("sha256:")?ref.slice("sha256:".length):ref;if(!HEX64.test(hex3))throw new EpEnvelopeError("contract-invalid",`contract reference ${JSON.stringify(ref)} is not a sha256 digest; a garbled reference never resolves (SPEC 13.7)`);return hex3}var sha256Ref=hex3=>`sha256:${hex3}`;function buildContractClosureManifest(rootRef,memberRefs){const root=sha256Ref(contractRefToHex(rootRef));const members=[...new Set(memberRefs.map(r=>sha256Ref(contractRefToHex(r))))].sort();return{v:1,root,members}}var CONTRACT_CLOSURE_MAX_ARTIFACTS=64;function assertManifestDigest(ref,what){if(typeof ref!=="string"||!isContractDigest(ref))throw new EpEnvelopeError("contract-invalid",`${what} must be exactly "sha256:<64-hex>" (SPEC 13.7); a bare-hex or otherwise-spelled digest gives one closure two identities and never names it`)}function parseClosureManifest(value,what){if(value===null||typeof value!=="object"||Array.isArray(value))throw new EpEnvelopeError("contract-invalid",`${what} is not a manifest object (SPEC 13.7)`);const o=value;for(const k of Object.keys(o))if(!["v","root","members"].includes(k))throw new EpEnvelopeError("contract-invalid",`${what} carries the unknown field "${k}"; the manifest schema is closed (SPEC 13.7)`);if(o.v!==1||typeof o.root!=="string"||!Array.isArray(o.members))throw new EpEnvelopeError("contract-invalid",`${what} is not { v: 1, root, members } (SPEC 13.7)`);assertManifestDigest(o.root,`${what} root`);if(o.members.length>CONTRACT_CLOSURE_MAX_ARTIFACTS)throw new EpEnvelopeError("contract-invalid",`${what} names ${o.members.length} members, above the ${CONTRACT_CLOSURE_MAX_ARTIFACTS}-artifact ceiling (SPEC 13.7)`);for(let i=0;i<o.members.length;i++){const m=o.members[i];assertManifestDigest(m,`${what} member ${i}`);if(i>0&&o.members[i-1]>=m)throw new EpEnvelopeError("contract-invalid",`${what} members are not strictly sorted/deduplicated at index ${i}; a noncanonical manifest never names a closure (SPEC 13.7)`)}return{v:1,root:o.root,members:o.members}}var import__=__toESM(require__(),1);var FULL={neg:true,ranges:[]};var EMPTY={neg:false,ranges:[]};var set2=(...ranges)=>({neg:false,ranges});var single=c=>set2([c,c]);function rangesOverlap(a,b){for(const[al,ah]of a)for(const[bl,bh]of b)if(al<=bh&&bl<=ah)return true;return false}function rangesCover(outer,[lo,hi]){return outer.some(([ol,oh])=>ol<=lo&&hi<=oh)}function intersects(a,b){if(!a.neg&&!b.neg)return rangesOverlap(a.ranges,b.ranges);if(a.neg&&b.neg)return true;const pos=a.neg?b:a;const neg=a.neg?a:b;return!pos.ranges.every(r=>rangesCover(neg.ranges,r))}function union2(a,b){if(!a.neg&&a.ranges.length===0)return b;if(!b.neg&&b.ranges.length===0)return a;if(a.neg||b.neg)return FULL;return{neg:false,ranges:[...a.ranges,...b.ranges]}}var PatternRefused=class extends Error{};var refuse=reason2=>{throw new PatternRefused(reason2)};var Parser=class{src;i=0;constructor(src){this.src=src}peek(){return this.src[this.i]}next(){return this.src[this.i++]}eof(){return this.i>=this.src.length}parse(){const node=this.alternation();if(!this.eof())refuse(`unexpected "${this.peek()}" at ${this.i}`);return node}alternation(){const branches=[this.sequence()];while(this.peek()==="|"){this.next();branches.push(this.sequence())}return branches.length===1?branches[0]:{kind:"alt",branches}}sequence(){const items=[];while(!this.eof()&&this.peek()!=="|"&&this.peek()!==")")items.push(this.quantified());return{kind:"seq",items}}quantified(){let node=this.atom();for(;;){const c=this.peek();let min,max;if(c==="*"){min=0;max=Infinity}else if(c==="+"){min=1;max=Infinity}else if(c==="?"){min=0;max=1}else if(c==="{"){const m=/^\{(\d+)(?:,(\d*))?\}/.exec(this.src.slice(this.i));if(!m)break;min=parseInt(m[1],10);max=m[2]===void 0?min:m[2]===""?Infinity:parseInt(m[2],10);if(max<min)refuse(`quantifier {${min},${max}} is inverted`);this.i+=m[0].length-1}else break;this.next();if(this.peek()==="?")this.next();node={kind:"quant",body:node,min,max}}return node}atom(){const c=this.next();if(c==="("){if(this.peek()==="?"){const ahead=this.src.slice(this.i,this.i+3);if(/^\?(:|<[a-zA-Z_])/.test(ahead)){this.next();if(this.peek()==="<"){while(this.next()!==">"){if(this.eof())refuse("unterminated group name")}}else this.next()}else{refuse("lookarounds and special groups are outside the profile's safe subset")}}const body=this.alternation();if(this.next()!==")")refuse("unterminated group");return body}if(c==="[")return{kind:"atom",set:this.charClass()};if(c===".")return{kind:"atom",set:FULL};if(c==="^")return{kind:"anchor",at:"start"};if(c==="$")return{kind:"anchor",at:"end"};if(c==="\\")return{kind:"atom",set:this.escape(false)};if(c===")"||c===void 0)refuse("unbalanced group");return{kind:"atom",set:single(this.codePoint())}}codePoint(){const cp=this.src.codePointAt(this.i-1);if(cp>65535)this.i++;return cp}charClass(){let neg=false;if(this.peek()==="^"){this.next();neg=true}const ranges=[];let approx=false;while(this.peek()!=="]"){if(this.eof())refuse("unterminated character class");let lo;const c=this.next();if(c==="\\"){if(this.peek()==="b"){this.next();lo=8}else{const s=this.escape(true);if(s.neg||s.ranges.length!==1||s.ranges[0][0]!==s.ranges[0][1]){approx=true;for(const r of s.neg?[[0,1114111]]:s.ranges)ranges.push(r)}else lo=s.ranges[0][0]}}else lo=this.codePoint();if(lo!==void 0){if(this.peek()==="-"&&this.src[this.i+1]!=="]"&&this.src[this.i+1]!==void 0){this.next();const hiC=this.next();const hi=hiC==="\\"?(()=>{const s=this.escape(true);if(s.neg||s.ranges.length!==1){approx=true;return 1114111}return s.ranges[0][0]})():this.codePoint();ranges.push([lo,hi])}else ranges.push([lo,lo])}}this.next();if(neg&&approx)return FULL;return{neg,ranges}}escape(inClass){const c=this.next();if(c===void 0)refuse("dangling escape");if(!inClass&&c>="1"&&c<="9")refuse(`backreference \\${c} is outside the profile's safe subset`);if(c==="k")refuse("named backreferences are outside the profile's safe subset");if(c==="b"||c==="B")return EMPTY;switch(c){case"d":return set2([48,57]);case"D":return{neg:true,ranges:[[48,57]]};case"w":return set2([48,57],[65,90],[95,95],[97,122]);case"W":return{neg:true,ranges:[[48,57],[65,90],[95,95],[97,122]]};case"s":return set2([9,13],[32,32],[160,160],[8232,8233]);case"S":return{neg:true,ranges:[[9,13],[32,32],[160,160],[8232,8233]]};case"n":return single(10);case"r":return single(13);case"t":return single(9);case"f":return single(12);case"v":return single(11);case"0":return single(0);case"x":{const m=/^[0-9a-fA-F]{2}/.exec(this.src.slice(this.i));if(!m)refuse("malformed \\x escape");this.i+=2;return single(parseInt(m[0],16))}case"u":{const braced=/^\{([0-9a-fA-F]{1,6})\}/.exec(this.src.slice(this.i));if(braced){this.i+=braced[0].length;const cp2=parseInt(braced[1],16);if(cp2>=55296&&cp2<=57343)refuse("surrogate code point escapes are outside the safe subset");return single(cp2)}const m=/^[0-9a-fA-F]{4}/.exec(this.src.slice(this.i));if(!m)refuse("malformed \\u escape");this.i+=4;const cp=parseInt(m[0],16);if(cp>=55296&&cp<=57343)refuse("surrogate escapes are outside the safe subset (write the character or \\u{\u2026})");return single(cp)}case"p":case"P":{const m=/^\{[^}]*\}/.exec(this.src.slice(this.i));if(!m)refuse("malformed \\p escape");this.i+=m[0].length;return FULL}default:if(/[A-Za-z0-9]/.test(c))refuse(`escape \\${c} is outside the profile's safe subset`);return single(c.codePointAt(0))}}};var CHOICE_BUDGET=64;var CHOICE_SAT=1<<20;var mulSat=(a,b)=>Math.min(a*b,CHOICE_SAT);function powSat(base,exp){let out=1;for(let i=0;i<exp&&out<CHOICE_SAT;i++)out=mulSat(out,base);return out}function edgeRepeat(facts,pick2){const deeper=new Array(facts.length+1);deeper[facts.length]=EMPTY;for(let i=facts.length-1;i>=0;i--)deeper[i]=union2(pick2(facts[i]),deeper[i+1]);let acc=EMPTY;for(let i=0;i<facts.length;i++){acc=union2(acc,pick2(facts[i]));if(!facts[i].nullable&&!intersects(facts[i].set,deeper[i+1]))break}return acc}function assertStartAnchored(node){switch(node.kind){case"anchor":if(node.at!=="start")refuse("a top-level branch must begin with a '^' start anchor (Ajv tests patterns unanchored)");return;case"seq":if(node.items.length===0)refuse("an empty top-level branch is not start-anchored");assertStartAnchored(node.items[0]);return;case"alt":for(const b of node.branches)assertStartAnchored(b);return;default:refuse("a top-level branch must begin with a '^' start anchor (Ajv tests patterns unanchored)")}}function analyze(node){switch(node.kind){case"anchor":return{set:EMPTY,nullable:true,variable:false,ambiguousAlt:false,choices:1,leadRep:EMPTY,trailRep:EMPTY};case"atom":return{set:node.set,nullable:node.set.ranges.length===0&&!node.set.neg,variable:false,ambiguousAlt:false,choices:1,leadRep:EMPTY,trailRep:EMPTY};case"seq":{const facts=node.items.map(analyze);for(let i=0;i<facts.length;i++){const T=facts[i].trailRep;if(T.ranges.length===0&&!T.neg)continue;for(let j=i+1;j<facts.length;j++){if(intersects(T,facts[j].leadRep))refuse("two overlapping variable repetitions in sequence (polynomial backtracking class)");if(!facts[j].nullable&&!intersects(facts[j].set,T))break}}return{set:facts.reduce((s,f)=>union2(s,f.set),EMPTY),nullable:facts.every(f=>f.nullable),variable:facts.some(f=>f.variable),ambiguousAlt:facts.some(f=>f.ambiguousAlt),choices:facts.reduce((n,f)=>mulSat(n,f.choices),1),leadRep:edgeRepeat(facts,f=>f.leadRep),trailRep:edgeRepeat([...facts].reverse(),f=>f.trailRep)}}case"alt":{const facts=node.branches.map(analyze);let ambiguous=facts.some(f=>f.ambiguousAlt);if(facts.filter(f=>f.nullable).length>1)ambiguous=true;for(let i=0;i<facts.length&&!ambiguous;i++){for(let j=i+1;j<facts.length;j++){if(intersects(facts[i].set,facts[j].set)){ambiguous=true;break}}}return{set:facts.reduce((s,f)=>union2(s,f.set),EMPTY),nullable:facts.some(f=>f.nullable),variable:facts.some(f=>f.variable),ambiguousAlt:ambiguous,choices:ambiguous?facts.reduce((n,f)=>Math.min(n+f.choices,CHOICE_SAT),0):facts.reduce((n,f)=>Math.max(n,f.choices),1),leadRep:facts.reduce((s,f)=>union2(s,f.leadRep),EMPTY),trailRep:facts.reduce((s,f)=>union2(s,f.trailRep),EMPTY)}}case"quant":{const body=analyze(node.body);const repeats=node.max>1||node.max===Infinity;if(repeats){if(body.variable)refuse("repeats a group that itself contains a quantifier (exponential backtracking class)");if(body.nullable)refuse("repeats a nullable body (unbounded ambiguity on empty matches)");if(body.ambiguousAlt)refuse("repeats an ambiguous alternation (branches overlap; exponential backtracking class)")}const nondet=node.max>node.min;return{set:body.set,nullable:body.nullable||node.min===0,variable:body.variable||nondet||repeats,ambiguousAlt:body.ambiguousAlt,choices:node.max===node.min?powSat(body.choices,node.min):node.min===0&&node.max===1?Math.min(body.choices+1,CHOICE_SAT):body.choices,leadRep:nondet?union2(body.set,body.leadRep):body.leadRep,trailRep:nondet?union2(body.set,body.trailRep):body.trailRep}}}}function assertSafePattern(pattern,maxChars){if(pattern.length>maxChars)throw new Error(`pattern of ${pattern.length} characters exceeds the profile complexity bound (${maxChars})`);try{const ast=new Parser(pattern).parse();assertStartAnchored(ast);const facts=analyze(ast);if(facts.choices>CHOICE_BUDGET)refuse(`aggregate alternation ambiguity of ${facts.choices>=CHOICE_SAT?"at least ":""}${facts.choices} paths exceeds the ${CHOICE_BUDGET}-path budget (the fixed-alternation exponential class)`)}catch(e){if(e instanceof PatternRefused)throw new Error(`pattern ${JSON.stringify(pattern)} is outside the profile's safe subset: ${e.message}`);throw new Error(`pattern ${JSON.stringify(pattern)} did not parse under the profile's safe subset: ${e.message}`)}}var AJV_PROFILE_OPTIONS=Object.freeze({strict:false,allErrors:true,ownProperties:true,validateFormats:false,loadSchema:void 0,validateSchema:true,meta:true,unicodeRegExp:true,inlineRefs:false});var sharedMeta;var ProfileAjv=class extends import__.Ajv2020{validateSchema(schema,throwOrLogError){if(schema===null||typeof schema!=="object")return super.validateSchema(schema,throwOrLogError);if(!sharedMeta){const ajv=new import__.Ajv2020(AJV_PROFILE_OPTIONS);sharedMeta={ajv,keys:new Set([...Object.keys(ajv.schemas),...Object.keys(ajv.refs)])}}if(schema.$schema!==void 0&&!sharedMeta.keys.has(schema.$schema))return super.validateSchema(schema,throwOrLogError);try{return sharedMeta.ajv.validateSchema(schema,throwOrLogError)}finally{this.errors=sharedMeta.ajv.errors}}};function singleDocumentClosure(root){const manifest=buildContractClosureManifest(contractDigest(root),[]);return{manifest,closureDigest:contractDigest(manifest)}}var VOID_SCHEMA=Object.freeze({type:"null"});var VOID_SCHEMA_ARTIFACT_DIGEST=contractDigest(VOID_SCHEMA);var VOID_SCHEMA_DIGEST=singleDocumentClosure(VOID_SCHEMA).closureDigest;var STORE_REF=/^cotal:(sha256:[0-9a-f]{64})(#.*)?$/;var ContractInvalidError=class extends Error{code="contract-invalid";constructor(message){super(message);this.name="ContractInvalidError"}};function canonicalOrInvalid(v,label){try{return canonicalJson(v)}catch(e){throw new ContractInvalidError(`${label}: ${e.message}`)}}function digestOrInvalid(v,label){try{return contractDigest(v)}catch(e){throw new ContractInvalidError(`${label}: ${e.message}`)}}function structuralDepth(v,depth=0){if(depth>SCHEMA_PROFILE.maxDepth)return depth;if(v===null||typeof v!=="object")return depth;let max=depth;const children=Array.isArray(v)?v:Object.values(v);for(const c of children){const d=structuralDepth(c,depth+1);if(d>max)max=d;if(max>SCHEMA_PROFILE.maxDepth)return max}return max}function assertBoundedPattern(p,label,where){try{assertSafePattern(p,SCHEMA_PROFILE.maxPatternChars)}catch(e){throw new ContractInvalidError(`${label}: ${where} refused: ${e.message}`)}}function collectRefs(v,label,out=[]){if(v===null||typeof v!=="object")return out;if(Array.isArray(v)){for(const c of v)collectRefs(c,label,out);return out}for(const[k,c]of Object.entries(v)){if((k==="$ref"||k==="$dynamicRef")&&typeof c==="string")out.push(c);if(k==="pattern"&&typeof c==="string")assertBoundedPattern(c,label,"a pattern");if(k==="patternProperties"&&c!==null&&typeof c==="object"&&!Array.isArray(c)){for(const p of Object.keys(c))assertBoundedPattern(p,label,"a patternProperties key")}collectRefs(c,label,out)}return out}var SCHEMA_VALUED_KEYS=["not","if","then","else","items","contains","additionalProperties","propertyNames","unevaluatedItems","unevaluatedProperties","contentSchema","additionalItems"];var SCHEMA_VALUED_MAP_KEYS=["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"];var SCHEMA_VALUED_LIST_KEYS=["allOf","anyOf","oneOf","prefixItems"];var SCALAR_KEYS=["type","enum","const","multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","maxItems","minItems","uniqueItems","maxContains","minContains","maxProperties","minProperties","required","dependentRequired","format","contentEncoding","contentMediaType","title","description","default","deprecated","readOnly","writeOnly","examples","$comment","$id","$schema","$ref","$anchor","$dynamicRef","$dynamicAnchor","$vocabulary"];var ADMITTED=new Set([...SCHEMA_VALUED_KEYS,...SCHEMA_VALUED_MAP_KEYS,...SCHEMA_VALUED_LIST_KEYS,...SCALAR_KEYS]);function assertAdmittedVocabulary(doc,label){const atSchema=(d,path)=>{if(typeof d==="boolean")return;if(d===null||typeof d!=="object"||Array.isArray(d))return;for(const[k,v]of Object.entries(d)){if(!ADMITTED.has(k))throw new ContractInvalidError(`${label}: keyword ${JSON.stringify(k)} at ${path||"/"} is not in the profile's admitted vocabulary; an unrecognised keyword is REFUSED rather than ignored, because this profile cannot count what it does not recognise`);const here=`${path}/${k}`;if(SCHEMA_VALUED_KEYS.includes(k))atSchema(v,here);else if(SCHEMA_VALUED_MAP_KEYS.includes(k)&&v&&typeof v==="object"&&!Array.isArray(v))for(const[name,sub]of Object.entries(v))atSchema(sub,`${here}/${name}`);else if(SCHEMA_VALUED_LIST_KEYS.includes(k)&&Array.isArray(v))v.forEach((sub,i)=>atSchema(sub,`${here}/${i}`))}};atSchema(doc,"")}function assertDocumentProfile(doc,label){const canonical=canonicalOrInvalid(doc,label);const bytes=Buffer.byteLength(canonical,"utf8");if(bytes>SCHEMA_PROFILE.maxDocumentBytes)throw new ContractInvalidError(`${label}: document is ${bytes} bytes (profile max ${SCHEMA_PROFILE.maxDocumentBytes})`);if(structuralDepth(doc)>SCHEMA_PROFILE.maxDepth)throw new ContractInvalidError(`${label}: nesting exceeds profile depth ${SCHEMA_PROFILE.maxDepth}`);assertAdmittedVocabulary(doc,label);const storeRefs=[];for(const ref of collectRefs(doc,label)){if(ref.startsWith("#"))continue;const m=STORE_REF.exec(ref);if(!m)throw new ContractInvalidError(`${label}: external $ref ${JSON.stringify(ref)}; only local '#\u2026' or digest-pinned 'cotal:sha256:<hex>' references are permitted (no ambient resolution)`);storeRefs.push(m[1])}return storeRefs}var COMPILED=new WeakSet;function makeCompiled(validate2,closureDigest){const compiled=Object.freeze({validate:validate2,closureDigest});COMPILED.add(compiled);return compiled}function assertClosureProfile(bundle){const members=bundle.members??{};for(const d of Object.keys(members)){if(!isContractDigest(d))throw new ContractInvalidError(`bundle member key ${JSON.stringify(d)} is not a sha256 digest`)}const seen=new Set;let closureBytes=0;let frontier=assertDocumentProfile(bundle.root,"root schema");closureBytes+=Buffer.byteLength(canonicalOrInvalid(bundle.root,"root schema"),"utf8");for(let chain=0;frontier.length>0;chain++){if(chain>=SCHEMA_PROFILE.maxRefChain)throw new ContractInvalidError(`reference chain exceeds profile depth ${SCHEMA_PROFILE.maxRefChain}`);const next=[];for(const digest of frontier){if(seen.has(digest))continue;seen.add(digest);const member=members[digest];if(member===void 0)throw new ContractInvalidError(`unresolved digest reference ${digest}: not present in the bundle (schemas are closed; nothing is fetched)`);if(digestOrInvalid(member,`member ${digest}`)!==digest)throw new ContractInvalidError(`bundle member under ${digest} does not hash to its key (content is ${digestOrInvalid(member,`member ${digest}`)})`);closureBytes+=Buffer.byteLength(canonicalOrInvalid(member,`member ${digest}`),"utf8");if(closureBytes>SCHEMA_PROFILE.maxClosureBytes)throw new ContractInvalidError(`closure is ${closureBytes} bytes (profile max ${SCHEMA_PROFILE.maxClosureBytes})`);next.push(...assertDocumentProfile(member,`member ${digest}`))}frontier=next}const extras=Object.keys(members).filter(d=>!seen.has(d));if(extras.length>0)throw new ContractInvalidError(`bundle carries ${extras.length} member(s) unreachable from the root (${extras.slice(0,3).join(", ")}${extras.length>3?", \u2026":""})`);return contractDigest(buildContractClosureManifest(digestOrInvalid(bundle.root,"root schema"),[...seen]))}function widestMapKeywordSize(doc,max=0){if(doc===null||typeof doc!=="object"||Array.isArray(doc))return max;for(const[k,v]of Object.entries(doc)){if(SCHEMA_VALUED_MAP_KEYS.includes(k)&&v&&typeof v==="object"&&!Array.isArray(v)){const size=Object.keys(v).length;if(size>max)max=size;for(const sub of Object.values(v))max=widestMapKeywordSize(sub,max)}else if(SCHEMA_VALUED_KEYS.includes(k)){max=widestMapKeywordSize(v,max)}else if(SCHEMA_VALUED_LIST_KEYS.includes(k)&&Array.isArray(v)){for(const sub of v)max=widestMapKeywordSize(sub,max)}}return max}function widestClosurePropertyCount(bundle){let max=widestMapKeywordSize(bundle.root);for(const member of Object.values(bundle.members??{}))max=widestMapKeywordSize(member,max);return max}function compileWithinBudget(bundle){const ajv=new ProfileAjv(AJV_PROFILE_OPTIONS);let validate2;try{for(const[digest,member]of Object.entries(bundle.members??{}))ajv.addSchema(member,`cotal:${digest}`);validate2=ajv.compile(bundle.root)}catch(e){if(e instanceof RangeError){const width=widestClosurePropertyCount(bundle);throw new ContractInvalidError(`schema does not compile under the 2020-12 profile: the generated validator's code shape overflowed the call stack (${e.message}) compiling a ${width}-property object, which every profile ceiling (document/closure bytes, depth, ref-chain, pattern length, admitted vocabulary) had already admitted; this is the compiler's generated-code shape running out of stack, not a defect in the schema`)}throw new ContractInvalidError(`schema does not compile under the 2020-12 profile: ${e.message}`)}return validate2}function compileContract(bundle){const closureDigest=assertClosureProfile(bundle);return makeCompiled(compileWithinBudget(bundle),closureDigest)}function serviceContractTable(rows){const contracts=Object.create(null);for(const row of rows){let pair2;Object.defineProperty(contracts,row.name,{enumerable:true,get:()=>{if(!pair2){pair2=Object.freeze({input:compileContract({root:row.input}),output:compileContract({root:row.output})})}return pair2}})}return{contracts:Object.freeze(contracts),artifactValues:()=>{const values=[];const seen=new Set;for(const r of rows){for(const source of[r.input,r.output]){const{manifest}=singleDocumentClosure(source);if(seen.has(manifest.root))continue;seen.add(manifest.root);values.push(source,manifest)}}return values}}}var isRec=v=>v!==null&&typeof v==="object"&&!Array.isArray(v);var URN=/^[a-z0-9][a-z0-9-]{0,62}(\.[a-z0-9][a-z0-9-]{0,62}){1,15}$/;var TRAIT_GUARDED="ai.cotal.guarded";var TRAIT_PRICED="ai.cotal.priced";var GOVERNED_TRAIT_URNS=Object.freeze([TRAIT_GUARDED,TRAIT_PRICED]);var CAPABILITY=/^[a-z][a-z0-9._-]{0,63}$/;function invalid(what){throw new ContractInvalidError(`cluster document does not validate: ${what}`)}function parseClusterDocument(raw){const o=isRec(raw)?raw:invalid("not an object");if(typeof o.urn!=="string"||!URN.test(o.urn))invalid(`urn ${JSON.stringify(o.urn)} is not a reverse-DNS cluster type URN`);if(typeof o.revision!=="number"||!Number.isSafeInteger(o.revision)||o.revision<0)invalid("revision is not an unsigned integer");if(!Array.isArray(o.attributes))invalid("attributes is not an array");if(!Array.isArray(o.events))invalid("events is not an array");if(!Array.isArray(o.commands)||o.commands.length===0)invalid("commands must be a non-empty array");const seen=new Set;const commands=o.commands.map((c,i)=>{const cmd=isRec(c)?c:invalid(`commands[${i}] is not an object`);const name=typeof cmd.name==="string"?cmd.name:invalid(`commands[${i}].name is not a string`);try{assertCommandToken(name)}catch(e){invalid(`commands[${i}].name: ${e.message}`)}if(name==="describe")invalid(`commands[${i}] declares "describe": reserved, served by the machinery, never a cluster command (SPEC 13.7)`);if(seen.has(name))invalid(`command "${name}" is declared twice`);seen.add(name);if(cmd.class!=="ephemeral"&&cmd.class!=="journal")invalid(`command "${name}" class ${JSON.stringify(cmd.class)} is not "ephemeral" | "journal"`);if(typeof cmd.targeted!=="boolean")invalid(`command "${name}" must declare targeted as a boolean (SPEC 13.7)`);let modes;if(cmd.targeted){if(!Array.isArray(cmd.modes)||cmd.modes.length===0)invalid(`targeted command "${name}" must declare its admitted authorization modes (SPEC 13.7)`);const uniq=new Set;for(const m of cmd.modes){if(typeof m!=="string"||!isEpAuthzMode(m))invalid(`command "${name}" admits unknown mode ${JSON.stringify(m)}`);if(uniq.has(m))invalid(`command "${name}" admits mode "${m}" twice`);uniq.add(m)}modes=[...cmd.modes]}else if(cmd.modes!==void 0){invalid(`untargeted command "${name}" must not declare authorization modes`)}if(typeof cmd.capability!=="string"||!CAPABILITY.test(cmd.capability))invalid(`command "${name}" capability is not a bounded capability token`);if(!isContractDigest(cmd.inputDigest))invalid(`command "${name}" inputDigest is not a sha256 closure digest`);if(!isContractDigest(cmd.outputDigest))invalid(`command "${name}" outputDigest is not a sha256 closure digest`);let traits;if(cmd.traits!==void 0){if(!Array.isArray(cmd.traits))invalid(`command "${name}" traits is not an array`);const tSeen=new Set;for(const t of cmd.traits){if(typeof t!=="string"||!URN.test(t))invalid(`command "${name}" trait ${JSON.stringify(t)} is not a reverse-DNS trait URN (SPEC 13.7)`);if(tSeen.has(t))invalid(`command "${name}" declares trait "${t}" twice`);tSeen.add(t)}traits=[...cmd.traits]}let action;if(cmd.action!==void 0){if(cmd.action!==true)invalid(`command "${name}" action ${JSON.stringify(cmd.action)} is not true (the action composite is present or absent; "false" is a second way to say absent)`);if(cmd.class!=="journal")invalid(`command "${name}" declares the action composite but class "${cmd.class}": an action command's submissions are journal-class (SPEC 13.7)`);action=true}let admissionCeiling;if(cmd.class==="journal"){const ceil=isRec(cmd.admissionCeiling)?cmd.admissionCeiling:invalid(`journal-class command "${name}" must declare admissionCeiling {maxBytes, maxDepth, maxItems}: the canonicalizer reads its ceilings from the digest-verified surface, never from a constant`);const nums={};for(const f of["maxBytes","maxDepth","maxItems"]){const v=ceil[f];if(typeof v!=="number"||!Number.isSafeInteger(v)||v<=0)invalid(`command "${name}" admissionCeiling.${f} ${JSON.stringify(v)} is not a positive safe integer`);nums[f]=v}admissionCeiling={maxBytes:nums.maxBytes,maxDepth:nums.maxDepth,maxItems:nums.maxItems}}else if(cmd.admissionCeiling!==void 0){invalid(`ephemeral command "${name}" declares admissionCeiling: an ephemeral command receives no journal submissions, so a ceiling on it is unreadable by anything`)}let readinessDeadlineMs;if(cmd.readinessDeadlineMs!==void 0){if(!action)invalid(`command "${name}" declares readinessDeadlineMs without the action composite: readiness is goal state and only an action command has a goal`);if(typeof cmd.readinessDeadlineMs!=="number"||!Number.isSafeInteger(cmd.readinessDeadlineMs)||cmd.readinessDeadlineMs<0)invalid(`command "${name}" readinessDeadlineMs ${JSON.stringify(cmd.readinessDeadlineMs)} is not a non-negative safe integer (SPEC 13.11)`);readinessDeadlineMs=cmd.readinessDeadlineMs}return{name,class:cmd.class,targeted:cmd.targeted,...modes?{modes}:{},capability:cmd.capability,inputDigest:cmd.inputDigest,outputDigest:cmd.outputDigest,...traits?{traits}:{},...action?{action}:{},...admissionCeiling?{admissionCeiling}:{},...readinessDeadlineMs!==void 0?{readinessDeadlineMs}:{}}});return{urn:o.urn,revision:o.revision,attributes:[...o.attributes],commands,events:[...o.events]}}var REGISTRY_ENDPOINT="registry";var REGISTRY_ENDPOINTS_COMMAND="endpoints";var REGISTRY_ENDPOINTS_CAPABILITY="registry.endpoints";var REGISTRY_PAGE_LIMIT=100;var REGISTRY_ENDPOINTS_GRANT=Object.freeze({endpoint:REGISTRY_ENDPOINT,command:REGISTRY_ENDPOINTS_COMMAND});var NAME={type:"string",minLength:1,maxLength:128};var TOKEN={type:"string",minLength:1,maxLength:64};var ENDPOINTS_INPUT={type:"object",additionalProperties:false,properties:{limit:{type:"integer",minimum:1,maximum:REGISTRY_PAGE_LIMIT},after:NAME}};var FORM={type:"object",additionalProperties:false,required:["rail","literals","covered"],properties:{rail:{enum:["ep","ep.v1","epj"]},route:{enum:["one","all","inst"]},mode:TOKEN,literals:{type:"object",additionalProperties:{type:"array",items:TOKEN}},covered:{type:"array",items:{type:"object",additionalProperties:{type:["string","null"],maxLength:64}}}}};var ENDPOINTS_OUTPUT={type:"object",additionalProperties:false,required:["rows","source"],properties:{rows:{type:"array",maxItems:REGISTRY_PAGE_LIMIT,items:{type:"object",additionalProperties:false,required:["endpoint","instances","commands"],properties:{endpoint:NAME,instances:{type:"array",items:{type:"object",additionalProperties:false,required:["instanceId","state","artifacts"],properties:{instanceId:TOKEN,state:{type:["string","null"],maxLength:64},artifacts:{enum:["verified","missing","invalid"]}}}},commands:{type:"array",items:{type:"object",additionalProperties:false,required:["name","class","forms"],properties:{name:TOKEN,class:{enum:["ephemeral","journal"]},forms:{type:"array",items:FORM},instances:{type:"array",items:TOKEN}}}},unprojected:{type:"array",items:TOKEN}}}},next:NAME,source:{enum:["recorded-ceiling","no-permission-system"]}}};var ROWS=[{name:REGISTRY_ENDPOINTS_COMMAND,capability:REGISTRY_ENDPOINTS_CAPABILITY,input:ENDPOINTS_INPUT,output:ENDPOINTS_OUTPUT,targeted:false}];var TABLE=serviceContractTable(ROWS);var REGISTRY_CONTRACTS=TABLE.contracts;var registryContractArtifactValues=TABLE.artifactValues;var import_jetstream15=__toESM(require_mod4(),1);var import_jetstream5=__toESM(require_mod4(),1);var import_transport_node5=__toESM(require_transport_node(),1);var GOAL_TERMINAL_STATES=Object.freeze(["succeeded","failed","cancelled","expired","uncertain"]);function assertClosedKeys(o,allowed,what){for(const k of Object.keys(o))if(!allowed.includes(k))throw new EpEnvelopeError("internal",`${what} carries unknown field ${JSON.stringify(k)}; a closed schema admits no extras - garbled state never authorizes (SPEC 13.4)`)}function assertGoalResultFactShape(raw,subject,ref){if(raw===null||typeof raw!=="object"||Array.isArray(raw))throw new EpEnvelopeError("internal",`goal result fact on ${subject} is not an object; garbled state never authorizes (SPEC 13.6)`);const o=raw;assertClosedKeys(o,["v","goalId","fingerprint","state","outcomeDigest","data","committer","ts"],`goal result fact on ${subject}`);if(o.committer!==void 0){const cm=o.committer;if(cm===null||typeof cm!=="object"||Array.isArray(cm))throw new EpEnvelopeError("internal",`goal result fact on ${subject} committer is not an object; garbled state never authorizes (SPEC 13.6)`);assertClosedKeys(cm,["instanceId","epoch"],`goal result fact on ${subject} committer`);if(typeof cm.instanceId!=="string"||cm.instanceId.length===0||typeof cm.epoch!=="number"||!Number.isSafeInteger(cm.epoch)||cm.epoch<0)throw new EpEnvelopeError("internal",`goal result fact on ${subject} carries a malformed committer; garbled state never authorizes (SPEC 13.6)`)}if(o.v!==1||typeof o.goalId!=="string"||typeof o.fingerprint!=="string"||o.fingerprint.length===0||typeof o.state!=="string"||!GOAL_TERMINAL_STATES.includes(o.state)||typeof o.outcomeDigest!=="string"||o.outcomeDigest.length===0||typeof o.ts!=="number"||!Number.isSafeInteger(o.ts)||o.ts<0)throw new EpEnvelopeError("internal",`goal result fact on ${subject} is malformed; garbled state never authorizes (SPEC 13.6)`);if(o.goalId!==ref.goalId)throw new EpEnvelopeError("internal",`goal result fact on ${subject} names goalId ${JSON.stringify(o.goalId)}, not its subject's ${ref.goalId}; a mis-subjected fact never authorizes (SPEC 13.4)`);return o}function goalOutcomeDigestMismatch(subject){return new EpEnvelopeError("internal",`goal result fact on ${subject} carries an outcomeDigest that does not match its payload; a digest-inconsistent fact never authorizes (SPEC 13.6)`)}async function withDeadline(p,ms,onTimeout){let timer;const timeout=new Promise((_,rej)=>{timer=setTimeout(()=>rej(onTimeout()),Math.max(1,ms))});try{return await Promise.race([p,timeout])}finally{clearTimeout(timer)}}var import_jetstream3=__toESM(require_mod4(),1);var import_transport_node3=__toESM(require_transport_node(),1);var MAX_SCHEDULE_MS=Date.UTC(9999,11,31,23,59,59,999);var import_jetstream4=__toESM(require_mod4(),1);var import_transport_node4=__toESM(require_transport_node(),1);var import_nkeys3=__toESM(require_mod(),1);var ANCHOR_ROLES=Object.freeze(["handles","traits","receipts","resume","sessions","authz-slots","obligations","payments","consents"]);var BRANDED_CONTEXTS=new WeakSet;function assertCtx(ctx){if(!BRANDED_CONTEXTS.has(ctx))throw new EpEnvelopeError("failed-precondition",`the action context was not constructed by actionContext(); a hand-assembled resource bundle never authorizes - the space bond is constructed, not asserted (SPEC 13.4)`)}var GUARD_CLEARANCES=new WeakMap;var clearanceMintClaimed=false;function claimGuardClearanceMint(){if(clearanceMintClaimed)throw new EpEnvelopeError("permission-denied","the guard-clearance mint is already claimed by THE gate; a guarded goal's edge into running opens only through it (SPEC 13.6)");clearanceMintClaimed=true;return(ctx,goalId)=>{assertCtx(ctx);const clearance=Object.freeze({goalId:assertIdToken(goalId,"goalId")});GUARD_CLEARANCES.set(clearance,ctx);return clearance}}var GOAL_STATES=Object.freeze(["accepted","running","waiting","cancelling","succeeded","failed","cancelled","expired","uncertain"]);function parseGoalResultFact(raw,subject,ref){const o=assertGoalResultFactShape(raw,subject,ref);if(contractDigest(o.data===void 0?null:o.data)!==o.outcomeDigest)throw goalOutcomeDigestMismatch(subject);return o}var import_nats_core2=__toESM(require_mod3(),1);function base64url3(bytes){let binary="";for(const b of bytes)binary+=String.fromCharCode(b);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function fromBase64url(text2){const b64=text2.replace(/-/g,"+").replace(/_/g,"/");const binary=atob(b64+"=".repeat((4-b64.length%4)%4));return Uint8Array.from(binary,ch=>ch.charCodeAt(0))}var import_nats_core=__toESM(require_mod3(),1);var BROKER_REFUSAL_CAUSE="either no grant covers it, or it was granted after this connection authenticated, which still has its earlier permissions: reconnect and retry (SPEC 13.2)";function openPublishDenialWatch(nc,subject,refusal,what){const statusStream=nc.status();if(typeof statusStream?.stop!=="function")throw new EpEnvelopeError("unavailable",`the NATS connection's status() stream does not expose stop(); the ${what} permission watch cannot be released and would leak a listener per call`);const statusIter=statusStream[Symbol.asyncIterator]();const denied=new Promise((_,reject)=>{void(async()=>{for(;;){const{value:s,done}=await statusIter.next();if(done===true||s===void 0)return;if(s.type!=="error")continue;if(s.error instanceof import_nats_core.PermissionViolationError&&s.error.subject===subject){reject(refusal(s.error));return}}})().catch(()=>{})});return{denied,release(){statusStream.stop();void statusIter.return?.(void 0)}}}var nonce=()=>base64url3(globalThis.crypto.getRandomValues(new Uint8Array(24)));function subjectTarget(t){if(t.mode==="self")return{mode:"self"};if(t.mode==="handle"||t.mode==="exact")return{mode:t.mode,tOwner:t.owner,tActor:t.actor,tUid:t.lifecycleUid};return{mode:t.mode,tOwner:t.owner}}function bodyTarget(t){if(t.mode==="self")return void 0;return{owner:assertBoundedOwner(t.owner,"target owner"),actor:t.actor,lifecycleUid:assertLifecycleToken(t.lifecycleUid,"target lifecycleUid"),...t.mappingRevision!==void 0?{mappingRevision:t.mappingRevision}:{}}}function buildRequest(space2,route,op,verb){let args;try{args=op.args===void 0?void 0:JSON.parse(JSON.stringify(op.args))}catch(e){throw new EpEnvelopeError("bad-request",`args cannot be sent as JSON: ${e instanceof Error?e.message:String(e)}`,void 0,"not-executed")}try{assertArgsValid(op.contract.input.validate,args)}catch(e){if(!(e instanceof EpEnvelopeError))throw e;const property=op.contract.input.validate.errors?.[0]?.params?.additionalProperty;throw new EpEnvelopeError(e.code,e.message,typeof property==="string"?[{kind:EP_UNDECLARED_ARG,property,...op.bind!==void 0?{instanceId:op.bind.instanceId}:{}}]:void 0,"not-executed")}if(op.bind!==void 0){if(op.command==="describe")throw new EpEnvelopeError("bad-request","describe carries no bind: it is the bootstrap that produces one (SPEC 13.3)");if(route.mode==="all")throw new EpEnvelopeError("bad-request","a scatter addresses every incarnation; a bind would make every member but one refuse (SPEC 13.5)");if(route.mode==="inst"&&op.bind.instanceId!==route.instanceId)throw new EpEnvelopeError("bad-request",`bind.instanceId "${op.bind.instanceId}" contradicts the inst-rail route's instance "${route.instanceId}" (SPEC 13.2)`)}const n=nonce();const subject=epRequestSubject(space2,{route,endpoint:op.endpoint,command:op.command,...op.target?{target:subjectTarget(op.target)}:{},caller:op.caller,nonce:n});const requestId=op.id!==void 0?assertIdToken(op.id,"pinned envelope id"):nonce();const env={v:1,id:requestId,op:{endpoint:op.endpoint,command:op.command,inputDigest:op.contract.input.closureDigest,outputDigest:op.contract.output.closureDigest},class:"ephemeral",replyExpected:verb.replyExpected,...op.goalId!==void 0?{goalId:op.goalId}:{},...op.target&&op.target.mode!=="self"?{target:bodyTarget(op.target)}:{},...op.bind!==void 0?{bind:{instanceId:assertLifecycleToken(op.bind.instanceId,"bind instanceId"),epoch:op.bind.epoch}}:{},...args!==void 0?{args}:{},from:{id:`${op.caller.owner}.${op.caller.actor}`,name:op.name??op.caller.actor},...verb.deadlineMs!==void 0?{deadlineMs:verb.deadlineMs}:{},...op.correlation!==void 0?{correlation:op.correlation}:{},...op.auth!==void 0?{auth:op.auth}:{}};return{subject,requestId,n,body:new TextEncoder().encode(JSON.stringify(env))}}var MAX_TIMER_MS=2147483647;function assertDeadline(deadlineMs,what="deadlineMs"){if(!Number.isSafeInteger(deadlineMs)||deadlineMs<=0||deadlineMs>MAX_TIMER_MS)throw new EpEnvelopeError("bad-request",`${what} ${deadlineMs} must be a positive budget within the timer bound ${MAX_TIMER_MS}ms (SPEC 13.3: bounded, never unbounded; a larger setTimeout clamps to 1ms)`);return deadlineMs}function isNoRespondersMsg(msg){const h2=msg.headers;return h2!=null&&(h2.code===503||h2.status==="503")}async function raceBounded(read,ms,what,details){let t;try{return await Promise.race([(async()=>read())(),new Promise((_,reject)=>{t=setTimeout(()=>reject(new EpEnvelopeError("deadline-exceeded",`${what} did not settle within the ${ms}ms budget (SPEC 13.5)`,details)),ms)})])}finally{if(t!==void 0)clearTimeout(t)}}var unansweredDetail=op=>({kind:EP_UNANSWERED,endpoint:op.endpoint,command:op.command,rail:epPlaneTokens(op.caller).join(".")});function replySubjectFor(space2,caller,n){return`${spacePrefix(space2)}.${epPlaneTokens(caller).join(".")}.reply.*.*.*.${callerRailTokens(caller).join(".")}.${n}`}function noRespondersReplyTo(space2,caller,n){return`${spacePrefix(space2)}.${epPlaneTokens(caller).join(".")}.reply._nr._nr._nr.${callerRailTokens(caller).join(".")}.${n}`}function staleEpochRefusal(op,responder,held2,reference,rail){const who=`the ${op.endpoint} instance ${responder.instanceId}`;const ahead=responder.epoch>held2;const situation=reference==="bind"?ahead?`${who} answered at epoch ${responder.epoch}, but this handle resolved against it at epoch ${held2}: a SUCCESSOR of the bound incarnation answered (a restart or supersession), so the handle is the stale side; re-resolve to adopt it`:`${who} answered at epoch ${responder.epoch}, but this handle resolved against it at epoch ${held2}: a SUPERSEDED incarnation still connected answered, and its reply is rejected`:ahead?`${who} answered at epoch ${responder.epoch}, but a currency read of its registered epoch returned ${held2}: the responder is ahead of the registry read (the read lags a restart), so its reply is rejected until the read catches up; nothing of this caller's is stale`:`${who} answered at epoch ${responder.epoch}, but a currency read of its registered epoch returned ${held2}: a SUPERSEDED incarnation still connected answered, and its reply is rejected`;const detail={kind:EP_UNBOUND_RESPONDER,endpoint:op.endpoint,command:op.command,answeredBy:responder.instanceId,...reference==="bind"?{boundTo:responder.instanceId}:{},answeredEpoch:responder.epoch,heldEpoch:held2,reference,pinned:rail==="inst"};return new EpEnvelopeError("expired",`${situation}. THIS SAYS NOTHING ABOUT WHETHER THE COMMAND RAN: ${responder.instanceId} received the request and answered it, so if "${op.command}" mutates, that effect may already have landed; verify the outcome ('ps'/'inspect'/roster) before re-issuing (SPEC 13.2, the stale-reply rejection rule)`,[detail])}function parseAttributedReply(space2,subject,data,requestId,op,expect){const parsed=parseEpSubject(subject);if(!parsed||parsed.plane!=="reply")throw new EpEnvelopeError("internal",`a message on the caller's reply rail does not parse as a reply subject: ${subject}`);if(parsed.endpoint!==op.endpoint)throw new EpEnvelopeError("internal",`reply endpoint "${parsed.endpoint}" is not the invoked endpoint "${op.endpoint}" (SPEC 13.2: the caller binds a reply to the requested identity, never trusts the subject alone)`);if(expect?.instanceId!==void 0&&parsed.instanceId!==expect.instanceId)throw new EpEnvelopeError("internal",`reply instance "${parsed.instanceId}" is not the addressed instance "${expect.instanceId}" (SPEC 13.2)`);if(expect?.epoch!==void 0&&parsed.epoch!==expect.epoch)throw staleEpochRefusal(op,{instanceId:parsed.instanceId,epoch:parsed.epoch},expect.epoch,"bind","inst");let rawBody;try{rawBody=JSON.parse(new TextDecoder().decode(data))}catch(e){throw new EpEnvelopeError("internal",`the reply body on the caller's rail is not JSON (${e instanceof Error?e.message:String(e)}); an unparseable reply is a responder bug surfaced as the caller boundary's structured refusal (SPEC 13.3)`)}const reply=parseEndpointReply(rawBody);if(reply.id!==requestId)throw new EpEnvelopeError("internal",`reply id "${reply.id}" does not echo the request id "${requestId}" on its nonce-scoped rail (SPEC 13.3)`);if(reply.ok)assertOutputValid(op.contract.output.validate,reply.data);return{reply,responder:{endpoint:parsed.endpoint,instanceId:parsed.instanceId,epoch:parsed.epoch}}}async function epCall(nc,space2,route,op,opts){opts.signal?.throwIfAborted();const deadlineMs=assertDeadline(opts.deadlineMs);if(route.mode==="one"&&opts.currentEpoch===void 0)throw new EpEnvelopeError("bad-request","epCall on the `one` rail requires opts.currentEpoch: the queue winner is not implicitly current, and a superseded-but-connected member's reply must be rejected (SPEC 13.2, the stale-reply rejection rule)");const req=buildRequest(space2,route,op,{replyExpected:true,deadlineMs});const expect=route.mode==="inst"?{instanceId:route.instanceId,epoch:route.epoch}:void 0;const noRespReplyTo=noRespondersReplyTo(space2,op.caller,req.n);const started=Date.now();let sub;let timer;let denialWatch;let onAbort;let published=false;const cancelled=new Promise((_,reject)=>{onAbort=()=>reject(new EpEnvelopeError("unavailable",`${op.endpoint}.${op.command} observation cancelled; the request may have executed`,published?[{...unansweredDetail(op),requestId:req.requestId}]:void 0,"unknown"));opts.signal?.addEventListener("abort",onAbort,{once:true})});try{denialWatch=openPublishDenialWatch(nc,req.subject,()=>new EpEnvelopeError("permission-denied",`the call for ${op.endpoint}.${op.command} was REFUSED BY THE BROKER, not unanswered: this caller's credential does not authorize publishing to "${req.subject}"${route.mode==="inst"?` (the instance rail for ${route.instanceId})`:""}. The responder may be perfectly healthy. The current credential did not authorize this route, command or target, and the broker does not say which; ${BROKER_REFUSAL_CAUSE}`,void 0,"not-executed"),"call");const outcome=new Promise((resolve,reject)=>{sub=nc.subscribe(replySubjectFor(space2,op.caller,req.n),{callback:(err3,msg2)=>{if(err3){reject(new EpEnvelopeError("unavailable",`the caller's reply subscription failed: ${err3.message}`));return}if(msg2.subject===noRespReplyTo){if(isNoRespondersMsg(msg2)){reject(new EpEnvelopeError("unavailable",`no responder for ${op.endpoint}.${op.command} (SPEC 13.5)`,[unansweredDetail(op)],"not-executed"));return}reject(new EpEnvelopeError("internal",`a non-503 message reached the reserved no-responders sentinel for ${op.endpoint}.${op.command}; nothing but the broker control frame is addressable there`));return}resolve({subject:msg2.subject,data:msg2.data})}});opts.signal?.throwIfAborted();nc.publish(req.subject,req.body,{reply:noRespReplyTo});published=true});const timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new EpEnvelopeError("deadline-exceeded",`no reply to ${op.endpoint}.${op.command} within the ${deadlineMs}ms budget (SPEC 13.5)`,[{...unansweredDetail(op),requestId:req.requestId}],"unknown")),deadlineMs)});const msg=await Promise.race([outcome,timeout,denialWatch.denied,cancelled]);const attributed=parseAttributedReply(space2,msg.subject,msg.data,req.requestId,op,expect);if(attributed.reply.ok===false&&bindRefusalMarked(attributed.reply.error)){if(op.bind===void 0)throw new EpEnvelopeError("internal",`${op.endpoint}.${op.command} replied with a bind refusal to a request that carried no bind`);const r=attributed.responder;if(r.instanceId===op.bind.instanceId&&r.epoch===op.bind.epoch)throw new EpEnvelopeError("internal",`${op.endpoint} instance ${r.instanceId} refused ${op.command} as the wrong incarnation, but the reply subject attributes it to exactly the bound one (${op.bind.instanceId} epoch ${op.bind.epoch}); the body does not get to contradict its own attribution (SPEC 13.3)`);const refusal=(attributed.reply.error?.details??[]).find(d=>d.kind===EP_BIND_REFUSED);if(refusal===void 0)throw new EpEnvelopeError("internal",`${op.endpoint}.${op.command} came back marked ${EP_BIND_REFUSED} with no such detail to derive it from (SPEC 13.3)`);if(refusal.boundTo.instanceId!==op.bind.instanceId||refusal.boundTo.epoch!==op.bind.epoch)throw new EpEnvelopeError("internal",`${op.endpoint} refused ${op.command} against bind ${refusal.boundTo.instanceId} epoch ${refusal.boundTo.epoch}, but this request carried ${op.bind.instanceId} epoch ${op.bind.epoch}; a refusal computed from another request proves nothing about this one (SPEC 13.3)`);if(refusal.servedBy.instanceId!==r.instanceId||refusal.servedBy.epoch!==r.epoch)throw new EpEnvelopeError("internal",`${op.endpoint} refused ${op.command} claiming to be served by ${refusal.servedBy.instanceId} epoch ${refusal.servedBy.epoch}, but the reply subject attributes it to ${r.instanceId} epoch ${r.epoch}; the body does not get to contradict its own attribution (SPEC 13.3)`);return attributed}if(route.mode==="one"){const remaining=deadlineMs-(Date.now()-started);if(remaining<=0)throw new EpEnvelopeError("deadline-exceeded",`no budget left to verify the \`one\` responder's currency within ${deadlineMs}ms (SPEC 13.5)`);let cur;try{cur=await raceBounded(()=>opts.currentEpoch(attributed.responder.instanceId),remaining,`the \`one\` currency read for ${op.endpoint}.${op.command}`)}catch(e){if(e instanceof EpEnvelopeError)throw e;throw new EpEnvelopeError("internal",`the \`one\` currency read threw (${e instanceof Error?e.message:String(e)}); the documented error catalog holds at this boundary (SPEC 13.3)`)}if(!Number.isSafeInteger(cur)||cur<0)throw new EpEnvelopeError("failed-precondition",`the \`one\` currency read returned a non-integer/negative epoch ${String(cur)}; a garbled currency read is refused as the read's own failure, never reported as responder staleness (SPEC 13.2)`);if(attributed.responder.epoch!==cur)throw staleEpochRefusal(op,attributed.responder,cur,opts.currencyReference??"registry","one")}return attributed}finally{sub?.unsubscribe();if(timer!==void 0)clearTimeout(timer);denialWatch?.release();if(onAbort)opts.signal?.removeEventListener("abort",onAbort)}}var dec3=new TextDecoder;var enc3=new TextEncoder;var nonce2=()=>base64url3(globalThis.crypto.getRandomValues(new Uint8Array(24)));var DESCRIBE_RETRY_MS=250;function caughtText(e,fallback){try{return e instanceof Error?e.message:String(e)}catch{return fallback}}var GOAL_FOLLOW_MARGIN_MS=1e4;async function describeEndpoint(nc,space2,endpoint,caller,opts={}){opts.signal?.throwIfAborted();if(opts.classInstanceId!==void 0){assertLifecycleToken(opts.classInstanceId,"classInstanceId");if(opts.instanceId!==void 0)throw new EpEnvelopeError("bad-request","a describe cannot select both an instance route and a class responder")}const deadlineMs=opts.deadlineMs??1e4;const n=nonce2();const requestId=nonce2();const route=opts.instanceId!==void 0?{mode:"inst",instanceId:opts.instanceId}:{mode:"one"};const subject=epRequestSubject(space2,{route,endpoint,command:"describe",caller,nonce:n});const rail=epPlaneTokens(caller).join(".");const env={v:1,id:requestId,op:{endpoint,command:"describe"},class:"ephemeral",replyExpected:true,deadlineMs,from:{id:`${caller.owner}.${caller.actor}`,name:caller.actor}};let sub;let timer;let retryTimer;let denialWatch;let onAbort;const startedAt2=performance.now();const unanswered=ms=>new EpEnvelopeError("deadline-exceeded",`no describe reply from ${endpoint}${opts.instanceId!==void 0?` instance ${opts.instanceId}`:opts.classInstanceId!==void 0?` class responder ${opts.classInstanceId}`:""} within ${ms}ms on the ${rail} rail`,[{kind:EP_UNANSWERED,endpoint,command:"describe",rail}]);const cancelled=new Promise((_,reject)=>{onAbort=()=>reject(opts.signal?.reason?.name==="TimeoutError"?unanswered(Math.round(performance.now()-startedAt2)):opts.signal?.reason);opts.signal?.addEventListener("abort",onAbort,{once:true})});try{denialWatch=openPublishDenialWatch(nc,subject,()=>new EpEnvelopeError("permission-denied",`the describe for ${endpoint} was REFUSED BY THE BROKER, not unanswered: this caller's credential does not authorize publishing to "${subject}"${opts.instanceId!==void 0?` (the instance rail for ${opts.instanceId}: an instance-addressed call needs a credential minted with that instance, not a class-rail one)`:""}. The responder may be perfectly healthy; ${BROKER_REFUSAL_CAUSE}`,void 0,"not-executed"),"describe");const got=new Promise((resolve,reject)=>{sub=nc.subscribe(epCallerReplyFilter(space2,caller),{callback:(err3,msg)=>{if(err3){reject(new EpEnvelopeError("unavailable",`describe reply subscription failed: ${err3.message}`));return}const parsed=parseEpSubject(msg.subject);if(!parsed||parsed.plane!=="reply"||parsed.endpoint!==endpoint||parsed.nonce!==n)return;let reply2;try{reply2=parseEndpointReply(JSON.parse(dec3.decode(msg.data)))}catch{return}if(reply2.id!==requestId)return;if(opts.classInstanceId!==void 0&&parsed.instanceId!==opts.classInstanceId)return;resolve({body:reply2,responder:{instanceId:parsed.instanceId,epoch:parsed.epoch}})}});const request=enc3.encode(JSON.stringify(env));nc.publish(subject,request);retryTimer=setInterval(()=>{try{nc.publish(subject,request)}catch(e){reject(new EpEnvelopeError("unavailable",`the describe retry for ${endpoint} could not publish: ${caughtText(e,"unknown publish failure")}`))}},DESCRIBE_RETRY_MS)});const timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(unanswered(deadlineMs)),deadlineMs)});const{body:reply,responder}=await Promise.race([got,timeout,denialWatch.denied,cancelled]);if(reply.ok!==true){const e=reply.error;throw new EpEnvelopeError(e?.code??"unavailable",`describe(${endpoint}) failed: ${e?.message??"unknown"}`)}return{answer:reply.data,responder}}finally{sub?.unsubscribe();if(timer!==void 0)clearTimeout(timer);if(retryTimer!==void 0)clearInterval(retryTimer);if(onAbort)opts.signal?.removeEventListener("abort",onAbort);denialWatch?.release()}}var BIND_SPLIT_REISSUES=16;async function invokeCommand(nc,space2,service,command,args,opts){const resolved=service.commands.get(command);if(resolved===void 0)throw new EpEnvelopeError("not-found",`command "${command}" is not in ${service.endpoint}'s visible surface; describe lists ${[...service.commands.keys()].sort().join(", ")||"(none)"}`);if(resolved.targeted&&opts.target===void 0)throw new EpEnvelopeError("bad-request",`command "${command}" is targeted (modes: ${resolved.modes.join(", ")}); an invoke needs its target`);if(!resolved.targeted&&opts.target!==void 0)throw new EpEnvelopeError("bad-request",`command "${command}" is untargeted; an invoke must not carry a target`);const caller=opts.caller??service.caller;if(caller.owner!==service.caller.owner||caller.actor!==service.caller.actor||caller.uid!==service.caller.uid)throw new EpEnvelopeError("bad-request","a call's caller must name the triple its describe ran as");let sendArgs=args;if(sendArgs===void 0&&!resolved.contract.input.validate(null)&&resolved.contract.input.validate({}))sendArgs={};const describeBound=instanceId=>{if(instanceId!==service.responder.instanceId){throw new EpEnvelopeError("failed-precondition",service.pinnedInstanceId!==void 0?`the ${service.endpoint} instance ${instanceId} answered but this handle is PINNED to ${service.pinnedInstanceId}; a pinned call names its instance and never accepts another. ${instanceId} did receive and answer the request, so if "${command}" mutates, that effect may already have landed - verify before re-issuing (SPEC 13.2)`:`the ${service.endpoint} instance ${instanceId} won the class queue but this UNPINNED handle resolved against ${service.responder.instanceId}; the describe and the invoke are separate trips through the same queue, so in a multi-instance space this is an ordinary split and not necessarily a supersession - the handle cannot currently adopt a different winner. THIS SAYS NOTHING ABOUT WHETHER THE COMMAND RAN: ${instanceId} received the request and answered it, possibly after this error was raised. For a read that is harmless and re-issuing is safe; if "${command}" mutates, verify the outcome ('ps'/'inspect'/roster) before re-issuing, because a retry that assumes failure duplicates the effect. A call that addresses one instance does not split (SPEC 13.2)`,[{kind:EP_UNBOUND_RESPONDER,endpoint:service.endpoint,command,answeredBy:instanceId,boundTo:service.responder.instanceId,pinned:service.pinnedInstanceId!==void 0}])}return service.responder.epoch};const bind=opts.currentEpoch===void 0?{instanceId:service.pinnedInstanceId??service.responder.instanceId,epoch:service.responder.epoch}:void 0;const deadline=Date.now()+(opts.deadlineMs??1e4);const call=route=>epCall(nc,space2,route,{endpoint:service.endpoint,command,contract:resolved.contract,caller,...sendArgs!==void 0?{args:sendArgs}:{},...opts.target?{target:opts.target}:{},...bind!==void 0?{bind}:{},...opts.id!==void 0?{id:opts.id}:{}},{deadlineMs:deadline-Date.now(),signal:opts.signal,currentEpoch:opts.currentEpoch??describeBound,currencyReference:opts.currentEpoch?"registry":"bind"});if(service.pinnedInstanceId!==void 0)return call({mode:"inst",instanceId:service.pinnedInstanceId,epoch:service.responder.epoch});try{return await call({mode:"one"})}catch(e){if(!(e instanceof EpEnvelopeError)||e.code!=="permission-denied"||e.outcome!=="not-executed"||deadline<=Date.now())throw e;return call({mode:"inst",instanceId:service.responder.instanceId,epoch:service.responder.epoch})}}function goalFollowRefusal(service){if(service.commands.has("goal-result"))return void 0;return{reply:{v:1,id:globalThis.crypto.randomUUID(),ok:false,error:{code:"failed-precondition",outcome:"not-executed",message:`endpoint "${service.endpoint}" does not support "goal-result"; upgrade manager to enable durable goal following (SPEC 13.6)`}},responder:{endpoint:service.endpoint,instanceId:service.responder.instanceId,epoch:service.responder.epoch}}}function goalProgressOrigin(space2,endpoint,caller,subject){const head=`${spacePrefix(space2)}.epe.${endpointToken(endpoint)}.`;if(!subject.startsWith(head))return void 0;const[instanceId,epoch,...tail]=subject.slice(head.length).split(".");const triple=callerTokens(caller);if(tail.length!==6||tail[0]!=="goal"||tail[1]!==triple[0]||tail[2]!==triple[1]||tail[3]!==triple[2]||tail[5]!=="progress")return void 0;if(!instanceId||!epoch||!tail[4])return void 0;return{instanceId,epoch,goalId:tail[4]}}async function submitAndFollowGoalWith(verifyFact,nc,space2,endpoint,caller,deadlineMs,submit,opts){if(!Number.isSafeInteger(deadlineMs)||deadlineMs<=0)throw new EpEnvelopeError("bad-request","goal following requires a positive integer deadline",void 0,"not-executed");const acceptingCaller={...caller};const terminals=new Map;const terminalKey=(goalId,instanceId,epoch)=>`${goalId}\0${instanceId}\0${epoch}`;let terminalPromptedRead=false;const progressSubject=epGoalProgressGrantRow(space2,endpoint,acceptingCaller);const work=new AbortController;const timers=new Set;let activeNc=nc;let activeSub;let generation=0;let unbindReconnect;let completed=false;let stopped=opts?.signal?.aborted===true;let submitted=false;let subError;let observationError;let wake;let abortPhase;let needsReconcile=false;let reading=false;let progressReady=false;const aborted2=new Promise(resolve=>{abortPhase=resolve});const onAbort=()=>{stopped=true;work.abort();abortPhase?.();wake?.()};const phaseError=code=>new EpEnvelopeError(code,submitted?"the goal submission was interrupted while in flight; its outcome is unknown. It may have been accepted or executed; do NOT retry without inspecting 'ps'/'inspect' first (SPEC 13.6)":"goal observation stopped or exceeded its deadline before submission; the manager request WAS NOT RUN",void 0,submitted?"unknown":"not-executed");let deadline=Date.now()+deadlineMs;const bounded=async(operation,until)=>{if(stopped||completed)throw phaseError("unavailable");const remaining=until-Date.now();if(remaining<=0)throw phaseError("deadline-exceeded");let timer;try{return await Promise.race([operation(),aborted2.then(()=>{throw phaseError("unavailable")}),new Promise((_,reject)=>{timer=setTimeout(()=>reject(phaseError("deadline-exceeded")),Math.min(remaining,2147483647));timers.add(timer)})])}finally{if(timer!==void 0){clearTimeout(timer);timers.delete(timer)}}};const subscribe=next=>{if(completed||stopped)return;const mine=++generation;activeSub?.unsubscribe();activeNc=next;progressReady=false;subError=void 0;activeSub=next.subscribe(progressSubject,{callback:(err3,msg)=>{if(completed||stopped||mine!==generation)return;if(err3){subError??=err3;wake?.();return}const origin=goalProgressOrigin(space2,endpoint,acceptingCaller,msg.subject);if(!origin)return;let ev;try{ev=JSON.parse(dec3.decode(msg.data))}catch{return}if(ev?.phase==="terminal"&&ev.goalId===origin.goalId){terminals.set(terminalKey(origin.goalId,origin.instanceId,origin.epoch),{state:String(ev.state),data:ev.data});if(!terminalPromptedRead){terminalPromptedRead=true;needsReconcile=true}wake?.()}}})};const replaceConnection=next=>{if(completed||stopped)return;try{subscribe(next)}catch(err3){subError=err3 instanceof Error?err3:new Error(String(err3));wake?.();return}const mine=generation;void bounded(()=>next.flush(),deadline).then(()=>{if(completed||stopped||mine!==generation)return;progressReady=true;needsReconcile=true;wake?.()},err3=>{if(completed||stopped||mine!==generation)return;subError=err3 instanceof Error?err3:new Error(String(err3));wake?.()})};try{opts?.signal?.addEventListener("abort",onAbort,{once:true});if(stopped)throw phaseError("unavailable");if(opts?.prepare){let timer;try{await Promise.race([opts.prepare(work.signal,deadline),aborted2,new Promise(resolve=>{timer=setTimeout(()=>{work.abort(new DOMException("the goal follow's deadline passed","TimeoutError"));setTimeout(resolve,0)},Math.min(deadline-Date.now(),2147483647))})]);work.signal.throwIfAborted()}catch(err3){throw stopped?phaseError("unavailable"):work.signal.aborted&&!unansweredRequest(err3)?phaseError("deadline-exceeded"):err3}finally{clearTimeout(timer)}}subscribe(opts?.currentNc?.()??nc);unbindReconnect=opts?.onReconnect?.(replaceConnection);for(;;){const preparing=activeNc;try{await bounded(()=>preparing.flush(),deadline)}catch(err3){if(!stopped&&preparing!==activeNc)continue;throw err3}if(stopped)throw phaseError("unavailable");const current2=opts?.currentNc?.();if(current2&¤t2!==activeNc)subscribe(current2);if(preparing===activeNc){progressReady=true;break}}if(stopped)throw phaseError("unavailable");submitted=true;let attributed;let submission;try{attributed=await bounded(()=>submission=submit(work.signal),deadline)}catch(err3){work.abort();let turn;const cause=submission?await Promise.race([submission.then(()=>err3,failure2=>failure2),new Promise(resolve=>{turn=setTimeout(()=>resolve(err3),0)})]).finally(()=>clearTimeout(turn)):err3;if(cause instanceof EpEnvelopeError&&cause.outcome==="not-executed")throw cause;const failure=stopped?phaseError("unavailable"):err3;const message2=failure instanceof Error?failure.message:String(failure);throw new EpEnvelopeError(failure instanceof EpEnvelopeError?failure.code:"unavailable",failure instanceof EpEnvelopeError&&failure.outcome==="unknown"&&message2.includes("do NOT retry")?message2:`${message2}; the submission outcome is unknown. It may have been accepted or executed; do NOT retry without inspecting 'ps'/'inspect' first (SPEC 13.6)`,cause instanceof EpEnvelopeError?cause.details:void 0,"unknown")}if(attributed.reply.ok!==true)return attributed;const acceptance=attributed.reply.data;const goalId=acceptance?.goalId;if(typeof goalId!=="string")return attributed;const acceptedFingerprint=typeof acceptance?.fingerprint==="string"?acceptance.fingerprint:void 0;const acceptedBy=attributed.responder;const acceptedKey2=terminalKey(goalId,acceptedBy.instanceId,acceptedBy.epoch);const readinessDeadlineMs=acceptance?.readinessDeadlineMs;const followDeadlineMs=typeof readinessDeadlineMs==="number"&&Number.isSafeInteger(readinessDeadlineMs)&&readinessDeadlineMs>=0?Math.max(deadlineMs,readinessDeadlineMs+GOAL_FOLLOW_MARGIN_MS):deadlineMs;deadline=Date.now()+followDeadlineMs;const reconcileAt=deadline-Math.min(deadlineMs,followDeadlineMs/2);let finalReadRequested=false;const reconcile=async()=>{if(!opts?.reconcile||completed||stopped||reading||!progressReady)return;reading=true;needsReconcile=false;try{const result=await opts.reconcile(goalId,attributed,{caller:{...acceptingCaller},signal:work.signal,deadlineMs:Math.max(1,deadline-Date.now())});if(completed||stopped||Date.now()>=deadline)return;if(!result||typeof result!=="object"||result.goalId!==goalId)throw new EpEnvelopeError("internal","goal-result reply is malformed or names a different goal; it cannot authorize this outcome (SPEC 13.6)");if(result.result!==void 0){const ref={endpoint,caller:acceptingCaller,goalId};const fact=await verifyFact(result.result,"goal-result reply",ref);if(acceptedFingerprint!==void 0&&fact.fingerprint!==acceptedFingerprint)throw new EpEnvelopeError("internal","goal result fingerprint does not match the accepted goal (SPEC 13.6)");if(fact.committer!==void 0&&fact.committer.instanceId!==acceptedBy.instanceId)throw new EpEnvelopeError("internal",`goal result fact was committed by instance ${fact.committer.instanceId}, not ${acceptedBy.instanceId}, which accepted the goal; it cannot authorize this outcome (SPEC 13.6)`);terminals.set(acceptedKey2,{state:fact.state,data:fact.data})}}catch(err3){if(!completed&&!stopped&&Date.now()<deadline)observationError=err3 instanceof Error?err3:new Error(String(err3))}finally{reading=false;if(!completed&&!stopped)wake?.()}};const current=opts?.currentNc?.();if(current&¤t!==activeNc&&!stopped)replaceConnection(current);needsReconcile=true;while(!terminals.has(acceptedKey2)&&!stopped&&!observationError&&!subError&&Date.now()<deadline){if(!finalReadRequested&&Date.now()>=reconcileAt){finalReadRequested=true;needsReconcile=true}if(needsReconcile&&!reading)void reconcile();if(terminals.has(acceptedKey2)||stopped||observationError||subError)break;await new Promise(resolve=>{const until=finalReadRequested?deadline:reconcileAt;const timer=setTimeout(()=>{timers.delete(timer);wake=void 0;resolve()},Math.max(0,Math.min(until-Date.now(),2147483647)));timers.add(timer);wake=()=>{clearTimeout(timer);timers.delete(timer);wake=void 0;resolve()}})}const terminal=terminals.get(acceptedKey2);const observationFailure=(code,reason2)=>({...attributed,reply:{...attributed.reply,ok:false,data:void 0,error:{code,outcome:"unknown",message:`the goal "${goalId}" was accepted, but ${reason2}. THE GOAL IS UNAFFECTED - it may already have succeeded; this is not evidence the goal failed. Do NOT retry: another submission could duplicate the effect. Inspect 'ps'/'inspect' first (SPEC 13.6)`}}});if(stopped)return observationFailure("unavailable","the endpoint was stopped while awaiting its outcome");if(observationError)return observationFailure("unavailable",`following its outcome failed: ${observationError.message}`);if(!terminal&&subError)return subError instanceof import_nats_core2.PermissionViolationError?observationFailure("permission-denied",`this caller is NOT PERMITTED to hear its outcome: the broker refused the per-goal progress subscription "${progressSubject}" (${subError.message}); grant this caller the per-goal progress read row`):observationFailure("unavailable",`the per-goal progress subscription "${progressSubject}" FAILED (${subError.name}: ${subError.message}); this is NOT a grant refusal, so changing ACLs is the wrong remedy`);if(!terminal)return observationFailure("deadline-exceeded",`no terminal arrived within ${followDeadlineMs}ms; this is a timeout on the WAIT`);if(terminal.state==="succeeded")return{...attributed,reply:{...attributed.reply,ok:true,data:terminal.data,error:void 0}};const d=terminal.data??{};const raw=typeof d.error==="string"?d.error:typeof d.reason==="string"?d.reason:`the goal settled ${terminal.state}`;const details=Array.isArray(d.details)?d.details:void 0;const message=renderLifecycleBlocked(raw,details?{details}:void 0);const fromAccept=lifecycleBlockedFrom(attributed.reply.error);const merged=details??(fromAccept?[fromAccept]:void 0);return{...attributed,reply:{...attributed.reply,ok:false,error:{code:terminal.state,message,...merged?{details:merged}:{}}}}}finally{completed=true;opts?.signal?.removeEventListener("abort",onAbort);unbindReconnect?.();activeSub?.unsubscribe();for(const timer of timers)clearTimeout(timer);timers.clear();wake=void 0;work.abort();abortPhase?.()}}var import_jetstream6=__toESM(require_mod4(),1);var import_transport_node6=__toESM(require_transport_node(),1);var import_node_crypto6=require("node:crypto");var CONTRACT_ARTIFACT_MAX_BYTES=256*1024;var CONTRACT_CLOSURE_MAX_BYTES=1024*1024;var CONTRACT_CLOSURE_MAX_REF_DEPTH=32;var STORE_RESOURCES=new WeakMap;async function contractStoreContext(nc,space2){if(nc===null||typeof nc!=="object"||typeof nc.close!=="function")throw new EpEnvelopeError("failed-precondition","a contract-store context is constructed from ONE binding-layer connection; separate resources are never accepted (SPEC 13.4)");if(typeof space2!=="string"||space2.length===0)throw new EpEnvelopeError("failed-precondition","a contract-store context needs a space");const js=(0,import_jetstream6.jetstream)(nc);const jsm=await(0,import_jetstream6.jetstreamManager)(nc,{checkAPI:false});const ctx=Object.freeze({space:space2});STORE_RESOURCES.set(ctx,{js,jsm});return ctx}function resources(ctx){const r=ctx===null||typeof ctx!=="object"?void 0:STORE_RESOURCES.get(ctx);if(r===void 0)throw new EpEnvelopeError("failed-precondition",`the contract-store context was not constructed by contractStoreContext(); a hand-assembled resource bundle never authorizes - the space bond is constructed, not asserted (SPEC 13.4)`);return r}function contractArtifactDigestHex(bytes){return(0,import_node_crypto6.createHash)("sha256").update(bytes).digest("hex")}function assertCanonicalArtifactBytes(bytes,what){let text2;try{text2=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new EpEnvelopeError("contract-invalid",`${what} is not valid UTF-8; only strict canonical JSON is a contract artifact (SPEC 13.7)`)}let value;try{value=JSON.parse(text2)}catch(e){throw new EpEnvelopeError("contract-invalid",`${what} does not parse as JSON (${e.message}); only strict canonical JSON is a contract artifact (SPEC 13.7)`)}let canonical;try{canonical=canonicalJson(value)}catch(e){throw new EpEnvelopeError("contract-invalid",`${what} is not interchangeable I-JSON (${e.message}); only strict canonical JSON is a contract artifact (SPEC 13.7)`)}if(canonical!==text2)throw new EpEnvelopeError("contract-invalid",`${what} is not its own RFC 8785 canonical serialization; a noncanonical encoding never gets its own content identity (SPEC 13.7)`);return value}function verifyStored(data,digestHex,subject){if(data.length>CONTRACT_ARTIFACT_MAX_BYTES)return void 0;if(contractArtifactDigestHex(data)!==digestHex)return void 0;try{assertCanonicalArtifactBytes(data,`the artifact at ${subject}`)}catch{return void 0}return data}async function fetchContractArtifact(ctx,digestHex,opts={}){const{jsm}=resources(ctx);const stream=epcStreamName(ctx.space);const subject=epcSubject(ctx.space,digestHex);const read=async req=>{try{const stored=await jsm.direct.getMessage(stream,req);return stored===null?"absent":stored.data}catch(e){if(e?.code===10037)return"absent";throw new EpEnvelopeError("unavailable",`the contract-store read for ${digestHex} failed (a failed observation is never absence, SPEC 13.7): ${e?.message??String(e)}`)}};const last=await read({last_by_subj:subject});if(last==="absent")return void 0;const okLast=verifyStored(last,digestHex,subject);if(okLast!==void 0)return okLast;if(opts.lastOnly)throw new ContractStoreCorruptError(`the message at ${subject} does not recompute its digest as strict canonical JSON (SPEC 13.7)`);const first=await read({seq:0,next_by_subj:subject});if(first==="absent")return void 0;const okFirst=verifyStored(first,digestHex,subject);if(okFirst!==void 0)return okFirst;throw new ContractStoreCorruptError(`no message at ${subject} recomputes its digest as strict canonical JSON (checked both the last and the create-only winner); verify-on-read is the tamper boundary and a store with no verifying artifact never serves (SPEC 13.7)`)}var ContractStoreCorruptError=class extends EpEnvelopeError{constructor(message){super("internal",message)}};async function fetchContractClosure(ctx,closureDigestRef,extractRefs,opts={}){resources(ctx);const max=opts.maxArtifacts??CONTRACT_CLOSURE_MAX_ARTIFACTS;if(!Number.isSafeInteger(max)||max<=0||max>CONTRACT_CLOSURE_MAX_ARTIFACTS)throw new EpEnvelopeError("failed-precondition",`maxArtifacts must be a positive integer at or below the frozen ${CONTRACT_CLOSURE_MAX_ARTIFACTS}-artifact ceiling (a caller narrows, never widens); got ${JSON.stringify(opts.maxArtifacts)} (SPEC 13.7)`);const budgetMs=opts.walkBudgetMs??3e4;if(!Number.isSafeInteger(budgetMs)||budgetMs<=0)throw new EpEnvelopeError("failed-precondition",`walkBudgetMs must be a positive integer; got ${JSON.stringify(opts.walkBudgetMs)}`);if(typeof extractRefs!=="function")throw new EpEnvelopeError("failed-precondition","a closure fetch requires the reference-resolution seam (extractRefs); the store never guesses a document's reference shape (SPEC 13.7)");const startedAt2=performance.now();const overBudget=()=>performance.now()-startedAt2>budgetMs;const raceBudget=async(p,what)=>{opts.signal?.throwIfAborted();const rem=budgetMs-(performance.now()-startedAt2);if(rem<=0)throw new EpEnvelopeError("deadline-exceeded",`the closure walk exhausted its ${budgetMs}ms budget before ${what} (SPEC 13.7/13.8)`);let timer;let onAbort;const bound=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new EpEnvelopeError("deadline-exceeded",`the closure walk exceeded its ${budgetMs}ms budget during ${what}; a closure fetch is bounded and fails loud, never hangs (SPEC 13.7/13.8)`)),rem);onAbort=()=>reject(opts.signal?.reason);opts.signal?.addEventListener("abort",onAbort,{once:true})});try{return await Promise.race([p,bound])}finally{clearTimeout(timer);if(onAbort)opts.signal?.removeEventListener("abort",onAbort)}};const getArtifact=hex3=>{const memo=opts.artifactMemo;if(!memo)return fetchContractArtifact(ctx,hex3);const hit=memo.get(hex3);if(hit)return hit;const p=fetchContractArtifact(ctx,hex3);p.catch(()=>{});memo.set(hex3,p);return p};const closureHex=contractRefToHex(closureDigestRef);const manifestBytes=await raceBudget(getArtifact(closureHex),`the manifest fetch for ${closureHex}`);if(manifestBytes===void 0)throw new EpEnvelopeError("failed-precondition",`the closure manifest ${closureHex} is not published; a closure digest names its manifest artifact (SPEC 13.7)`);const manifest=parseClosureManifest(assertCanonicalArtifactBytes(manifestBytes,`the manifest ${closureHex}`),`the manifest ${closureHex}`);const rootHex=contractRefToHex(manifest.root);const out=new Map;let totalBytes=0;let rootReReached=false;const queue=[{hex:rootHex,depth:0}];while(queue.length>0){if(overBudget())throw new EpEnvelopeError("deadline-exceeded",`the closure walk for ${closureHex} exceeded its ${budgetMs}ms budget; a closure fetch is bounded and fails loud, never hangs (SPEC 13.7/13.8)`);const{hex:hex3,depth}=queue.shift();if(depth>CONTRACT_CLOSURE_MAX_REF_DEPTH)throw new EpEnvelopeError("contract-invalid",`the closure walk for ${closureHex} exceeds the ${CONTRACT_CLOSURE_MAX_REF_DEPTH}-deep reference chain bound (SPEC 13.7)`);if(out.has(hex3))continue;if(out.size>=max)throw new EpEnvelopeError("failed-precondition",`the contract closure exceeds the ${max}-artifact bound; a truncated closure never verifies as complete (SPEC 13.7)`);const bytes=await raceBudget(getArtifact(hex3),`the fetch of ${hex3}`);if(bytes===void 0)throw new EpEnvelopeError("failed-precondition",`the closure references artifact ${hex3} but it is not published; a closure is fetched all-or-nothing (SPEC 13.7)`);totalBytes+=bytes.length;if(totalBytes>CONTRACT_CLOSURE_MAX_BYTES)throw new EpEnvelopeError("contract-invalid",`the closure for ${closureHex} exceeds the ${CONTRACT_CLOSURE_MAX_BYTES}-byte bound (SPEC 13.7)`);out.set(hex3,bytes);const refs=extractRefs(new Uint8Array(bytes),hex3);if(!Array.isArray(refs)||!refs.every(r=>typeof r==="string"))throw new EpEnvelopeError("internal",`the reference-resolution seam returned a non-string-array for ${hex3}; a garbled resolution never extends a closure (SPEC 13.7)`);if(refs.length>CONTRACT_CLOSURE_MAX_ARTIFACTS)throw new EpEnvelopeError("contract-invalid",`artifact ${hex3} names ${refs.length} references, above the ${CONTRACT_CLOSURE_MAX_ARTIFACTS}-reference cap; an unbounded reference list never extends a closure (SPEC 13.7)`);if(overBudget())throw new EpEnvelopeError("deadline-exceeded",`the closure walk for ${closureHex} exceeded its ${budgetMs}ms budget resolving references for ${hex3} (SPEC 13.7/13.8)`);for(const r of refs){const rHex=contractRefToHex(r);if(rHex===rootHex)rootReReached=true;queue.push({hex:rHex,depth:depth+1})}}const walked=new Set;for(const hex3 of out.keys())if(hex3!==rootHex||rootReReached)walked.add(sha256Ref(hex3));const memberSet=new Set(manifest.members);for(const m of walked)if(!memberSet.has(m))throw new EpEnvelopeError("contract-invalid",`the closure walk reached ${m} but the manifest ${closureHex} does not name it; an under-naming manifest never verifies (SPEC 13.7)`);for(const m of memberSet)if(!walked.has(m))throw new EpEnvelopeError("contract-invalid",`the manifest ${closureHex} names ${m} but the walk never reached it; an over-naming manifest never verifies (SPEC 13.7)`);return{manifest,artifacts:out}}var SERVICE_RENEWAL_TTL_SECONDS=24*60*60;var SERVICE_AUTHORITY_MAX_BYTES=2*1024*1024;var SERVICE_CALLER_PAYLOAD_OVERHEAD=1024;var SERVICE_CALLER_PAYLOAD_FLOOR=SERVICE_AUTHORITY_MAX_BYTES+SERVICE_CALLER_PAYLOAD_OVERHEAD;var MANAGER_START_PAYLOAD_FLOOR=CONTRACT_ARTIFACT_MAX_BYTES+SERVICE_CALLER_PAYLOAD_OVERHEAD;var import_nkeys4=__toESM(require_mod(),1);var import_node_crypto7=require("node:crypto");var Types;(function(Types2){Types2["Operator"]="operator";Types2["Account"]="account";Types2["User"]="user";Types2["Activation"]="activation";Types2["AuthorizationResponse"]="authorization_response"})(Types||(Types={}));(function(nacl2){"use strict";var u64=function(h2,l){this.hi=h2|0>>>0;this.lo=l|0>>>0};var gf=function(init){var i,r=new Float64Array(16);if(init)for(i=0;i<init.length;i++)r[i]=init[i];return r};var randombytes=function(){throw new Error("no PRNG")};var _0=new Uint8Array(16);var _9=new Uint8Array(32);_9[0]=9;var gf0=gf(),gf1=gf([1]),_121665=gf([56129,1]),D=gf([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),D2=gf([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),X=gf([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),Y=gf([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),I=gf([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function L32(x,c){return x<<c|x>>>32-c}function ld32(x,i){var u=x[i+3]&255;u=u<<8|x[i+2]&255;u=u<<8|x[i+1]&255;return u<<8|x[i+0]&255}function dl64(x,i){var h2=x[i]<<24|x[i+1]<<16|x[i+2]<<8|x[i+3];var l=x[i+4]<<24|x[i+5]<<16|x[i+6]<<8|x[i+7];return new u64(h2,l)}function st32(x,j,u){var i;for(i=0;i<4;i++){x[j+i]=u&255;u>>>=8}}function ts64(x,i,u){x[i]=u.hi>>24&255;x[i+1]=u.hi>>16&255;x[i+2]=u.hi>>8&255;x[i+3]=u.hi&255;x[i+4]=u.lo>>24&255;x[i+5]=u.lo>>16&255;x[i+6]=u.lo>>8&255;x[i+7]=u.lo&255}function vn(x,xi,y,yi,n){var i,d=0;for(i=0;i<n;i++)d|=x[xi+i]^y[yi+i];return(1&d-1>>>8)-1}function crypto_verify_16(x,xi,y,yi){return vn(x,xi,y,yi,16)}function crypto_verify_32(x,xi,y,yi){return vn(x,xi,y,yi,32)}function core(out,inp,k,c,h2){var w=new Uint32Array(16),x=new Uint32Array(16),y=new Uint32Array(16),t=new Uint32Array(4);var i,j,m;for(i=0;i<4;i++){x[5*i]=ld32(c,4*i);x[1+i]=ld32(k,4*i);x[6+i]=ld32(inp,4*i);x[11+i]=ld32(k,16+4*i)}for(i=0;i<16;i++)y[i]=x[i];for(i=0;i<20;i++){for(j=0;j<4;j++){for(m=0;m<4;m++)t[m]=x[(5*j+4*m)%16];t[1]^=L32(t[0]+t[3]|0,7);t[2]^=L32(t[1]+t[0]|0,9);t[3]^=L32(t[2]+t[1]|0,13);t[0]^=L32(t[3]+t[2]|0,18);for(m=0;m<4;m++)w[4*j+(j+m)%4]=t[m]}for(m=0;m<16;m++)x[m]=w[m]}if(h2){for(i=0;i<16;i++)x[i]=x[i]+y[i]|0;for(i=0;i<4;i++){x[5*i]=x[5*i]-ld32(c,4*i)|0;x[6+i]=x[6+i]-ld32(inp,4*i)|0}for(i=0;i<4;i++){st32(out,4*i,x[5*i]);st32(out,16+4*i,x[6+i])}}else{for(i=0;i<16;i++)st32(out,4*i,x[i]+y[i]|0)}}function crypto_core_salsa20(out,inp,k,c){core(out,inp,k,c,false);return 0}function crypto_core_hsalsa20(out,inp,k,c){core(out,inp,k,c,true);return 0}var sigma=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k){var z2=new Uint8Array(16),x=new Uint8Array(64);var u,i;if(!b)return 0;for(i=0;i<16;i++)z2[i]=0;for(i=0;i<8;i++)z2[i]=n[i];while(b>=64){crypto_core_salsa20(x,z2,k,sigma);for(i=0;i<64;i++)c[cpos+i]=(m?m[mpos+i]:0)^x[i];u=1;for(i=8;i<16;i++){u=u+(z2[i]&255)|0;z2[i]=u&255;u>>>=8}b-=64;cpos+=64;if(m)mpos+=64}if(b>0){crypto_core_salsa20(x,z2,k,sigma);for(i=0;i<b;i++)c[cpos+i]=(m?m[mpos+i]:0)^x[i]}return 0}function crypto_stream_salsa20(c,cpos,d,n,k){return crypto_stream_salsa20_xor(c,cpos,null,0,d,n,k)}function crypto_stream(c,cpos,d,n,k){var s=new Uint8Array(32);crypto_core_hsalsa20(s,n,k,sigma);return crypto_stream_salsa20(c,cpos,d,n.subarray(16),s)}function crypto_stream_xor(c,cpos,m,mpos,d,n,k){var s=new Uint8Array(32);crypto_core_hsalsa20(s,n,k,sigma);return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,n.subarray(16),s)}function add1305(h2,c){var j,u=0;for(j=0;j<17;j++){u=u+(h2[j]+c[j]|0)|0;h2[j]=u&255;u>>>=8}}var minusp=new Uint32Array([5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252]);function crypto_onetimeauth(out,outpos,m,mpos,n,k){var s,i,j,u;var x=new Uint32Array(17),r=new Uint32Array(17),h2=new Uint32Array(17),c=new Uint32Array(17),g=new Uint32Array(17);for(j=0;j<17;j++)r[j]=h2[j]=0;for(j=0;j<16;j++)r[j]=k[j];r[3]&=15;r[4]&=252;r[7]&=15;r[8]&=252;r[11]&=15;r[12]&=252;r[15]&=15;while(n>0){for(j=0;j<17;j++)c[j]=0;for(j=0;j<16&&j<n;++j)c[j]=m[mpos+j];c[j]=1;mpos+=j;n-=j;add1305(h2,c);for(i=0;i<17;i++){x[i]=0;for(j=0;j<17;j++)x[i]=x[i]+h2[j]*(j<=i?r[i-j]:320*r[i+17-j]|0)|0|0}for(i=0;i<17;i++)h2[i]=x[i];u=0;for(j=0;j<16;j++){u=u+h2[j]|0;h2[j]=u&255;u>>>=8}u=u+h2[16]|0;h2[16]=u&3;u=5*(u>>>2)|0;for(j=0;j<16;j++){u=u+h2[j]|0;h2[j]=u&255;u>>>=8}u=u+h2[16]|0;h2[16]=u}for(j=0;j<17;j++)g[j]=h2[j];add1305(h2,minusp);s=-(h2[16]>>>7)|0;for(j=0;j<17;j++)h2[j]^=s&(g[j]^h2[j]);for(j=0;j<16;j++)c[j]=k[j+16];c[16]=0;add1305(h2,c);for(j=0;j<16;j++)out[outpos+j]=h2[j];return 0}function crypto_onetimeauth_verify(h2,hpos,m,mpos,n,k){var x=new Uint8Array(16);crypto_onetimeauth(x,0,m,mpos,n,k);return crypto_verify_16(h2,hpos,x,0)}function crypto_secretbox(c,m,d,n,k){var i;if(d<32)return-1;crypto_stream_xor(c,0,m,0,d,n,k);crypto_onetimeauth(c,16,c,32,d-32,c);for(i=0;i<16;i++)c[i]=0;return 0}function crypto_secretbox_open(m,c,d,n,k){var i;var x=new Uint8Array(32);if(d<32)return-1;crypto_stream(x,0,32,n,k);if(crypto_onetimeauth_verify(c,16,c,32,d-32,x)!==0)return-1;crypto_stream_xor(m,0,c,0,d,n,k);for(i=0;i<32;i++)m[i]=0;return 0}function set25519(r,a){var i;for(i=0;i<16;i++)r[i]=a[i]|0}function car25519(o){var c;var i;for(i=0;i<16;i++){o[i]+=65536;c=Math.floor(o[i]/65536);o[(i+1)*(i<15?1:0)]+=c-1+37*(c-1)*(i===15?1:0);o[i]-=c*65536}}function sel25519(p,q,b){var t,c=~(b-1);for(var i=0;i<16;i++){t=c&(p[i]^q[i]);p[i]^=t;q[i]^=t}}function pack25519(o,n){var i,j,b;var m=gf(),t=gf();for(i=0;i<16;i++)t[i]=n[i];car25519(t);car25519(t);car25519(t);for(j=0;j<2;j++){m[0]=t[0]-65517;for(i=1;i<15;i++){m[i]=t[i]-65535-(m[i-1]>>16&1);m[i-1]&=65535}m[15]=t[15]-32767-(m[14]>>16&1);b=m[15]>>16&1;m[14]&=65535;sel25519(t,m,1-b)}for(i=0;i<16;i++){o[2*i]=t[i]&255;o[2*i+1]=t[i]>>8}}function neq25519(a,b){var c=new Uint8Array(32),d=new Uint8Array(32);pack25519(c,a);pack25519(d,b);return crypto_verify_32(c,0,d,0)}function par25519(a){var d=new Uint8Array(32);pack25519(d,a);return d[0]&1}function unpack25519(o,n){var i;for(i=0;i<16;i++)o[i]=n[2*i]+(n[2*i+1]<<8);o[15]&=32767}function A(o,a,b){var i;for(i=0;i<16;i++)o[i]=a[i]+b[i]|0}function Z(o,a,b){var i;for(i=0;i<16;i++)o[i]=a[i]-b[i]|0}function M(o,a,b){var i,j,t=new Float64Array(31);for(i=0;i<31;i++)t[i]=0;for(i=0;i<16;i++){for(j=0;j<16;j++){t[i+j]+=a[i]*b[j]}}for(i=0;i<15;i++){t[i]+=38*t[i+16]}for(i=0;i<16;i++)o[i]=t[i];car25519(o);car25519(o)}function S(o,a){M(o,a,a)}function inv25519(o,i){var c=gf();var a;for(a=0;a<16;a++)c[a]=i[a];for(a=253;a>=0;a--){S(c,c);if(a!==2&&a!==4)M(c,c,i)}for(a=0;a<16;a++)o[a]=c[a]}function pow2523(o,i){var c=gf();var a;for(a=0;a<16;a++)c[a]=i[a];for(a=250;a>=0;a--){S(c,c);if(a!==1)M(c,c,i)}for(a=0;a<16;a++)o[a]=c[a]}function crypto_scalarmult(q,n,p){var z2=new Uint8Array(32);var x=new Float64Array(80),r,i;var a=gf(),b=gf(),c=gf(),d=gf(),e=gf(),f=gf();for(i=0;i<31;i++)z2[i]=n[i];z2[31]=n[31]&127|64;z2[0]&=248;unpack25519(x,p);for(i=0;i<16;i++){b[i]=x[i];d[i]=a[i]=c[i]=0}a[0]=d[0]=1;for(i=254;i>=0;--i){r=z2[i>>>3]>>>(i&7)&1;sel25519(a,b,r);sel25519(c,d,r);A(e,a,c);Z(a,a,c);A(c,b,d);Z(b,b,d);S(d,e);S(f,a);M(a,c,a);M(c,b,e);A(e,a,c);Z(a,a,c);S(b,a);Z(c,d,f);M(a,c,_121665);A(a,a,d);M(c,c,a);M(a,d,f);M(d,b,x);S(b,e);sel25519(a,b,r);sel25519(c,d,r)}for(i=0;i<16;i++){x[i+16]=a[i];x[i+32]=c[i];x[i+48]=b[i];x[i+64]=d[i]}var x32=x.subarray(32);var x16=x.subarray(16);inv25519(x32,x32);M(x16,x16,x32);pack25519(q,x16);return 0}function crypto_scalarmult_base(q,n){return crypto_scalarmult(q,n,_9)}function crypto_box_keypair(y,x){randombytes(x,32);return crypto_scalarmult_base(y,x)}function crypto_box_beforenm(k,y,x){var s=new Uint8Array(32);crypto_scalarmult(s,x,y);return crypto_core_hsalsa20(k,_0,s,sigma)}var crypto_box_afternm=crypto_secretbox;var crypto_box_open_afternm=crypto_secretbox_open;function crypto_box(c,m,d,n,y,x){var k=new Uint8Array(32);crypto_box_beforenm(k,y,x);return crypto_box_afternm(c,m,d,n,k)}function crypto_box_open(m,c,d,n,y,x){var k=new Uint8Array(32);crypto_box_beforenm(k,y,x);return crypto_box_open_afternm(m,c,d,n,k)}function add64(){var a=0,b=0,c=0,d=0,m16=65535,l,h2,i;for(i=0;i<arguments.length;i++){l=arguments[i].lo;h2=arguments[i].hi;a+=l&m16;b+=l>>>16;c+=h2&m16;d+=h2>>>16}b+=a>>>16;c+=b>>>16;d+=c>>>16;return new u64(c&m16|d<<16,a&m16|b<<16)}function shr64(x,c){return new u64(x.hi>>>c,x.lo>>>c|x.hi<<32-c)}function xor64(){var l=0,h2=0,i;for(i=0;i<arguments.length;i++){l^=arguments[i].lo;h2^=arguments[i].hi}return new u64(h2,l)}function R(x,c){var h2,l,c1=32-c;if(c<32){h2=x.hi>>>c|x.lo<<c1;l=x.lo>>>c|x.hi<<c1}else if(c<64){h2=x.lo>>>c|x.hi<<c1;l=x.hi>>>c|x.lo<<c1}return new u64(h2,l)}function Ch(x,y,z2){var h2=x.hi&y.hi^~x.hi&z2.hi,l=x.lo&y.lo^~x.lo&z2.lo;return new u64(h2,l)}function Maj(x,y,z2){var h2=x.hi&y.hi^x.hi&z2.hi^y.hi&z2.hi,l=x.lo&y.lo^x.lo&z2.lo^y.lo&z2.lo;return new u64(h2,l)}function Sigma0(x){return xor64(R(x,28),R(x,34),R(x,39))}function Sigma1(x){return xor64(R(x,14),R(x,18),R(x,41))}function sigma0(x){return xor64(R(x,1),R(x,8),shr64(x,7))}function sigma1(x){return xor64(R(x,19),R(x,61),shr64(x,6))}var K=[new u64(1116352408,3609767458),new u64(1899447441,602891725),new u64(3049323471,3964484399),new u64(3921009573,2173295548),new u64(961987163,4081628472),new u64(1508970993,3053834265),new u64(2453635748,2937671579),new u64(2870763221,3664609560),new u64(3624381080,2734883394),new u64(310598401,1164996542),new u64(607225278,1323610764),new u64(1426881987,3590304994),new u64(1925078388,4068182383),new u64(2162078206,991336113),new u64(2614888103,633803317),new u64(3248222580,3479774868),new u64(3835390401,2666613458),new u64(4022224774,944711139),new u64(264347078,2341262773),new u64(604807628,2007800933),new u64(770255983,1495990901),new u64(1249150122,1856431235),new u64(1555081692,3175218132),new u64(1996064986,2198950837),new u64(2554220882,3999719339),new u64(2821834349,766784016),new u64(2952996808,2566594879),new u64(3210313671,3203337956),new u64(3336571891,1034457026),new u64(3584528711,2466948901),new u64(113926993,3758326383),new u64(338241895,168717936),new u64(666307205,1188179964),new u64(773529912,1546045734),new u64(1294757372,1522805485),new u64(1396182291,2643833823),new u64(1695183700,2343527390),new u64(1986661051,1014477480),new u64(2177026350,1206759142),new u64(2456956037,344077627),new u64(2730485921,1290863460),new u64(2820302411,3158454273),new u64(3259730800,3505952657),new u64(3345764771,106217008),new u64(3516065817,3606008344),new u64(3600352804,1432725776),new u64(4094571909,1467031594),new u64(275423344,851169720),new u64(430227734,3100823752),new u64(506948616,1363258195),new u64(659060556,3750685593),new u64(883997877,3785050280),new u64(958139571,3318307427),new u64(1322822218,3812723403),new u64(1537002063,2003034995),new u64(1747873779,3602036899),new u64(1955562222,1575990012),new u64(2024104815,1125592928),new u64(2227730452,2716904306),new u64(2361852424,442776044),new u64(2428436474,593698344),new u64(2756734187,3733110249),new u64(3204031479,2999351573),new u64(3329325298,3815920427),new u64(3391569614,3928383900),new u64(3515267271,566280711),new u64(3940187606,3454069534),new u64(4118630271,4000239992),new u64(116418474,1914138554),new u64(174292421,2731055270),new u64(289380356,3203993006),new u64(460393269,320620315),new u64(685471733,587496836),new u64(852142971,1086792851),new u64(1017036298,365543100),new u64(1126000580,2618297676),new u64(1288033470,3409855158),new u64(1501505948,4234509866),new u64(1607167915,987167468),new u64(1816402316,1246189591)];function crypto_hashblocks(x,m,n){var z2=[],b=[],a=[],w=[],t,i,j;for(i=0;i<8;i++)z2[i]=a[i]=dl64(x,8*i);var pos=0;while(n>=128){for(i=0;i<16;i++)w[i]=dl64(m,8*i+pos);for(i=0;i<80;i++){for(j=0;j<8;j++)b[j]=a[j];t=add64(a[7],Sigma1(a[4]),Ch(a[4],a[5],a[6]),K[i],w[i%16]);b[7]=add64(t,Sigma0(a[0]),Maj(a[0],a[1],a[2]));b[3]=add64(b[3],t);for(j=0;j<8;j++)a[(j+1)%8]=b[j];if(i%16===15){for(j=0;j<16;j++){w[j]=add64(w[j],w[(j+9)%16],sigma0(w[(j+1)%16]),sigma1(w[(j+14)%16]))}}}for(i=0;i<8;i++){a[i]=add64(a[i],z2[i]);z2[i]=a[i]}pos+=128;n-=128}for(i=0;i<8;i++)ts64(x,8*i,z2[i]);return n}var iv=new Uint8Array([106,9,230,103,243,188,201,8,187,103,174,133,132,202,167,59,60,110,243,114,254,148,248,43,165,79,245,58,95,29,54,241,81,14,82,127,173,230,130,209,155,5,104,140,43,62,108,31,31,131,217,171,251,65,189,107,91,224,205,25,19,126,33,121]);function crypto_hash(out,m,n){var h2=new Uint8Array(64),x=new Uint8Array(256);var i,b=n;for(i=0;i<64;i++)h2[i]=iv[i];crypto_hashblocks(h2,m,n);n%=128;for(i=0;i<256;i++)x[i]=0;for(i=0;i<n;i++)x[i]=m[b-n+i];x[n]=128;n=256-128*(n<112?1:0);x[n-9]=0;ts64(x,n-8,new u64(b/536870912|0,b<<3));crypto_hashblocks(h2,x,n);for(i=0;i<64;i++)out[i]=h2[i];return 0}function add(p,q){var a=gf(),b=gf(),c=gf(),d=gf(),e=gf(),f=gf(),g=gf(),h2=gf(),t=gf();Z(a,p[1],p[0]);Z(t,q[1],q[0]);M(a,a,t);A(b,p[0],p[1]);A(t,q[0],q[1]);M(b,b,t);M(c,p[3],q[3]);M(c,c,D2);M(d,p[2],q[2]);A(d,d,d);Z(e,b,a);Z(f,d,c);A(g,d,c);A(h2,b,a);M(p[0],e,f);M(p[1],h2,g);M(p[2],g,f);M(p[3],e,h2)}function cswap(p,q,b){var i;for(i=0;i<4;i++){sel25519(p[i],q[i],b)}}function pack(r,p){var tx=gf(),ty=gf(),zi=gf();inv25519(zi,p[2]);M(tx,p[0],zi);M(ty,p[1],zi);pack25519(r,ty);r[31]^=par25519(tx)<<7}function scalarmult(p,q,s){var b,i;set25519(p[0],gf0);set25519(p[1],gf1);set25519(p[2],gf1);set25519(p[3],gf0);for(i=255;i>=0;--i){b=s[i/8|0]>>(i&7)&1;cswap(p,q,b);add(q,p);add(p,p);cswap(p,q,b)}}function scalarbase(p,s){var q=[gf(),gf(),gf(),gf()];set25519(q[0],X);set25519(q[1],Y);set25519(q[2],gf1);M(q[3],X,Y);scalarmult(p,q,s)}function crypto_sign_keypair(pk,sk,seeded){var d=new Uint8Array(64);var p=[gf(),gf(),gf(),gf()];var i;if(!seeded)randombytes(sk,32);crypto_hash(d,sk,32);d[0]&=248;d[31]&=127;d[31]|=64;scalarbase(p,d);pack(pk,p);for(i=0;i<32;i++)sk[i+32]=pk[i];return 0}var L=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function modL(r,x){var carry,i,j,k;for(i=63;i>=32;--i){carry=0;for(j=i-32,k=i-12;j<k;++j){x[j]+=carry-16*x[i]*L[j-(i-32)];carry=Math.floor((x[j]+128)/256);x[j]-=carry*256}x[j]+=carry;x[i]=0}carry=0;for(j=0;j<32;j++){x[j]+=carry-(x[31]>>4)*L[j];carry=x[j]>>8;x[j]&=255}for(j=0;j<32;j++)x[j]-=carry*L[j];for(i=0;i<32;i++){x[i+1]+=x[i]>>8;r[i]=x[i]&255}}function reduce(r){var x=new Float64Array(64),i;for(i=0;i<64;i++)x[i]=r[i];for(i=0;i<64;i++)r[i]=0;modL(r,x)}function crypto_sign(sm,m,n,sk){var d=new Uint8Array(64),h2=new Uint8Array(64),r=new Uint8Array(64);var i,j,x=new Float64Array(64);var p=[gf(),gf(),gf(),gf()];crypto_hash(d,sk,32);d[0]&=248;d[31]&=127;d[31]|=64;var smlen=n+64;for(i=0;i<n;i++)sm[64+i]=m[i];for(i=0;i<32;i++)sm[32+i]=d[32+i];crypto_hash(r,sm.subarray(32),n+32);reduce(r);scalarbase(p,r);pack(sm,p);for(i=32;i<64;i++)sm[i]=sk[i];crypto_hash(h2,sm,n+64);reduce(h2);for(i=0;i<64;i++)x[i]=0;for(i=0;i<32;i++)x[i]=r[i];for(i=0;i<32;i++){for(j=0;j<32;j++){x[i+j]+=h2[i]*d[j]}}modL(sm.subarray(32),x);return smlen}function unpackneg(r,p){var t=gf(),chk=gf(),num=gf(),den=gf(),den2=gf(),den4=gf(),den6=gf();set25519(r[2],gf1);unpack25519(r[1],p);S(num,r[1]);M(den,num,D);Z(num,num,r[2]);A(den,r[2],den);S(den2,den);S(den4,den2);M(den6,den4,den2);M(t,den6,num);M(t,t,den);pow2523(t,t);M(t,t,num);M(t,t,den);M(t,t,den);M(r[0],t,den);S(chk,r[0]);M(chk,chk,den);if(neq25519(chk,num))M(r[0],r[0],I);S(chk,r[0]);M(chk,chk,den);if(neq25519(chk,num))return-1;if(par25519(r[0])===p[31]>>7)Z(r[0],gf0,r[0]);M(r[3],r[0],r[1]);return 0}function crypto_sign_open(m,sm,n,pk){var i;var t=new Uint8Array(32),h2=new Uint8Array(64);var p=[gf(),gf(),gf(),gf()],q=[gf(),gf(),gf(),gf()];if(n<64)return-1;if(unpackneg(q,pk))return-1;for(i=0;i<n;i++)m[i]=sm[i];for(i=0;i<32;i++)m[i+32]=pk[i];crypto_hash(h2,m,n);reduce(h2);scalarmult(p,q,h2);scalarbase(q,sm.subarray(32));add(p,q);pack(t,p);n-=64;if(crypto_verify_32(sm,0,t,0)){for(i=0;i<n;i++)m[i]=0;return-1}for(i=0;i<n;i++)m[i]=sm[i+64];return n}var crypto_secretbox_KEYBYTES=32,crypto_secretbox_NONCEBYTES=24,crypto_secretbox_ZEROBYTES=32,crypto_secretbox_BOXZEROBYTES=16,crypto_scalarmult_BYTES=32,crypto_scalarmult_SCALARBYTES=32,crypto_box_PUBLICKEYBYTES=32,crypto_box_SECRETKEYBYTES=32,crypto_box_BEFORENMBYTES=32,crypto_box_NONCEBYTES=crypto_secretbox_NONCEBYTES,crypto_box_ZEROBYTES=crypto_secretbox_ZEROBYTES,crypto_box_BOXZEROBYTES=crypto_secretbox_BOXZEROBYTES,crypto_sign_BYTES=64,crypto_sign_PUBLICKEYBYTES=32,crypto_sign_SECRETKEYBYTES=64,crypto_sign_SEEDBYTES=32,crypto_hash_BYTES=64;nacl2.lowlevel={crypto_core_hsalsa20,crypto_stream_xor,crypto_stream,crypto_stream_salsa20_xor,crypto_stream_salsa20,crypto_onetimeauth,crypto_onetimeauth_verify,crypto_verify_16,crypto_verify_32,crypto_secretbox,crypto_secretbox_open,crypto_scalarmult,crypto_scalarmult_base,crypto_box_beforenm,crypto_box_afternm,crypto_box,crypto_box_open,crypto_box_keypair,crypto_hash,crypto_sign,crypto_sign_keypair,crypto_sign_open,crypto_secretbox_KEYBYTES,crypto_secretbox_NONCEBYTES,crypto_secretbox_ZEROBYTES,crypto_secretbox_BOXZEROBYTES,crypto_scalarmult_BYTES,crypto_scalarmult_SCALARBYTES,crypto_box_PUBLICKEYBYTES,crypto_box_SECRETKEYBYTES,crypto_box_BEFORENMBYTES,crypto_box_NONCEBYTES,crypto_box_ZEROBYTES,crypto_box_BOXZEROBYTES,crypto_sign_BYTES,crypto_sign_PUBLICKEYBYTES,crypto_sign_SECRETKEYBYTES,crypto_sign_SEEDBYTES,crypto_hash_BYTES,gf,D,L,pack25519,unpack25519,M,A,S,Z,pow2523,add,set25519,modL,scalarmult,scalarbase};function checkLengths(k,n){if(k.length!==crypto_secretbox_KEYBYTES)throw new Error("bad key size");if(n.length!==crypto_secretbox_NONCEBYTES)throw new Error("bad nonce size")}function checkBoxLengths(pk,sk){if(pk.length!==crypto_box_PUBLICKEYBYTES)throw new Error("bad public key size");if(sk.length!==crypto_box_SECRETKEYBYTES)throw new Error("bad secret key size")}function checkArrayTypes(){for(var i=0;i<arguments.length;i++){if(!(arguments[i]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}}function cleanup(arr){for(var i=0;i<arr.length;i++)arr[i]=0}nacl2.randomBytes=function(n){var b=new Uint8Array(n);randombytes(b,n);return b};nacl2.secretbox=function(msg,nonce3,key){checkArrayTypes(msg,nonce3,key);checkLengths(key,nonce3);var m=new Uint8Array(crypto_secretbox_ZEROBYTES+msg.length);var c=new Uint8Array(m.length);for(var i=0;i<msg.length;i++)m[i+crypto_secretbox_ZEROBYTES]=msg[i];crypto_secretbox(c,m,m.length,nonce3,key);return c.subarray(crypto_secretbox_BOXZEROBYTES)};nacl2.secretbox.open=function(box,nonce3,key){checkArrayTypes(box,nonce3,key);checkLengths(key,nonce3);var c=new Uint8Array(crypto_secretbox_BOXZEROBYTES+box.length);var m=new Uint8Array(c.length);for(var i=0;i<box.length;i++)c[i+crypto_secretbox_BOXZEROBYTES]=box[i];if(c.length<32)return null;if(crypto_secretbox_open(m,c,c.length,nonce3,key)!==0)return null;return m.subarray(crypto_secretbox_ZEROBYTES)};nacl2.secretbox.keyLength=crypto_secretbox_KEYBYTES;nacl2.secretbox.nonceLength=crypto_secretbox_NONCEBYTES;nacl2.secretbox.overheadLength=crypto_secretbox_BOXZEROBYTES;nacl2.scalarMult=function(n,p){checkArrayTypes(n,p);if(n.length!==crypto_scalarmult_SCALARBYTES)throw new Error("bad n size");if(p.length!==crypto_scalarmult_BYTES)throw new Error("bad p size");var q=new Uint8Array(crypto_scalarmult_BYTES);crypto_scalarmult(q,n,p);return q};nacl2.scalarMult.base=function(n){checkArrayTypes(n);if(n.length!==crypto_scalarmult_SCALARBYTES)throw new Error("bad n size");var q=new Uint8Array(crypto_scalarmult_BYTES);crypto_scalarmult_base(q,n);return q};nacl2.scalarMult.scalarLength=crypto_scalarmult_SCALARBYTES;nacl2.scalarMult.groupElementLength=crypto_scalarmult_BYTES;nacl2.box=function(msg,nonce3,publicKey,secretKey){var k=nacl2.box.before(publicKey,secretKey);return nacl2.secretbox(msg,nonce3,k)};nacl2.box.before=function(publicKey,secretKey){checkArrayTypes(publicKey,secretKey);checkBoxLengths(publicKey,secretKey);var k=new Uint8Array(crypto_box_BEFORENMBYTES);crypto_box_beforenm(k,publicKey,secretKey);return k};nacl2.box.after=nacl2.secretbox;nacl2.box.open=function(msg,nonce3,publicKey,secretKey){var k=nacl2.box.before(publicKey,secretKey);return nacl2.secretbox.open(msg,nonce3,k)};nacl2.box.open.after=nacl2.secretbox.open;nacl2.box.keyPair=function(){var pk=new Uint8Array(crypto_box_PUBLICKEYBYTES);var sk=new Uint8Array(crypto_box_SECRETKEYBYTES);crypto_box_keypair(pk,sk);return{publicKey:pk,secretKey:sk}};nacl2.box.keyPair.fromSecretKey=function(secretKey){checkArrayTypes(secretKey);if(secretKey.length!==crypto_box_SECRETKEYBYTES)throw new Error("bad secret key size");var pk=new Uint8Array(crypto_box_PUBLICKEYBYTES);crypto_scalarmult_base(pk,secretKey);return{publicKey:pk,secretKey:new Uint8Array(secretKey)}};nacl2.box.publicKeyLength=crypto_box_PUBLICKEYBYTES;nacl2.box.secretKeyLength=crypto_box_SECRETKEYBYTES;nacl2.box.sharedKeyLength=crypto_box_BEFORENMBYTES;nacl2.box.nonceLength=crypto_box_NONCEBYTES;nacl2.box.overheadLength=nacl2.secretbox.overheadLength;nacl2.sign=function(msg,secretKey){checkArrayTypes(msg,secretKey);if(secretKey.length!==crypto_sign_SECRETKEYBYTES)throw new Error("bad secret key size");var signedMsg=new Uint8Array(crypto_sign_BYTES+msg.length);crypto_sign(signedMsg,msg,msg.length,secretKey);return signedMsg};nacl2.sign.open=function(signedMsg,publicKey){checkArrayTypes(signedMsg,publicKey);if(publicKey.length!==crypto_sign_PUBLICKEYBYTES)throw new Error("bad public key size");var tmp=new Uint8Array(signedMsg.length);var mlen=crypto_sign_open(tmp,signedMsg,signedMsg.length,publicKey);if(mlen<0)return null;var m=new Uint8Array(mlen);for(var i=0;i<m.length;i++)m[i]=tmp[i];return m};nacl2.sign.detached=function(msg,secretKey){var signedMsg=nacl2.sign(msg,secretKey);var sig=new Uint8Array(crypto_sign_BYTES);for(var i=0;i<sig.length;i++)sig[i]=signedMsg[i];return sig};nacl2.sign.detached.verify=function(msg,sig,publicKey){checkArrayTypes(msg,sig,publicKey);if(sig.length!==crypto_sign_BYTES)throw new Error("bad signature size");if(publicKey.length!==crypto_sign_PUBLICKEYBYTES)throw new Error("bad public key size");var sm=new Uint8Array(crypto_sign_BYTES+msg.length);var m=new Uint8Array(crypto_sign_BYTES+msg.length);var i;for(i=0;i<crypto_sign_BYTES;i++)sm[i]=sig[i];for(i=0;i<msg.length;i++)sm[i+crypto_sign_BYTES]=msg[i];return crypto_sign_open(m,sm,sm.length,publicKey)>=0};nacl2.sign.keyPair=function(){var pk=new Uint8Array(crypto_sign_PUBLICKEYBYTES);var sk=new Uint8Array(crypto_sign_SECRETKEYBYTES);crypto_sign_keypair(pk,sk);return{publicKey:pk,secretKey:sk}};nacl2.sign.keyPair.fromSecretKey=function(secretKey){checkArrayTypes(secretKey);if(secretKey.length!==crypto_sign_SECRETKEYBYTES)throw new Error("bad secret key size");var pk=new Uint8Array(crypto_sign_PUBLICKEYBYTES);for(var i=0;i<pk.length;i++)pk[i]=secretKey[32+i];return{publicKey:pk,secretKey:new Uint8Array(secretKey)}};nacl2.sign.keyPair.fromSeed=function(seed){checkArrayTypes(seed);if(seed.length!==crypto_sign_SEEDBYTES)throw new Error("bad seed size");var pk=new Uint8Array(crypto_sign_PUBLICKEYBYTES);var sk=new Uint8Array(crypto_sign_SECRETKEYBYTES);for(var i=0;i<32;i++)sk[i]=seed[i];crypto_sign_keypair(pk,sk,true);return{publicKey:pk,secretKey:sk}};nacl2.sign.publicKeyLength=crypto_sign_PUBLICKEYBYTES;nacl2.sign.secretKeyLength=crypto_sign_SECRETKEYBYTES;nacl2.sign.seedLength=crypto_sign_SEEDBYTES;nacl2.sign.signatureLength=crypto_sign_BYTES;nacl2.hash=function(msg){checkArrayTypes(msg);var h2=new Uint8Array(crypto_hash_BYTES);crypto_hash(h2,msg,msg.length);return h2};nacl2.hash.hashLength=crypto_hash_BYTES;nacl2.verify=function(x,y){checkArrayTypes(x,y);if(x.length===0||y.length===0)return false;if(x.length!==y.length)return false;return vn(x,0,y,0,x.length)===0?true:false};nacl2.setPRNG=function(fn){randombytes=fn};(function(){var crypto2=typeof globalThis!=="undefined"?globalThis.crypto||globalThis.msCrypto:null;if(crypto2&&crypto2.getRandomValues){var QUOTA=65536;nacl2.setPRNG(function(x,n){var i,v=new Uint8Array(n);for(i=0;i<n;i+=QUOTA){crypto2.getRandomValues(v.subarray(i,i+Math.min(n-i,QUOTA)))}for(i=0;i<n;i++)x[i]=v[i];cleanup(v)})}else if(typeof require!=="undefined"){crypto2=require("crypto");if(crypto2&&crypto2.randomBytes){nacl2.setPRNG(function(x,n){var i,v=crypto2.randomBytes(n);for(i=0;i<n;i++)x[i]=v[i];cleanup(v)})}}})()})(typeof module!=="undefined"&&module.exports?module.exports:globalThis.nacl=globalThis.nacl||{});var nacl=typeof module!=="undefined"&&module.exports?module.exports:globalThis.nacl;var denoHelper={fromSeed:nacl.sign.keyPair.fromSeed,sign:nacl.sign.detached,verify:nacl.sign.detached.verify,randomBytes:nacl.randomBytes,scalarBaseMultiply:nacl.scalarMult.base,seal:nacl.box,open:nacl.box.open};var helper;function setEd25519Helper(lib){helper=lib}var crc16tab=new Uint16Array([0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920]);var NKeysErrorCode2;(function(NKeysErrorCode3){NKeysErrorCode3["InvalidPrefixByte"]="nkeys: invalid prefix byte";NKeysErrorCode3["InvalidKey"]="nkeys: invalid key";NKeysErrorCode3["InvalidPublicKey"]="nkeys: invalid public key";NKeysErrorCode3["InvalidSeedLen"]="nkeys: invalid seed length";NKeysErrorCode3["InvalidSeed"]="nkeys: invalid seed";NKeysErrorCode3["InvalidCurveSeed"]="nkeys: invalid curve seed";NKeysErrorCode3["InvalidCurveKey"]="nkeys: not a valid curve key";NKeysErrorCode3["InvalidCurveOperation"]="nkeys: curve key is not valid for sign/verify";NKeysErrorCode3["InvalidNKeyOperation"]="keys: only curve key can seal/open";NKeysErrorCode3["InvalidEncoding"]="nkeys: invalid encoded key";NKeysErrorCode3["InvalidRecipient"]="nkeys: not a valid recipient public curve key";NKeysErrorCode3["InvalidEncrypted"]="nkeys: encrypted input is not valid";NKeysErrorCode3["CannotSign"]="nkeys: cannot sign, no private key available";NKeysErrorCode3["PublicKeyOnly"]="nkeys: no seed or private key available";NKeysErrorCode3["InvalidChecksum"]="nkeys: invalid checksum";NKeysErrorCode3["SerializationError"]="nkeys: serialization error";NKeysErrorCode3["ApiError"]="nkeys: api error";NKeysErrorCode3["ClearedPair"]="nkeys: pair is cleared"})(NKeysErrorCode2||(NKeysErrorCode2={}));var Prefix2;(function(Prefix3){Prefix3[Prefix3["Unknown"]=-1]="Unknown";Prefix3[Prefix3["Seed"]=144]="Seed";Prefix3[Prefix3["Private"]=120]="Private";Prefix3[Prefix3["Operator"]=112]="Operator";Prefix3[Prefix3["Server"]=104]="Server";Prefix3[Prefix3["Cluster"]=16]="Cluster";Prefix3[Prefix3["Account"]=0]="Account";Prefix3[Prefix3["User"]=160]="User";Prefix3[Prefix3["Curve"]=184]="Curve"})(Prefix2||(Prefix2={}));setEd25519Helper(denoHelper);var Algorithms;(function(Algorithms2){Algorithms2["v1"]="ed25519";Algorithms2["v2"]="ed25519-nkey"})(Algorithms||(Algorithms={}));var import_nats_core3=__toESM(require_mod3(),1);var import_nkeys5=__toESM(require_mod(),1);function idFromCreds(creds){return identityFromCreds(creds).id}function jwtFromCreds(creds){return creds.match(/BEGIN NATS USER JWT-----\s*([\s\S]*?)\s*------END NATS USER JWT/)?.[1].trim()}function credsFingerprint(creds){const jwt2=jwtFromCreds(creds);if(!jwt2)throw new Error("creds: no NATS user JWT block found - cannot fingerprint");return(0,import_node_crypto7.createHash)("sha256").update(jwt2).digest("hex")}function credsClaims(creds){const payload=jwtFromCreds(creds)?.split(".")[1];if(!payload)throw new Error("creds: no NATS user JWT block found");try{return JSON.parse(Buffer.from(payload,"base64url").toString("utf8"))}catch{throw new Error("creds: undecodable user JWT payload")}}function credsRenewalDelayMs(creds){const claims2=credsClaims(creds);if(typeof claims2.exp!=="number")throw new Error("creds source returned a cred without a numeric exp - a standing-renewal endpoint requires bounded creds (mint with a lifetime, or pass a static string instead of a source)");const iatMs=(typeof claims2.iat==="number"?claims2.iat:Date.now()/1e3)*1e3;const expMs=claims2.exp*1e3;return iatMs+.75*(expMs-iatMs)-Date.now()}function identityFromCreds(creds){const seedM=creds.match(/BEGIN USER NKEY SEED-----\s*([\s\S]*?)\s*------END USER NKEY SEED/);if(!seedM)throw new Error("creds: no user nkey seed block found");const seed=seedM[1].trim();const signer=nativeNkeySigner(new TextEncoder().encode(seed));const id2=signer.getPublicKey();signer.clear();const payload=jwtFromCreds(creds)?.split(".")[1];const sub=payload?JSON.parse(Buffer.from(payload,"base64url").toString("utf8")).sub:void 0;if(sub&&sub!==id2)throw new Error(`creds: seed identity ${id2} != JWT subject ${sub}`);return{id:id2,seed}}var ED25519_P=(1n<<255n)-19n;async function drainAndClose(nc,graceMs=1e3){let timer;try{if(!nc.isClosed()){await Promise.race([nc.drain().catch(()=>{}),nc.closed(),new Promise(resolve=>{timer=setTimeout(resolve,graceMs)})])}}finally{clearTimeout(timer);await nc.close()}}var import_nkeys9=__toESM(require_mod(),1);var import_transport_node14=__toESM(require_transport_node(),1);var import_node_events=require("node:events");var import_node_crypto10=require("node:crypto");var import_promises=require("node:timers/promises");var import_node_net=require("node:net");var import_transport_node13=__toESM(require_transport_node(),1);var import_nats_core6=__toESM(require_mod3(),1);var LIVENESS_PLANES=Object.freeze(["manager","delivery"]);function isLivenessPlane(plane){return LIVENESS_PLANES.includes(plane)}function responderFromLease(lease,expectedHolder){if(lease===void 0)return"unbound";if(lease.ready!==true)return"unbound";if(expectedHolder!==void 0&&lease.holder!==expectedHolder)return"stale";return"bound"}function responderFromProbe(outcome,answered){if(outcome==="replied")return answered??"unknown";if(outcome==="noResponders")return"unbound";return"unknown"}function parseLivenessAnswer(body,expectPlane){if(typeof body!=="object"||body===null)return void 0;const{plane,responder,instance}=body;if(typeof plane!=="string"||!isLivenessPlane(plane)||plane!==expectPlane)return void 0;if(responder!=="bound"&&responder!=="unbound"&&responder!=="stale"&&responder!=="unknown")return void 0;if(instance!==void 0&&(typeof instance!=="string"||instance===""))return void 0;return instance===void 0?{plane,responder}:{plane,responder,instance}}var import_node_crypto8=require("node:crypto");var startedAt=Math.floor(performance.timeOrigin);var scopes=new Map;function processRuntime(lifecycleUid){let own=scopes.get(lifecycleUid);if(!own){own=Object.freeze({id:(0,import_node_crypto8.randomUUID)(),startedAt,source:"endpoint-process"});scopes.set(lifecycleUid,own)}return own}var import_nkeys6=__toESM(require_mod(),1);function nativeCredsAuthenticator(creds){return nonce3=>{const blocks=/\s*(?:(?:[-]{3,}[^\n]*[-]{3,}\n)(.+)(?:\n\s*[-]{3,}[^\n]*[-]{3,}\n))/ig;const text2=typeof creds==="function"?creds():creds;const jwtBlock=blocks.exec(text2);if(!jwtBlock)throw new Error("unable to parse credentials");const seedBlock=blocks.exec(text2);if(!seedBlock)throw new Error("unable to parse credentials");const seed=new TextEncoder().encode(seedBlock[1].trim());let signer;try{signer=nativeNkeySigner(seed);return{jwt:jwtBlock[1].trim(),nkey:signer.getPublicKey(),sig:nonce3?(0,import_nkeys6.encode)(signer.sign(new TextEncoder().encode(nonce3))):""}}finally{seed.fill(0);signer?.clear()}}}var RENEWAL_WINDOW=Object.freeze({from:.5,to:.8});var RENEWAL_SPACING_MS=1e3;var MAX_TIMER_MS2=2147483647;var armed=new Map;function pickFree(taken,from,to){const free=[];let lo=from;for(const t of[...taken].sort((a,b)=>a-b)){if(t-RENEWAL_SPACING_MS>lo)free.push([lo,Math.min(to,t-RENEWAL_SPACING_MS)]);lo=Math.max(lo,t+RENEWAL_SPACING_MS);if(lo>=to)break}if(lo<=to)free.push([lo,to]);const total=free.reduce((sum,[a,b])=>sum+(b-a),0);if(free.length===0)return from+Math.random()*(to-from);let r=Math.random()*total;for(const[a,b]of free){if(r<=b-a)return a+r;r-=b-a}return free[free.length-1][1]}function armRenewal(space2,issuedAtMs,expiresAtMs,renew,minDelayMs=0){const now=Date.now();const life=Math.max(0,expiresAtMs-issuedAtMs);const from=Math.max(issuedAtMs+RENEWAL_WINDOW.from*life,now+minDelayMs);const to=Math.max(issuedAtMs+RENEWAL_WINDOW.to*life,from);const taken=armed.get(space2)??new Set;armed.set(space2,taken);const at=pickFree([...taken],from,to);taken.add(at);const release=()=>{taken.delete(at);if(taken.size===0&&armed.get(space2)===taken)armed.delete(space2)};let timer;const wait=()=>{const left=at-Date.now();timer=setTimeout(left>MAX_TIMER_MS2?wait:()=>{release();renew()},Math.min(Math.max(0,left),MAX_TIMER_MS2));timer.unref?.()};wait();return()=>{clearTimeout(timer);release()}}function renewalDeadlineMs(issuedAtMs,expiresAtMs){return issuedAtMs+RENEWAL_WINDOW.to*Math.max(0,expiresAtMs-issuedAtMs)}function jitteredBackoffMs(attempt,baseMs,capMs){const step=Math.min(capMs,baseMs*2**attempt);return step/2+Math.random()*(step/2)}var BROKER_FLOOR=Object.freeze({major:2,minor:12});function parseServerVersion(v){const m=/^(\d+)\.(\d+)\.(\d+)/.exec(v.trim());if(!m)return null;return{major:Number(m[1]),minor:Number(m[2]),patch:Number(m[3])}}function meetsBrokerFloor(version2){const p=parseServerVersion(version2);if(!p)return false;if(p.major!==BROKER_FLOOR.major)return p.major>BROKER_FLOOR.major;return p.minor>=BROKER_FLOOR.minor}function requireBrokerFloor(nc){const version2=nc.info?.version;if(!version2)throw new Error("control surface: connected broker reports no server version; refusing to start (floor is nats-server >= 2.12)");if(!meetsBrokerFloor(version2))throw new Error(`control surface: nats-server ${version2} is below the required floor 2.12; upgrade the broker (no degraded mode exists)`)}var import_jetstream10=__toESM(require_mod4(),1);var import_node_crypto9=require("node:crypto");var import_transport_node8=__toESM(require_transport_node(),1);var import_kv4=__toESM(require_mod6(),1);var import_obj=__toESM(require_mod7(),1);var import_jetstream7=__toESM(require_mod4(),1);function isJetStreamMissing(e,...codes){return e instanceof import_jetstream7.JetStreamApiError&&codes.includes(e.code)}function isConsumerNotFound(e){return isJetStreamMissing(e,import_jetstream7.JetStreamApiCodes.ConsumerNotFound)}function isStreamNotFound(e){return isJetStreamMissing(e,import_jetstream7.JetStreamApiCodes.StreamNotFound)}function isConsumerAlreadyExists(e){return isJetStreamMissing(e,10148)}var import_kv2=__toESM(require_mod6(),1);var import_internal=__toESM(require_internal_mod3(),1);var import_jetstream8=__toESM(require_mod4(),1);var IncompleteKvScan=class extends Error{bucket;received;expected;constructor(bucket,received,expected){super(`reading ${bucket} ended after ${received} of ~${expected} entries without reaching the end of the bucket - the connection or consumer died mid-pass. Refusing to return a partial view (a short or empty result here is indistinguishable from a real answer). Retry; if it persists, the link to the broker is dropping.`);this.bucket=bucket;this.received=received;this.expected=expected;this.name="IncompleteKvScan"}};async function liveKvEntries(kv,filterOrOptions,options){let filter;let opts;if(typeof filterOrOptions==="string"||Array.isArray(filterOrOptions)){filter=filterOrOptions;opts=options}else if(filterOrOptions&&typeof filterOrOptions==="object"){if(options!==void 0){throw new TypeError("liveKvEntries does not accept a third argument when the second argument is options")}opts=filterOrOptions}else{opts=options}if(opts?.signal?.aborted){throw opts.signal.reason??new Error("scan aborted")}if(!(kv instanceof import_internal.Bucket))throw new Error(`liveKvEntries needs the @nats-io/kv Bucket implementation to bind its own consumer (got ${kv?.constructor?.name??typeof kv}). Refusing to fall back to history(), whose hidden bind-time pending count is exactly the ambiguity this exists to remove.`);const bucket=kv;const cc=bucket._buildCC(filter??">",import_internal.KvWatchInclude.AllHistory,{headers_only:false});cc.mem_storage=true;const oc=await bucket.js.consumers.getPushConsumer(bucket.stream,cc);const own=oc;const api=own.api;const owned=[{name:own.name,answered:Promise.resolve(true)}];own.api=Object.assign(Object.create(api),{add:(...args)=>{const created=api.add(...args);owned.push({name:args[1].name,answered:created.then(()=>true,e=>e instanceof import_jetstream8.JetStreamApiError)});return created}});const latest=new Map;let received=0;let sawTerminal=false;let bucketName=bucket.bucket;let expected=0;let complete=false;try{const initialInfo=await oc.info(true);opts?.onConsumer?.(initialInfo);expected=initialInfo.num_pending;if(opts?.signal?.aborted){throw opts.signal.reason??new Error("scan aborted")}if(expected!==0){const iter=await oc.consume();const onAbort=()=>{iter.stop(opts?.signal?.reason??new Error("scan aborted"))};opts?.signal?.addEventListener("abort",onAbort,{once:true});try{for await(const m of iter){if(opts?.signal?.aborted)break;const e=bucket.jmToWatchEntry(m,false);received++;bucketName=e.bucket;const prior=latest.get(e.key);if(prior===void 0||e.revision>=prior.revision)latest.set(e.key,e);if(m.info.pending===0){sawTerminal=true;break}}}finally{opts?.signal?.removeEventListener("abort",onAbort);await iter.close()}}complete=expected===0||sawTerminal}finally{try{const answered=await Promise.all(owned.map(c=>c.answered));if(owned.at(-1).name!==own.name)throw new Error(`scan consumer ${own.name} was not created through the scan's consumer API - the pinned nats.js changed shape`);const deleteOwn=opts?.deleteOwnConsumer??((_stream,_name,del)=>del());let unanswered;for(let i=owned.length-1;i>=0;i--){const target2=owned[i].name;try{await deleteOwn(bucket.stream,target2,()=>bucket.jsm.consumers.delete(bucket.stream,target2))}catch(e){if(isPublishPermissionDenied(e))break;if(!isConsumerNotFound(e))throw e;if(!answered[i])unanswered??=target2}}if(unanswered)throw new Error(`the broker never answered the create of scan consumer ${unanswered}, so it can land after its delete and live until its inactive_threshold`)}catch(e){if(complete&&!opts?.signal?.aborted)throw e}}if(opts?.signal?.aborted){throw opts.signal.reason??new Error("scan aborted")}if(expected===0)return[];if(!sawTerminal)throw new IncompleteKvScan(bucketName,received,expected);const out=[];for(const e of latest.values())if(e.operation!=="DEL"&&e.operation!=="PURGE")out.push(e);return out}var DIRECT_BATCH=1024;async function lastKvEntries(kv){if(!(kv instanceof import_internal.Bucket))throw new Error(`lastKvEntries needs the @nats-io/kv Bucket implementation to address its backing stream (got ${kv?.constructor?.name??typeof kv})`);const bucket=kv;const nc=bucket.jsm.getConnection?.();if(nc===void 0)throw new Error("lastKvEntries needs the bucket's JetStream manager to expose its connection, to tell a denied Direct Get from a slow one");const watch=openPublishDenialWatch(nc,`${bucket.jsm.getOptions().apiPrefix||"$JS.API"}.DIRECT.GET.${bucket.stream}`,err3=>err3,"Direct Get");let page;try{const read=(async()=>{const latest=new Map;for(let seq=1;;){let last=0,pending=-1;try{await new Promise((resolve,reject)=>{bucket.jsm.direct.getBatch(bucket.stream,{seq,batch:DIRECT_BATCH,next_by_subj:`${bucket.prefix}.>`,callback:(done,sm)=>{if(done){done.err?reject(done.err):resolve();return}try{const e=bucket.smToEntry(sm);const prior=latest.get(e.key);if(prior===void 0||e.revision>=prior.revision)latest.set(e.key,e);last=sm.seq;pending=sm.pending}catch(e){page?.stop(e);reject(e)}}}).then(iter=>{page=iter},reject)})}catch(e){if(last===0&&e?.code===404)break;throw e}if(pending===0)break;if(last===0)throw new IncompleteKvScan(bucket.bucket,latest.size,latest.size+Math.max(pending,1));seq=last+1}return[...latest.values()]})();read.catch(()=>{});return await Promise.race([read,watch.denied.catch(err3=>{page?.stop(err3);throw err3})])}finally{watch.release()}}async function openAclRegistry(nc,space2,opts={}){const kvm=new import_kv2.Kvm(nc);return opts.create?kvm.create(aclBucket(space2)):kvm.open(aclBucket(space2))}async function readAcl(kv,owner2,lifecycleUid){const e=await kv.get(aclKey(owner2,lifecycleUid));if(!e||e.operation==="DEL"||e.operation==="PURGE")return void 0;try{const record3=e.json();if(!Array.isArray(record3.allowSubscribe))return void 0;return{record:record3,revision:e.revision}}catch{return void 0}}async function aclRetired(kv,owner2,lifecycleUid){const e=await kv.get(aclKey(owner2,lifecycleUid));return e?.operation==="DEL"||e?.operation==="PURGE"}var AmbiguousAclAlias=class extends Error{principal;lifecycleUids;constructor(principal,lifecycleUids){super(`read-ACL alias "${principal}" resolves to ${lifecycleUids.length} live lifecycle rows (${lifecycleUids.join(", ")}); at most one lifecycle may be live per alias (SPEC 13.1) - refusing to authorize on a first-match guess`);this.principal=principal;this.lifecycleUids=lifecycleUids}};async function readAclForAlias(kv,principal){const first=await enumerateLiveAclRows(kv,principal);if(first.length>1)throw new AmbiguousAclAlias(principal,first.map(l=>l.lifecycleUid).sort());const second=await enumerateLiveAclRows(kv,principal);if(second.length>1)throw new AmbiguousAclAlias(principal,second.map(l=>l.lifecycleUid).sort());if(second.length===0)return void 0;if(first.length===1&&first[0].lifecycleUid!==second[0].lifecycleUid)throw new AmbiguousAclAlias(principal,[first[0].lifecycleUid,second[0].lifecycleUid].sort());return{record:second[0].record,revision:second[0].revision,lifecycleUid:second[0].lifecycleUid}}async function enumerateLiveAclRows(kv,principal){const live=[];for(const e of await liveKvEntries(kv,aclAliasFilter(principal))){const parsed=parseLifecycleSubjectKey(e.key);if(!parsed||`${parsed.owner}.${parsed.actor}`!==principal)continue;let record3;try{record3=e.json()}catch{continue}if(!Array.isArray(record3.allowSubscribe))continue;live.push({lifecycleUid:parsed.lifecycleUid,record:record3,revision:e.revision})}return live}async function reissueAcl(kv,owner2,lifecycleUid,allowSubscribe){return writeAcl(kv,owner2,lifecycleUid,allowSubscribe,{reissue:true})}async function commitAcl(kv,owner2,lifecycleUid,allowSubscribe){return writeAcl(kv,owner2,lifecycleUid,allowSubscribe,{reissue:false})}async function writeAcl(kv,owner2,lifecycleUid,allowSubscribe,opts){const key=aclKey(owner2,lifecycleUid);let lastErr;for(let attempt=0;attempt<5;attempt++){const cur=await readAcl(kv,owner2,lifecycleUid);let issued;if(opts.reissue||!cur){issued=[...allowSubscribe]}else{issued=[...cur.record.issuedAllowSubscribe??cur.record.allowSubscribe];const excess=allowSubscribe.filter(a=>!patternInAllow(issued,a));if(excess.length>0){throw new Error(`commitAcl: cannot raise ACL above mint-time ceiling without reissue (entries [${excess.join(", ")}] not within ceiling [${issued.join(", ")}]); use reissueAcl from the provisioning path that also remints the JWT`)}}const next={allowSubscribe:[...allowSubscribe],issuedAllowSubscribe:issued,revision:(cur?.record.revision??0)+1,updatedAt:Date.now()};const data=new TextEncoder().encode(JSON.stringify(next));if(!cur){try{await kv.create(key,data);return next}catch(e){lastErr=e;try{const raw=await kv.get(key);if(raw){await kv.update(key,data,raw.revision);return next}}catch(e2){lastErr=e2}continue}}try{await kv.update(key,data,cur.revision);return next}catch(e){lastErr=e;continue}}throw new Error(`acl CAS exhausted retries for ${owner2}${lastErr?` - last error: ${lastErr instanceof Error?lastErr.message:String(lastErr)}`:""}`,lastErr instanceof Error?{cause:lastErr}:void 0)}var import_kv3=__toESM(require_mod6(),1);var StaleMembershipWrite=class extends Error{constructor(channel,owner2,attempted,current){super(`stale membership write for ${channel}/${owner2}: generation ${attempted} < current ${current}`);this.name="StaleMembershipWrite"}};async function openMembersRegistry(nc,space2,opts={}){const kvm=new import_kv3.Kvm(nc);return opts.create?kvm.create(membersBucket(space2)):kvm.open(membersBucket(space2))}async function readMember(kv,channel,owner2,lifecycleUid){const e=await kv.get(memberKey(channel,owner2,lifecycleUid));if(!e||e.operation==="DEL"||e.operation==="PURGE")return void 0;try{return{record:e.json(),revision:e.revision}}catch{return void 0}}async function commitMemberRevision(kv,next){const key=memberKey(next.channel,next.owner,next.lifecycleUid);const data=new TextEncoder().encode(JSON.stringify(next));for(let attempt=0;attempt<5;attempt++){const cur=await readMember(kv,next.channel,next.owner,next.lifecycleUid);if(!cur){try{return{record:next,revision:await kv.create(key,data)}}catch{continue}}if(next.generation<cur.record.generation)throw new StaleMembershipWrite(next.channel,next.owner,next.generation,cur.record.generation);try{return{record:next,revision:await kv.update(key,data,cur.revision)}}catch{continue}}throw new Error(`members CAS exhausted retries for ${key}`)}async function tombstoneMember(kv,channel,owner2,lifecycleUid,leaveCursor,writerIdentity,expectedGeneration){const key=memberKey(channel,owner2,lifecycleUid);let generation=expectedGeneration;for(let attempt=0;attempt<5;attempt++){const cur=await readMember(kv,channel,owner2,lifecycleUid);if(!cur)return void 0;generation??=cur.record.generation;if(cur.record.generation!==generation)throw new StaleMembershipWrite(channel,owner2,generation,cur.record.generation);if(cur.record.leaveCursor!==void 0&&cur.record.leaveCursor<=leaveCursor)return cur.record;const next={...cur.record,state:"live-confirmed",leaveCursor,writerIdentity,updatedAt:Date.now()};try{await kv.update(key,new TextEncoder().encode(JSON.stringify(next)),cur.revision);return next}catch{continue}}throw new Error(`members CAS exhausted retries for ${key}`)}async function activateMember(kv,channel,owner2,lifecycleUid,expectedGeneration,expectedJoinCursor){const key=memberKey(channel,owner2,lifecycleUid);for(let attempt=0;attempt<5;attempt++){const cur=await readMember(kv,channel,owner2,lifecycleUid);if(!cur)return void 0;const r=cur.record;if(r.generation!==expectedGeneration||r.joinCursor!==expectedJoinCursor||r.leaveCursor!==void 0)return void 0;if(r.activated)return r;const next={...r,activated:true,updatedAt:Date.now()};try{await kv.update(key,new TextEncoder().encode(JSON.stringify(next)),cur.revision);return next}catch{continue}}return void 0}async function deleteMember(kv,channel,owner2,lifecycleUid){await kv.purge(memberKey(channel,owner2,lifecycleUid))}async function listMembers(kv,filter={}){const out=[];for(const e of await liveKvEntries(kv)){const parsed=parseMemberKey(e.key);if(!parsed)continue;if(filter.channel!==void 0&&parsed.channel!==filter.channel)continue;if(filter.covering!==void 0&&parsed.channel!==filter.covering&&!(isChannelFamily(parsed.channel)&&subjectMatches(parsed.channel,filter.covering)))continue;if(filter.owner!==void 0&&parsed.principal!==filter.owner)continue;try{out.push(e.json())}catch{}}return out}function durableEligible(rec,seq){if(seq<=rec.joinCursor)return false;if(rec.leaveCursor!==void 0&&seq>rec.leaveCursor)return false;return true}var inventoryPasses=new WeakMap;function inventoryPassAfterNow(kv){let passes=inventoryPasses.get(kv);if(passes===void 0)inventoryPasses.set(kv,passes={});const state=passes;if(state.next)return state.next;const next=(state.running??Promise.resolve([])).catch(()=>[]).then(()=>{state.next=void 0;const pass=liveKvEntries(kv);state.running=pass;const done=()=>{if(state.running===pass)state.running=void 0};pass.then(done,done);return pass});state.next=next;return next}async function listLifecycleMemberChannels(kv,principal,lifecycleUid){const pr=parsePrincipalKey(principal);if(!pr)throw new Error(`listLifecycleMemberChannels: invalid principal "${principal}"`);assertLifecycleToken(lifecycleUid);const channels=new Set;for(const e of await inventoryPassAfterNow(kv)){const parsed=parseMemberKey(e.key);if(!parsed)continue;if(parsed.principal!==principal||parsed.lifecycleUid!==lifecycleUid)continue;if(!isConcreteChannel(parsed.channel)&&!isChannelFamily(parsed.channel))continue;channels.add(parsed.channel)}return[...channels].sort()}var import_jetstream9=__toESM(require_mod4(),1);var import_transport_node7=__toESM(require_transport_node(),1);var DEFAULT_DUPLICATE_WINDOW_MS=2*60*1e3;var DEFAULT_DUPLICATE_WINDOW=(0,import_transport_node7.nanos)(DEFAULT_DUPLICATE_WINDOW_MS);var PLANE3_MAX_MSGS_PER_SUBJECT=1e3;var BACKUP_PLANE3_DEDUP_WINDOW_MS=2*60*60*1e3;var PLANE3_DUPLICATE_WINDOW=(0,import_transport_node7.nanos)(BACKUP_PLANE3_DEDUP_WINDOW_MS);var DELIVERY_LIMIT_HEADER="Cotal-Delivery-Limit";var HISTORY_NO_COUNT=-1;var CHAT_HISTORY_DEFAULT=Object.freeze({maxAgeMs:0,perSubject:1e3});var INBOX_HISTORY_DEFAULT=Object.freeze({maxAgeMs:0,perSubject:PLANE3_MAX_MSGS_PER_SUBJECT});var DM_HISTORY_DEFAULT=Object.freeze({maxAgeMs:0,perSubject:HISTORY_NO_COUNT});var HISTORY_MAX_AGE_MS=3650*864e5;function historyLimitDefault(stream){if(stream==="chat")return CHAT_HISTORY_DEFAULT;return stream==="dm"?DM_HISTORY_DEFAULT:INBOX_HISTORY_DEFAULT}function historyLimitStreamOf(space2,stream){if(stream===chatStream(space2))return"chat";if(stream===inboxStream(space2))return"inbox";if(stream===dlvStream(space2))return"dlv";if(stream===dmStream(space2))return"dm";return void 0}function baseConfig(name,subjects){return{name,subjects,retention:import_jetstream9.RetentionPolicy.Limits,storage:import_jetstream9.StorageType.File,max_consumers:-1,max_msgs:-1,max_bytes:-1,max_age:0,max_msgs_per_subject:-1,max_msg_size:-1,discard:import_jetstream9.DiscardPolicy.Old,num_replicas:1,no_ack:false,duplicate_window:DEFAULT_DUPLICATE_WINDOW,compression:import_jetstream9.StoreCompression.None,allow_direct:false,mirror_direct:false,discard_new_per_subject:false,allow_rollup_hdrs:false,deny_delete:false,deny_purge:false,sealed:false,consumer_limits:{}}}function canonicalBackupStreamConfig(space2,stream,limit){const p=spacePrefix(space2);const target2=historyLimitStreamOf(space2,stream);const limits=target2&&{max_age:(0,import_transport_node7.nanos)((limit??historyLimitDefault(target2)).maxAgeMs),max_msgs_per_subject:(limit??historyLimitDefault(target2)).perSubject};if(target2==="chat")return{...baseConfig(stream,[`${p}.chat.>`]),...limits,allow_direct:true};if(target2==="dm")return{...baseConfig(stream,[`${p}.inst.>`]),...limits};if(stream===taskStream(space2)){return{...baseConfig(stream,[`${p}.svc.>`]),retention:import_jetstream9.RetentionPolicy.Workqueue}}if(target2==="inbox")return{...baseConfig(stream,[`${p}.dinbox.>`]),...limits,duplicate_window:PLANE3_DUPLICATE_WINDOW};if(target2==="dlv")return{...baseConfig(stream,[`${p}.dlv.>`]),...limits,duplicate_window:PLANE3_DUPLICATE_WINDOW};if(stream===wfjStreamName(space2))return baseConfig(stream,[`${p}.wfj.*`]);if(stream===recordsKvStreamName(space2))return{...kvStoreConfig(stream,recordsBucket(space2)),allow_direct:true,...endpointAuthorityStoreDefinitions(space2).records.hardenAfterCreate};if(stream===`KV_${admissionBucket(space2)}`)return{...kvStoreConfig(stream,admissionBucket(space2)),...admissionStoreDefinition(space2).hardenAfterCreate};for(const bucket of[channelBucket(space2),aclBucket(space2),membersBucket(space2)]){if(stream===`KV_${bucket}`){return{...baseConfig(stream,[`$KV.${bucket}.>`]),max_msgs_per_subject:1,discard:import_jetstream9.DiscardPolicy.New,allow_direct:true,allow_rollup_hdrs:true}}}throw new Error(`stream ${JSON.stringify(stream)} is not a backed-up stream for space ${JSON.stringify(space2)}`)}function kvStoreConfig(name,bucket){return{...baseConfig(name,[`$KV.${bucket}.>`]),max_msgs_per_subject:1,discard:import_jetstream9.DiscardPolicy.New,allow_rollup_hdrs:true}}var PRESENCE_STORAGE=import_jetstream10.StorageType.Memory;var DINBOX_MAX_ACK_PENDING=1e3;var MANAGER_LEASE_TTL_MS=1e4;var MANAGER_LEASE_RENEW_MS=MANAGER_LEASE_TTL_MS/4;var MANAGER_LEASE_ATTEMPT_MS=2e3;var LEGACY_MEMBERSHIP_MAX_BYTES=64*1024*1024;var MEMBERSHIP_MAX_VALUE_SIZE=256*1024;var ANYCAST_RECORD_MAX_VALUE_SIZE=64*1024;var LEGACY_ARTIFACT_STORE_MAX_BYTES=4*1024*1024*1024;function standaloneConnectOpts(auth){if(auth?.tls===void 0)throw new Error("standaloneConnectOpts requires an explicit `tls` boolean: pass `tls: true` to REQUIRE TLS, or `tls: false` for a plaintext broker. It has no default, because defaulting it would silently connect without the requirement that protects the credentials being passed.");const tlsOpt=auth.tls?{tls:{}}:{};if(auth.bearer!==void 0){if(!auth.sentinelCreds)throw new Error("user-mode standalone connect requires sentinelCreds alongside the bearer");if(auth.creds)throw new Error("standalone connect takes creds OR bearer+sentinelCreds, never both");const nonce3=`ibx${(0,import_node_crypto9.randomUUID)().replace(/-/g,"")}`;return{name:nonce3,inboxPrefix:`_INBOX_${nonce3}`,authenticator:[nativeCredsAuthenticator(auth.sentinelCreds),(0,import_transport_node8.tokenAuthenticator)(auth.bearer)],...tlsOpt}}const creds=auth.creds;if(!creds)return{...tlsOpt};return{authenticator:nativeCredsAuthenticator(creds),inboxPrefix:`_INBOX_${idFromCreds(typeof creds==="function"?creds():creds)}`,...tlsOpt}}function spaceMessageStreamConfigs(space2){return[chatStream(space2),dmStream(space2),taskStream(space2),inboxStream(space2),dlvStream(space2)].map(stream=>canonicalBackupStreamConfig(space2,stream))}function anycastStoreDefinition(space2){return{bucket:anycastBucket(space2),createOptions:{history:1,max_bytes:-1,maxValueSize:ANYCAST_RECORD_MAX_VALUE_SIZE}}}async function createSpaceStreams(jsm,space2){for(const definition of spaceMessageStreamConfigs(space2)){if(historyLimitStreamOf(space2,definition.name)){try{await jsm.streams.info(definition.name);continue}catch(e){if(!isStreamNotFound(e))throw e}}await jsm.streams.add(definition)}}function dmDurableConfig(space2,owner2,actor2,lifecycleUid,opts={}){const frontier=opts.activationFrontier??0;if(!Number.isInteger(frontier)||frontier<0)throw new Error(`dmDurableConfig activationFrontier must be a non-negative integer, got ${String(frontier)}`);const cfg={durable_name:dmDurable(owner2,actor2,lifecycleUid),filter_subject:unicastRecvFilter(space2,owner2,actor2),ack_policy:import_jetstream10.AckPolicy.Explicit,ack_wait:(0,import_transport_node8.nanos)(opts.ackWaitMs??6e4),...frontier>0?{deliver_policy:import_jetstream10.DeliverPolicy.StartSequence,opt_start_seq:frontier+1}:{deliver_policy:import_jetstream10.DeliverPolicy.All}};if(opts.inactiveThresholdMs)cfg.inactive_threshold=(0,import_transport_node8.nanos)(opts.inactiveThresholdMs);return cfg}function taskDurableConfig(space2,role,opts={}){return{durable_name:taskDurable(role),filter_subject:anycastServeFilter(space2,role),ack_policy:import_jetstream10.AckPolicy.Explicit,ack_wait:(0,import_transport_node8.nanos)(opts.ackWaitMs??6e4)}}function inboxReaderConfig(space2,opts={}){return{durable_name:readerDurable(opts.shard,opts.shards),filter_subject:`${spacePrefix(space2)}.dinbox.>`,ack_policy:import_jetstream10.AckPolicy.Explicit,ack_wait:(0,import_transport_node8.nanos)(opts.ackWaitMs??6e4),deliver_policy:import_jetstream10.DeliverPolicy.All,max_ack_pending:DINBOX_MAX_ACK_PENDING}}function dlvDurableConfig(space2,owner2,actor2,lifecycleUid,opts={}){const cfg={durable_name:dlvDurable(owner2,actor2,lifecycleUid),filter_subject:dlvSubject(space2,owner2,actor2,lifecycleUid),ack_policy:import_jetstream10.AckPolicy.Explicit,ack_wait:(0,import_transport_node8.nanos)(opts.ackWaitMs??6e4),deliver_policy:import_jetstream10.DeliverPolicy.All};if(opts.inactiveThresholdMs)cfg.inactive_threshold=(0,import_transport_node8.nanos)(opts.inactiveThresholdMs);return cfg}function fanoutDurableConfig(space2,opts={}){return{durable_name:fanoutDurable(opts.shard,opts.shards),filter_subject:chatWildcard(space2),ack_policy:import_jetstream10.AckPolicy.Explicit,ack_wait:(0,import_transport_node8.nanos)(opts.ackWaitMs??6e4),deliver_policy:import_jetstream10.DeliverPolicy.New}}var TTL_RECONCILE_CANARY_KEY="_cotal_ttl_reconcile";var import_transport_node9=__toESM(require_transport_node(),1);var import_nkeys8=__toESM(require_mod(),1);var enc4=new TextEncoder;var dec4=new TextDecoder("utf-8",{fatal:true});var PLACEMENT_COMMANDS=Object.freeze(["describe","resolve-cwd","spawn"]);var PLACED_LIFECYCLE_COMMANDS=Object.freeze(["turn"]);var import_nats_core4=__toESM(require_mod3(),1);var import_jetstream11=__toESM(require_mod4(),1);var import_obj2=__toESM(require_mod7(),1);var ARTIFACT_PART_KIND="artifact";function isArtifactPart(value){if(!value||typeof value!=="object")return false;const p=value;return p.kind===ARTIFACT_PART_KIND&&typeof p.name==="string"&&p.name.length>0&&typeof p.mediaType==="string"&&p.mediaType.length>0&&typeof p.digest==="string"&&isContractDigest(p.digest)&&typeof p.size==="number"&&Number.isSafeInteger(p.size)&&p.size>=0}var TRANSFER_CHUNK_MAX=128*1024;var HEADER_ROOM=4*1024;var import_nkeys7=__toESM(require_mod(),1);var REMOTE_MANAGER_AUTHORITY_OPERATIONS=Object.freeze(["prepare","activate","renew","session","retire","renewStandingBundle","renewRunDriver","transferReader"]);var REMOTE_MANAGER_MAINTENANCE_OPERATIONS=Object.freeze(["evict-family-principal","reconcile-registration"]);var MANAGED_AGENT_RUNTIME_STATES=Object.freeze(["reserved","creating","bound","create-unknown","closing","closed"]);var MANAGED_AGENT_RUNTIME_READINESS=Object.freeze(["ready","bound-not-ready","none"]);var MANAGED_AGENT_RETIREMENT_PHASES=Object.freeze(["intent","released","retired","deprovisioned","terminal"]);var REMOTE_MANAGER_IDENTITY_NAMES=Object.freeze(["supervisor","executor","serve","goalWriter","sessionLedger"]);var import_jetstream12=__toESM(require_mod4(),1);var import_transport_node10=__toESM(require_transport_node(),1);var DEFAULT_TRANSFER_TIMEOUT_MS=5*60*1e3;function principalFromDurable(name,prefix){if(!name.startsWith(prefix))return void 0;const match=/^([A-Za-z0-9_]+)-([A-Za-z0-9_]+)-([a-z0-9]+)$/.exec(name.slice(prefix.length));return match?{owner:match[1],actor:match[2],lifecycleUid:match[3]}:void 0}function expectedConsumerConfig(space2,stream,name){if(stream===chatStream(space2)&&name===FANOUT_DURABLE)return fanoutDurableConfig(space2);if(stream===inboxStream(space2)&&name===INBOX_READER_DURABLE)return inboxReaderConfig(space2);if(stream===dmStream(space2)){const principal=principalFromDurable(name,"dm_");if(principal)return dmDurableConfig(space2,principal.owner,principal.actor,principal.lifecycleUid)}if(stream===dlvStream(space2)){const principal=principalFromDurable(name,"dlv_");if(principal)return dlvDurableConfig(space2,principal.owner,principal.actor,principal.lifecycleUid)}if(stream===taskStream(space2)&&/^svc_[A-Za-z0-9_-]+$/.test(name))return{...taskDurableConfig(space2,name.slice("svc_".length)),deliver_policy:import_jetstream12.DeliverPolicy.All};throw new Error(`unsupported persistent consumer ${stream}/${name}`)}var CONSUMER_KEYS=new Set(["ack_policy","ack_wait","backoff","deliver_group","deliver_policy","deliver_subject","description","durable_name","filter_subject","filter_subjects","flow_control","headers_only","idle_heartbeat","inactive_threshold","max_ack_pending","max_batch","max_bytes","max_deliver","max_expires","max_waiting","mem_storage","metadata","name","num_replicas","opt_start_seq","opt_start_time","pause_until","priority_groups","priority_policy","priority_timeout","rate_limit_bps","replay_policy","sample_freq"]);function validatePersistentConsumer(space2,stream,info){const expected=expectedConsumerConfig(space2,stream,info.name);const config2=info.config;const unknown2=Object.keys(config2).filter(key=>!CONSUMER_KEYS.has(key));if(unknown2.length)throw new Error(`${stream}/${info.name} has unsupported consumer fields: ${unknown2.sort().join(", ")}`);if(config2.name!==void 0&&config2.name!==info.name)throw new Error(`${stream}/${info.name} has a mismatched name`);if(config2.durable_name!==info.name)throw new Error(`${stream}/${info.name} is not a canonical durable`);if(config2.deliver_subject||config2.deliver_group)throw new Error(`${stream}/${info.name} is a push consumer`);if(config2.filter_subject!==expected.filter_subject||(config2.filter_subjects?.length??0)!==0)throw new Error(`${stream}/${info.name} has a noncanonical filter`);if(config2.ack_policy!==import_jetstream12.AckPolicy.Explicit||config2.ack_wait!==expected.ack_wait)throw new Error(`${stream}/${info.name} has noncanonical ACK settings`);const task=stream===taskStream(space2);const migrated=!task&&config2.deliver_policy===import_jetstream12.DeliverPolicy.StartSequence;const implicitTaskAll=task&&config2.deliver_policy===void 0;if(config2.deliver_policy!==expected.deliver_policy&&!migrated&&!implicitTaskAll)throw new Error(`${stream}/${info.name} has a noncanonical delivery policy`);if(migrated){if(!Number.isSafeInteger(config2.opt_start_seq)||(config2.opt_start_seq??0)<1)throw new Error(`${stream}/${info.name} has an invalid creation lower bound`)}else if(config2.opt_start_seq!==void 0||config2.opt_start_time!==void 0){throw new Error(`${stream}/${info.name} has an unexpected start bound`)}const expectedMaxAck=expected.max_ack_pending??1e3;if((config2.max_ack_pending??1e3)!==expectedMaxAck)throw new Error(`${stream}/${info.name} has noncanonical max_ack_pending`);if((config2.max_deliver??-1)!==-1||(config2.max_waiting??512)!==512)throw new Error(`${stream}/${info.name} has noncanonical delivery limits`);if((config2.replay_policy??import_jetstream12.ReplayPolicy.Instant)!==import_jetstream12.ReplayPolicy.Instant||(config2.num_replicas??0)!==0)throw new Error(`${stream}/${info.name} has noncanonical replay/replica settings`);for(const key of["backoff","description","flow_control","headers_only","idle_heartbeat","inactive_threshold","max_batch","max_bytes","max_expires","mem_storage","metadata","pause_until","priority_groups","priority_policy","priority_timeout","rate_limit_bps","sample_freq"]){const value=config2[key];if(key==="metadata"&&value&&typeof value==="object"&&!Array.isArray(value)&&Object.entries(value).every(([metadataKey,metadataValue])=>metadataKey.startsWith("_nats.")&&typeof metadataValue==="string"))continue;if(value!==void 0&&value!==false&&value!==0&&value!==""&&!(Array.isArray(value)&&value.length===0)&&!(typeof value==="object"&&value!==null&&Object.keys(value).length===0))throw new Error(`${stream}/${info.name} has active unsupported setting ${key}`)}}function isRestoredConsumer(space2,stream,info,wanted){if(info.name!==wanted.durable_name||info.config.deliver_policy!==import_jetstream12.DeliverPolicy.StartSequence||info.config.ack_wait!==wanted.ack_wait)return false;try{validatePersistentConsumer(space2,stream,info)}catch{return false}return true}var FIVE_MINUTES=5*60;var MAX_CONTROL_LINE_BYTES=65536;var CONNECT_ENVELOPE_OVERHEAD_BYTES=512;var MAX_MINTED_JWT_BYTES=MAX_CONTROL_LINE_BYTES-CONNECT_ENVELOPE_OVERHEAD_BYTES;var STANDING_RENEWABLE_TTL_SEC=24*60*60;var ROTATION_RENEWED_TTL_SEC=30*24*60*60;var CREDENTIAL_LIFETIMES={agent:{class:"mixed",note:"manager children, foreground spawn/join, and `cotal mint` static outputs all use this profile; split or repair flow required before default exp"},"manager-caller":{class:"mixed",note:"short-lived user-auth view bound to the bearer expiry and one manager instance"},observer:{class:"static-operator-managed",note:"out-of-band dashboard/audit credential from `cotal mint`"},admin:{class:"static-operator-managed",note:"out-of-band elevated dashboard/audit credential from `cotal mint`"},supervisor:{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"manager's always-on endpoint; the manager holds the DATA seed and self-remints via the endpoint creds source"},delivery:{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"server-side Plane-3 daemon; seed-less - the manager re-signs .cotal/delivery.creds for the SAME nkey, requests delivery-admin reloadCreds for explicit adoption, and the endpoint source re-read is only a backstop"},"membership-rw":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"membership feed writer; seed-less - the manager re-signs the membership-rw.creds store key for the SAME nkey, the feed adopts it on a 75% preflight-proven renewal timer (its active self-heal), and delivery-admin reloadCreds is the explicit adoption on top"},provisioner:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"setup/spawn provisioning window only"},deprovisioner:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"target-pinned teardown window only"},"retirement-requester":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one despawn's retirement request window; request+reply only"},"lifecycle-executor":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one static lifecycle operation's 13.1 state-write window (activation / terminal / renewal ledger append)"},"endpoint-serve-executor":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one endpoint registration/serve-mint window (13.1 epgate CAS + epcred stage/revoke + eprepair cursor for one (endpoint, instanceId))"},operator:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"send/dm/join/probe-style operator command"},purger:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"history purge command"},backup:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"offline snapshot phase; exact stream and delivery subject, memory-only"},restore:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"offline restore initiation or exact-ID upload phase, memory-only"},probe:{class:"one-shot",defaultTtlSeconds:60,note:"connect-only preflight"},"channel-writer":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"channel registry mutation command"},"channel-purger":{class:"mixed",note:"one-shot for CLI, standing inside web; split or renewal required before default exp"},teardown:{class:"one-shot",note:"space teardown can be long/destructive; needs TTL budget/remint guard before default exp"},"issued-store-recreate":{class:"one-shot",defaultTtlSeconds:30*60,note:"one `up --recreate-issued-stores` step: snapshot and delete the two pre-retention issued-authority stores of one space; 30 minutes bounds a large store's snapshot"},"control-caller-privileged":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"ps/start control call"},"control-caller-admin":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"stop/attach admin control call"},deployer:{class:"one-shot",note:"manifest deploy spans planning/launch/ledger; needs near-expiry guard or remint before default exp"},"endpoint-serve":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"per-instance endpoint serve credential (SPEC 13.9); the managing authority re-mints on renewal and on takeover (new epoch), and the 13.1 barrier revokes the superseded one"},"goal-writer":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"self-mediated goal-writer for spawn-as-action; the manager re-mints for the SAME nkey on renewal, disjoint from the serve credential"},"session-caller":{class:"one-shot",defaultTtlSeconds:24*60*60,note:"per-session console/CLI caller cred: rails-only for ONE \xA713.6 session; TTL-BOUND to the session (the face mints with expiresAt = the session exp; the 24h default is the SESSION_GRANT_MAX_TTL ceiling, never a standing lifetime); NEVER renewed - a new session mints a new cred"},"dm-reader":{class:"mixed",note:"user-auth own-DM reader view: one dm_ durable's INFO/NEXT/ACK, bound to the bearer expiry (which the IdP proof bounds); renewed by re-exchange, never a standing credential"},"session-serving":{class:"one-shot",defaultTtlSeconds:24*60*60,note:"per-session SERVING cred: rails-only for ONE \xA713.6 session, the mirror of session-caller with the directions swapped; minted at redemption and TTL-BOUND to the session (the 24h default is the SESSION_GRANT_MAX_TTL ceiling, never a standing lifetime); NEVER renewed - a new session mints a new cred, and the session's terminal revokes this one by name"},"session-ledger":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"manager's session LEDGER: the dedicated sessions-bucket `session.<id>` rows and NOTHING else - no session rail of any shape. Standing because SPEC 13.6 makes it the durable revocation authority that must survive the serving endpoint; the manager re-mints for the SAME nkey on the half-TTL loop (the goal-writer precedent)"},"run-driver":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"one workflow run's driver, per takeover attempt (SPEC 14.6): the hosting manager mints it when it takes the run over and re-mints for the SAME nkey on renewal; a new takeover mints a new one"},"run-mediator":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"trusted workflow host operations, bound to one run and attempt; kept on the hosting process's connection"},"run-operator":{class:"one-shot",defaultTtlSeconds:60,note:"one served run-status / run-ps / run-answer call (SPEC 14.3): the hosting manager mints it per call on its own connection, never the serve rails; 60s bounds a copied cred to a minute"},"registry-reader":{class:"standing-renewable",defaultTtlSeconds:60*60,renewalOwner:"registry host",note:"the registry's reads (SPEC 13.20), no write of any shape; the evidence-store read is stream-scoped, so it can read every recorded ceiling in the space (a NAMED RESIDUAL), and one hour bounds a copied credential; the process hosting the registry re-mints it"},issuer:{class:"mixed",defaultTtlSeconds:FIVE_MINUTES,renewalOwner:"auth-service",note:"renewed as the auth plane's held session for connect-time issuance (re-minted before exp, closed with the plane); one-shot for every other issuance window and for a lifecycle terminal's issuance retirement (SPEC 13.15)"},"run-admitter":{class:"one-shot",defaultTtlSeconds:60,note:"one hosted run's admission record create, or its revocation marker (SPEC 14.8); 60s bounds a copied cred to a minute"},"transfer-writer":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one carried resume per CLI call: one object's chunk and meta subjects in one instance's transfer bucket"},"transfer-reader":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one transcript-receive or sweep over the minting instance's own transfer bucket"},"endpoint-evictor":{class:"one-shot",defaultTtlSeconds:60,note:"one re-registration's verify-evict window: a scoped delivery-admin caller that kicks+verifies the SUPERSEDED serve family before the epoch advances; 60s bounds a copied cred to a minute"},"remote-manager":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"auth-service",note:"the scoped remote manager lifecycle: own lease/presence plus same-owner agent provisioning; issued only by the typed supervise protocol, never by `cotal mint` or a raw view/profile string"},"environment-bootstrap":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one admitted environment's bootstrap caller; explicit expiry capped by admission and five minutes"},"environment-manager-supervisor":{class:"standing-renewable",renewalOwner:"environment-authority",note:"own lease/presence/liveness; explicit expiry capped by admission, no auth-store access"},"environment-manager-executor":{class:"standing-renewable",renewalOwner:"environment-authority",note:"own admitted authority instance RPC; explicit expiry capped by admission, no direct store access"},"environment-manager-goal-writer":{class:"standing-renewable",renewalOwner:"environment-authority",note:"manager goal rows without the auth-read belt; explicit expiry capped by admission"},"membership-observer":{class:"rotation-renewed",defaultTtlSeconds:ROTATION_RENEWED_TTL_SEC,renewalOwner:"system-account rotation",note:"$SYS-account CONNZ observer; NOT online-renewable ($SYS seed dies at `up`) - bounded exp, renewed only by rotateSystemAccount + broker restart; doctor warns near expiry"},"account-census":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"Host-only account CONNZ and account-qualified replies; at most five minutes, no KICK or client-side renewal"},"connection-evictor":{class:"rotation-renewed",defaultTtlSeconds:ROTATION_RENEWED_TTL_SEC,renewalOwner:"system-account rotation",note:"$SYS-account KICK-only live-eviction cred; same rotation-renewed posture as the observer"}};for(const p of Object.values(CREDENTIAL_LIFETIMES))Object.freeze(p);Object.freeze(CREDENTIAL_LIFETIMES);var LIFETIME_TTL_SNAP=new Map(Object.entries(CREDENTIAL_LIFETIMES).map(([k,p])=>[k,p.defaultTtlSeconds]));function inspectCredHealth(creds,nowSec=Math.floor(Date.now()/1e3)){let claims2;try{claims2=credsClaims(creds)}catch(e){return{state:"unreadable",error:e.message}}const{iat,exp}=claims2;if(typeof exp!=="number")return{state:"unbounded",iat};if(typeof iat!=="number")return{state:"unreadable",iat:void 0,exp,error:"user JWT carries exp but no iat - cannot place the renewal point"};const renewAt=Math.floor(iat+.75*(exp-iat));if(nowSec>=exp)return{state:"expired",iat,exp,renewAt};if(nowSec>=renewAt)return{state:"near-expiry",iat,exp,renewAt};return{state:"healthy",iat,exp,renewAt}}var BASE_LIMITS={subs:-1,conn:-1,leaf:-1,imports:-1,exports:-1,data:-1,payload:-1,wildcards:true};var DATA_LIMITS={...BASE_LIMITS,mem_storage:-1,disk_storage:-1};var SYS_LIMITS={...BASE_LIMITS,mem_storage:0,disk_storage:0};var SPAWN_VIEW_READS=Object.freeze(["status","models","resolve-cwd","list-dir","ps"]);function parseSecretStoreIdentity(raw){if(raw===null||typeof raw!=="object"||Array.isArray(raw))throw new Error("secret-store identity must be an object");const o=raw;const keys=Object.keys(o);if(o.kind==="fs"){if(keys.some(k=>k!=="kind"&&k!=="root"&&k!=="id"))throw new Error("secret-store identity of kind fs admits only {kind, root, id}");if(typeof o.root!=="string"||!o.root.trim())throw new Error("secret-store identity of kind fs requires a non-blank root");if(typeof o.id!=="string"||!o.id.trim())throw new Error("secret-store identity of kind fs requires a non-blank id");return{kind:"fs",root:o.root,id:o.id}}if(o.kind==="injected"){if(keys.some(k=>k!=="kind"&&k!=="coordinate"))throw new Error("secret-store identity of kind injected admits only {kind, coordinate}");if(typeof o.coordinate!=="string"||!o.coordinate.trim())throw new Error("secret-store identity of kind injected requires a non-blank coordinate");return{kind:"injected",coordinate:o.coordinate}}throw new Error('secret-store identity kind must be "fs" or "injected"')}var import_node_fs4=require("node:fs");var import_yaml=__toESM(require_dist2(),1);function peerLabel(card){return(card.role?`${card.name}/${card.role}`:card.name).replace(/[\p{Cc}\p{Zl}\p{Zp}[\]]+/gu," ")}var LINE_BREAK=/\r\n?|[\n\v\f\u0085\u2028\u2029]/;var AmbiguousPeerError=class extends Error{target;candidates;constructor(target2,candidates){super(`"${target2}" is ambiguous - ${candidates.length} peers share that name: `+candidates.map(c=>`${c.name} (${c.id}, ${c.status})`).join("; ")+`. Re-send to the exact instance id.`);this.target=target2;this.candidates=candidates;this.name="AmbiguousPeerError"}};function candidate(p){return{id:p.card.id,name:p.card.name,role:p.card.role,status:p.status,ts:p.ts}}function resolvePeer(roster,target2,opts={}){const peers=opts.selfId?roster.filter(p=>p.card.id!==opts.selfId):roster;const byId=peers.find(p=>p.card.id===target2);if(byId)return byId;const want=target2.trim().toLowerCase();if(!want)return void 0;const matches=peers.filter(p=>p.card.name.toLowerCase()===want);if(matches.length===0){const labelled=peers.find(p=>p.card.role&&peerLabel(p.card).trim().toLowerCase()===want);if(labelled)throw new Error(`"${target2}" is the roster label of ${labelled.card.name} (role ${labelled.card.role}), not an address: use the name "${labelled.card.name}" or its instance id`);return void 0}const live=matches.filter(p=>p.status!=="offline");const pool=live.length>0?live:matches;if(pool.length===1)return pool[0];throw new AmbiguousPeerError(target2,pool.map(candidate))}function sharedNameIds(roster,opts={}){const peers=opts.selfId?roster.filter(p=>p.card.id!==opts.selfId):roster;const groups=new Map;for(const p of peers){const key=p.card.name.trim().toLowerCase();const group=groups.get(key);if(group)group.push(p);else groups.set(key,[p])}const ids=new Set;for(const group of groups.values()){const live=group.filter(p=>p.status!=="offline");const pool=live.length>0?live:group;if(pool.length>1)for(const p of pool)ids.add(p.card.id)}return ids}var MAX_NAME_LENGTH=128;function assertValidName(name){if(name.length===0||name!==name.trim())throw new Error(`invalid name ${JSON.stringify(name)}: must be non-empty with no surrounding whitespace`);if(name.length>MAX_NAME_LENGTH)throw new Error(`invalid name ${JSON.stringify(name.slice(0,32))}\u2026: ${name.length} characters exceeds the ${MAX_NAME_LENGTH}-character limit (the CONNECT line budget that carries it)`);if(LINE_BREAK.test(name))throw new Error(`invalid name ${JSON.stringify(name)}: must be a single line`);if(name.includes("/"))throw new Error(`invalid name ${JSON.stringify(name)}: "/" is reserved (the owner/name separator)`);if(name.includes("\\"))throw new Error(`invalid name ${JSON.stringify(name)}: "\\" is reserved (a Windows path separator)`);if(!isWellFormedUnicode(name))throw new Error(`invalid name ${JSON.stringify(name)}: contains an unpaired UTF-16 surrogate. Such a name cannot survive UTF-8 encoding \u2014 it is replaced with U+FFFD \u2014 so distinct names would silently become one identity.`)}function utf16Problem(text2){return text2.startsWith("\uFFFD\uFFFD")||text2.includes("\0")?"it is saved as UTF-16, and Cotal reads only UTF-8":void 0}var PERSONA_ENDPOINT_MAX_COMMANDS=256;var ENTRY_KEYS=["endpoint","commands","instanceId"];function parsePersonaEndpoints(raw,where){if(raw===void 0||raw===null)return void 0;const fail3=detail=>{throw new Error(`${where}: "endpoints" ${detail}`)};if(!Array.isArray(raw))fail3("must be a list of { endpoint, commands, instanceId? } entries");const merged=new Map;let total=0;for(const item of raw){if(item===null||typeof item!=="object"||Array.isArray(item))fail3("entries must be mappings of endpoint, commands and an optional instanceId");const proto=Object.getPrototypeOf(item);if(proto!==Object.prototype&&proto!==null)fail3("entries must be plain mappings");const rec=item;const extra=Reflect.ownKeys(rec).find(k=>typeof k!=="string"||!ENTRY_KEYS.includes(k));if(extra!==void 0)fail3(`entry has unknown key ${String(extra)}; an entry takes endpoint, commands and instanceId`);const endpoint=rec.endpoint;if(typeof endpoint!=="string")fail3("entry needs an endpoint name");try{endpointToken(endpoint)}catch(e){fail3(`entry: ${e.message}`)}if(!endpoint.includes("."))fail3(`entry names "${endpoint}", a single-label endpoint; those are the reference endpoints, reached through the baseline and the spawn, run and admin capabilities. A persona hands on a reverse-DNS endpoint such as com.example.orders`);let instanceId;if(rec.instanceId!==void 0){if(typeof rec.instanceId!=="string")fail3(`entry for ${endpoint}: instanceId must be a string`);try{instanceId=assertLifecycleToken(rec.instanceId,"instanceId")}catch(e){fail3(`entry for ${endpoint}: ${e.message}`)}}const commands=rec.commands;if(!Array.isArray(commands)||commands.length===0)fail3(`entry for ${endpoint} needs a non-empty commands list`);const key=`${endpoint}\0${instanceId??""}`;const into=merged.get(key)??{endpoint,commands:[],...instanceId!==void 0?{instanceId}:{}};for(const c of commands){if(typeof c!=="string")fail3(`entry for ${endpoint}: commands must be strings`);try{assertCommandToken(c)}catch(e){fail3(`entry for ${endpoint}: ${e.message}`)}if(RESERVED_COMMANDS.includes(c))fail3(`entry for ${endpoint} names the reserved command "${c}"; describe is granted on every endpoint and cancel is not handed on`);if(!into.commands.includes(c)){into.commands.push(c);total++}}merged.set(key,into)}if(total>PERSONA_ENDPOINT_MAX_COMMANDS)fail3(`names ${total} commands; a persona may name at most ${PERSONA_ENDPOINT_MAX_COMMANDS}`);return[...merged.values()].map(e=>({...e,commands:[...e.commands].sort()})).sort((a,b)=>a.endpoint<b.endpoint?-1:a.endpoint>b.endpoint?1:(a.instanceId??"")<(b.instanceId??"")?-1:1)}function parseFrontmatter(src,path){let doc;try{doc=(0,import_yaml.parse)(src)}catch(e){throw new Error(`agent file ${path}: invalid YAML frontmatter; ${e.message}`)}if(doc===null||doc===void 0)return{};if(typeof doc!=="object"||Array.isArray(doc))throw new Error(`agent file ${path}: frontmatter must be a YAML mapping (key: value pairs)`);return doc}var AGENT_FILE_FENCE=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;var MODELED_KEYS=new Set(["name","role","kind","description","tags","subscribe","allowSubscribe","allowPublish","quiet","muted","agent","model","variant","launchOptions","capabilities","endpoints","owner"]);var RENAMED_KEYS=["channels","publish"];function assertLaunchSelectors(def,where){for(const k of["model","variant"]){const v=def[k];if(v!==void 0&&!v.trim())throw new Error(`${where}: "${k}" must not be empty`)}}function assertValidKind(kind,where){if(kind==="agent"||kind==="endpoint")return kind;throw new Error(`${where?`${where}: `:`invalid kind ${JSON.stringify(kind)}: `}"kind" must be "agent" or "endpoint"`)}function loadAgentFile(path){return parseAgentFileSource((0,import_node_fs4.readFileSync)(path,"utf8"),path)}function parseAgentFileSource(src,path){const encoding=utf16Problem(src);if(encoding)throw new Error(`agent file ${path}: ${encoding}; save it as UTF-8`);const m=AGENT_FILE_FENCE.exec(src.replace(/^\uFEFF/,"").replace(/\r\n/g,"\n"));if(!m)throw new Error(`agent file ${path}: missing "---" frontmatter block`);const fm=parseFrontmatter(m[1],path);const persona=m[2].trim();const str2=k=>{const v=fm[k];if(v===void 0||v===null)return void 0;if(typeof v==="object")throw new Error(`agent file ${path}: "${k}" must be a scalar`);return String(v)};const list2=k=>{const v=fm[k];if(v===void 0||v===null)return void 0;return(Array.isArray(v)?v:[v]).map(x=>{if(x===null||typeof x==="object")throw new Error(`agent file ${path}: "${k}" list items must be scalars`);return String(x)})};const name=str2("name");if(!name)throw new Error(`agent file ${path}: "name" is required`);assertValidName(name);const model=str2("model");const variant=str2("variant");assertLaunchSelectors({model,variant},`agent file ${path}`);const rawKind=str2("kind");const kind=rawKind!==void 0?assertValidKind(rawKind,`agent file ${path}`):void 0;for(const old of RENAMED_KEYS)if(old in fm)throw new Error(`agent file ${path}: "${old}" was renamed - use "subscribe"/"allowSubscribe" (read) and "allowPublish" (post)`);const subscribe=list2("subscribe");const allowSubscribe=list2("allowSubscribe");const allowPublish=list2("allowPublish");const quiet=list2("quiet");const muted=list2("muted");for(const ch of[...subscribe??[],...allowSubscribe??[],...allowPublish??[]])try{assertValidChannel(ch)}catch(e){throw new Error(`agent file ${path}: ${e.message}`)}let effAllow;try{effAllow=resolveReadAcl(subscribe??[],allowSubscribe)}catch(e){throw new Error(`agent file ${path}: ${e.message}`)}const both=(quiet??[]).filter(c=>(muted??[]).includes(c));if(both.length)throw new Error(`agent file ${path}: channel(s) [${both.join(", ")}] are in both quiet and muted - pick one`);for(const[field,chans]of[["quiet",quiet],["muted",muted]])for(const ch of chans??[]){try{assertValidChannel(ch)}catch(e){throw new Error(`agent file ${path}: ${e.message}`)}if(!isConcreteChannel(ch))throw new Error(`agent file ${path}: ${field} channel "${ch}" must be a concrete channel (no wildcard)`);if(!channelInAllow(effAllow,ch))throw new Error(`agent file ${path}: ${field} channel "${ch}" is not within your read ACL / allowSubscribe [${effAllow.join(", ")}]`)}const launchOptionsRaw=fm["launchOptions"];let launchOptions;if(launchOptionsRaw!==void 0&&launchOptionsRaw!==null){if(typeof launchOptionsRaw!=="object"||Array.isArray(launchOptionsRaw))throw new Error(`agent file ${path}: "launchOptions" must be a mapping of key: value pairs`);launchOptions=launchOptionsRaw}const meta3={};for(const[k,v]of Object.entries(fm))if(!MODELED_KEYS.has(k)&&v!==null&&typeof v!=="object")meta3[k]=String(v);return{name,role:str2("role"),kind,description:str2("description"),tags:list2("tags"),agent:str2("agent"),subscribe,allowSubscribe,allowPublish,quiet,muted,model,variant,launchOptions,capabilities:list2("capabilities"),endpoints:parsePersonaEndpoints(fm["endpoints"],`agent file ${path}`),owner:str2("owner"),meta:Object.keys(meta3).length?meta3:void 0,persona:persona||void 0}}function nextHeartbeat(phaseMs,intervalMs,lastBeat,nowMs){const beat=Math.max(lastBeat+1,Math.ceil((nowMs-phaseMs)/intervalMs));return{beat,delayMs:Math.max(0,phaseMs+beat*intervalMs-nowMs)}}var import_jetstream13=__toESM(require_mod4(),1);var import_jetstream14=__toESM(require_mod4(),1);var import_kv7=__toESM(require_mod6(),1);var import_internal2=__toESM(require_internal_mod3(),1);var import_kv5=__toESM(require_mod6(),1);var import_transport_node11=__toESM(require_transport_node(),1);async function openDeliveryRegistry(nc,space2){return new import_kv5.Kvm(nc).open(deliveryBucket(space2))}var import_kv6=__toESM(require_mod6(),1);var import_transport_node12=__toESM(require_transport_node(),1);var MAX_CHANNEL_DESCRIPTION=200;var MAX_CHANNEL_INSTRUCTIONS=2e3;function validateChannelConfig(cfg){validateChannelDefaults(cfg);validateText("description",cfg.description,MAX_CHANNEL_DESCRIPTION);validateText("instructions",cfg.instructions,MAX_CHANNEL_INSTRUCTIONS)}function validateText(field,text2,max){if(text2===void 0)return;if(typeof text2!=="string")throw new Error(`channel ${field} must be a string`);if(text2.length>max)throw new Error(`channel ${field} too long (${text2.length} > ${max} chars)`)}function validateChannelDefaults(d){if(d.replay!==void 0&&typeof d.replay!=="boolean")throw new Error(`invalid replay "${d.replay}" - expected true or false`);if(d.replayWindow!==void 0)parseDuration(d.replayWindow);if(d.deliveryClass!==void 0&&d.deliveryClass!=="live"&&d.deliveryClass!=="durable")throw new Error(`invalid deliveryClass "${d.deliveryClass}" - expected "live" or "durable"`)}function decodeChannelEntry(e){const value=e.json();if(typeof value!=="object"||value===null||Array.isArray(value))throw new Error("not a JSON object");if(e.key===CHANNEL_DEFAULTS_KEY)validateChannelDefaults(value);else validateChannelConfig(value);return value}function parseDuration(s){const m=/^(\d+)(s|m|h|d)$/.exec(s.trim());if(!m)throw new Error(`invalid duration "${s}" - expected <number><s|m|h|d>, e.g. "24h"`);const n=Number(m[1]);const unit={s:1e3,m:6e4,h:36e5,d:864e5}[m[2]];return n*unit}function effectiveReplay(cfg,defaults){return cfg?.replay??defaults?.replay??true}function effectiveReplayWindowMs(cfg,defaults){const w=cfg?.replayWindow??defaults?.replayWindow;return w===void 0?void 0:parseDuration(w)}function effectiveDeliveryClass(cfg,defaults){return cfg?.deliveryClass??defaults?.deliveryClass??"durable"}async function openChannelRegistry(nc,space2,opts={}){const kvm=new import_kv6.Kvm(nc);return opts.create?kvm.create(channelBucket(space2)):kvm.open(channelBucket(space2))}async function readChannelConfig(kv,channel){return decode4(kv,channel)}async function readChannelDefaults(kv){return decode4(kv,CHANNEL_DEFAULTS_KEY)}async function decode4(kv,key){return entryValue(await kv.get(key))}function entryValue(e){return entryDecode(e).value}function entryDecode(e){if(!e||e.operation==="DEL"||e.operation==="PURGE")return{};try{return{value:decodeChannelEntry(e)}}catch(err3){return{error:err3.message}}}var ANYCAST_RECORD_RETENTION_MS=24*60*60*1e3;var ANYCAST_STATUS_OP="anycastStatus";var ANYCAST_CANCEL_OP="anycastCancel";var ANYCAST_TAKES_OP="anycastTakes";var ANYCAST_RECORDS_CREDENTIAL_OUTDATED="this delivery daemon's credential was minted before anycast request records existed, so it records no takes and answers no status or cancel; restart the daemon on a credential minted at this version (`cotal up` mints one)";var ANYCAST_NOTICE_KEY="cotalAnycastNotice";function anycastRecordKey(epoch,seq){return`r.${epoch.replace(/[^0-9A-Za-z]/g,"")}.${seq}`}function isAnycastSeq(seq){return typeof seq==="number"&&Number.isSafeInteger(seq)&&seq>0}function holderOf(t){return{id:t.id,name:t.name}}function noticeEvent(row,notice){const{taker,previous,role,seq}=notice;const text2=notice.event==="taken"?`${taker.name} (${taker.id}) took your @${role} request (seq ${seq}).`:`${previous.name} (${previous.id}) did not confirm your @${role} request (seq ${seq}) before its ack wait ran out, and ${taker.name} (${taker.id}) took it. ${previous.name} may already have started it.`;return{key:`anycast.${anycastRecordKey(row.epoch,row.seq).slice(2)}.${row.rev}`,text:text2,notice}}function decideTake(row,stored,t){const taker={...holderOf(t.holder),count:t.count,at:t.now};if(!row){const next={v:1,epoch:t.epoch,seq:t.seq,id:stored.id,role:stored.role,sender:stored.sender,rev:1,state:"taken",taker,outbox:[]};next.outbox.push(noticeEvent(next,{seq:t.seq,role:stored.role,event:"taken",taker:holderOf(taker)}));return{reply:{ok:true},next}}if(row.state==="cancelled")return{reply:{ok:false,code:"cancelled",error:`request seq ${t.seq} was cancelled by its sender`}};const current=row.taker;if(current.id===t.holder.id&¤t.count===t.count)return{reply:{ok:true}};if(t.count>current.count){const moved=current.id!==t.holder.id;const next={...row,rev:row.rev+1,taker,previous:moved?{...holderOf(current),count:current.count}:row.previous,outbox:[...row.outbox]};if(moved)next.outbox.push(noticeEvent(next,{seq:t.seq,role:row.role,event:"redelivered",taker:holderOf(taker),previous:holderOf(current)}));return{reply:{ok:true},next}}return{reply:{ok:false,code:"taken",error:`request seq ${t.seq} was taken by ${current.name} (${current.id}) on delivery ${current.count}`}}}function statusFor(row,stored,q){if(row){if(row.sender!==q.caller||q.id!==void 0&&row.id!==q.id)return{state:"unknown",seq:q.seq};if(row.state==="cancelled")return{state:"cancelled",seq:q.seq,role:row.role,removal:row.removal??"pending"};const taker=row.taker;return{state:"taken",seq:q.seq,role:row.role,taker:holderOf(taker),at:taker.at,...row.previous?{previous:holderOf(row.previous)}:{}}}if(!stored||stored.sender!==q.caller||q.id!==void 0&&stored.id!==q.id)return{state:"unknown",seq:q.seq};return{state:"waiting",seq:q.seq,role:stored.role}}function decideCancel(row,stored,q){const status2=statusFor(row,stored,q);if(status2.state!=="waiting")return{status:status2};const s=stored;return{status:{state:"cancelled",seq:q.seq,role:s.role,removal:"pending"},next:{v:1,epoch:q.epoch,seq:q.seq,id:s.id,role:s.role,sender:s.sender,rev:1,state:"cancelled",removal:"pending",outbox:[]}}}function storedRequest(subject,data){const parsed=parseSubject(subject);if(!parsed||parsed.kind!=="svc")return void 0;let id2;try{id2=JSON.parse(new TextDecoder().decode(data)).id}catch{return void 0}if(typeof id2!=="string")return void 0;return{role:parsed.rest,sender:parsed.sender,id:id2}}function isNoMessageFound(e){return e?.code===10043||/no message found/i.test(String(e?.message??""))}var encoder=new TextEncoder;function readRow(e){if(!e||e.operation!=="PUT")return void 0;const row=e.json();if(row?.v!==1||typeof row.epoch!=="string"||!isAnycastSeq(row.seq)||!Array.isArray(row.outbox))throw new Error(`anycast record ${e.key} is not a version-1 record`);return row}var AnycastRequestAuthority=class{deps;flushing=new Map;constructor(deps){this.deps=deps}now(){return this.deps.now?.()??Date.now()}async queued(seq){for(let attempt=0;attempt<3;attempt++){const before=(await this.deps.jsm.streams.info(this.deps.stream)).created;const sm=await this.deps.jsm.streams.getMessage(this.deps.stream,{seq});const after=(await this.deps.jsm.streams.info(this.deps.stream)).created;if(before!==after)continue;return{epoch:before,stored:sm?storedRequest(sm.subject,sm.data):void 0}}throw new Error(`the ${this.deps.stream} stream was recreated during the read; retry`)}async take(role,req){for(let attempt=0;attempt<5;attempt++){const{epoch,stored}=await this.queued(req.seq);if(req.epoch!==epoch)return{ok:false,code:"mismatch",error:`the copy of seq ${req.seq} came from a ${this.deps.stream} stream that has since been recreated`};if(!stored){const row=readRow(await this.deps.kv.get(anycastRecordKey(epoch,req.seq)));if(row?.state==="cancelled"&&row.id===req.id)return{ok:false,code:"cancelled",error:`request seq ${req.seq} was cancelled by its sender`};return{ok:false,code:"gone",error:`request seq ${req.seq} is no longer on the queue`}}if(stored.role!==role||stored.id!==req.id)return{ok:false,code:"mismatch",error:`seq ${req.seq} on the queue is not the @${role} request ${req.id}`};const key=anycastRecordKey(epoch,req.seq);const entry=await this.deps.kv.get(key);const{reply,next}=decideTake(readRow(entry),stored,{epoch,seq:req.seq,holder:req.from,count:req.count,now:this.now()});if(!next)return reply;if(!this.deps.mayAct())return{ok:false,code:"busy",error:"the delivery daemon stopped serving while the take was in flight; retry"};if(!await this.write(key,next,entry))continue;if(next.outbox.length)this.flushSoon(key);return reply}return{ok:false,code:"busy",error:`request seq ${req.seq} changed under five takes in a row; retry`}}async status(caller,q){const{epoch,stored}=await this.queued(q.seq);const row=readRow(await this.deps.kv.get(anycastRecordKey(epoch,q.seq)));return statusFor(row,stored,{...q,caller})}async cancel(caller,q){for(let attempt=0;attempt<5;attempt++){const{epoch,stored}=await this.queued(q.seq);const key=anycastRecordKey(epoch,q.seq);const entry=await this.deps.kv.get(key);const row=readRow(entry);const{status:status2,next}=decideCancel(row,stored,{...q,epoch,caller,now:this.now()});if(!next){if(status2.state==="cancelled"&&status2.removal==="pending")return this.remove(key);return status2}if(!this.deps.mayAct())throw new Error("the delivery daemon stopped serving while the cancel was in flight; retry");if(!await this.write(key,next,entry))continue;return this.remove(key)}throw new Error(`request seq ${q.seq} changed under five cancels in a row; retry`)}async remove(key){let removal;for(let attempt=0;attempt<5;attempt++){const entry=await this.deps.kv.get(key);const row=readRow(entry);if(!row||row.state!=="cancelled")throw new Error(`anycast record ${key} is not a cancelled request`);if(row.removal!=="pending")return{state:"cancelled",seq:row.seq,role:row.role,removal:row.removal??"pending"};if(removal===void 0){const epoch=(await this.deps.jsm.streams.info(this.deps.stream)).created;if(epoch!==row.epoch)removal="already-gone";else{if(!this.deps.mayAct())return{state:"cancelled",seq:row.seq,role:row.role,removal:"pending"};try{await this.deps.jsm.streams.deleteMessage(this.deps.stream,row.seq,false);removal="deleted"}catch(e){if(!isNoMessageFound(e))throw e;removal="already-gone"}}}if(await this.write(key,{...row,removal},entry))return{state:"cancelled",seq:row.seq,role:row.role,removal}}throw new Error(`anycast record ${key} changed under five writes in a row; retry`)}async write(key,row,entry){try{const bytes=encoder.encode(JSON.stringify(row));if(entry&&entry.operation==="PUT")await this.deps.kv.update(key,bytes,entry.revision);else await this.deps.kv.create(key,bytes);return true}catch(e){if(isCasLoss(e))return false;throw e}}flushSoon(key){void this.flush(key).catch(e=>this.deps.onError(e))}flush(key){const prior=this.flushing.get(key)??Promise.resolve();const run=prior.then(async()=>{for(let attempt=0;attempt<16;attempt++){if(!this.deps.mayAct())return;const entry=await this.deps.kv.get(key);const row=readRow(entry);const event=row?.outbox[0];if(!row||!event)return;await this.deps.send(row.sender,event);await this.write(key,{...row,outbox:row.outbox.filter(e=>e.key!==event.key)},entry)}});const settled=run.finally(()=>{if(this.flushing.get(key)===settled)this.flushing.delete(key)});this.flushing.set(key,settled);return settled}async sweep(){const keys=[];for await(const k of await this.deps.kv.keys("r.>"))keys.push(k);for(const key of keys){if(!this.deps.mayAct())return;try{await this.maintain(key)}catch(e){this.deps.onError(e)}}}async maintain(key){let row=readRow(await this.deps.kv.get(key));if(!row)return;if(row.outbox.length)await this.flush(key);if(row.state==="cancelled"&&row.removal==="pending")await this.remove(key);const entry=await this.deps.kv.get(key);row=readRow(entry);if(!row||!this.deps.mayAct())return;if(row.leftAt===void 0){const{epoch,stored}=await this.queued(row.seq);if(epoch===row.epoch&&stored?.id===row.id)return;await this.write(key,{...row,leftAt:this.now()},entry)}else if(this.now()-row.leftAt>ANYCAST_RECORD_RETENTION_MS&&!row.outbox.length){try{await this.deps.kv.delete(key,{previousSeq:entry.revision})}catch(e){if(!isCasLoss(e))throw e}}}};var import_nats_core5=__toESM(require_mod3(),1);function isPermissionDenied(e){if(e instanceof import_nats_core5.PermissionViolationError)return true;if(e?.cause instanceof import_nats_core5.PermissionViolationError)return true;return/permissions?\s+violation/i.test(String(e?.message??""))}var DEFAULT_SERVER="nats://127.0.0.1:4222";var PLANE3_FRAME_HEADER="Cotal-Delivery-Frame";var ANYCAST_CONTROL_OPS=new Set([ANYCAST_STATUS_OP,ANYCAST_CANCEL_OP,ANYCAST_TAKES_OP]);var MAX_TAKES_IN_FLIGHT=64;var ANYCAST_SWEEP_MS=10*60*1e3;var ANYCAST_TAKE_TIMEOUT_MS=5e3;var DELIVERY_LIMIT_READ_MS=5e3;function deliveryLimitOf(value){if(value===void 0||value==="")return PLANE3_MAX_MSGS_PER_SUBJECT;if(value==="none")return null;if(!/^[1-9]\d*$/.test(value)||!Number.isSafeInteger(Number(value)))throw new Error(`plane-3 delivery: ${DELIVERY_LIMIT_HEADER} ${JSON.stringify(value)} is not a count`);return Number(value)}var MULTI_FILTER_BATCH=1e3;var MULTI_FILTER_READ_CONCURRENCY=4;var HISTORY_READER_INACTIVE_MS=5*6e4;var MAX_TIMER_MS3=2147483647;var DmDurableMissingError=class extends Error{stream;durable;code="dm-durable-missing";constructor(stream,durable){super(`dm-durable-missing: durable "${durable}" on stream "${stream}" does not exist; a DM-only endpoint binds an existing durable and never creates one`);this.stream=stream;this.durable=durable;this.name="DmDurableMissingError"}};var DmBindRefusedError=class extends Error{stream;durable;code="dm-bind-refused";constructor(stream,durable,cause){super(`dm-bind-refused: binding durable "${durable}" on stream "${stream}" was refused (${cause instanceof Error?cause.message:String(cause)})`,{cause});this.stream=stream;this.durable=durable;this.name="DmBindRefusedError"}};var PresenceWriteStuckError=class extends Error{bucket;since;consecutiveFailures;ttlMs;lastError;code="presence-write-stuck";transient=false;constructor(bucket,since,consecutiveFailures,ttlMs,lastError){super(`presence writes to bucket ${JSON.stringify(bucket)} have failed ${consecutiveFailures} consecutive times for at least one TTL (${ttlMs}ms); the presence view is not live until a write succeeds or the broker store is repaired${lastError?` (last refusal: ${lastError})`:""}`);this.bucket=bucket;this.since=since;this.consecutiveFailures=consecutiveFailures;this.ttlMs=ttlMs;this.lastError=lastError;this.name="PresenceWriteStuckError"}};var READER_MAX_REDELIVERIES=10;var READ_HISTORY_DEFAULT_LIMIT=100;var READ_HISTORY_MAX_LIMIT=200;function fitHistoryPage(items,budget){const enc7=new TextEncoder;let used=enc7.encode(JSON.stringify({ok:true,data:{items:[],complete:false}})).length;let first=items.length;for(let i=items.length-1;i>=0;i--){const size=enc7.encode(JSON.stringify(items[i])).length+1;if(used+size>budget)break;used+=size;first=i}return first===items.length?[]:items.slice(first)}function membershipChange(e,update){const operation=e.operation;if(e.key===MEMBERSHIP_FEED_KEY){let asOf;if(operation==="PUT"){try{asOf=e.json().observedAt}catch{}}return{type:"heartbeat",revision:e.revision,update,asOf}}let member;if(operation==="PUT"){try{const rec=e.json();member={id:e.key,live:rec.live??[],durable:rec.durable??[],observedAt:rec.observedAt}}catch{}}return{type:"member",id:e.key,operation,revision:e.revision,update,member}}var CotalEndpoint=class _CotalEndpoint extends import_node_events.EventEmitter{card;space;channels;servers;token;user;pass;credsSource;currentCreds;credsTimer;watchDeletePermissions=new WeakMap;userMode=false;bearerSource;currentBearer;presentedExp;cancelBearerRenewal;bearerRenewalFailures=0;bearerRefusalSurfaced=false;bearerAdoptedAtMs=0;authExpiryReconnectTimer;sentinelCreds;tls;transportPingIntervalMs;transportMaxPingOut;transportConnectTimeoutMs;heartbeatMs;ttlMs;doRegister;doWatch;doWatchChannels;readOnce;doConsume;dmOnly;dmOnlyInFlight;ackWaitMs;inactiveThresholdMs;nc;requestsAwaitingReply=new Map;onConnection;beforeBind;js;jsm;kv;channelKv;presenceWatchIter;channelWatchIter;kvWatchDeletes=new Set;kvWatchBinds=new Set;leaseWatchIntent;leaseWatchIter;leaseWatchDeletes=new Set;leaseWatchBinds=new Set;membersKv;aclKv;deliveryKv;managerLeaseKv;daemonRenewalLeaseRevision;membershipFeedKv;membershipFeedWatches=new Set;deliveryServeSub;deliveryAdminServeSub;takeServeSub;anycastAuthority;taskEpoch;anycastUnavailable;anycastSweep;takesInFlight=0;retiringLifecycles=new Map;membershipWrites=new Map;plane3Quiesced=false;plane3;channelConfigs=new Map;channelDefaults={};channelRead;channelReadGeneration=0;channelReadApplied=0;histLock=Promise.resolve();subs=[];taps=[];livenessResponders=new Map;streamMsgs=[];chatSubs=new Map;chatSubDenied=new Set;plane3Channels=new Map;pendingDurableLeave=new Map;pendingBootJoins=new Set;chatSubRefusals=new WeakSet;reportedSubRefusals=new WeakSet;ownWatchDeletePrefixes=new Set;historyReaderSlots=new Map;firstConnect=true;heartbeatTimer;sweepTimer;presenceWriteFailingSince;lastPresenceWriteError;presenceWriteFailures=0;presenceWriteEscalated=false;presencePutGeneration=0;presencePutSettled;roster=new Map;presenceRead;presenceReadGeneration=0;presenceReadApplied=0;presenceSnapshot=Promise.resolve();presenceSnapshotPopulated=false;lastPresenceWatchAt=0;presenceViewState="unpopulated";presenceRebind;presenceEpoch=0;presenceWatchEmpty=false;presenceRebindAt=0;status="idle";activity;statusSince=Date.now();activitySince;activeAt;condition;conditionRevision=0;environment;attentionMode;channelModes;stopped=false;stopPromise;startPromise;ownedConnections=new Set;rebuildPromise;reconnecting=false;reestablishing=false;backoffResolve;backoffTimer;retryMs=3e3;retryAttempt=0;connId;owner;actor;actorIsEphemeral;ownLifecycleUid;backfillFloor;acceptedToken;issuedGeneration;resolvedServices=new Map;serviceInvocations=new WeakMap;resolvedCommandServices=new Map;activeGoalFollowers=new Set;splitsRecovered=0;presenceBindingDrops=0;get principal(){return{owner:this.owner,actor:this.actor}}get splitRecoveryCount(){return this.splitsRecovered}get presenceBindingDropCount(){return this.presenceBindingDrops}requireLifecycleUid(what){if(!this.ownLifecycleUid)throw new Error(`${what} requires this endpoint's lifecycleUid (EndpointOptions.lifecycleUid): dm/dlv/chathist broker resources are lifecycle-keyed names (SPEC 13.1)`);return this.ownLifecycleUid}constructor(opts){super();let selfMintedConnId=false;this.space=opts.space;assertValidName(opts.card.name);assertValidKind(opts.card.kind);if(opts.card.role!==void 0)assertValidRole(opts.card.role);if(opts.bearer){if(opts.creds||opts.token||opts.user||opts.pass)throw new Error("bearer (user-mode auth) is mutually exclusive with creds/token/user/pass");if(!opts.sentinelCreds)throw new Error("user-mode bearer requires sentinelCreds (the shared auth-account creds presented alongside it)")}if(opts.bearer){this.userMode=true;if(typeof opts.bearer==="function"){if(!opts.card.owner||!opts.card.actor)throw new Error("a bearer source requires explicit card.owner + card.actor (no bearer to derive them from at construction)");this.owner=opts.card.owner;this.actor=opts.card.actor;this.bearerSource=opts.bearer}else{const claims2=decodeBearerPrincipal(opts.bearer);if(opts.card.owner&&opts.card.owner!==claims2.owner)throw new Error(`card.owner ${opts.card.owner} != bearer owner ${claims2.owner}`);if(opts.card.actor&&opts.card.actor!==claims2.actor)throw new Error(`card.actor ${opts.card.actor} != bearer actor ${claims2.actor}`);this.owner=claims2.owner;this.actor=claims2.actor;this.currentBearer=opts.bearer}this.connId=assertInboxConnId(`ibx${(0,import_node_crypto10.randomUUID)().replace(/-/g,"")}`);this.sentinelCreds=opts.sentinelCreds;this.actorIsEphemeral=false}else{if(typeof opts.creds==="function"){if(!opts.card.id)throw new Error("a creds source requires an explicit card.id (no cred to derive the identity from at construction)");this.credsSource=opts.creds;this.connId=opts.card.id;selfMintedConnId=false}else{const credId=opts.creds?idFromCreds(opts.creds):void 0;if(opts.card.id&&credId&&opts.card.id!==credId)throw new Error(`card.id ${opts.card.id} != creds identity ${credId} - they must be the same nkey`);this.currentCreds=opts.creds;selfMintedConnId=opts.card.id===void 0&&credId===void 0;this.connId=opts.card.id??credId??(0,import_node_crypto10.randomUUID)().replace(/-/g,"")}this.owner=opts.card.owner??DEV_OWNER;this.actor=opts.card.actor??this.connId;this.actorIsEphemeral=opts.card.actor===void 0&&selfMintedConnId}this.ownLifecycleUid=opts.lifecycleUid!==void 0?assertLifecycleToken(opts.lifecycleUid):this.authed?void 0:mintLifecycleUid();if(opts.backfillFloor!==void 0){if(!Number.isInteger(opts.backfillFloor)||opts.backfillFloor<0)throw new Error(`EndpointOptions.backfillFloor must be a non-negative integer stream sequence, got ${opts.backfillFloor}`);this.backfillFloor=opts.backfillFloor}if(opts.acceptedToken!==void 0){if(!opts.creds)throw new Error("EndpointOptions.acceptedToken names a static issuance and needs creds beside it (SPEC 13.15)");this.acceptedToken=assertGeneration(opts.acceptedToken,"acceptedToken")}const principal=principalKey(this.owner,this.actor);this.card={...opts.card,id:principal.key,owner:this.owner,actor:this.actor};this.environment=(opts.environment===void 0?process.env.COTAL_ENVIRONMENT:opts.environment)?.trim()||void 0;this.servers=opts.servers??DEFAULT_SERVER;this.token=opts.token;this.user=opts.user;this.pass=opts.pass;this.tls=opts.tls??false;for(const[label,value]of[["transportPingIntervalMs",opts.transportPingIntervalMs],["transportMaxPingOut",opts.transportMaxPingOut],["transportConnectTimeoutMs",opts.transportConnectTimeoutMs]]){if(value!==void 0&&(!Number.isSafeInteger(value)||value<=0))throw new Error(`EndpointOptions.${label} must be a positive safe integer`)}if(opts.transportPingIntervalMs===void 0!==(opts.transportMaxPingOut===void 0))throw new Error("EndpointOptions transportPingIntervalMs and transportMaxPingOut must be configured together");this.onConnection=opts.onConnection;this.beforeBind=opts.beforeBind;this.transportPingIntervalMs=opts.transportPingIntervalMs??1e4;this.transportMaxPingOut=opts.transportMaxPingOut??2;this.transportConnectTimeoutMs=opts.transportConnectTimeoutMs;this.channels=opts.channels??[];this.heartbeatMs=opts.heartbeatMs??2e3;this.ttlMs=opts.ttlMs??6e3;this.doRegister=opts.registerPresence??true;this.doWatch=opts.watchPresence??true;this.doWatchChannels=opts.watchChannels??true;this.doConsume=opts.consume??true;this.readOnce=opts.readOnce??false;if(this.readOnce&&(this.doConsume||this.doRegister))throw new Error("EndpointOptions.readOnce requires consume and registerPresence false: a one-time read cannot keep a consumer's channel cache or its own presence current");if(opts.dmOnly!==void 0){if(typeof opts.dmOnly.handler!=="function")throw new Error("EndpointOptions.dmOnly.handler must be a function");const settle=opts.dmOnly.settleTimeoutMs;if(settle!==void 0&&(!Number.isSafeInteger(settle)||settle<=0))throw new Error("EndpointOptions.dmOnly.settleTimeoutMs must be a positive safe integer");if(!this.authed)throw new Error("EndpointOptions.dmOnly requires creds or a bearer: it binds a provisioned durable and never creates one");if(!this.doConsume||this.doRegister||this.doWatch||this.doWatchChannels||this.readOnce)throw new Error("EndpointOptions.dmOnly requires consume true and registerPresence, watchPresence, watchChannels and readOnce false");if(this.channels.length||opts.card.role||opts.acceptedToken!==void 0)throw new Error("EndpointOptions.dmOnly takes no channels, role or acceptedToken: the endpoint reads only its own DM durable");this.requireLifecycleUid("EndpointOptions.dmOnly");this.dmOnly=opts.dmOnly}this.channelModes=opts.channelModes&&Object.keys(opts.channelModes).length?opts.channelModes:void 0;this.ackWaitMs=opts.ackWaitMs??6e4;this.inactiveThresholdMs=opts.inactiveThresholdMs??6e5}ref(){return{id:this.card.id,name:this.card.name,role:this.card.role}}get authed(){return Boolean(this.currentCreds||this.credsSource)||this.userMode}start(){if(this.startPromise)return this.startPromise;const flight=this.startOnce().finally(()=>{if(this.startPromise===flight)this.startPromise=void 0});this.startPromise=flight;return flight}async startOnce(){try{await this.connectAndBind()}catch(error51){if(!this.stopped)throw error51}if(await this.tearDownIfStopped())return;this.superviseConnection()}static BEARER_MIN_RENEWAL_MS=5e3;static BEARER_RETRY_MS=5e3;static BEARER_RETRY_CAP_MS=6e4;emitRecoverable(err3){this.emit("warning",err3)}async refreshBearer(initial=false){try{const bearer=await this.bearerSource();const claims2=decodeBearerPrincipal(bearer);if(claims2.owner!==this.owner||claims2.actor!==this.actor)throw new Error(`bearer source returned principal ${claims2.owner}.${claims2.actor}, expected ${this.owner}.${this.actor}`);const expiryMs=bearerExpiryMs(bearer);const held2=this.currentBearer;if(held2!==void 0){if(expiryMs<=Date.now())throw new Error("the bearer source returned a token that has already expired - nothing adopted");if(bearer===held2&&Date.now()>=bearerRenewalDeadlineMs(held2,this.bearerAdoptedAtMs))throw new Error("the bearer source re-served the token already held and it cannot carry another cycle (the auth service has not issued a fresh one) - nothing adopted")}if(bearer!==held2)this.bearerAdoptedAtMs=Date.now();this.currentBearer=bearer;this.bearerRenewalFailures=0;const{issuedAtMs,expiresAtMs}=bearerLifetimeMs(bearer,this.bearerAdoptedAtMs);this.armBearerTimer(armRenewal(this.space,issuedAtMs,expiresAtMs,()=>void this.renewBearerOnTimer(),_CotalEndpoint.BEARER_MIN_RENEWAL_MS))}catch(e){if(initial)throw e;if(this.bearerRenewalFailures===0)this.emitRecoverable(new Error(`bearer refresh failed (${e instanceof Error?e.message:String(e)}) - retrying with backoff; this connection dies at its current token's expiry if the auth service stays down`));const named=retryAfterMs(e);const delay3=named>0?named:jitteredBackoffMs(this.bearerRenewalFailures,_CotalEndpoint.BEARER_RETRY_MS,_CotalEndpoint.BEARER_RETRY_CAP_MS);this.bearerRenewalFailures++;const timer=setTimeout(()=>void this.renewBearerOnTimer(),delay3);timer.unref?.();this.armBearerTimer(()=>clearTimeout(timer))}}armBearerTimer(cancel){this.cancelBearerRenewal?.();this.cancelBearerRenewal=cancel;if(this.stopped)cancel()}async renewBearerOnTimer(){const held2=this.currentBearer;await this.refreshBearer();if(this.stopped||this.currentBearer===held2)return;if(this.nc&&!this.nc.isClosed())await this.swapConnectionOntoFreshCreds();else this.kickBackoff()}bearerForWire(){const bearer=this.currentBearer;if(bearer!==void 0&&bearerExpiryMs(bearer)>Date.now())return bearer;throw new Error(this.bearerSource?"this endpoint's user bearer has expired and renewal through the auth exchange is failing - not presenting the expired token to the broker; retrying with backoff":"this endpoint's user bearer has expired and it holds no bearer source to renew it - re-authenticate and rebuild the endpoint (construct it with a bearer FUNCTION for standing renewal)")}static CREDS_RETRY_MS=6e4;static presentableCreds(creds,opts){const{exp}=credsClaims(creds);if(typeof exp==="number"&&exp*1e3<=Date.now())throw new Error(opts.renewable?"this endpoint's creds have expired and renewal is failing - not presenting the expired credential to the broker; retrying with backoff":"this endpoint's creds have expired and it holds no creds source to renew them - replace the credential and rebuild the endpoint (pass a creds FUNCTION for standing renewal)");return creds}presentCreds(){const creds=this.credsForWire();this.presentedExp=credsClaims(creds).exp;return creds}presentBearer(){const bearer=this.bearerForWire();this.presentedExp=bearerExpiryMs(bearer)/1e3;return bearer}credsForWire(){if(!this.currentCreds)throw new Error(this.credsSource?"this endpoint has no credential to present yet (the creds source has not returned one) - not dialing without auth material":"this endpoint was constructed with an empty creds string - not dialing without auth material (an empty credential is not anonymous access)");return _CotalEndpoint.presentableCreds(this.currentCreds,{renewable:Boolean(this.credsSource)})}wireCreds(){return this.credsForWire()}static assertRenewableGeneration(candidate2,current,delayMs){const{exp}=credsClaims(candidate2);if(typeof exp==="number"&&exp*1e3<=Date.now())throw new Error("the creds source returned an already-expired credential (its `exp` is in the past) - nothing adopted; the renewal owner has not re-signed it, or the store is serving a stale generation");if(current!==void 0&&credsFingerprint(candidate2)===credsFingerprint(current)&&delayMs<=0)throw new Error("the creds source still holds the previous generation past its renewal point (the renewal owner has not re-signed it) - nothing adopted")}static PREFLIGHT_MS=4e3;static RESIDENT_SWAP_DEFER_MS=250;static RESIDENT_SWAP_GATE_MS=5e3;residentSwap;static RELOAD_DEADLINE_MS=12e3;async fetchFreshCreds(){const creds=await this.credsSource();const id2=idFromCreds(creds);if(id2!==this.connId)throw new Error(`creds source returned identity ${id2}, expected ${this.connId} - renewal may not swap the connection's nkey`);const delay3=credsRenewalDelayMs(creds);_CotalEndpoint.assertRenewableGeneration(creds,this.currentCreds,delay3);this.currentCreds=creds;this.armCredsRefresh(delay3);const{iat,exp}=credsClaims(creds);return{iat,exp}}async swapConnectionOntoFreshCreds(){const nc=this.nc;if(nc&&!this.stopped){await nc.reconnect().catch(()=>{});if(this.nc===nc&&!this.stopped)this.armAuthExpiryReconnectFence(nc)}}disableLibraryReconnect(nc){const protocol=nc.protocol;if(protocol?.options)protocol.options.reconnect=false}async closeWithoutLibraryReconnect(nc){if(!nc)return;this.disableLibraryReconnect(nc);await nc.close();if(!nc.isClosed())throw new Error("endpoint connection closure is unproved; consumer custody must be retained");this.ownedConnections.delete(nc)}armAuthExpiryReconnectFence(nc){clearTimeout(this.authExpiryReconnectTimer);this.authExpiryReconnectTimer=void 0;const credsExp=this.currentCreds&&credsClaims(this.currentCreds).exp;const expiryMs=this.userMode&&this.currentBearer?bearerExpiryMs(this.currentBearer):typeof credsExp==="number"?credsExp*1e3:void 0;if(expiryMs===void 0||this.stopped)return;const delay3=Math.max(0,expiryMs-Date.now()-500);this.authExpiryReconnectTimer=delay3>MAX_TIMER_MS3?setTimeout(()=>{if(this.nc===nc)this.armAuthExpiryReconnectFence(nc)},MAX_TIMER_MS3):setTimeout(()=>{if(this.nc===nc)this.disableLibraryReconnect(nc)},delay3);this.authExpiryReconnectTimer.unref?.()}async refreshCreds(initial=false){try{await this.fetchFreshCreds()}catch(e){if(initial)throw e;this.emitRecoverable(new Error(`creds refresh failed (${e instanceof Error?e.message:String(e)}) - retrying; this connection dies at its current JWT's expiry if renewal keeps failing`));this.armCredsRefresh(_CotalEndpoint.CREDS_RETRY_MS)}}credsTxn=Promise.resolve();runCredsTxn(fn){const next=this.credsTxn.then(fn,fn);this.credsTxn=next.then(()=>void 0,()=>void 0);return next}async adoptFreshCreds(opts={}){const deadline=opts.deadline??Date.now()+_CotalEndpoint.RELOAD_DEADLINE_MS;if(Date.now()>deadline)throw new Error("reloadCreds: the request deadline elapsed while queued behind another credential transaction; nothing adopted");const candidate2=await withDeadline(this.credsSource(),deadline-Date.now(),()=>new Error("reloadCreds: the creds source did not return before the daemon deadline; nothing adopted"));const id2=idFromCreds(candidate2);if(id2!==this.connId)throw new Error(`creds source returned identity ${id2}, expected ${this.connId} - renewal may not swap the connection's nkey`);if(opts.expected!==void 0&&credsFingerprint(candidate2)!==opts.expected)throw new Error("reloadCreds: re-read credential generation did not match the expected re-signed generation (a different store, or a torn/stale read); nothing adopted");const proven=_CotalEndpoint.presentableCreds(candidate2,{renewable:true});const probe=await probeConnect(this.servers,{creds:proven,tls:this.tls,timeoutMs:Math.max(500,Math.min(_CotalEndpoint.PREFLIGHT_MS,deadline-Date.now()))});if(!probe.ok)throw new Error(`reloadCreds: the broker did not accept the re-signed credential (${probe.reason}); nothing adopted`);if(Date.now()>deadline)throw new Error("reloadCreds: the proof exceeded the daemon deadline; nothing adopted");const delay3=credsRenewalDelayMs(candidate2);_CotalEndpoint.assertRenewableGeneration(candidate2,this.currentCreds,delay3);this.currentCreds=candidate2;this.armCredsRefresh(delay3);this.emit("creds-adopted",credsClaims(candidate2));return credsClaims(candidate2)}async renewCredsOnTimer(){const deadline=Date.now()+_CotalEndpoint.RELOAD_DEADLINE_MS;try{await this.runCredsTxn(()=>this.adoptFreshCreds({deadline}));await this.swapConnectionOntoFreshCreds()}catch(e){this.emitRecoverable(new Error(`creds refresh failed (${e instanceof Error?e.message:String(e)}) - retrying; this connection dies at its current JWT's expiry if renewal keeps failing`));this.armCredsRefresh(_CotalEndpoint.CREDS_RETRY_MS)}}async refreshCredsRequestSafe(){if(!this.credsSource)throw new Error("credential refresh requires a creds source");const nc=this.nc;if(!nc||this.stopped)throw new Error("credential refresh requires a running endpoint");const deadline=Date.now()+_CotalEndpoint.RELOAD_DEADLINE_MS;await this.runCredsTxn(async()=>{await this.adoptFreshCreds({deadline});if(this.nc!==nc||this.stopped)throw new Error("endpoint connection changed during credential refresh");await requestSafeReconnect(nc,()=>this.requestsAwaitingReply.get(nc)?.size??0);if(this.nc===nc&&!this.stopped)this.armAuthExpiryReconnectFence(nc)})}async reloadCreds(expected){if(!this.credsSource)throw new Error("reloadCreds: this endpoint has no creds source (a static cred cannot be renewed in place)");const deadline=Date.now()+_CotalEndpoint.RELOAD_DEADLINE_MS;const{iat,exp}=await this.runCredsTxn(()=>this.adoptFreshCreds({expected,deadline}));return{identity:this.connId,iat,exp}}scheduleResidentSwap(){if(this.stopped)return;const swap=new Promise(resolve=>{setTimeout(resolve,_CotalEndpoint.RESIDENT_SWAP_DEFER_MS).unref?.()}).then(async()=>{const back=this.transportBack(_CotalEndpoint.RESIDENT_SWAP_GATE_MS);await this.swapConnectionOntoFreshCreds();await back}).finally(()=>{if(this.residentSwap===swap)this.residentSwap=void 0});this.residentSwap=swap}transportBack(ms){return new Promise(resolve=>{const done=()=>{clearTimeout(timer);this.off("transport",seen);resolve()};const seen=state=>{if(state.connected)done()};const timer=setTimeout(done,ms);timer.unref?.();this.on("transport",seen)})}armCredsRefresh(delayMs){if(this.stopped)return;clearTimeout(this.credsTimer);this.credsTimer=delayMs>MAX_TIMER_MS3?setTimeout(()=>this.armCredsRefresh(delayMs-MAX_TIMER_MS3),MAX_TIMER_MS3):setTimeout(()=>void this.renewCredsOnTimer(),Math.max(1e3,delayMs));this.credsTimer.unref?.()}async connectAndBind(){try{await this.bindConnection()}catch(error51){await this.closeFailedBind();throw error51}}async bindConnection(){this.clearConnectionScoped();if(this.bearerSource){if(!this.currentBearer)await this.refreshBearer(true);else if(this.bearerRenewalFailures===0&&Date.now()>=bearerRenewalDeadlineMs(this.currentBearer,this.bearerAdoptedAtMs))await this.refreshBearer()}if(this.credsSource){const stale=!this.currentCreds||credsRenewalDelayMs(this.currentCreds)<=0;if(stale)await this.refreshCreds(!this.currentCreds)}if(this.userMode){try{this.bearerForWire();this.bearerRefusalSurfaced=false}catch(e){if(!this.bearerRefusalSurfaced){this.bearerRefusalSurfaced=true;throw e}throw new RepeatedRefusal(e.message)}}let watchDeletePermission;this.nc=await dialerFor(this.servers)({servers:this.servers,noAsyncTraces:true,name:this.userMode?this.connId:`cotal:${this.card.name}`,inboxPrefix:`_INBOX_${this.connId}`,...this.transportPingIntervalMs===void 0?{}:{pingInterval:this.transportPingIntervalMs},...this.transportMaxPingOut===void 0?{}:{maxPingOut:this.transportMaxPingOut},...this.transportConnectTimeoutMs===void 0?{}:{timeout:this.transportConnectTimeoutMs},...authOpts({token:this.token,user:this.user,pass:this.pass,creds:this.currentCreds!==void 0||this.credsSource?()=>this.presentCreds():void 0,bearer:this.userMode?()=>this.presentBearer():void 0,sentinelCreds:this.sentinelCreds,tls:this.tls,onCreds:creds=>{watchDeletePermission=void 0;try{const nats=credsClaims(creds).nats;if(nats?.pub!==void 0)watchDeletePermission=importNativeSubjectPermissions({pub:nats.pub}).publish}catch{}}})});this.watchDeletePermissions.set(this.nc,()=>watchDeletePermission);this.ownedConnections.add(this.nc);const owned=this.nc;void owned.closed().then(()=>this.ownedConnections.delete(owned));this.onConnection?.(this.nc);requireBrokerFloor(this.nc);this.armAuthExpiryReconnectFence(this.nc);this.watchStatus();this.js=(0,import_jetstream13.jetstream)(this.nc);if(this.dmOnly){await this.beforeBind?.();if(this.stopped)return;await this.bindDmOnly(this.dmOnly);if(this.stopped)return;this.emit("connection",{connected:true});return}if(this.acceptedToken!==void 0){const ref=await readAcceptedRow(this.nc,this.space,this.acceptedToken);const uid2=this.requireLifecycleUid("an issued endpoint");if(ref.owner!==this.owner||ref.actor!==this.actor||ref.uid!==uid2)throw new Error(`the accepted row names ${ref.owner}.${ref.actor} (uid ${ref.uid}), not this endpoint ${this.owner}.${this.actor} (uid ${uid2}); refusing to ride a foreign issuance (SPEC 13.15)`);this.issuedGeneration=ref.generation}await this.beforeBind?.();if(this.stopped)return;if(this.doWatch||this.doRegister){const kvm=new import_kv7.Kvm(this.nc);this.kv=this.authed?await kvm.open(presenceBucket(this.space)):await kvm.create(presenceBucket(this.space),{ttl:this.ttlMs,storage:PRESENCE_STORAGE})}if(this.doWatch&&this.readOnce)await this.readPresenceOnce();else if(this.doWatch){await this.startPresenceWatch();this.sweepTimer=setInterval(()=>this.sweep(),Math.max(500,Math.floor(this.ttlMs/3)))}const watchChannels=this.doWatch&&this.doWatchChannels;if(watchChannels||this.doConsume){this.channelKv=await openChannelRegistry(this.nc,this.space,{create:!this.authed});if(watchChannels)await(this.readOnce?this.readChannelsOnce():this.startChannelWatch());else if(this.readsChannelsOnDemand)await this.readChannels()}if(this.leaseWatchIntent)await this.bindDeliveryLeaseWatch();if(this.authed&&(this.doConsume||this.doRegister))this.requireLifecycleUid(this.doConsume?"an authed consuming endpoint":"an authed presence-registering endpoint");if(this.doConsume){this.jsm=await(0,import_jetstream13.jetstreamManager)(this.nc);if(!this.authed)await this.ensureStreams();await this.startConsumers()}if(this.doRegister&&!this.doConsume&&this.authed&&this.card.kind==="agent"){const jsm=this.jsm??(this.jsm=await(0,import_jetstream13.jetstreamManager)(this.nc));const uid2=this.requireLifecycleUid("an authed presence-registering agent");try{await jsm.consumers.info(dmStream(this.space),dmDurable(this.owner,this.actor,uid2))}catch(e){throw new Error(`lifecycle proof failed for ${this.card.id} (uid ${uid2}): its dm_ durable is not present at the broker, so this incarnation's uid does not match its provisioned resources - refusing to publish presence (SPEC 13.1 fail-before-presence): ${e?.message??String(e)}`)}}if(this.doRegister){try{await this.publishPresence()}catch(e){const detail=e?.message??String(e);throw new Error(`presence registration failed for ${this.card.id}: the space's presence KV bucket "${presenceBucket(this.space)}" did not accept this endpoint's first write (${detail}). The bucket can be OPENED and WATCHED while refusing every write, so a healthy-looking connection does not rule this out; a broker whose store has latched refuses until it is restarted, and no client can clear it (#1356).`)}const phase=Date.now();let beat=0;const arm=()=>{const next=nextHeartbeat(phase,this.heartbeatMs,beat,Date.now());beat=next.beat;const handle=setTimeout(()=>{this.publishPresence().catch(e=>this.emitRecoverable(e));if(this.heartbeatTimer===handle)arm()},next.delayMs);this.heartbeatTimer=handle};arm()}await this.rearmMembershipWatches();await this.armPlane3();for(const plane of this.livenessResponders.keys())this.bindLiveness(plane);for(const tap of this.taps)this.bindTap(tap);if(this.stopped)return;this.emit("connection",{connected:true});if(this.nc){for(const follower of this.activeGoalFollowers){follower.reconnected(this.nc)}}}clearConnectionScoped(){if(this.authExpiryReconnectTimer){clearTimeout(this.authExpiryReconnectTimer);this.authExpiryReconnectTimer=void 0}if(this.heartbeatTimer){clearInterval(this.heartbeatTimer);this.heartbeatTimer=void 0}if(this.sweepTimer){clearInterval(this.sweepTimer);this.sweepTimer=void 0}for(const msgs of this.streamMsgs){try{msgs.stop()}catch{}}this.streamMsgs.length=0;this.presenceEpoch++;this.presenceRebind=void 0;if(this.presenceWatchIter)this.retireKvWatch(this.presenceWatchIter);this.presenceWatchIter=void 0;if(this.channelWatchIter)this.retireKvWatch(this.channelWatchIter);this.channelWatchIter=void 0;this.stopDeliveryLeaseWatch();for(const sub of this.chatSubs.values()){try{sub.unsubscribe()}catch{}}this.chatSubs.clear();this.chatSubDenied.clear();this.ownWatchDeletePrefixes.clear();this.roster.clear();this.presenceRead=void 0;this.presenceReadGeneration++;this.presenceReadApplied=this.presenceReadGeneration;this.clearPresenceWriteFailure();this.lastPresenceWatchAt=0;this.presenceRebindAt=0;this.presenceWatchEmpty=false;this.presenceSnapshotPopulated=false;this.emitPresenceViewIfChanged();this.channelConfigs.clear();this.channelDefaults={};this.channelRead=void 0;this.channelReadGeneration++;this.channelReadApplied=this.channelReadGeneration;for(const watch of this.membershipFeedWatches)watch.arm=watch.arm.catch(()=>{}).then(()=>this.disarmMembershipWatch(watch)).catch(err3=>{this.emit("error",err3)})}async closeFailedBind(){const failedNc=this.nc;if(failedNc)this.disableLibraryReconnect(failedNc);this.clearConnectionScoped();this.nc=void 0;this.js=void 0;this.jsm=void 0;this.kv=void 0;this.channelKv=void 0;this.membersKv=void 0;this.aclKv=void 0;this.membershipFeedKv=void 0;this.deliveryKv=void 0;this.managerLeaseKv=void 0;this.daemonRenewalLeaseRevision=void 0;if(this.deliveryServeSub){try{this.deliveryServeSub.unsubscribe()}catch{}this.deliveryServeSub=void 0}if(this.deliveryAdminServeSub){try{this.deliveryAdminServeSub.unsubscribe()}catch{}this.deliveryAdminServeSub=void 0}this.dropAnycastRequests();for(const sub of this.subs){try{sub.unsubscribe()}catch{}}this.subs.length=0;if(!failedNc)return;this.emit("transport",{connected:false});this.emit("connection",{connected:false});try{await failedNc.close();return}catch{}if(!failedNc.isClosed?.()){try{await drainAndClose(failedNc);return}catch{}}const proto=failedNc.protocol;const transport=proto?.transport;if(transport&&!transport.isClosed){try{await transport.close?.()}catch{}if(!transport.isClosed){try{transport.disconnect?.()}catch{}}}}async tearDownIfStopped(){if(!this.stopped)return false;const nc=this.nc;if(nc)this.disableLibraryReconnect(nc);this.clearConnectionScoped();await this.closeWithoutLibraryReconnect(nc);this.nc=void 0;return true}superviseConnection(){const nc=this.nc;if(!nc)return;void nc.closed().then(err3=>{if(this.stopped)return;if(this.nc!==nc)return;this.emit("connection",{connected:false});this.emit("error",new Error(`mesh connection closed${err3?`: ${err3.message||err3.name}`:""} - re-establishing`));void this.reestablishLoop()})}rebuild(){if(this.rebuildPromise)return this.rebuildPromise;const p=this.doRebuild().finally(()=>{if(this.rebuildPromise===p)this.rebuildPromise=void 0});this.rebuildPromise=p;return p}async doRebuild(){const oldNc=this.nc;if(oldNc)this.disableLibraryReconnect(oldNc);this.reconnecting=true;try{this.clearConnectionScoped();if(oldNc&&!oldNc.isClosed())await Promise.all([...[...this.membershipFeedWatches].map(watch=>watch.arm),this.settleDeliveryLeaseWatches(),this.settleKvWatches()]);this.nc=void 0;this.js=void 0;this.jsm=void 0;this.kv=void 0;this.channelKv=void 0;this.membersKv=void 0;this.aclKv=void 0;this.membershipFeedKv=void 0;this.deliveryKv=void 0;this.managerLeaseKv=void 0;this.daemonRenewalLeaseRevision=void 0;this.emit("transport",{connected:false});this.emit("connection",{connected:false});await this.closeWithoutLibraryReconnect(oldNc);if(this.stopped)return;try{await this.connectAndBind()}catch(error51){if(!this.stopped)throw error51}if(await this.tearDownIfStopped())return;this.superviseConnection()}finally{this.reconnecting=false}}static RETRY_BACKOFF_CAP_MS=6e4;nextRetryDelayMs(){const delay3=Math.min(this.retryMs*2**this.retryAttempt,_CotalEndpoint.RETRY_BACKOFF_CAP_MS);this.retryAttempt++;return Math.round(delay3/2+Math.random()*(delay3/2))}async reestablishLoop(){if(this.reestablishing)return;this.reestablishing=true;try{while(!this.stopped){try{await this.rebuild();this.retryAttempt=0;return}catch(e){const delay3=this.nextRetryDelayMs();if(!this.stopped&&!(e instanceof RepeatedRefusal))this.emitRecoverable(this.userMode&&isAuthRejection(e)?new Error(`the broker refused this endpoint's bearer for ${this.owner}.${this.actor} - retrying in ${Math.ceil(delay3/1e3)}s; the space's auth service logs why`,{cause:e}):e);if(this.stopped)return;await new Promise(resolve=>{this.backoffResolve=resolve;this.backoffTimer=setTimeout(resolve,delay3)})}}}finally{this.reestablishing=false}}kickBackoff(){this.backoffResolve?.();if(this.backoffTimer){clearTimeout(this.backoffTimer);this.backoffTimer=void 0}}async reconnect(){if(this.stopped)throw new Error("endpoint stopped - cannot reconnect");this.kickBackoff();try{await this.rebuild()}catch(e){void this.reestablishLoop();throw e}}stop(){return this.stopPromise??=this.stopOnce()}async stopOnce(){if(this.nc)this.disableLibraryReconnect(this.nc);this.stopped=true;for(const follower of this.activeGoalFollowers){follower.cancel()}this.activeGoalFollowers.clear();this.presenceEpoch++;this.presenceRebind=void 0;this.kickBackoff();if(this.heartbeatTimer)clearInterval(this.heartbeatTimer);if(this.sweepTimer)clearInterval(this.sweepTimer);this.cancelBearerRenewal?.();if(this.credsTimer)clearTimeout(this.credsTimer);if(this.authExpiryReconnectTimer)clearTimeout(this.authExpiryReconnectTimer);for(const watch of this.membershipFeedWatches){watch.stopped=true;watch.arm=watch.arm.catch(()=>{}).then(async()=>{await this.disarmMembershipWatch(watch);await this.deleteRetainedMembershipConsumer(watch)})}await Promise.all([...this.membershipFeedWatches].map(watch=>watch.arm.catch(err3=>{if(this.nc&&!this.nc.isClosed())throw err3})));for(const watch of this.membershipFeedWatches){watch.resolveStop?.();watch.resolveStop=void 0;watch.rejectStop=void 0}this.membershipFeedWatches.clear();for(const msgs of this.streamMsgs){try{msgs.stop()}catch{}}if(this.presenceWatchIter)this.retireKvWatch(this.presenceWatchIter);this.presenceWatchIter=void 0;if(this.channelWatchIter)this.retireKvWatch(this.channelWatchIter);this.channelWatchIter=void 0;this.stopDeliveryLeaseWatch();try{if(this.doRegister){this.status="offline";await this.publishPresence()}}catch{}await Promise.all([this.settleDeliveryLeaseWatches(),this.settleKvWatches()]);let dmOnlyUnsettled=false;if(this.dmOnly&&this.dmOnlyInFlight){const settleMs=this.dmOnly.settleTimeoutMs??3e4;dmOnlyUnsettled=await withDeadline(this.dmOnlyInFlight.then(()=>false),settleMs,()=>new Error("unsettled")).catch(()=>true)}await this.closeWithoutLibraryReconnect(this.nc);this.clearPresenceWriteFailure();await this.rebuildPromise;await this.startPromise;if([...this.ownedConnections].some(nc=>!nc.isClosed()))throw new Error("endpoint stop could not prove its connection closed; local consumer custody must be retained");if(dmOnlyUnsettled)throw new Error(`endpoint stop closed the connection but the DM-only handler did not settle within ${this.dmOnly?.settleTimeoutMs??3e4}ms; its copy stays unacked and handler custody must be retained`)}async multicast(text2,opts){const channel=opts?.channel??this.channels.find(isConcreteChannel);if(channel===void 0)throw new Error("no default channel: this endpoint is not on any concrete channel, so there is nothing to broadcast to - name a channel explicitly, or join one first");if(!isConcreteChannel(channel))throw new Error(`cannot publish to wildcard channel "${channel}" - pick a concrete sub-channel`);const msg={id:(0,import_node_crypto10.randomUUID)(),ts:Date.now(),space:this.space,from:this.ref(),channel,mentions:normalizeMentions(opts?.mentions),parts:opts?.parts??[{kind:"text",text:text2}],replyTo:opts?.replyTo,contextId:opts?.contextId};await this.publishMsg(chatSubject(this.space,this.owner,this.actor,channel),msg);return msg}get maxPayload(){const max=this.nc?.info?.max_payload;if(typeof max!=="number"||!Number.isFinite(max)||max<=0)throw new Error(`${this.notLiveMsg()} - max_payload is only known while connected`);return max}async assertExpectationSemantics(){if(!this.jsm)throw new Error(this.notLiveMsg());const stream=chatStream(this.space);let replicas;try{replicas=(await this.jsm.streams.info(stream)).config.num_replicas}catch(e){throw new Error(`cannot verify expectation semantics: stream "${stream}" info unavailable (${e.message}). Serialized appends are refused rather than run on an unverified stream.`)}if(replicas!==1)throw new Error(`stream "${stream}" reports num_replicas=${String(replicas)}; serialized appends on THIS stream require 1 \u2014 a property of this one stream, not of the broker, so a clustered deployment is fine so long as this stream is R1, which a cluster can host. On a replicated stream the dedup cache is consulted before the subject expectation, so a retry returns a duplicate ack instead of a conflict and a lost message reads as success.`)}casEnvelope(opts){return{id:opts.id,ts:Date.now(),space:this.space,from:this.ref(),channel:opts.channel,mentions:normalizeMentions(opts.mentions),parts:opts.parts,replyTo:opts.replyTo,contextId:opts.contextId}}encodedSize(opts){if(!isConcreteChannel(opts.channel))throw new Error(`cannot publish to wildcard channel "${opts.channel}" - pick a concrete sub-channel`);assertIdToken(opts.id,"publish id");if(!Number.isSafeInteger(opts.expectedLastSubjectSeq)||opts.expectedLastSubjectSeq<0)throw new Error(`expectedLastSubjectSeq must be a non-negative safe integer, got ${JSON.stringify(opts.expectedLastSubjectSeq)}`);if(!Array.isArray(opts.parts)||opts.parts.length===0)throw new Error("encodedSize requires at least one part");const mh=(0,import_transport_node13.headers)();mh.set("Nats-Msg-Id",opts.id);mh.set("Nats-Expected-Last-Subject-Sequence",`${opts.expectedLastSubjectSeq}`);const headerBytes=mh.encode().length;return headerBytes+Buffer.byteLength(JSON.stringify(this.casEnvelope(opts)),"utf8")}async multicastExpecting(opts){if(!this.js)throw new Error(this.notLiveMsg());if(!isConcreteChannel(opts.channel))throw new Error(`cannot publish to wildcard channel "${opts.channel}" - pick a concrete sub-channel`);assertIdToken(opts.id,"publish id");const expected=opts.expectedLastSubjectSeq;if(!Number.isSafeInteger(expected)||expected<0)throw new Error(`expectedLastSubjectSeq must be a non-negative safe integer, got ${JSON.stringify(expected)}`);if(!Array.isArray(opts.parts)||opts.parts.length===0)throw new Error("multicastExpecting requires at least one part");const message=this.casEnvelope(opts);assertPartsSerializable(message.parts);const ack=await this.js.publish(chatSubject(this.space,this.owner,this.actor,opts.channel),JSON.stringify(message),{msgID:opts.id,expect:{lastSubjectSequence:expected}});return{message,ack:{seq:ack.seq,duplicate:ack.duplicate===true}}}async unicast(instanceId,text2,opts){const{msg}=await this.unicastAttributed(instanceId,text2,opts);return msg}async unicastAttributed(instanceId,text2,opts){if(!this.js)throw new Error(this.notLiveMsg());const msg={id:(0,import_node_crypto10.randomUUID)(),ts:Date.now(),space:this.space,from:this.ref(),to:instanceId,parts:opts?.parts??[{kind:"text",text:text2}],replyTo:opts?.replyTo,contextId:opts?.contextId};const recip=parsePrincipalKey(instanceId);if(!recip)throw new Error(`unicast: "${instanceId}" is not a valid recipient principal <owner>.<actor>`);assertPartsSerializable(msg.parts);const subject=unicastSubject(this.space,recip.owner,recip.actor,this.owner,this.actor);try{const ack=await this.js.publish(subject,JSON.stringify(msg),{msgID:msg.id});return{msg,ack:{seq:ack.seq,duplicate:ack.duplicate===true}}}catch(error51){if(error51 instanceof import_transport_node13.TimeoutError)throw new Error(`${error51.message} publishing to ${JSON.stringify(subject)}. The send outcome is unknown: the broker may have stored the message. Check before resending.`,{cause:error51});throw error51}}async anycast(service,text2,opts){const{msg}=await this.anycastAttributed(service,text2,opts);return msg}async anycastAttributed(service,text2,opts){if(!this.js)throw new Error(this.notLiveMsg());assertValidRole(service);const msg={id:(0,import_node_crypto10.randomUUID)(),ts:Date.now(),space:this.space,from:this.ref(),toService:service,parts:opts?.parts??[{kind:"text",text:text2}],replyTo:opts?.replyTo,contextId:opts?.contextId};assertPartsSerializable(msg.parts);const ack=await this.js.publish(anycastSubject(this.space,service,this.owner,this.actor),JSON.stringify(msg),{msgID:msg.id});return{msg,ack:{seq:ack.seq,duplicate:ack.duplicate===true}}}tap(handler,opts){const tap={handler,subject:opts?.subject??spaceWildcard(this.space)};this.taps.push(tap);this.bindTap(tap)}bindTap(tap){if(!this.nc)return;const sub=this.nc.subscribe(tap.subject);this.subs.push(sub);void(async()=>{for await(const m of sub){let decoded;try{decoded=m.json()}catch{decoded=void 0}const parsed=parseSubject(m.subject);if(decoded!==void 0&&(parsed?.kind==="chat"||parsed?.kind==="inst"||parsed?.kind==="svc")){if(!isFromSubjectSender(decoded,parsed))continue;decoded=authenticatedMessage(decoded,parsed)}tap.handler(m.subject,decoded)}})().catch(e=>this.emit("error",e))}serveControl(service,handler,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());const sub=this.nc.subscribe(controlServiceSubject(this.space,service,"*","*"),{queue:service});this.subs.push(sub);const inOwnTime=opts.concurrent;let inOrder=Promise.resolve();void(async()=>{for await(const m of sub){if(opts.boundReply&&(!m.reply||!m.reply.startsWith(`${m.subject}.reply.`))){this.emit("error",new Error(`rejected ${service} request on ${m.subject}: reply target "${m.reply??"(none)"}" is not under the sender's own reply subtree`));continue}const answer=()=>this.answerControl(service,handler,m);if(inOwnTime===void 0){await answer();continue}let own=false;try{own=inOwnTime(m.json())}catch{}if(own)void answer().catch(e=>this.emit("error",e));else inOrder=inOrder.then(answer).catch(e=>{this.emit("error",e)})}})().catch(e=>{if(!this.reportSubscriptionDenial(e))this.emit("error",e)});return sub}async answerControl(service,handler,m){let body;try{let reply;const req=m.json();const parsed=parseSubject(m.subject);if(!parsed||!isFromSubjectSender(req,parsed)){this.emit("error",new Error(`rejected control request on ${m.subject}: from ${req.from?.id??"(none)"} does not match subject sender ${parsed?.sender??"(unparseable)"}`));reply={ok:false,error:"sender mismatch - request rejected"}}else{reply=await handler(req)}body=JSON.stringify(reply)}catch(e){body=JSON.stringify({ok:false,error:e.message})}try{m.respond(body)}catch(e){const refused={ok:false,error:`the ${service} reply is ${Buffer.byteLength(body)} bytes and was not published: ${e.message}`};try{m.respond(JSON.stringify(refused))}catch(err3){this.emit("error",new Error(`could not answer ${service} request on ${m.subject}: ${refused.error}, and the refusal failed too: ${err3.message}`))}}}async requestBoundReply(nc,subject,body,reply,timeoutMs){let pending=this.requestsAwaitingReply.get(nc);if(!pending){const waiting=new Set;this.requestsAwaitingReply.set(nc,waiting);void nc.closed().then(error51=>{this.requestsAwaitingReply.delete(nc);const failure=error51??new import_transport_node13.ClosedConnectionError;for(const reject of waiting)reject(failure);waiting.clear()});pending=waiting}let rejectClosed;const closed3=new Promise((_resolve,reject)=>{rejectClosed=reject;pending.add(reject)});try{return await Promise.race([nc.request(subject,body,{timeout:timeoutMs,noMux:true,reply}),closed3])}finally{pending.delete(rejectClosed)}}async requestControl(service,req,timeoutMs=5e3){if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=controlServiceSubject(this.space,service,this.owner,this.actor);const reply=`${reqSubject}.reply.${(0,import_node_crypto10.randomUUID)()}`;const body={...req,from:req.from??this.ref()};const m=await this.requestBoundReply(this.nc,reqSubject,JSON.stringify(body),reply,timeoutMs);return m.json()}serviceRailCaller(){return this.serviceCaller()}serviceCaller(){const triple={owner:this.owner,actor:this.actor,uid:this.requireLifecycleUid("invokeService")};if(this.acceptedToken===void 0)return triple;if(this.issuedGeneration===void 0)throw new Error("invokeService: the issued generation is not yet discovered on this connection");return{...triple,generation:this.issuedGeneration}}async followServiceGoal(endpoint,submit,deadlineMs=1e4,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());if(this.stopped)throw new Error("endpoint stopped - cannot follow goal");const abortController=new AbortController;const onAbort=()=>abortController.abort();if(opts.signal?.aborted)onAbort();else opts.signal?.addEventListener("abort",onAbort,{once:true});let reconnectHandler;const entry={cancel:()=>abortController.abort(),reconnected:nc=>reconnectHandler?.(nc)};this.activeGoalFollowers.add(entry);try{const reconcile=opts.reconcile??(async(goalId,_attributed,context)=>{const current=this.serviceCaller();if(current.owner!==context.caller.owner||current.actor!==context.caller.actor||current.uid!==context.caller.uid)throw new Error("the renewed goal reader no longer has the accepting caller's full identity");const q=await this.invokeService(endpoint,"goal-result",{goalId},{deadlineMs:Math.min(deadlineMs,context.deadlineMs),signal:context.signal});if(q.reply.ok!==true)throw new Error(q.reply.error.message);return q.reply.data});return await submitAndFollowGoal(this.nc,this.space,endpoint,this.serviceCaller(),deadlineMs,submit,{reconcile,currentNc:()=>this.nc,onReconnect:cb=>{reconnectHandler=cb;return()=>{reconnectHandler=void 0}},signal:abortController.signal,prepare:opts.prepare})}finally{opts.signal?.removeEventListener("abort",onAbort);this.activeGoalFollowers.delete(entry)}}clearResolvedService(endpoint){this.resolvedServices.delete(endpoint);this.resolvedCommandServices.delete(endpoint)}beginServiceInvocation(nc){let pending=this.serviceInvocations.get(nc);if(!pending){pending=new Set;this.serviceInvocations.set(nc,pending)}let settle;const request=new Promise(resolve=>{settle=resolve});pending.add(request);return()=>{pending.delete(request);settle()}}async waitServiceRecovery(recovery,deadline,signal,timeout){let onAbort;const cancelled=new Promise((_,reject)=>{onAbort=()=>reject(signal?.reason);if(signal?.aborted)onAbort();else signal?.addEventListener("abort",onAbort,{once:true})});try{await withDeadline(Promise.race([recovery,cancelled]),deadline-Date.now(),timeout)}finally{if(onAbort)signal?.removeEventListener("abort",onAbort)}signal?.throwIfAborted();if(deadline<=Date.now())throw timeout()}async describeService(endpoint,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());if(opts.refresh)this.clearResolvedService(endpoint);const cached2=opts.instanceId===void 0?this.resolvedServices.get(endpoint):void 0;if(cached2)return cached2;const svc=await resolveService(this.nc,this.space,endpoint,this.serviceCaller(),{deadlineMs:opts.deadlineMs??1e4,signal:opts.signal,...opts.instanceId!==void 0?{instanceId:opts.instanceId}:{}});if(opts.instanceId===void 0)this.resolvedServices.set(endpoint,svc);return svc}async listingCaller(){if(!this.nc)throw new Error(this.notLiveMsg());return registryListingCaller(this.nc,this.space,this.serviceCaller(),{connId:this.connId,...this.presentedExp!==void 0?{exp:this.presentedExp}:{}})}async listEndpoints(input,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());const nc=this.nc;const listing=this.authed?await this.listingCaller():void 0;if(this.authed&&listing===void 0)return{unbound:true};return this.listEndpointsOver(nc,listing,input,opts)}async listEndpointsOver(nc,listing,input,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());const own=this.nc;const result=await listRegistryEndpoints(this.space,(deadlineMs,signal)=>resolveService(own,this.space,REGISTRY_ENDPOINT,this.serviceCaller(),{deadlineMs,signal,commands:[REGISTRY_ENDPOINTS_COMMAND]}),{nc,...listing?{caller:listing}:{}},input,opts);if(result.unbound)return result;for(const row of result.page?.rows??[])this.clearResolvedService(row.endpoint);return result}async invokeService(endpoint,command,args,opts={}){const deadline=Date.now()+(opts.deadlineMs??1e4);const rebuilding=this.rebuildPromise;if(rebuilding){await this.waitServiceRecovery(rebuilding,deadline,opts.signal,()=>new EpEnvelopeError("deadline-exceeded","the invocation deadline elapsed waiting for connection recovery",void 0,"not-executed"));opts={...opts,deadlineMs:deadline-Date.now()}}const nc=this.nc;if(!nc)throw new Error(this.notLiveMsg());try{return await this.invokeServiceOnce(endpoint,command,args,opts,rebuilding?deadline:void 0)}catch(e){if(!(e instanceof EpEnvelopeError)||e.code!=="permission-denied"||e.outcome!=="not-executed"||deadline<=Date.now())throw e;opts.signal?.throwIfAborted();const recovery=(async()=>{for(;;){opts.signal?.throwIfAborted();if(deadline<=Date.now())throw e;const pending=this.serviceInvocations.get(nc);if(!pending?.size)break;await Promise.allSettled([...pending])}if(this.nc===nc)await this.reconnect();else await this.rebuildPromise})();await this.waitServiceRecovery(recovery,deadline,opts.signal,()=>e);this.clearResolvedService(endpoint);return this.invokeServiceOnce(endpoint,command,args,{...opts,deadlineMs:deadline-Date.now()},deadline)}}async invokeServiceOnce(endpoint,command,args,opts={},retryDeadline){if(!this.nc)throw new Error(this.notLiveMsg());const nc=this.nc;const caller=this.serviceCaller();const resolve=async(signal=opts.signal,deadlineMs=opts.deadlineMs??1e4)=>{signal?.throwIfAborted();if(retryDeadline!==void 0)deadlineMs=Math.min(deadlineMs,retryDeadline-Date.now());if(deadlineMs<=0)throw new EpEnvelopeError("deadline-exceeded","the invocation deadline elapsed before resolve",void 0,"not-executed");const needed=opts.follow?[command,"goal-result"]:[command];const classSelected=opts.instanceId===void 0&&opts.classInstanceId===void 0;const full=classSelected?this.resolvedServices.get(endpoint):void 0;if(full&&needed.every(name=>full.commands.has(name)))return full;const cacheKey=[...needed].sort().join("\0");const commandCache=classSelected?this.resolvedCommandServices.get(endpoint):void 0;const cached2=commandCache?.get(cacheKey);if(cached2)return cached2;const svc=await resolveService(nc,this.space,endpoint,caller,{deadlineMs,signal,commands:needed,...opts.follow&&command!=="goal-result"?{optionalCommands:["goal-result"]}:{},...opts.instanceId!==void 0?{instanceId:opts.instanceId}:{},...opts.classInstanceId!==void 0?{classInstanceId:opts.classInstanceId}:{}});if(classSelected){let byCommand=this.resolvedCommandServices.get(endpoint);if(!byCommand){byCommand=new Map;this.resolvedCommandServices.set(endpoint,byCommand)}byCommand.set(cacheKey,svc)}return svc};const invokeOpts={...opts.target?{target:opts.target}:{},...opts.deadlineMs!==void 0?{deadlineMs:opts.deadlineMs}:{}};const invokeResolved=(service,signal)=>{signal?.throwIfAborted();const unfollowable=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable)return Promise.resolve(unfollowable);const deadlineMs=retryDeadline===void 0?invokeOpts.deadlineMs:retryDeadline-Date.now();if(deadlineMs!==void 0&&deadlineMs<=0)throw new EpEnvelopeError("deadline-exceeded","the invocation deadline elapsed before publish",void 0,"not-executed");return invokeCommand(nc,this.space,service,command,args,{...invokeOpts,deadlineMs,signal})};const resolveFirst=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{try{return await resolve(signal,deadline-Date.now())}catch(e){if(!(e instanceof EpEnvelopeError)||e.code!=="failed-precondition")throw e;const left=deadline-Date.now();if(left<=0)throw e;return await resolve(signal,left)}};const doInvoke=async(service,signal=opts.signal)=>{signal?.throwIfAborted();try{let r=await invokeResolved(service,signal);const unmappedHere=x=>opts.instanceId===void 0&&replyTargetUnmapped(x.reply.error);let unmapped=unmappedHere(r)?r:void 0;for(let reissues=0;reissues<BIND_SPLIT_REISSUES&&r.reply.ok===false&&(replyRefusedBeforeEffect(r.reply.error)||unmappedHere(r));reissues++){this.splitsRecovered++;this.emit("split-recovered",{endpoint,command,servedBy:r.responder,splitsRecovered:this.splitsRecovered,boundTo:(r.reply.error.details??[]).find(d=>d.kind===EP_BIND_REFUSED)?.boundTo});this.clearResolvedService(endpoint);const raw=r.reply.error.code;const refusalCode=raw==="expired"?"expired":raw==="failed-precondition"?"failed-precondition":void 0;if(refusalCode===void 0)throw new EpEnvelopeError("internal",`${endpoint}.${command} came back marked as refused before it ran, but with code ${String(raw)}; the fence produces only failed-precondition or expired (SPEC 13.2)`,r.reply.error.details);let reissueTarget;try{reissueTarget=await resolve(signal);const unfollowable=opts.follow?goalFollowRefusal(reissueTarget):void 0;if(unfollowable)throw new Error(unfollowable.reply.error.message)}catch(reissue){throw new EpEnvelopeError(refusalCode,`${endpoint}.${command} WAS NOT RUN - the incarnation that received it refused it before any effect, and the re-issue could not be resolved: ${reissue instanceof Error?reissue.message:String(reissue)}. Re-resolve and re-issue when the endpoint is reachable (SPEC 13.2)`,r.reply.error.details,"not-executed")}r=await invokeResolved(reissueTarget,signal);if(unmappedHere(r))unmapped=r}return replyRefusedBeforeEffect(r.reply.error)?unmapped??r:r}catch(e){if(respondedButUnbound(e)){this.clearResolvedService(endpoint);if(!isRepeatSafeCommand(endpoint,command))throw e;return await invokeResolved(await resolve(signal),signal)}throw e}};const release=this.beginServiceInvocation(nc);try{if(!opts.follow)return await doInvoke(await resolveFirst());let service;return await this.followServiceGoal(endpoint,async signal=>{try{return await doInvoke(service,signal)}finally{release()}},opts.deadlineMs??1e4,{signal:opts.signal,prepare:async(signal,deadline)=>{service=await resolveFirst(signal,deadline)}})}finally{release()}}async requestDelivery(op,args,timeoutMs=5e3){if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=controlServiceSubject(this.space,CONTROL_DELIVERY,this.owner,this.actor);const reply=`${reqSubject}.reply.${(0,import_node_crypto10.randomUUID)()}`;const body={op,args,from:this.ref()};const m=await this.requestBoundReply(this.nc,reqSubject,JSON.stringify(body),reply,timeoutMs);return m.json()}async requestDeliveryAdmin(op,args,timeoutMs=5e3){if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=controlServiceSubject(this.space,CONTROL_DELIVERY_ADMIN,this.owner,this.actor);const reply=`${reqSubject}.reply.${(0,import_node_crypto10.randomUUID)()}`;const body={op,args,from:this.ref()};const m=await this.requestBoundReply(this.nc,reqSubject,JSON.stringify(body),reply,timeoutMs);return m.json()}getRoster(){return[...this.roster.values()].sort((a,b)=>a.card.name.localeCompare(b.card.name))}async readPresence(){if(this.doWatch&&!this.readOnce)throw new Error("readPresence is for an endpoint that does not watch presence; this one keeps its roster live (getRoster)");const kv=this.kv;if(!kv)throw new Error(this.nc?"readPresence needs the presence bucket open (registerPresence or watchPresence)":this.notLiveMsg());if(this.presenceRead)return this.presenceRead;const generation=++this.presenceReadGeneration;const roster=(async()=>{let entries;try{entries=await lastKvEntries(kv)}catch(e){if(!isPublishPermissionDenied(e))throw e;throw new Error(`presence read refused for ${this.card.id}: this credential may not publish $JS.API.DIRECT.GET.KV_${presenceBucket(this.space)}, the on-demand roster read (SPEC Appendix B). A credential minted by an older issuer can lack this grant even when newly minted; upgrade the manager or auth service that issues credentials, then mint a new credential. Reusing credentials or reconnecting does not add the grant.`,{cause:e})}const at=Date.now();const read=new Map;for(const e of entries){if(e.key===TTL_RECONCILE_CANARY_KEY||e.operation==="DEL"||e.operation==="PURGE")continue;const p=this.decodePresence(e);if(p)read.set(e.key,p.status==="offline"||at-p.ts>this.ttlMs?this.toOffline(p):p)}if(generation>this.presenceReadApplied){this.presenceReadApplied=generation;for(const[id2,p]of this.roster)if(!read.has(id2))read.set(id2,p.status==="offline"?p:this.toOffline(p));this.roster.clear();for(const[id2,p]of read)this.roster.set(id2,p)}return this.getRoster()})();this.presenceRead=roster;const settled=()=>{if(this.presenceRead===roster)this.presenceRead=void 0};roster.then(settled,settled);return roster}presenceView(){if(!this.doWatch)return{state:"current",fresh:true};if(!this.presenceSnapshotPopulated)return{state:"unpopulated",fresh:false};if(this.presenceWatchEmpty)return{state:"current",fresh:true};const staleSince=this.lastPresenceWatchAt+this.ttlMs;if(Date.now()<staleSince)return{state:"current",fresh:true};return{state:"stale",fresh:false,staleSince}}async waitForPresenceSnapshot(timeoutMs=1e3){let timer;try{return await Promise.race([this.presenceSnapshot.then(()=>"snapshot"),new Promise(resolve=>{timer=setTimeout(()=>resolve("timeout"),timeoutMs)})])}finally{if(timer)clearTimeout(timer)}}assertPresenceUpdate(update){assertPresenceRow({card:this.card,status:this.status,activity:this.activity,condition:this.condition,attention:this.attentionMode,ts:Date.now(),...update},this.card.id)}async setActivity(activity){this.assertPresenceUpdate({activity});if(activity!==this.activity)this.statusSince=this.activitySince=Date.now();this.activity=activity;await this.publishPresence()}async setStatus(status2,activity){this.assertPresenceUpdate({status:status2,...activity===void 0?{}:{activity}});if(activity!==void 0&&activity!==this.activity)this.statusSince=this.activitySince=Date.now();if(activity!==void 0)this.activity=activity;if(status2!==this.status)this.statusSince=Date.now();this.status=status2;await this.publishPresence()}noteActivity(at=Date.now()){if(Number.isFinite(at)&&at>(this.activeAt??0))this.activeAt=at}async setCondition(condition){this.assertPresenceUpdate({condition:condition??void 0});this.condition=condition??void 0;this.conditionRevision++;await this.publishPresence()}async setAttention(attention){this.assertPresenceUpdate({attention});this.attentionMode=attention;await this.publishPresence()}async setChannelModes(modes){this.channelModes=Object.keys(modes).length?modes:void 0;await this.publishPresence()}async setCardModel(model,variant,provider){const m=model.trim();const v=variant?.trim();const p=provider?.trim();if(!m||this.card.meta?.model===m&&this.card.meta.variant===v&&(p===void 0||this.card.meta?.provider===p))return;const meta3={...this.card.meta??{},model:m};if(v)meta3.variant=v;else delete meta3.variant;if(p)meta3.provider=p;this.card.meta=meta3;await this.publishPresence()}async setCardCwd(cwd){if(!cwd||this.card.meta?.cwd===cwd)return;this.card.meta={...this.card.meta??{},cwd};await this.publishPresence()}get readsChannelsOnDemand(){return this.doConsume&&this.doWatchChannels&&!this.doWatch}async readChannels(){if(!this.readsChannelsOnDemand)throw new Error("readChannels is for a consumer that reads presence on demand; this endpoint watches the channel registry or keeps no cache of it");const kv=this.channelKv;if(!kv)throw new Error(this.notLiveMsg());if(this.channelRead)return this.channelRead;const generation=++this.channelReadGeneration;const read=(async()=>{let entries;try{entries=await lastKvEntries(kv)}catch(e){if(!isPublishPermissionDenied(e))throw e;throw new Error(`channel registry read refused for ${this.card.id}: this credential may not publish $JS.API.DIRECT.GET.KV_${channelBucket(this.space)}, the on-demand registry read (SPEC Appendix B). A credential minted by an older issuer can lack this grant even when newly minted; upgrade the manager or auth service that issues credentials, then mint a new credential. Reusing credentials or reconnecting does not add the grant.`,{cause:e})}if(generation<=this.channelReadApplied)return;this.channelReadApplied=generation;this.channelConfigs.clear();this.channelDefaults={};for(const e of entries)this.handleChannelEntry(e)})();this.channelRead=read;const settled=()=>{if(this.channelRead===read)this.channelRead=void 0};read.then(settled,settled);return read}getChannelConfig(channel){return this.channelConfigs.get(channel)}channelReplay(channel){return effectiveReplay(this.channelConfigs.get(channel),this.channelDefaults)}channelReplayWindow(channel){return this.channelConfigs.get(channel)?.replayWindow??this.channelDefaults.replayWindow}async channelReplayPolicy(channel){if(!this.nc)throw new Error(this.notLiveMsg());const kv=this.channelKv??await openChannelRegistry(this.nc,this.space,{create:false});let cfg;let defaults;try{[cfg,defaults]=await Promise.all([isConcreteChannel(channel)?readChannelConfig(kv,channel):Promise.resolve(void 0),readChannelDefaults(kv)])}catch(e){if(!isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.StreamNotFound))throw e}return{replay:effectiveReplay(cfg,defaults),window:cfg?.replayWindow??defaults?.replayWindow??null,registered:cfg!==void 0}}channelDeliveryClass(channel){return effectiveDeliveryClass(this.channelConfigs.get(channel),this.channelDefaults)}joinedChannels(){return[...this.channels]}async joinChannel(channel){if(!this.jsm)throw new Error(this.notLiveMsg());if(this.channels.includes(channel))return{joined:false,backfilled:0,durable:this.plane3Channels.has(channel)};if(this.readsChannelsOnDemand)await this.readChannels();const armed2=await this.armJoin([channel]);this.subscribeChat(channel);try{await this.confirmChatSub()}catch(e){this.unsubscribeChat(channel);throw new Error(`cannot join "${channel}": live subscription could not be confirmed (${e.message})`)}if(this.chatSubDenied.has(channel)){this.unsubscribeChat(channel);throw new Error(`cannot join "${channel}": not within this agent's read ACL (allowSubscribe)`)}this.channels.push(channel);let durable=false;let reason2;const family=isChannelFamily(channel);if(!family&&!isConcreteChannel(channel))reason2="a pattern with * or the root > has no stored copies; follow a concrete channel or a family such as review.>";else if(family||effectiveDeliveryClass(this.channelConfigs.get(channel),this.channelDefaults)==="durable"){try{const r=await this.durableJoinChannel(channel);if(r.durable){this.plane3Channels.set(channel,r.generation??0);durable=true}else{reason2=r.reason??"durable backstop unavailable"}}catch(e){reason2=`durable backstop unavailable (${e.message})`}}const backfilled=await this.backfillArmed(armed2);return{joined:true,backfilled,durable,...reason2!==void 0?{reason:reason2}:{}}}async leaveChannel(channel){if(!this.jsm)throw new Error(this.notLiveMsg());if(!this.channels.includes(channel))return{left:false};if(this.readsChannelsOnDemand)await this.readChannels();if(this.authed&&(isChannelFamily(channel)||effectiveDeliveryClass(this.channelConfigs.get(channel),this.channelDefaults)==="durable")){let generation=this.plane3Channels.get(channel);if(generation===void 0)generation=(await this.fetchMemberships())?.find(m=>m.channel===channel)?.generation;if(generation!==void 0){await this.durableLeaveChannel(channel,generation);this.plane3Channels.delete(channel)}}this.unsubscribeChat(channel);const i=this.channels.indexOf(channel);if(i>=0)this.channels.splice(i,1);return{left:true}}async chatRetention(){if(!this.nc)throw new Error(this.notLiveMsg());const mgr=await(0,import_jetstream13.jetstreamManager)(this.nc);let info;try{info=await mgr.streams.info(chatStream(this.space),{subjects_filter:">"})}catch(e){if(!isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.StreamNotFound))throw e;return{perSender:null,maxAgeMs:null,oldestAt:null,senders:[],stream:false,lastSeq:0}}const senders=[];for(const[subject,messages]of Object.entries(info.state.subjects??{})){const p=parseSubject(subject);if(p?.kind==="chat"&&isPrincipalOwnerToken(p.owner))senders.push({channel:p.rest,sender:p.sender,messages})}const cap=info.config.max_msgs_per_subject;const age=info.config.max_age;return{perSender:typeof cap==="number"&&cap>0?cap:null,maxAgeMs:typeof age==="number"&&age>0?Math.round(age/1e6):null,oldestAt:info.state.messages>0?info.state.first_ts:null,senders:senders.sort((a,b)=>a.channel.localeCompare(b.channel)||a.sender.localeCompare(b.sender)),stream:true,lastSeq:info.state.last_seq}}async listChannels(){if(!this.nc)throw new Error(this.notLiveMsg());if(this.readsChannelsOnDemand)await this.readChannels();const mgr=await(0,import_jetstream13.jetstreamManager)(this.nc);const counts=new Map;try{const info=await mgr.streams.info(chatStream(this.space),{subjects_filter:">"});if(info.state.subjects){for(const[subject,count]of Object.entries(info.state.subjects)){const p=parseSubject(subject);if(p?.kind==="chat"&&isPrincipalOwnerToken(p.owner))counts.set(p.rest,(counts.get(p.rest)??0)+count)}}}catch(e){if(!isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.StreamNotFound))throw e}const channels=new Set([...counts.keys(),...this.channelConfigs.keys()]);return[...channels].map(channel=>({channel,messages:counts.get(channel)??0,config:this.channelConfigs.get(channel)})).sort((a,b)=>a.channel.localeCompare(b.channel))}async channelMembers(channel){const members=(await listMembers(await this.membersRegistry())).filter(r=>r.leaveCursor===void 0&&r.activated===true);const byId=new Map;for(const p of this.roster.values())byId.set(p.card.id,p);const memberForId=id2=>{const p=byId.get(id2);return p?{id:p.card.id,name:p.card.name,role:p.card.role,live:p.status!=="offline"}:{id:id2,name:id2,live:false}};const byName=(a,b)=>a.name.localeCompare(b.name);if(channel!==void 0){const stored=await this.deliveryClassFresh(channel)==="durable";const ids=new Set(members.filter(r=>r.channel===channel||stored&&isChannelFamily(r.channel)&&subjectMatches(r.channel,channel)).map(r=>r.owner));return[...ids].map(memberForId).sort(byName)}const map2=new Map;for(const r of members){const arr=map2.get(r.channel);const m=memberForId(r.owner);if(arr){if(!arr.some(x=>x.id===m.id))arr.push(m)}else{map2.set(r.channel,[m])}}for(const arr of map2.values())arr.sort(byName);return map2}async membershipFeedRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.membershipFeedKv??=await new import_kv7.Kvm(this.nc).open(membershipBucket(this.space));return this.membershipFeedKv}async readMembership(){const kv=await this.membershipFeedRegistry();const members=[];let asOf;let entries;try{entries=await lastKvEntries(kv)}catch(e){if(!isPublishPermissionDenied(e))throw e;throw new Error(`membership read refused for ${this.card.id}: this credential may not publish $JS.API.DIRECT.GET.KV_${membershipBucket(this.space)}, the membership feed read (SPEC Appendix B). A credential minted by an older issuer can lack this grant even when newly minted; upgrade the manager or auth service that issues credentials, then mint a new credential. Reusing credentials or reconnecting does not add the grant.`,{cause:e})}for(const e of entries){if(e.key===MEMBERSHIP_FEED_KEY){try{asOf=e.json().observedAt}catch{}continue}try{const rec=e.json();members.push({id:e.key,live:rec.live??[],durable:rec.durable??[],observedAt:rec.observedAt})}catch{}}return{asOf,members}}async watchMembership(onChange,onClosed){if(this.stopped)throw new Error("endpoint stopped - cannot watch membership");const watch={onChange,onClosed,stopped:false,arm:Promise.resolve()};this.membershipFeedWatches.add(watch);watch.arm=watch.arm.catch(()=>{}).then(()=>this.armMembershipWatch(watch));try{await watch.arm}catch(err3){watch.stopped=true;this.membershipFeedWatches.delete(watch);await this.disarmMembershipWatch(watch);throw err3}return{stop:async()=>{if(watch.stopPromise)return watch.stopPromise;watch.stopped=true;watch.stopPromise=new Promise((resolve,reject)=>{watch.resolveStop=resolve;watch.rejectStop=reject});watch.arm=watch.arm.catch(()=>{}).then(async()=>{await this.disarmMembershipWatch(watch);await this.deleteRetainedMembershipConsumer(watch);this.finishMembershipWatchStop(watch)}).catch(err3=>{watch.rejectStop?.(err3)});return watch.stopPromise}}}async armMembershipWatch(watch){if(watch.stopped)return;const kv=await this.membershipFeedRegistry();await this.deleteRetainedMembershipConsumer(watch);if(!(kv instanceof import_internal2.Bucket))throw new Error("membership watch needs the @nats-io/kv Bucket implementation");const cc=kv._buildCC(">",import_internal2.KvWatchInclude.LastValue,{headers_only:false});const consumer=await kv.js.consumers.getPushConsumer(kv.stream,cc);const info=await consumer.info(true);this.recordOwnWatchConsumer(info);watch.consumer=consumer;const permission2=this.nc&&this.watchDeletePermissions.get(this.nc);if(permission2)this.watchDeletePermissions.set(consumer,permission2);watch.consumerStream=info.stream_name;watch.consumerName=info.name;let replaying=info.num_pending>0;let iter;try{iter=await consumer.consume({callback:jm=>{if(watch.stopped||watch.consumer!==consumer)return;const entry=kv.jmToWatchEntry(jm,!replaying);watch.onChange(membershipChange(entry,!replaying));if(replaying&&jm.info.pending===0){replaying=false;watch.onChange({type:"replayed",revision:entry.revision})}}})}catch(err3){await this.disarmMembershipWatch(watch);throw err3}watch.iter=iter;if(watch.stopped){await this.disarmMembershipWatch(watch);return}if(!replaying)watch.onChange({type:"replayed",revision:0});iter.closed().then(()=>{if(watch.stopped||watch.consumer!==consumer)return;const err3=new Error("membership watch closed");watch.onClosed?.(err3);this.emit("error",err3)}).catch(()=>{})}async deleteRetainedMembershipConsumer(watch){if(!watch.consumerStream||!watch.consumerName)return;if(!this.nc||this.nc.isClosed())return;if(this.watchConsumerDeleteDenied(watch.consumerStream,watch.consumerName,this.nc)){watch.consumerStream=void 0;watch.consumerName=void 0;return}const jsm=await(0,import_jetstream13.jetstreamManager)(this.nc);if(await this.deleteMembershipConsumer(jsm,watch.consumerStream,watch.consumerName)){watch.consumerStream=void 0;watch.consumerName=void 0}}finishMembershipWatchStop(watch){if(!watch.stopped||watch.consumer||watch.iter||watch.consumerStream||watch.consumerName)return;this.membershipFeedWatches.delete(watch);watch.resolveStop?.();watch.resolveStop=void 0;watch.rejectStop=void 0}recordOwnWatchConsumer({stream_name,name}){const prefix=`$JS.API.CONSUMER.DELETE.${stream_name}.${name.slice(0,name.lastIndexOf("_")+1)}`;this.ownWatchDeletePrefixes.add(prefix);return prefix}isOwnWatchDelete(subject){const cut=subject.lastIndexOf("_")+1;return/^\d+$/.test(subject.slice(cut))&&this.ownWatchDeletePrefixes.has(subject.slice(0,cut))}watchConsumerDeleteDenied(stream,name,owner2){const permission2=owner2&&this.watchDeletePermissions.get(owner2)?.();return Boolean(permission2&&!issuedPermitsSubject(permission2,`$JS.API.CONSUMER.DELETE.${stream}.${name}`))}async deleteOwnConsumer(consumer){const{stream_name,name}=await consumer.info(true);if(this.watchConsumerDeleteDenied(stream_name,name,consumer))return;try{await consumer.delete()}catch(e){if(!isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.ConsumerNotFound)&&!isPublishPermissionDenied(e))throw e}}async deleteMembershipConsumer(jsm,stream,name){try{return await jsm.consumers.delete(stream,name)}catch(err3){if(membershipConsumerReleased(err3))return true;throw err3}}async disarmMembershipWatch(watch){const iter=watch.iter;const consumer=watch.consumer;watch.iter=void 0;watch.consumer=void 0;try{iter?.stop()}catch{}if(consumer){if(watch.consumerStream&&watch.consumerName&&this.watchConsumerDeleteDenied(watch.consumerStream,watch.consumerName,consumer)){watch.consumerStream=void 0;watch.consumerName=void 0;return}try{const deleted=await consumer.delete();if(deleted){watch.consumerStream=void 0;watch.consumerName=void 0}}catch(err3){if(membershipConsumerReleased(err3)){watch.consumerStream=void 0;watch.consumerName=void 0}else{const closedEpoch=err3 instanceof import_transport_node13.ClosedConnectionError;const timeout=err3 instanceof import_transport_node13.TimeoutError;if(timeout||closedEpoch){this.emit("error",err3)}else{throw err3}}}}}async rearmMembershipWatches(){await Promise.all([...this.membershipFeedWatches].map(async watch=>{watch.arm=watch.arm.catch(()=>{}).then(async()=>{await this.disarmMembershipWatch(watch);await this.deleteRetainedMembershipConsumer(watch);if(!watch.stopped)await this.armMembershipWatch(watch)});try{await watch.arm;this.finishMembershipWatchStop(watch)}catch(err3){this.emit("error",err3)}}))}async channelHistory(channel,opts){const from=opts?.publisher;const subject=from===void 0?chatSubject(this.space,"*","*",channel):chatSubject(this.space,assertValidOwnerToken(from.owner),assertValidOwnerToken(from.actor),channel);return(await this.streamHistory(chatStream(this.space),[subject],opts?.limit??100,void 0,opts?.signal)).map(r=>r.msg)}async channelHistoryPage(channel,opts){assertValidChannel(channel);if(!isConcreteChannel(channel))throw new Error("channelHistoryPage requires one concrete channel");const limit=opts?.limit??50;if(!Number.isSafeInteger(limit)||limit<1||limit>1e3)throw new Error("channelHistoryPage limit must be a whole number from 1 to 1000");if(!this.nc||!this.js)throw new Error(this.notLiveMsg());const jsm=this.jsm??=await(0,import_jetstream13.jetstreamManager)(this.nc);const signal=AbortSignal.any([AbortSignal.timeout(1e4),...opts?.signal?[opts.signal]:[]]);signal.throwIfAborted();const stream=chatStream(this.space);const name=chatHistDurable(this.owner,this.actor,this.requireLifecycleUid("channelHistoryPage"));const subject=chatSubject(this.space,"*","*",channel);const marker=(0,import_node_crypto10.randomUUID)();let created;for(;;){signal.throwIfAborted();try{created=await jsm.consumers.add(stream,{name,description:marker,filter_subject:subject,ack_policy:import_jetstream13.AckPolicy.None,deliver_policy:import_jetstream13.DeliverPolicy.All,mem_storage:true,inactive_threshold:(0,import_transport_node13.nanos)(250)});break}catch(e){if(!(e instanceof import_jetstream13.JetStreamApiError)||e.code!==10148)throw e;await(0,import_promises.setTimeout)(50,void 0,{signal})}}signal.throwIfAborted();const owns=info=>info.created===created.created&&info.config.description===marker&&info.config.filter_subject===subject;if(!owns(created))throw new Error("channelHistoryPage: consumer ownership was not established");const consumer=await this.js.consumers.get(stream,name);const pending=created.num_pending;const out=[];let delivered=0;if(pending>0){const iter=await consumer.consume({max_messages:Math.min(pending,32)});const stop=()=>iter.stop(abortReason(signal));signal.addEventListener("abort",stop,{once:true});try{signal.throwIfAborted();for await(const m of iter){signal.throwIfAborted();if(!subjectMatches(subject,m.subject))throw new Error("channelHistoryPage: consumer delivered another channel; ownership was lost");delivered++;const msg=historyMessageFromDelivery(m);if(msg){out.push(msg);if(out.length>limit+1)out.shift()}if(delivered>=pending)break}}finally{signal.removeEventListener("abort",stop);iter.stop()}signal.throwIfAborted();if(delivered!==pending)throw new Error(`channelHistoryPage: read ${delivered} of ${pending} messages before the window was cut short`)}signal.throwIfAborted();if(!owns(await consumer.info()))throw new Error("channelHistoryPage: consumer ownership was lost");signal.throwIfAborted();return{items:out.slice(-limit),complete:out.length<=limit}}async multiChannelHistory(channels,opts){const subjects=[...new Set(channels.map(channel=>{if(!isConcreteChannel(channel))throw new Error(`multiChannelHistory: "${channel}" is a wildcard channel - one consumer's filter subjects may not overlap, so name the concrete channels`);assertValidChannel(channel);return chatSubject(this.space,"*","*",channel)}))];if(subjects.length===0)return[];const limit=opts?.limit??100;const size=Math.max(1,Math.trunc(opts?.batch??MULTI_FILTER_BATCH));const batches=[];for(let i=0;i<subjects.length;i+=size)batches.push(subjects.slice(i,i+size));const pages2=new Array(batches.length);let next=0;const readBatch=async()=>{for(;;){const i=next++;if(i>=batches.length)return;pages2[i]=await this.streamHistory(chatStream(this.space),batches[i],limit,void 0,opts?.signal)}};await Promise.all(Array.from({length:Math.min(MULTI_FILTER_READ_CONCURRENCY,batches.length)},readBatch));const rows=pages2.flat().sort((a,b)=>a.seq-b.seq).slice(-limit);return rows.map(({seq,subject,msg})=>{const p=parseSubject(subject);if(p?.kind!=="chat")throw new Error(`multiChannelHistory: the broker delivered ${subject}, which is not a chat subject on this space`);return{channel:p.rest,seq,msg}})}async readHistory(channel,opts){const reply=await this.requestDelivery("readHistory",{channel,limit:opts?.limit});if(!reply.ok)throw new Error(reply.error??"readHistory failed");const data=reply.data;if(!Array.isArray(data?.items)||typeof data?.complete!=="boolean")throw new Error("readHistory: the delivery daemon returned a malformed page (expected { items, complete })");return{items:data.items,complete:data.complete}}async dmHistory(opts){try{return(await this.streamHistory(dmStream(this.space),[`${spacePrefix(this.space)}.inst.>`],opts?.limit??100,void 0,opts?.signal)).map(r=>r.msg)}catch(e){if(isPermissionDenied(e))return[];throw e}}async dmHistoryOf(principals,opts){const keys=[...new Set(principals)].map(p=>{const key=parsePrincipalKey(p);if(!key)throw new Error(`dmHistoryOf: "${p}" is not a principal <owner>.<actor>`);return key});if(!keys.length)return{state:"read",items:[]};const limit=opts?.limit??100;const read=subjects=>this.streamHistory(dmStream(this.space),subjects,limit,void 0,opts?.signal);let rows;try{rows=(await Promise.all([read(keys.map(k=>unicastRecvFilter(this.space,k.owner,k.actor))),read(keys.map(k=>unicastSubject(this.space,"*","*",k.owner,k.actor)))])).flat()}catch(e){if(isPermissionDenied(e))return{state:"denied",reason:e.message};throw e}const bySeq=new Map(rows.map(r=>[r.seq,r.msg]));return{state:"read",items:[...bySeq].sort(([a],[b])=>a-b).slice(-limit).map(([,msg])=>msg)}}async streamHistory(stream,subjects,limit,before,signal){if(!this.nc)throw new Error(this.notLiveMsg());signal?.throwIfAborted();if(!Number.isSafeInteger(limit))throw new Error(`history limit must be a whole number of messages this server can count exactly, received ${limit}`);if(limit<=0)return[];const nc=this.nc;let reader;try{reader=await this.acquireHistoryReader(nc,this.jsm??(this.jsm=await(0,import_jetstream13.jetstreamManager)(nc)),stream,signal);const ceiling=before!==void 0?before-1:await this.lastMatchingSeq(reader,subjects,signal);if(ceiling<1)return[];let span=Math.max(limit,64);let floor=1;let floorKnown=false;for(;;){signal?.throwIfAborted();const start=Math.max(floor,ceiling-span+1);const page=await this.drainWindow(reader,subjects,start,ceiling,limit,signal);if(page.length>=limit)return page.slice(-limit);if(!floorKnown){floor=Math.max(1,await this.firstMatchingSeq(reader,subjects,signal));floorKnown=true}if(start<=floor)return page.slice(-limit);span*=4}}catch(e){const msg=String(e?.message??"");if(/stream not found/i.test(msg)||e?.code===404)return[];throw e}finally{if(reader)this.releaseHistoryReader(reader)}}historyReaderId(nc){if(!this.userMode)return this.connId;const info=nc.info;if(!info)throw new Error("history: the server has not sent its INFO, so this connection has no history reader id yet");return calloutReaderId(info.server_id,info.client_id)}async acquireHistoryReader(nc,jsm,stream,signal){for(;;){signal?.throwIfAborted();const readerId=this.historyReaderId(nc);let pool=this.historyReaderSlots.get(stream);if(pool?.readerId!==readerId){pool={readerId,free:Array.from({length:HISTORY_READERS},(_,i)=>HISTORY_READERS-1-i),held:0,waiting:[],refusedUntil:0};this.historyReaderSlots.set(stream,pool)}if(pool.refusedUntil>Date.now())throw this.readerDeleteRefused(stream);const slot=pool.free.pop();if(slot!==void 0){pool.held++;return{nc,js:(0,import_jetstream13.jetstream)(nc),jsm,stream,pool,slot,name:historyReaderConsumer(readerId,slot),held:true,left:false}}if(pool.held===0)throw new Error(`history: every history reader name this connection has on ${stream} is set aside, held by a consumer it did not create (another process using the same credential, or one that stopped mid-read) or by a reader it could not confirm deleted; they expire ${HISTORY_READER_INACTIVE_MS/6e4} minutes after their last use`);const waitOn=pool;await new Promise((resolve,reject)=>{const wake=()=>{signal?.removeEventListener("abort",stop);resolve()};const stop=()=>{waitOn.waiting.splice(waitOn.waiting.indexOf(wake),1);reject(abortReason(signal))};waitOn.waiting.push(wake);signal?.addEventListener("abort",stop,{once:true})})}}releaseHistoryReader(reader){if(!reader.held)return;reader.held=false;const pool=reader.pool;pool.held--;if(!reader.left){pool.free.push(reader.slot);pool.waiting.shift()?.();return}this.setAsideHistoryReader(pool,reader.slot);if(pool.held===0)for(const wake of pool.waiting.splice(0))wake()}setAsideHistoryReader(pool,slot){setTimeout(()=>{pool.free.push(slot);pool.waiting.shift()?.()},HISTORY_READER_INACTIVE_MS).unref()}async openHistoryReader(reader,config2){const pool=reader.pool;for(;;){if(this.historyReaderId(reader.nc)!==pool.readerId)throw new Error(`history: the connection was re-established during the read on ${reader.stream}, so its history reader names changed; the read is not served`);const description=`cotal history read ${(0,import_node_crypto10.randomUUID)()}`;let info;try{info=await reader.jsm.consumers.add(reader.stream,{...config2,name:reader.name,description,ack_policy:import_jetstream13.AckPolicy.None,max_deliver:1,mem_storage:true,num_replicas:1,inactive_threshold:(0,import_transport_node13.nanos)(HISTORY_READER_INACTIVE_MS)})}catch(e){if(!isConsumerAlreadyExists(e))throw e}if(info?.config.description===description)return reader.js.consumers.getConsumerFromInfo(info);this.setAsideHistoryReader(pool,reader.slot);const next=pool.free.pop();if(next===void 0){reader.held=false;pool.held--;for(const wake of pool.waiting.splice(0))wake();throw new Error(`history: reader ${reader.name} on ${reader.stream} is held by a consumer this read did not create, and no other reader name is free`)}reader.slot=next;reader.name=historyReaderConsumer(pool.readerId,next)}}async closeHistoryReader(reader){try{await reader.jsm.consumers.delete(reader.stream,reader.name)}catch(e){if(isConsumerNotFound(e))return;reader.left=true;if(isPublishPermissionDenied(e)){if(this.historyReaderId(reader.nc)!==reader.pool.readerId)throw new Error(`history: the connection was re-established during the read on ${reader.stream}, so it may no longer delete its reader ${reader.name}, which expires on its own; the read is not served`);reader.pool.refusedUntil=Date.now()+HISTORY_READER_INACTIVE_MS;throw this.readerDeleteRefused(reader.stream)}throw e}}readerDeleteRefused(stream){return new Error(`history: this credential may not delete its own history readers on ${stream}; it predates the observer and admin reader-delete grant, so remint it`)}async firstMatchingSeq(reader,subjects,signal){signal?.throwIfAborted();const consumer=await this.openHistoryReader(reader,{filter_subjects:subjects,deliver_policy:import_jetstream13.DeliverPolicy.All});try{if((await consumer.info(true)).num_pending===0)return 0;signal?.throwIfAborted();const iter=await consumer.fetch({max_messages:1});const stop=()=>iter.stop(abortReason(signal));signal?.addEventListener("abort",stop,{once:true});try{signal?.throwIfAborted();for await(const m of iter)return m.seq}finally{signal?.removeEventListener("abort",stop);iter.stop()}throw new Error(`history: the broker reported messages on ${subjectLabel(subjects)} but delivered none - the read was cut short, not empty`)}finally{await this.closeHistoryReader(reader)}}async lastMatchingSeq(reader,subjects,signal){signal?.throwIfAborted();const consumer=await this.openHistoryReader(reader,{filter_subjects:subjects,deliver_policy:import_jetstream13.DeliverPolicy.Last});try{if((await consumer.info(true)).num_pending===0)return 0;signal?.throwIfAborted();const iter=await consumer.fetch({max_messages:1});const stop=()=>iter.stop(abortReason(signal));signal?.addEventListener("abort",stop,{once:true});try{signal?.throwIfAborted();for await(const m of iter)return m.seq}finally{signal?.removeEventListener("abort",stop);iter.stop()}throw new Error(`history: the broker reported messages on ${subjectLabel(subjects)} but delivered none - the read was cut short, not empty`)}finally{await this.closeHistoryReader(reader)}}async drainWindow(reader,subjects,start,ceiling,limit,signal){signal?.throwIfAborted();const out=[];const consumer=await this.openHistoryReader(reader,{filter_subjects:subjects,deliver_policy:import_jetstream13.DeliverPolicy.StartSequence,opt_start_seq:start});try{const pending=(await consumer.info(true)).num_pending;if(pending===0)return out;signal?.throwIfAborted();const iter=await consumer.consume({max_messages:Math.min(pending,32)});const stop=()=>iter.stop(abortReason(signal));signal?.addEventListener("abort",stop,{once:true});let delivered=0;let complete=false;try{signal?.throwIfAborted();for await(const m of iter){delivered++;if(m.info.deliverySequence!==delivered)throw new Error(`history: delivery ${m.info.deliverySequence} arrived where ${delivered} was due on ${subjectLabel(subjects)} - the window has a gap, so the page is not served`);if(m.seq>=ceiling){if(m.seq===ceiling){const msg2=historyMessageFromDelivery(m);if(msg2)out.push({seq:m.seq,subject:m.subject,msg:msg2})}complete=true;break}const msg=historyMessageFromDelivery(m);if(msg){out.push({seq:m.seq,subject:m.subject,msg});if(out.length>limit)out.shift()}if(delivered>=pending){complete=true;break}}}finally{signal?.removeEventListener("abort",stop);iter.stop()}if(!complete)throw new Error(`history: read ${delivered} of ${pending} messages on ${subjectLabel(subjects)} before the stream ended early - the window was cut short, not empty`);return out}finally{await this.closeHistoryReader(reader)}}watchStatus(){const nc=this.nc;if(!nc)return;const handedToRequest=this.trackRequestDenials(nc);void(async()=>{for await(const s of nc.status()){if(this.nc!==nc)continue;if(s.type==="disconnect"){this.emit("transport",{connected:false,server:s.server});continue}if(s.type==="reconnect"){this.armAuthExpiryReconnectFence(nc);this.emit("transport",{connected:true,server:s.server});for(const follower of this.activeGoalFollowers){follower.reconnected(nc)}continue}if(s.type==="close"){this.emit("transport",{connected:false});continue}if(s.type!=="error")continue;if(s.error instanceof import_transport_node13.PermissionViolationError&&this.chatSubRefusals.has(s.error))continue;if(s.error instanceof import_transport_node13.PermissionViolationError&&handedToRequest.has(s.error))continue;if(s.error instanceof import_transport_node13.PermissionViolationError&&s.error.operation==="publish"&&this.isOwnWatchDelete(s.error.subject))continue;if(!this.reportSubscriptionDenial(s.error))this.emit("error",describeStatusError(s.error))}})().catch(e=>{if(!this.stopped&&this.nc===nc)this.emit("error",e)});if(this.stopped)return;this.emit("transport",{connected:true,server:nc.getServer()})}reportSubscriptionDenial(error51){if(!(error51 instanceof import_transport_node13.PermissionViolationError)||error51.operation!=="subscription")return false;if(!this.reportedSubRefusals.has(error51)){this.reportedSubRefusals.add(error51);this.emit("error",describeStatusError(error51))}return true}trackRequestDenials(nc){const handed=new WeakSet;const request=nc.request.bind(nc);nc.request=(subject,payload,opts)=>{if(typeof subject==="string"&&this.ungrantedOwnWatchDelete(subject)){const violation=new import_transport_node13.PermissionViolationError(`Permissions Violation for Publish to "${subject}"`,"publish",subject);handed.add(violation);return Promise.reject(new import_transport_node13.RequestError("permissions violation",{cause:violation}))}const reply=request(subject,payload,opts);reply.catch(({cause})=>{if(cause instanceof import_transport_node13.PermissionViolationError&&cause.operation==="publish")handed.add(cause)});return reply};return handed}ungrantedOwnWatchDelete(subject){if(!this.isOwnWatchDelete(subject))return false;const permission2=this.watchDeletePermissions.get(this.nc)?.();return Boolean(permission2&&!issuedPermitsSubject(permission2,subject))}notLiveMsg(){return this.reconnecting||this.reestablishing?"reconnecting - try again shortly":"endpoint not started"}async publishMsg(subject,msg){if(!this.js)throw new Error(this.notLiveMsg());assertPartsSerializable(msg.parts);try{await this.js.publish(subject,JSON.stringify(msg),{msgID:msg.id})}catch(error51){if(error51 instanceof import_transport_node13.TimeoutError)throw new Error(`${error51.message} publishing to ${JSON.stringify(subject)}. The send outcome is unknown: the broker may have stored the message. Check before resending.`,{cause:error51});throw error51}}async ensureStreams(){if(!this.jsm)throw new Error(this.notLiveMsg());await createSpaceStreams(this.jsm,this.space)}async provisionDmInbox(owner2,actor2,lifecycleUid){await this.ensureDmDurable(owner2,actor2,lifecycleUid,{})}async ensureDmDurable(owner2,actor2,lifecycleUid,opts){const jsm=await this.manager();const stream=dmStream(this.space);const name=dmDurable(owner2,actor2,lifecycleUid);try{await jsm.consumers.info(stream,name);return}catch(e){if(!isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.ConsumerNotFound))throw e}const frontier=(await jsm.streams.info(stream)).state.last_seq;try{await jsm.consumers.add(stream,dmDurableConfig(this.space,owner2,actor2,lifecycleUid,{...opts,activationFrontier:frontier}))}catch(e){try{await jsm.consumers.info(stream,name);return}catch(probeError){if(isPermissionDenied(probeError))throw probeError}throw e}}async provisionDlvInbox(owner2,actor2,lifecycleUid){const jsm=await this.manager();await jsm.consumers.add(dlvStream(this.space),dlvDurableConfig(this.space,owner2,actor2,lifecycleUid))}async provisionTaskQueue(role){const jsm=await this.manager();await jsm.consumers.add(taskStream(this.space),taskDurableConfig(this.space,role))}async membersRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.membersKv??=await openMembersRegistry(this.nc,this.space);return this.membersKv}async aclRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.aclKv??=await openAclRegistry(this.nc,this.space);return this.aclKv}async commitAcl(targetId,lifecycleUid,allowSubscribe){await commitAcl(await this.aclRegistry(),targetId,lifecycleUid,allowSubscribe)}async reissueAcl(targetId,lifecycleUid,allowSubscribe){await reissueAcl(await this.aclRegistry(),targetId,lifecycleUid,allowSubscribe)}async aclForOwner(owner2,lifecycleUid){return(await readAcl(await this.aclRegistry(),owner2,lifecycleUid))?.record.allowSubscribe}async aclForAlias(principal){const row=await readAclForAlias(await this.aclRegistry(),principal);if(row===void 0)return void 0;const allow=row.record.allowSubscribe;const issued=row.record.issuedAllowSubscribe??allow;return{allowSubscribe:allow,issuedAllowSubscribe:issued,lifecycleUid:row.lifecycleUid}}async deliveryRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.deliveryKv??=await openDeliveryRegistry(this.nc,this.space);return this.deliveryKv}leaseIncarnation=(0,import_node_crypto10.randomUUID)();leaseAcquiredAt=new Map;encodeLease(shardIndex,ready,acquiredAt=this.leaseAcquiredAt.get(shardIndex)){return new TextEncoder().encode(JSON.stringify({holder:this.card.id,incarnation:this.leaseIncarnation,acquiredAt,since:Date.now(),ready}))}ownsDeliveryLease(info){return info.holder===this.card.id&&info.incarnation!==void 0&&info.incarnation===this.leaseIncarnation}async acquireDeliveryLease(shardIndex){const acquiredAt=Date.now();const revision=await(await this.deliveryRegistry()).create(leaseKey(shardIndex),this.encodeLease(shardIndex,false,acquiredAt));this.leaseAcquiredAt.set(shardIndex,acquiredAt);return revision}async markDeliveryLeaseReady(shardIndex,revision){return(await this.deliveryRegistry()).update(leaseKey(shardIndex),this.encodeLease(shardIndex,true),revision)}async markDeliveryLeaseNotReady(shardIndex,revision){return(await this.deliveryRegistry()).update(leaseKey(shardIndex),this.encodeLease(shardIndex,false),revision)}async renewDeliveryLease(shardIndex,revision){return(await this.deliveryRegistry()).update(leaseKey(shardIndex),this.encodeLease(shardIndex,true),revision)}async releaseDeliveryLease(shardIndex,revision){if(revision===void 0)return;await(await this.deliveryRegistry()).delete(leaseKey(shardIndex),{previousSeq:revision})}async readDeliveryLease(shardIndex){return(await this.readDeliveryLeaseEntry(shardIndex))?.info}async watchDeliveryLease(shardIndex,onEvent){this.leaseWatchIntent={shardIndex,onEvent};await this.bindDeliveryLeaseWatch();return()=>{if(this.leaseWatchIntent?.onEvent!==onEvent)return;this.leaseWatchIntent=void 0;this.stopDeliveryLeaseWatch()}}stopDeliveryLeaseWatch(){if(this.leaseWatchIter)this.retireDeliveryLeaseWatch(this.leaseWatchIter);this.leaseWatchIter=void 0}retireDeliveryLeaseWatch(iter){try{iter.stop()}catch{}if(!this.nc||this.nc.isClosed())return;const deleting=this.deleteOwnConsumer(kvWatchConsumer(iter)).catch(e=>this.emitRecoverable(new Error(`a retired delivery lease watch consumer was not deleted (${e.message}); the broker reaps it at its inactive threshold`)));this.leaseWatchDeletes.add(deleting);void deleting.then(()=>this.leaseWatchDeletes.delete(deleting))}async settleDeliveryLeaseWatches(){await Promise.allSettled(this.leaseWatchBinds);await Promise.all(this.leaseWatchDeletes)}retireKvWatch(iter){try{iter.stop()}catch{}if(!this.nc||this.nc.isClosed())return;const deleting=this.deleteOwnConsumer(kvWatchConsumer(iter)).catch(e=>this.emitRecoverable(new Error(`a retired KV watch consumer was not deleted (${e.message}); the broker reaps it at its inactive threshold`)));this.kvWatchDeletes.add(deleting);void deleting.then(()=>this.kvWatchDeletes.delete(deleting))}async settleKvWatches(){await Promise.allSettled(this.kvWatchBinds);await Promise.all(this.kvWatchDeletes)}bindKvWatch(kv){if(this.stopped)return Promise.resolve(void 0);const epoch=this.presenceEpoch;const binding=(async()=>{const permission2=this.nc&&this.watchDeletePermissions.get(this.nc);const iter=await kv.watch();const info=await kvWatchConsumer(iter).info(true);this.recordOwnWatchConsumer(info);if(permission2)this.watchDeletePermissions.set(kvWatchConsumer(iter),permission2);if(epoch===this.presenceEpoch&&!this.stopped)return{iter,info};this.retireKvWatch(iter);return void 0})();const settled=()=>{this.kvWatchBinds.delete(binding)};this.kvWatchBinds.add(binding);void binding.then(settled,settled);return binding}bindDeliveryLeaseWatch(){const binding=this.bindDeliveryLeaseWatchOnce();const settled=()=>{this.leaseWatchBinds.delete(binding)};this.leaseWatchBinds.add(binding);void binding.then(settled,settled);return binding}async bindDeliveryLeaseWatchOnce(){const intent=this.leaseWatchIntent;const epoch=this.presenceEpoch;const iter=await(await this.deliveryRegistry()).watch({key:leaseKey(intent.shardIndex)});if(this.leaseWatchIntent!==intent||epoch!==this.presenceEpoch){this.retireDeliveryLeaseWatch(iter);return}this.leaseWatchIter=iter;void(async()=>{for await(const e of iter){if(this.leaseWatchIter!==iter)break;if(e.operation==="DEL"||e.operation==="PURGE"){intent.onEvent(void 0);continue}try{intent.onEvent(e.json())}catch{intent.onEvent(void 0)}}})().catch(e=>this.emit("error",e))}async deliveryLeaseHolder(shardIndex){try{return(await this.readDeliveryLeaseEntry(shardIndex))?.info.holder}catch{return void 0}}async readDeliveryLeaseEntry(shardIndex){const e=await(await this.deliveryRegistry()).get(leaseKey(shardIndex));if(!e||e.operation==="DEL"||e.operation==="PURGE")return void 0;try{return{info:e.json(),revision:e.revision}}catch(err3){throw new Error(`delivery lease row "${leaseKey(shardIndex)}" exists but does not parse as a lease record (${err3.message}) - it is unreadable, not absent`)}}async managerLeaseRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());if(this.managerLeaseKv)return this.managerLeaseKv;const kvm=new import_kv7.Kvm((0,import_jetstream13.jetstream)(this.nc,{timeout:MANAGER_LEASE_ATTEMPT_MS}));if(this.authed){this.managerLeaseKv=await kvm.open(managerBucket(this.space))}else{try{this.managerLeaseKv=await kvm.create(managerBucket(this.space),{ttl:MANAGER_LEASE_TTL_MS})}catch{this.managerLeaseKv=await kvm.open(managerBucket(this.space))}}return this.managerLeaseKv}async holdDaemonRenewalLease(instanceId){const kv=await this.managerLeaseRegistry();const held2=this.daemonRenewalLeaseRevision;if(held2!==void 0){try{this.daemonRenewalLeaseRevision=await kv.update(MANAGER_RENEWAL_LEASE_KEY,this.encodeDaemonRenewalLease(instanceId),held2);return true}catch{this.daemonRenewalLeaseRevision=void 0}}try{this.daemonRenewalLeaseRevision=await kv.create(MANAGER_RENEWAL_LEASE_KEY,this.encodeDaemonRenewalLease(instanceId));return true}catch{return false}}async releaseDaemonRenewalLease(){const held2=this.daemonRenewalLeaseRevision;this.daemonRenewalLeaseRevision=void 0;if(held2===void 0)return;try{await(await this.managerLeaseRegistry()).delete(MANAGER_RENEWAL_LEASE_KEY,{previousSeq:held2})}catch{}}encodeDaemonRenewalLease(instanceId){return new TextEncoder().encode(JSON.stringify({instanceId,since:Date.now()}))}async readDaemonRenewalLease(){const e=await(await this.managerLeaseRegistry()).get(MANAGER_RENEWAL_LEASE_KEY);if(!e||e.operation!=="PUT")return void 0;return JSON.parse(new TextDecoder().decode(e.value))}encodeManagerLease(info){return new TextEncoder().encode(JSON.stringify(info))}async acquireManagerLease(info){return(await this.managerLeaseRegistry()).create(managerLeaseKey(info.instanceId),this.encodeManagerLease({...info,since:Date.now()}))}async renewManagerLease(info,revision){return(await this.managerLeaseRegistry()).update(managerLeaseKey(info.instanceId),this.encodeManagerLease({...info,since:Date.now()}),revision)}async readOwnManagerLease(instanceId){const e=await(await this.managerLeaseRegistry()).get(managerLeaseKey(instanceId));if(!e||e.operation!=="PUT")return void 0;return{info:JSON.parse(new TextDecoder().decode(e.value)),revision:e.revision,created:e.created.getTime()}}async releaseManagerLease(instanceId,revision){const kv=await this.managerLeaseRegistry();if(revision===void 0)await kv.delete(managerLeaseKey(instanceId));else await kv.delete(managerLeaseKey(instanceId),{previousSeq:revision})}async readManagerLease(){if(!this.nc)return void 0;try{const jsm=this.jsm??(this.jsm=await(0,import_jetstream13.jetstreamManager)(this.nc));const stream=`KV_${managerBucket(this.space)}`;const prefix=`$KV.${managerBucket(this.space)}.${MANAGER_LEASE_KEY}.`;const info=await jsm.streams.info(stream,{subjects_filter:`${prefix}*`});let newest;for(const subject of Object.keys(info.state.subjects??{})){let m;try{m=await jsm.streams.getMessage(stream,{last_by_subj:subject})}catch(e){if(e.code===import_jetstream13.JetStreamApiCodes.NoMessageFound)continue;throw e}if(m===null)continue;const op=m.header?.get("KV-Operation");if(op==="DEL"||op==="PURGE"||m.data.length===0)continue;if(newest===void 0||m.seq>newest.seq)newest={data:m.data,seq:m.seq}}if(newest===void 0)return void 0;return JSON.parse(new TextDecoder().decode(newest.data))}catch(e){const code=e.code;if(code===10037)return void 0;if(code===404||/stream not found/i.test(e?.message??""))return void 0;throw e}}async ownerMemberships(owner2,lifecycleUid){const recs=await listMembers(await this.membersRegistry(),{owner:owner2});return recs.filter(r=>r.lifecycleUid===lifecycleUid&&r.leaveCursor===void 0).map(r=>({channel:r.channel,generation:r.generation,activated:r.activated===true}))}async deliveryClassFresh(channel){if(!this.channelKv)return effectiveDeliveryClass(void 0,void 0);const[cfg,defaults]=await Promise.all([isConcreteChannel(channel)?readChannelConfig(this.channelKv,channel):Promise.resolve(void 0),readChannelDefaults(this.channelKv)]);return effectiveDeliveryClass(cfg,defaults)}resolveOwnerByName(name){const matches=[...this.roster.values()].filter(p=>p.card.name.toLowerCase()===name.toLowerCase());return matches.length===1?matches[0].card.id:void 0}plane3MsgId(entry,keySuffix){return entry.msg.id===""?{}:{msgID:`${entry.msg.id}:${keySuffix}`}}async publishDinbox(principal,lifecycleUid,entry){if(!this.js)return;const p=parsePrincipalKey(principal);if(!p)throw new Error(`publishDinbox: "${principal}" is not a valid member principal <owner>.<actor>`);await this.js.publish(dinboxSubject(this.space,p.owner,p.actor,lifecycleUid),JSON.stringify(entry),{...this.plane3MsgId(entry,`${principal}:${lifecycleUid}`)})}async fanoutDeliveredSeq(){const info=await this.consumerInfo(chatStream(this.space),FANOUT_DURABLE);return info?.delivered?.stream_seq??0}async durableJoinFor(owner2,channel,lifecycleUid,opts={}){if(!this.js)throw new Error(this.notLiveMsg());await this.manager();const kv=await this.membersRegistry();const existing=await readMember(kv,channel,owner2,lifecycleUid);const open5=existing?.record.state==="durable-active"&&existing.record.leaveCursor===void 0;if(open5&&existing.record.activated)return{durable:true,generation:existing.record.generation};const joinCursor=open5?existing.record.joinCursor:await this.chatFrontier();const generation=open5?existing.record.generation:(existing?.record.generation??0)+1;const base={channel,owner:owner2,lifecycleUid,state:"durable-active",joinCursor,generation,activated:false,writerIdentity:this.card.id,updatedAt:Date.now()};if(!open5){if(opts.aclFence&&!await this.aclAllows(owner2,lifecycleUid,channel))throw new Error(`durableJoin: "${channel}" is no longer within the read ACL of lifecycle ${lifecycleUid} (narrowed or retired); no membership row was written`);const written=await commitMemberRevision(kv,base);if(opts.aclFence)await this.keepRowIfAclAllows(kv,owner2,lifecycleUid,channel,written.revision)}const fence=Math.max(await this.chatFrontier(),await this.fanoutDeliveredSeq());await this.catchupCopy(owner2,lifecycleUid,channel,joinCursor,fence,generation);const activated=await activateMember(kv,channel,owner2,lifecycleUid,generation,joinCursor);if(!activated)return{durable:false,reason:"activation superseded by a concurrent leave or rejoin",generation};return{durable:true,generation}}async aclAllows(owner2,lifecycleUid,channel){const row=await readAcl(await this.aclRegistry(),owner2,lifecycleUid);return row!==void 0&&membershipInAllow(row.record.allowSubscribe,channel)}async keepRowIfAclAllows(kv,owner2,lifecycleUid,channel,revision){let disallowed=false;let why;try{if(await this.aclAllows(owner2,lifecycleUid,channel))return;disallowed=true;why="was narrowed or retired while the row was written"}catch(e){why=`could not be re-read after the row was written (${e.message})`}const fail3=(outcome,cause)=>new Error(`durableJoin: the read ACL of lifecycle ${lifecycleUid} ${why}; ${outcome}`,cause===void 0?void 0:{cause});try{if(disallowed)await deleteMember(kv,channel,owner2,lifecycleUid);else await kv.purge(memberKey(channel,owner2,lifecycleUid),{previousSeq:revision})}catch(e){if(!disallowed&&isCasLoss(e))throw fail3(`a later write replaced its "${channel}" row, which was left to that write`);throw fail3(`removing its "${channel}" row failed (${e.message})`,e)}throw fail3(`its "${channel}" row was removed`)}async durableLeaveFor(owner2,channel,lifecycleUid,expectedGeneration){if(!this.plane3)return;const kv=await this.membersRegistry();await tombstoneMember(kv,channel,owner2,lifecycleUid,await this.chatFrontier(),this.card.id,expectedGeneration)}async catchupCopy(owner2,lifecycleUid,channel,fromSeqExcl,toSeqIncl,generation){if(!this.js||!this.jsm||toSeqIncl<=fromSeqExcl)return 0;const subject=chatSubject(this.space,"*","*",channel);const family=isChannelFamily(channel);const durableClass=new Map;const stored=ch=>{if(!family)return Promise.resolve(true);let cls=durableClass.get(ch);if(cls===void 0)durableClass.set(ch,cls=this.deliveryClassFresh(ch).then(c=>c==="durable"));return cls};const cuP=parsePrincipalKey(owner2);const name=`cu_${cuP?lifecycleNameKey(cuP.owner,cuP.actor,lifecycleUid):`${token(owner2)}-${lifecycleUid}`}_${generation}`;await this.deleteConsumerIfPresent(chatStream(this.space),name);await this.jsm.consumers.add(chatStream(this.space),{name,filter_subject:subject,ack_policy:import_jetstream13.AckPolicy.None,mem_storage:true,inactive_threshold:(0,import_transport_node13.nanos)(3e4),deliver_policy:import_jetstream13.DeliverPolicy.StartSequence,opt_start_seq:fromSeqExcl+1});let copied=0;try{const consumer=await this.js.consumers.get(chatStream(this.space),name);let pending=(await consumer.info()).num_pending;while(pending>0){const want=Math.min(pending,256);const iter=await consumer.fetch({max_messages:want,expires:5e3});let got=0;for await(const m of iter){got++;if(m.seq>toSeqIncl)return copied;let msg;try{msg=m.json()}catch{continue}const parsed=parseSubject(m.subject);if(!parsed||!isFromSubjectSender(msg,parsed)||msg.from.id===owner2)continue;if(!await stored(parsed.rest))continue;await this.publishDinbox(owner2,lifecycleUid,{msg,channel:parsed.rest,seq:m.seq,reason:"durable-channel",generation,...family?{row:channel}:{}});copied++}if(got<want)break;pending-=got}}finally{await this.deleteConsumerIfPresent(chatStream(this.space),name)}return copied}async startPlane3(aclFor,opts={}){if(!this.js)throw new Error(this.notLiveMsg());this.plane3={aclFor,reloadMembershipCreds:opts.reloadMembershipCreds,evictPrincipal:opts.evictPrincipal,evictPrincipals:opts.evictPrincipals,planeConnLiveness:opts.planeConnLiveness,principalLiveness:opts.principalLiveness,reloadStoreIdentity:opts.reloadStoreIdentity,onDeliveryCredsAdopted:opts.onDeliveryCredsAdopted,startupComplete:opts.startupComplete};await this.armPlane3()}plane3MayAct(){return!this.plane3Quiesced}async handleDeliveryControl(req){if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon is not serving this shard (it is re-checking ownership); retry"};const caller=req.from.id;const args=req.args??{};if(req.op==="durableJoin")return this.deliveryJoin(caller,args);if(req.op==="durableLeave")return this.deliveryLeave(caller,args);if(req.op==="readHistory")return this.deliveryReadHistory(caller,args);if(req.op===ANYCAST_TAKES_OP)return this.anycastUnavailable?{ok:false,error:`delivery: ${this.anycastUnavailable}`}:{ok:true,data:{takes:true}};if(req.op===ANYCAST_STATUS_OP||req.op===ANYCAST_CANCEL_OP)return this.deliveryAnycast(req.op,caller,args);if(req.op==="listMemberships"){if(typeof args.lifecycleUid!=="string")return{ok:false,error:"listMemberships: the caller's lifecycleUid is required (membership rows are lifecycle-keyed, SPEC 13.1)"};let uid2;try{uid2=assertLifecycleToken(args.lifecycleUid)}catch(e){return{ok:false,error:e.message}}const memberships=await this.ownerMemberships(caller,uid2);if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon stopped serving this shard while the request was in flight; retry"};return{ok:true,data:{memberships}}}return{ok:false,error:`op "${req.op}" not supported on the delivery control service`}}checkDurableChannelArg(args,op,opts={}){const channel=typeof args.channel==="string"?args.channel.trim():"";if(!channel)return{ok:false,error:`${op}: channel must be a non-blank string`};try{assertValidChannel(channel)}catch(e){return{ok:false,error:e.message}}if(opts.family&&isChannelFamily(channel))return channel;if(!isConcreteChannel(channel))return{ok:false,error:opts.family?`${op}: "${channel}" stays live only: a durable membership takes a concrete channel or a family such as review.>, never the root > or a pattern with *`:`${op}: "${channel}" must be a concrete channel (durable membership is per-concrete-channel, not wildcard)`};return channel}async deliveryJoin(caller,args){const channel=this.checkDurableChannelArg(args,"durableJoin",{family:true});if(typeof channel!=="string")return channel;let acl;try{acl=await this.aclForAlias(caller)}catch(e){return{ok:false,error:e.message}}if(acl===void 0)return{ok:false,error:`durableJoin: no read ACL on record for ${caller} (not provisioned for durable delivery)`};if(!membershipInAllow(acl.allowSubscribe,channel))return{ok:false,error:`channel "${channel}" is not within your read ACL [${acl.allowSubscribe.join(", ")}]`};const uid2=acl.lifecycleUid;try{return{ok:true,data:await this.membershipWrite(caller,uid2,()=>this.durableJoinFor(caller,channel,uid2,{aclFence:true}))}}catch(e){return{ok:false,error:e.message}}}async lifecycleAclUnfenced(principal,lifecycleUid){try{const row=await readAcl(await this.aclRegistry(),principal,lifecycleUid);return row!==void 0&&row.record.allowSubscribe.length>0}catch{return true}}async membershipWrite(principal,lifecycleUid,write){if(this.retiringLifecycles.get(principal)?.has(lifecycleUid))throw new Error(`lifecycle ${lifecycleUid} of ${principal} is retiring: its membership inventory was requested, so its durable memberships no longer change`);const key=`${principal}/${lifecycleUid}`;const running=write();let writes=this.membershipWrites.get(key);if(writes===void 0)this.membershipWrites.set(key,writes=new Set);writes.add(running);try{return await running}finally{writes.delete(running);if(writes.size===0)this.membershipWrites.delete(key)}}async deliveryLeave(caller,args){const channel=this.checkDurableChannelArg(args,"durableLeave",{family:true});if(typeof channel!=="string")return channel;if(typeof args.generation!=="number"||!Number.isFinite(args.generation))return{ok:false,error:"durableLeave: a finite generation is required (fail-closed stale-leave guard)"};if(typeof args.lifecycleUid!=="string")return{ok:false,error:"durableLeave: the leaving incarnation's lifecycleUid is required (membership rows are lifecycle-keyed, SPEC 13.1)"};let uid2;try{uid2=assertLifecycleToken(args.lifecycleUid)}catch(e){return{ok:false,error:e.message}}const existing=await readMember(await this.membersRegistry(),channel,caller,uid2);if(!existing)return{ok:true,data:{channel,alreadyLeft:true}};const generation=args.generation;try{await this.membershipWrite(caller,uid2,()=>this.durableLeaveFor(caller,channel,uid2,generation))}catch(e){return{ok:false,error:e.message}}return{ok:true,data:{channel}}}async deliveryReadHistory(caller,args){const channel=this.checkDurableChannelArg(args,"readHistory");if(typeof channel!=="string")return channel;const asked=args.limit===void 0?READ_HISTORY_DEFAULT_LIMIT:args.limit;if(typeof asked!=="number"||!Number.isInteger(asked)||asked<1)return{ok:false,error:`readHistory: limit must be a positive integer (got ${JSON.stringify(args.limit)})`};const limit=Math.min(asked,READ_HISTORY_MAX_LIMIT);let acl;try{acl=await this.aclForAlias(caller)}catch(e){return{ok:false,error:e.message}}if(acl===void 0)return{ok:false,error:`readHistory: no read ACL on record for ${caller} - not permitted`};const inLive=channelInAllow(acl.allowSubscribe,channel);const inIssued=channelInAllow(acl.issuedAllowSubscribe,channel);if(!inLive||!inIssued){return{ok:false,error:`readHistory: channel "${channel}" is not within your read ACL [${acl.allowSubscribe.join(", ")}] - refused`}}let page;try{page=await this.channelHistory(channel,{limit:limit+1})}catch(e){return{ok:false,error:`readHistory: ${e.message}`}}const reachedStart=page.length<=limit;const wanted=reachedStart?page:page.slice(-limit);const fitted=fitHistoryPage(wanted,this.maxPayload);if(wanted.length>0&&fitted.length===0)return{ok:false,error:`readHistory: the newest message on "${channel}" alone exceeds the broker payload budget (${this.maxPayload} bytes) - refused loudly rather than served as an empty page`};return{ok:true,data:{items:fitted,complete:reachedStart&&fitted.length===wanted.length}}}async quiescePlane3(){this.plane3Quiesced=true;if(this.deliveryServeSub){try{this.deliveryServeSub.unsubscribe()}catch{}this.deliveryServeSub=void 0}if(this.deliveryAdminServeSub){try{this.deliveryAdminServeSub.unsubscribe()}catch{}this.deliveryAdminServeSub=void 0}this.dropAnycastRequests();for(const msgs of this.streamMsgs.splice(0)){try{msgs.stop()}catch{}}}plane3IsQuiesced(){return this.plane3Quiesced}async rearmPlane3(){if(!this.plane3Quiesced)return;this.plane3Quiesced=false;try{await this.armPlane3()}catch(e){this.plane3Quiesced=true;this.quiescePlane3();throw e}}async armPlane3(){if(!this.plane3||!this.js)return;if(this.plane3Quiesced)return;await this.manager();this.armDeliveryControl();await this.armAnycastRequests();await this.runFanout();await this.runReader()}armDeliveryControl(){if(this.deliveryServeSub){try{this.deliveryServeSub.unsubscribe()}catch{}const i=this.subs.indexOf(this.deliveryServeSub);if(i>=0)this.subs.splice(i,1)}this.deliveryServeSub=this.serveControl(CONTROL_DELIVERY,req=>this.handleDeliveryControl(req),{boundReply:true,concurrent:req=>ANYCAST_CONTROL_OPS.has(req.op)});if(this.deliveryAdminServeSub){try{this.deliveryAdminServeSub.unsubscribe()}catch{}const i=this.subs.indexOf(this.deliveryAdminServeSub);if(i>=0)this.subs.splice(i,1)}this.deliveryAdminServeSub=this.serveControl(CONTROL_DELIVERY_ADMIN,req=>this.handleDeliveryAdmin(req),{boundReply:true,concurrent:req=>req.op==="lifecycleMemberships"})}async armAnycastRequests(){if(!this.nc||!this.jsm)return;this.dropAnycastRequests();const definition=anycastStoreDefinition(this.space);let kv;try{kv=await new import_kv7.Kvm(this.nc).create(definition.bucket,definition.createOptions)}catch(e){if(!isPermissionDenied(e))throw e;this.anycastUnavailable=ANYCAST_RECORDS_CREDENTIAL_OUTDATED;this.emitRecoverable(new Error(`delivery: ${ANYCAST_RECORDS_CREDENTIAL_OUTDATED}`));return}this.anycastUnavailable=void 0;const authority=new AnycastRequestAuthority({jsm:this.jsm,kv,stream:taskStream(this.space),send:(to,event)=>this.sendAnycastNotice(to,event),mayAct:()=>this.plane3MayAct(),onError:e=>this.emitRecoverable(e)});this.anycastAuthority=authority;this.takeServeSub=this.serveTakes(authority);const sweep=()=>void authority.sweep().catch(e=>this.emitRecoverable(e));this.anycastSweep=setInterval(sweep,ANYCAST_SWEEP_MS);this.anycastSweep.unref?.();sweep()}dropAnycastRequests(){if(this.takeServeSub){try{this.takeServeSub.unsubscribe()}catch{}const i=this.subs.indexOf(this.takeServeSub);if(i>=0)this.subs.splice(i,1);this.takeServeSub=void 0}clearInterval(this.anycastSweep);this.anycastSweep=void 0;this.anycastAuthority=void 0}serveTakes(authority){const sub=this.nc.subscribe(takeServeFilter(this.space),{queue:TAKE_ROUTE});this.subs.push(sub);void(async()=>{for await(const m of sub){if(!m.reply||!m.reply.startsWith(`${m.subject}.reply.`)){this.emitRecoverable(new Error(`rejected take on ${m.subject}: reply target "${m.reply??"(none)"}" is not under the sender's own reply subtree`));continue}void this.answerTake(authority,m).catch(e=>this.emitRecoverable(e))}})().catch(e=>this.emitRecoverable(e));return sub}async answerTake(authority,m){let reply;if(this.takesInFlight>=MAX_TAKES_IN_FLIGHT)reply={ok:false,code:"busy",error:"the delivery daemon is answering too many takes; retry"};else{this.takesInFlight++;try{reply=await this.takeFor(authority,m)}catch(e){reply={ok:false,code:"busy",error:`the take could not be recorded: ${e.message}`}}finally{this.takesInFlight--}}m.respond(JSON.stringify(reply))}async takeFor(authority,m){if(!this.plane3MayAct())return{ok:false,code:"busy",error:"delivery: this daemon is not serving this shard (it is re-checking ownership); retry"};const parsed=parseTakeSubject(m.subject);let req;try{req=m.json()}catch{req=void 0}if(!parsed||!isPrincipalOwnerToken(parsed.owner)||req?.from?.id!==parsed.sender||typeof req.from.name!=="string")return{ok:false,code:"mismatch",error:"sender mismatch - take rejected"};if(!isAnycastSeq(req.seq)||!isAnycastSeq(req.count)||typeof req.id!=="string"||req.id.length>256||typeof req.epoch!=="string"||req.epoch.length>64)return{ok:false,code:"mismatch",error:"a take names a seq, the request id, a delivery count and the stream's creation time"};try{assertValidName(req.from.name)}catch(e){return{ok:false,code:"mismatch",error:`a take names its holder by a valid display name: ${e.message}`}}return authority.take(parsed.role,{from:{id:parsed.sender,name:req.from.name},seq:req.seq,id:req.id,count:req.count,epoch:req.epoch})}async sendAnycastNotice(to,event){if(!this.js)throw new Error(this.notLiveMsg());const recipient=parsePrincipalKey(to);if(!recipient)throw new Error(`anycast notice: "${to}" is not a principal`);const msg={id:event.key,ts:Date.now(),space:this.space,from:this.ref(),to,parts:[{kind:"text",text:event.text},{kind:"data",data:{[ANYCAST_NOTICE_KEY]:event.notice}}]};await this.js.publish(unicastSubject(this.space,recipient.owner,recipient.actor,this.owner,this.actor),JSON.stringify(msg),{msgID:msg.id})}async deliveryAnycast(op,caller,args){const authority=this.anycastAuthority;if(!authority)return{ok:false,error:`delivery: ${this.anycastUnavailable??"the anycast request records are not open on this daemon; retry"}`};if(!isAnycastSeq(args.seq))return{ok:false,error:`${op}: seq must be a whole number of at least 1`};if(args.id!==void 0&&(typeof args.id!=="string"||args.id.length>256))return{ok:false,error:`${op}: id must be a request id`};const q={seq:args.seq,...typeof args.id==="string"?{id:args.id}:{}};try{const status2=op===ANYCAST_CANCEL_OP?await authority.cancel(caller,q):await authority.status(caller,q);if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon stopped serving this shard while the request was in flight; retry"};return{ok:true,data:status2}}catch(e){return{ok:false,error:e.message}}}serveLiveness(plane,readState){if(!this.nc)throw new Error(this.notLiveMsg());const held2=this.livenessResponders.get(plane);if(held2)held2.readState=readState;else this.livenessResponders.set(plane,{readState});this.bindLiveness(plane)}bindLiveness(plane){const held2=this.livenessResponders.get(plane);if(!held2||!this.nc)return;if(held2.sub){try{held2.sub.unsubscribe()}catch{}const i=this.subs.indexOf(held2.sub);if(i>=0)this.subs.splice(i,1)}const{readState}=held2;const sub=this.nc.subscribe(livenessServeFilter(this.space,plane),{queue:`live.${plane}`});held2.sub=sub;this.subs.push(sub);const instance=(0,import_node_crypto10.randomUUID)();void(async()=>{for await(const m of sub){if(!m.reply||!m.reply.startsWith(`${m.subject}.reply.`)){this.emitRecoverable(new Error(`rejected liveness probe on ${m.subject}: reply target "${m.reply??"(none)"}" is not under the sender's own reply subtree`));continue}let responder;try{responder=await readState()}catch{responder="unknown"}const answer={plane,responder,instance};try{m.respond(JSON.stringify(answer))}catch{}}})().catch(e=>this.emit("error",e))}serveDeliveryLiveness(shardIndex=0){this.serveLiveness("delivery",async()=>responderFromLease(await this.readDeliveryLease(shardIndex),this.card.id))}async probeLiveness(plane,timeoutMs=2e3){if(!isLivenessPlane(plane))throw new Error(`liveness: "${plane}" is not a plane this surface answers for (${[...LIVENESS_PLANES].join(", ")})`);if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=livenessSubject(this.space,plane,this.owner,this.actor);const reply=`${reqSubject}.reply.${(0,import_node_crypto10.randomUUID)()}`;let outcome;let answered;let instance;try{const m=await this.requestBoundReply(this.nc,reqSubject,"",reply,timeoutMs);let body;try{body=m.json()}catch{body=void 0}const parsed=parseLivenessAnswer(body,plane);outcome=parsed?"replied":"malformed";answered=parsed?.responder;instance=parsed?.instance}catch(e){outcome=this.isNoResponders(e)?"noResponders":this.probeFailureOutcome(e)}const verdict={plane,responder:responderFromProbe(outcome,answered)};return instance===void 0?verdict:{...verdict,instance}}probeFailureOutcome(e){if(e instanceof import_transport_node13.AuthorizationError||e instanceof import_transport_node13.PermissionViolationError)return"refused";if(e instanceof import_transport_node13.TimeoutError)return"timeout";return"refused"}async handleDeliveryAdmin(req){await this.residentSwap;if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon is not serving this shard (it is re-checking ownership); retry"};if(req.op==="reloadCreds"){if(this.plane3?.startupComplete?.()===false)return{ok:false,error:"delivery: this daemon has not finished starting; nothing adopted - the next renewal pass or the daemon's 75% re-read adopts the re-signed creds"};const expected=req.args?.expected??{};const[delivery,membership]=await Promise.all([this.reloadCreds(expected.delivery).then(brokerAccepted=>({ok:true,brokerAccepted,residentSwap:"scheduled"}),e=>({ok:false,error:e.message})),this.plane3?.reloadMembershipCreds?this.plane3.reloadMembershipCreds(expected.membership).then(result=>({ok:true,...result}),e=>({ok:false,error:e.message})):Promise.resolve({ok:true,skipped:"no-membership-hook"})]);const failures=[delivery.ok?void 0:`delivery: ${delivery.error}`,membership.ok?void 0:`membership: ${membership.error}`].filter(m=>m!==void 0);if(delivery.ok){this.plane3?.onDeliveryCredsAdopted?.();this.scheduleResidentSwap()}return failures.length?{ok:false,error:failures.join("; "),data:{delivery,membership}}:{ok:true,data:{delivery,membership}}}if(req.op==="evictPrincipal"){if(!this.plane3?.evictPrincipal)return{ok:false,error:"evictPrincipal: no eviction executor wired on this daemon"};const principal=typeof req.args?.principal==="string"?req.args.principal.trim():"";if(!principal)return{ok:false,error:"evictPrincipal: a principal (owner.actor dot-form) is required"};try{return{ok:true,data:await this.plane3.evictPrincipal(principal)}}catch(e){return{ok:false,error:e.message}}}if(req.op==="evictPrincipals"){if(!this.plane3?.evictPrincipals)return{ok:false,error:"evictPrincipals: no batch eviction executor wired on this daemon"};const raw=req.args?.principals;const principals=Array.isArray(raw)?raw.map(p=>typeof p==="string"?p.trim():""):[];if(principals.length===0||principals.some(p=>!p))return{ok:false,error:"evictPrincipals: principals must be a non-empty array of owner.actor dot-form principals"};if(principals.length>EVICT_PRINCIPALS_MAX||new Set(principals).size!==principals.length)return{ok:false,error:`evictPrincipals: principals must be distinct and at most ${EVICT_PRINCIPALS_MAX}`};try{return{ok:true,data:await this.plane3.evictPrincipals(principals)}}catch(e){return{ok:false,error:e.message}}}if(req.op==="planeConnLiveness"){if(!this.plane3?.planeConnLiveness)return{ok:false,error:"planeConnLiveness: no plane-liveness oracle wired on this daemon"};try{return{ok:true,data:await this.plane3.planeConnLiveness(req.args?.query)}}catch(e){return{ok:false,error:e.message}}}if(req.op==="lifecycleMemberships"){const principal=typeof req.args?.principal==="string"?req.args.principal.trim():"";const uid2=typeof req.args?.lifecycleUid==="string"?req.args.lifecycleUid:"";if(!parsePrincipalKey(principal))return{ok:false,error:"lifecycleMemberships: a principal (owner.actor dot-form) is required"};try{assertLifecycleToken(uid2)}catch(e){return{ok:false,error:`lifecycleMemberships: ${e.message}`}}let marked=this.retiringLifecycles.get(principal);if(marked===void 0)this.retiringLifecycles.set(principal,marked=new Set);for(const earlier of[...marked])if(earlier!==uid2&&await aclRetired(await this.aclRegistry(),principal,earlier).catch(()=>false))marked.delete(earlier);if(await this.lifecycleAclUnfenced(principal,uid2))marked.add(uid2);else if(marked.size===0)this.retiringLifecycles.delete(principal);await Promise.allSettled(this.membershipWrites.get(`${principal}/${uid2}`)??[]);try{const channels=await listLifecycleMemberChannels(await this.membersRegistry(),principal,uid2);return{ok:true,data:{complete:true,channels}}}catch(e){return{ok:false,error:`lifecycleMemberships: the inventory read did not complete (${e.message})`}}}if(req.op==="principalLiveness"){if(!this.plane3?.principalLiveness)return{ok:false,error:"principalLiveness: no liveness oracle wired on this daemon"};const principal=typeof req.args?.principal==="string"?req.args.principal.trim():"";if(!principal)return{ok:false,error:"principalLiveness: a principal (owner.actor dot-form) is required"};try{return{ok:true,data:await this.plane3.principalLiveness(principal)}}catch(e){return{ok:false,error:e.message}}}if(req.op==="reloadStoreIdentity"){if(!this.plane3?.reloadStoreIdentity)return{ok:false,error:"reloadStoreIdentity: this daemon did not name the SecretStore it reloads from"};try{const identity=this.plane3.reloadStoreIdentity();let holdsDeliveryLease=false;try{const own=await this.readDeliveryLeaseEntry(0);holdsDeliveryLease=own!==void 0&&this.ownsDeliveryLease(own.info)}catch{holdsDeliveryLease=false}return{ok:true,data:{identity:parseSecretStoreIdentity(identity),responder:this.card.id,holdsDeliveryLease}}}catch(e){return{ok:false,error:e.message}}}return{ok:false,error:`op "${req.op}" not supported on the delivery admin service`}}async addPlane3Durable(stream,config2){try{await this.jsm.consumers.add(stream,config2)}catch(e){if(!isConsumerAlreadyExists(e)||!isRestoredConsumer(this.space,stream,await this.jsm.consumers.info(stream,config2.durable_name),config2))throw e}}async runFanout(){if(!this.js||!this.jsm)return;await this.addPlane3Durable(chatStream(this.space),fanoutDurableConfig(this.space,{ackWaitMs:this.ackWaitMs}));const consumer=await this.js.consumers.get(chatStream(this.space),FANOUT_DURABLE);const msgs=await consumer.consume();this.streamMsgs.push(msgs);void(async()=>{for await(const m of msgs){try{await this.fanOutMessage(m)}catch(e){if(!this.stopped)this.emit("error",e);try{m.nak()}catch{}}}})().catch(e=>{if(!this.stopped)this.emit("error",e)})}async fanOutMessage(m){if(!this.plane3MayAct())return;const parsed=parseSubject(m.subject);if(!parsed||parsed.kind!=="chat"){m.ack();return}const channel=parsed.rest;let msg;try{msg=m.json()}catch{m.ack();return}if(!isFromSubjectSender(msg,parsed)){m.ack();return}const seq=m.seq;const normalizedMsg=authenticatedChannelMessage(msg,channel);if(!this.plane3MayAct())return;if(await this.deliveryClassFresh(channel)==="durable"){for(const rec of await listMembers(await this.membersRegistry(),{covering:channel})){if(rec.owner===msg.from.id)continue;if(!durableEligible(rec,seq))continue;if(!this.plane3MayAct())return;await this.publishDinbox(rec.owner,rec.lifecycleUid,{msg:normalizedMsg,channel,seq,reason:"durable-channel",generation:rec.generation,...rec.channel!==channel?{row:rec.channel}:{}})}}else{for(const name of msg.mentions??[]){const owner2=this.resolveOwnerByName(name);if(!owner2||owner2===msg.from.id)continue;let row;try{row=await this.aclForAlias(owner2)}catch(e){this.emit("error",e);continue}if(!row||!channelInAllow(row.allowSubscribe,channel))continue;if(!this.plane3MayAct())return;await this.publishDinbox(owner2,row.lifecycleUid,{msg:normalizedMsg,channel,seq,reason:"live-mention",generation:0})}}if(!this.plane3MayAct())return;m.ack()}deliveryLimitRead;async deliveryLimitStamp(){const at=Date.now();if(this.deliveryLimitRead&&at-this.deliveryLimitRead.at<DELIVERY_LIMIT_READ_MS)return this.deliveryLimitRead.stamp;const count=(await this.jsm.streams.info(dlvStream(this.space))).config.max_msgs_per_subject;const stamp=count===HISTORY_NO_COUNT||count<1?"none":String(count);this.deliveryLimitRead={at,stamp};return stamp}async runReader(){if(!this.js||!this.jsm)return;await this.addPlane3Durable(inboxStream(this.space),inboxReaderConfig(this.space,{ackWaitMs:this.ackWaitMs}));const consumer=await this.js.consumers.get(inboxStream(this.space),INBOX_READER_DURABLE);const msgs=await consumer.consume();this.streamMsgs.push(msgs);void(async()=>{for await(const m of msgs){try{await this.readerHandle(m)}catch(e){if(!this.stopped)this.emit("error",e);try{m.nak()}catch{}}}})().catch(e=>{if(!this.stopped)this.emit("error",e)})}async lifecycleCoversPost(owner2,lifecycleUid,channel,seq){const kv=await this.membersRegistry();for(const row of[channel,...familiesCovering(channel).reverse()]){const rec=await readMember(kv,row,owner2,lifecycleUid);if(rec&&durableEligible(rec.record,seq))return true}return false}async removeRetiredMemberRow(channel,owner2,lifecycleUid){try{const kv=await this.membersRegistry();if(await readMember(kv,channel,owner2,lifecycleUid)===void 0)return;await deleteMember(kv,channel,owner2,lifecycleUid)}catch(e){this.emit("warning",new Error(`plane-3 reader: could not remove retired lifecycle ${owner2}.${lifecycleUid}'s "${channel}" member row: ${e.message}`))}}async readerHandle(m){if(!this.plane3MayAct())return;const pr=parseDinboxPrincipal(m.subject);if(!pr){m.ack();return}const owner2=`${pr.owner}.${pr.actor}`;let entry;try{entry=m.json()}catch{m.ack();return}if(!isRecord(entry)){m.ack();return}const redeliveries=m.info?.deliveryCount??1;const acl=await this.plane3?.aclFor(owner2,pr.lifecycleUid);if(acl===void 0){if(await aclRetired(await this.aclRegistry(),owner2,pr.lifecycleUid)){if(!this.plane3MayAct())return;let failure;try{await this.jsm.streams.deleteMessage(inboxStream(this.space),m.seq,false)}catch(e){if(!isJetStreamMissing(e,10043))failure=e instanceof Error?e:new Error(String(e))}if(!this.plane3MayAct())return;if(failure){if(redeliveries>=READER_MAX_REDELIVERIES){m.term();this.emit("error",new Error(`plane-3 reader: gave up removing entry ${m.seq} for retired lifecycle ${owner2}.${pr.lifecycleUid} after ${redeliveries} redeliveries: ${failure.message}`));return}m.nak(2e3);return}if(entry.reason==="durable-channel")await this.removeRetiredMemberRow(entry.row??entry.channel,owner2,pr.lifecycleUid);if(!this.plane3MayAct())return;m.ack();return}if(redeliveries>=READER_MAX_REDELIVERIES){m.term();this.emit("error",new Error(`plane-3 reader: gave up on entry for unknown owner ${owner2} after ${redeliveries} redeliveries`));return}m.nak(2e3);return}if(!channelInAllow(acl,entry.channel)){m.ack();return}if(entry.reason==="durable-channel"&&!await this.lifecycleCoversPost(owner2,pr.lifecycleUid,entry.channel,entry.seq)){m.ack();return}if(!this.plane3MayAct())return;try{const frame={version:1,channel:entry.channel,msg:authenticatedChannelMessage(entry.msg,entry.channel)};const frameHeaders=(0,import_transport_node13.headers)();frameHeaders.set(PLANE3_FRAME_HEADER,"1");frameHeaders.set(DELIVERY_LIMIT_HEADER,await this.deliveryLimitStamp());if(!this.plane3MayAct())return;await this.js.publish(dlvSubject(this.space,pr.owner,pr.actor,pr.lifecycleUid),JSON.stringify(frame),{...this.plane3MsgId(entry,`${owner2}:${pr.lifecycleUid}`),headers:frameHeaders})}catch{if(redeliveries>=READER_MAX_REDELIVERIES){m.term();this.emit("error",new Error(`plane-3 reader: gave up transferring ${entry.msg.id} for ${owner2} after ${redeliveries} redeliveries`));return}m.nak(2e3);return}if(!this.plane3MayAct())return;m.ack()}async pumpDlv(){if(!this.js)return;if(!this.ownLifecycleUid)return;const durable=dlvDurable(this.owner,this.actor,this.ownLifecycleUid);let consumer;try{consumer=await this.js.consumers.get(dlvStream(this.space),durable)}catch(e){if(isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.ConsumerNotFound))return;throw e}const lease=await this.readDeliveryLease(0);const liveDeliveryPlane=lease?.ready===true;if(!liveDeliveryPlane)this.emit("warning",new Error(`delivery durable "${durable}" for space "${this.space}" bound while the plane this connection reaches has no ready delivery lease, so the durable delivers nothing until a delivery daemon serves this plane. If a daemon serves this space on another plane, reconnect against it, which re-binds the durable there.`));const ackWaitMs=await ackWaitOf(consumer);const msgs=await consumer.consume();this.streamMsgs.push(msgs);void(async()=>{for await(const m of msgs){let limit;try{limit=deliveryLimitOf(m.headers?.get(DELIVERY_LIMIT_HEADER))}catch(e){this.emit("error",e);limit=null}if(limit!==null&&m.info.pending>=limit-1)this.emit("stored-copies-full",{limit});if(m.headers?.get(PLANE3_FRAME_HEADER)!=="1"){this.emit("error",new Error("plane-3 delivery: unauthenticated or unversioned DLV entry terminated"));try{m.term()}catch{}continue}let raw;try{raw=m.json()}catch(e){this.emit("error",e);try{m.term()}catch{}continue}if(!isPlane3DeliveryFrame(raw)){this.emit("error",new Error("plane-3 delivery: malformed versioned DLV entry terminated"));try{m.term()}catch{}continue}const msg=authenticatedChannelMessage(raw.msg,raw.channel);if(msg.from?.id===this.card.id){m.ack();continue}this.emit("message",msg,durableDelivery(m,ackWaitMs),{historical:false,kind:"channel"})}})().catch(e=>{if(!this.stopped)this.emit("error",e)})}async durableJoinChannel(channel){const reply=await this.requestDelivery("durableJoin",{channel},3e4);if(!reply.ok)throw new Error(reply.error??"durable join rejected");return reply.data??{durable:false}}async durableLeaveChannel(channel,generation){const lifecycleUid=this.requireLifecycleUid("leaving a durable channel");const reply=await this.requestDelivery("durableLeave",{channel,generation,lifecycleUid});if(!reply.ok)throw new Error(reply.error??"durable leave rejected")}async closeRefusedMembership(channel,generation){this.pendingDurableLeave.set(channel,generation);for(let attempt=0;;attempt++){if(this.stopped)return;try{await this.durableLeaveChannel(channel,generation);this.plane3Channels.delete(channel);this.pendingDurableLeave.delete(channel);return}catch(e){if(attempt===0)this.emitRecoverable(new Error(`channel "${channel}": Plane-3 durable membership (generation ${generation}) not yet tombstoned after a refused live sub - retrying; \xA77 boundary may be open until it succeeds (${e.message})`));await new Promise(r=>setTimeout(r,Math.min(3e4,1e3*2**attempt)))}}}pendingDurableLeaves(){return[...this.pendingDurableLeave.keys()]}isNoResponders(e){return e instanceof import_transport_node13.NoRespondersError||e instanceof import_transport_node13.RequestError&&e.isNoResponders()}async takeAnycast(role,seq,id2,count,epoch,nak){const nc=this.nc;if(!nc)return{taken:false,drop:false,reason:"daemon-down",detail:this.notLiveMsg()};const held2=(reason2,detail)=>({taken:false,drop:false,reason:reason2,detail});const subject=takeSubject(this.space,role,this.owner,this.actor);const body={from:{id:this.card.id,name:this.card.name},seq,id:id2,count,epoch};let reply;try{const m=await this.requestBoundReply(nc,subject,JSON.stringify(body),`${subject}.reply.${(0,import_node_crypto10.randomUUID)()}`,ANYCAST_TAKE_TIMEOUT_MS);reply=m.json()}catch(e){if(isPermissionDenied(e))return held2("credential-outdated","this seat's credential was minted before anycast takes existed, so it cannot take role requests; respawn the seat to get a current credential");if(this.isNoResponders(e))return this.takeResponderMissing();return held2("daemon-down",`the delivery daemon did not answer the take: ${e.message}`)}if(reply.ok)return{taken:true};if(reply.code==="mismatch"){const current=await this.readTaskEpoch().catch(()=>void 0);if(current!==void 0&¤t!==epoch)nak()}if(reply.code==="cancelled"||reply.code==="taken"||reply.code==="gone"||reply.code==="mismatch")return{taken:false,drop:true,reason:reply.code,detail:reply.error};return held2("daemon-busy",reply.error)}async takeResponderMissing(){const held2=(reason2,detail)=>({taken:false,drop:false,reason:reason2,detail});let reply;try{reply=await this.requestDelivery(ANYCAST_TAKES_OP,{},ANYCAST_TAKE_TIMEOUT_MS)}catch{return held2("daemon-down","no delivery daemon is answering on this mesh, so role requests wait on the queue until one does")}if(!reply.ok&&/not supported on the delivery control service/.test(reply.error??""))return held2("daemon-outdated","the delivery daemon predates anycast takes, so this seat holds role requests until the daemon is restarted at this version (`cotal up` runs it)");if(!reply.ok&&reply.error?.includes(ANYCAST_RECORDS_CREDENTIAL_OUTDATED))return held2("daemon-outdated",`this seat holds role requests until the delivery daemon can record takes: ${ANYCAST_RECORDS_CREDENTIAL_OUTDATED}`);return held2("daemon-down","the delivery daemon is not answering takes, so role requests wait on the queue until it does")}async anycastStatus(seq,id2){return this.anycastRequest(ANYCAST_STATUS_OP,seq,id2)}async cancelAnycast(seq,id2){return this.anycastRequest(ANYCAST_CANCEL_OP,seq,id2)}async anycastRequest(op,seq,id2){if(!this.authed)throw new Error("an open mesh runs no delivery daemon, so it keeps no record of anycast requests");if(!isAnycastSeq(seq))throw new Error(`seq must be a whole number of at least 1, got ${seq}`);let reply;try{reply=await this.requestDelivery(op,{seq,...id2!==void 0?{id:id2}:{}},1e4)}catch(e){if(this.isNoResponders(e))throw new Error("no delivery daemon is answering on this mesh, so the request's record cannot be read");throw e}if(!reply.ok){if(/not supported on the delivery control service/.test(reply.error??""))throw new Error("the delivery daemon predates anycast request status; restart it at this version (`cotal up` runs it)");throw new Error(reply.error??`${op} failed`)}return reply.data}async fetchMemberships(){let reply;try{reply=await this.requestDelivery("listMemberships",{lifecycleUid:this.requireLifecycleUid("listing durable memberships")},5e3)}catch(e){if(this.isNoResponders(e))return void 0;throw e}if(!reply.ok)throw new Error(reply.error??"listMemberships failed");return reply.data?.memberships??[]}async armBootDurableMemberships(){for(const channel of this.channels){if(this.plane3Channels.has(channel))continue;if(!isChannelFamily(channel)){if(!isConcreteChannel(channel))continue;const cls=await this.deliveryClassFresh(channel);if(cls!=="durable")continue}try{const r=await this.durableJoinChannel(channel);if(r.durable)this.plane3Channels.set(channel,r.generation??0);else void this.reconcileBootJoin(channel)}catch(e){if(!this.isNoResponders(e))this.emitRecoverable(e);void this.reconcileBootJoin(channel)}}}async reconcileBootJoin(channel){if(this.pendingBootJoins.has(channel))return;this.pendingBootJoins.add(channel);for(let attempt=0;;attempt++){await new Promise(r=>setTimeout(r,Math.min(3e4,1e3*2**attempt)));if(this.stopped||!this.channels.includes(channel)||this.plane3Channels.has(channel)){this.pendingBootJoins.delete(channel);return}try{const r=await this.durableJoinChannel(channel);if(r.durable){this.plane3Channels.set(channel,r.generation??0);this.pendingBootJoins.delete(channel);return}}catch(e){if(attempt===0&&!this.isNoResponders(e))this.emitRecoverable(new Error(`channel "${channel}": boot durable self-join not yet established - retrying until the delivery daemon is reachable (${e.message})`))}}}hasDurableMembership(channel){return this.plane3Channels.has(channel)}async manager(){if(!this.nc)throw new Error(this.notLiveMsg());this.jsm??=await(0,import_jetstream13.jetstreamManager)(this.nc);return this.jsm}async startConsumers(){if(!this.jsm)throw new Error(this.notLiveMsg());const ownUid=this.requireLifecycleUid("consuming the DM inbox");if(!this.authed){await this.ensureDmDurable(this.owner,this.actor,ownUid,{ackWaitMs:this.ackWaitMs,inactiveThresholdMs:this.inactiveThresholdMs})}await this.pump(dmStream(this.space),dmDurable(this.owner,this.actor,ownUid),{inbox:true});await this.pumpDlv();if(this.channels.length){const armed2=this.firstConnect?await this.armJoin(this.channels):void 0;for(const ch of this.channels)this.subscribeChat(ch);await this.confirmChatSub();if(armed2)await this.backfillArmed(armed2,this.backfillFloor)}if(this.firstConnect&&this.authed&&this.channels.length)await this.armBootDurableMemberships();this.firstConnect=false;if(this.card.role){if(!this.authed){await this.jsm.consumers.add(taskStream(this.space),taskDurableConfig(this.space,this.card.role,{ackWaitMs:this.ackWaitMs}))}await this.pump(taskStream(this.space),taskDurable(this.card.role),this.authed?{takeRole:this.card.role}:{})}}async pump(stream,durable,opts={}){if(!this.js)throw new Error(this.notLiveMsg());const consumer=opts.takeRole===void 0?await this.js.consumers.get(stream,durable):await this.bindTaskConsumer(stream,durable);const ackWaitMs=await ackWaitOf(consumer);const msgs=await consumer.consume();this.streamMsgs.push(msgs);if(opts.inbox)this.watchInbox(msgs,stream,durable);void(async()=>{for await(const m of msgs){const authed=this.authenticateStreamMsg(m);if(!authed)continue;const{msg,parsed}=authed;const delivery=durableDelivery(m,ackWaitMs);const role=opts.takeRole;if(role!==void 0){const epoch=this.taskEpoch;delivery.take=()=>this.takeAnycast(role,m.seq,msg.id,m.info.deliveryCount,epoch,()=>m.nak())}this.emit("message",authenticatedMessage(msg,parsed),delivery,{historical:false,kind:kindFromParsed(parsed.kind)})}})().catch(e=>{if(!this.stopped)this.emit("error",e)})}async bindTaskConsumer(stream,durable){for(let attempt=0;attempt<3;attempt++){const before=await this.readTaskEpoch();const consumer=await this.js.consumers.get(stream,durable);if(before===await this.readTaskEpoch())return consumer}throw new Error(`the ${stream} stream was recreated while its role consumer was binding; reconnect to bind it again`)}async readTaskEpoch(){const epoch=(await(await this.manager()).streams.info(taskStream(this.space))).created;this.taskEpoch=epoch;return epoch}watchInbox(msgs,stream,durable){const boundNc=this.nc;void(async()=>{let absences=0;let deleted=false;for await(const s of msgs.status()){if(this.stopped||this.nc!==boundNc)break;if(s.type==="next"){absences=0;deleted=false;continue}if(s.type==="consumer_deleted"){if(deleted)continue;deleted=true;absences=1}else if(s.type!=="consumer_not_found"&&s.type!=="stream_not_found")continue;if(++absences===2)this.emitRecoverable(new Error(`DM inbox missing: the broker reports consumer "${durable}" on stream "${stream}" missing, so direct messages to this endpoint are not delivered. The endpoint keeps checking; if the inbox does not come back, end this session and start a new one`))}})().catch(e=>{if(!this.stopped)this.emit("error",e)})}authenticateStreamMsg(m){let msg;try{msg=m.json()}catch(e){m.term();this.emit("error",e);return void 0}if(!isRecord(msg)||!isUsableMessageId(msg.id)){m.term();this.emit("error",new Error(`dropped message on ${m.subject}: absent or non-string id`));return void 0}const parsed=parseSubject(m.subject);if(!parsed||!isFromSubjectSender(msg,parsed)){m.term();this.emit("error",new Error(`dropped message on ${m.subject}: payload from ${msg.from?.id??"(none)"} does not match subject sender ${parsed?.sender??"(unparseable)"}`));return void 0}return{msg,parsed}}async bindDmOnly(mode){if(!this.js)throw new Error(this.notLiveMsg());const stream=dmStream(this.space);const durable=dmDurable(this.owner,this.actor,this.requireLifecycleUid("consuming the DM inbox"));let consumer;try{consumer=await this.js.consumers.get(stream,durable)}catch(e){if(isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.ConsumerNotFound))throw new DmDurableMissingError(stream,durable);throw new DmBindRefusedError(stream,durable,e)}const ackWaitMs=await ackWaitOf(consumer);if(this.dmOnlyInFlight){const settleMs=mode.settleTimeoutMs??3e4;await withDeadline(this.dmOnlyInFlight,settleMs,()=>new Error(`DM-only rebind waited ${settleMs}ms for the previous handler to settle; not reading the next DM yet`))}const msgs=await consumer.consume({max_messages:1});this.streamMsgs.push(msgs);const boundNc=this.nc;const retired=()=>this.stopped||this.nc!==boundNc||!boundNc||boundNc.isClosed();void(async()=>{for await(const m of msgs){if(retired())break;const authed=this.authenticateStreamMsg(m);if(!authed)continue;if(authed.parsed.kind!=="inst"){m.term();continue}const run=Promise.resolve().then(()=>mode.handler(authenticatedMessage(authed.msg,authed.parsed),dmOnlyDelivery(m,ackWaitMs,boundNc),{historical:false,kind:"dm"}));const flight=run.then(()=>{},()=>{});this.dmOnlyInFlight=flight;try{await run}catch(e){this.emit("error",e instanceof Error?e:new Error(String(e)))}finally{if(this.dmOnlyInFlight===flight)this.dmOnlyInFlight=void 0}}})().catch(e=>{if(!this.stopped)this.emit("error",e)})}subscribeChat(channel){if(!this.nc||this.chatSubs.has(channel))return;this.chatSubDenied.delete(channel);const subject=chatSubject(this.space,"*","*",channel);const sub=this.nc.subscribe(subject,{callback:(err3,m)=>{if(err3){if(err3 instanceof import_transport_node13.PermissionViolationError)this.chatSubRefusals.add(err3);this.chatSubDenied.add(channel);this.chatSubs.delete(channel);const i=this.channels.indexOf(channel);if(i>=0){this.channels.splice(i,1);const gen=this.plane3Channels.get(channel);if(gen!==void 0)void this.closeRefusedMembership(channel,gen);this.emit("error",new Error(`left channel "${channel}": its live subscription was refused by the broker`,{cause:err3}))}return}const parsed=parseSubject(m.subject);if(!parsed||parsed.kind!=="chat")return;let msg;try{msg=m.json()}catch(e){this.emit("error",e);return}if(!isRecord(msg)||!isUsableMessageId(msg.id))return;if(!isFromSubjectSender(msg,parsed))return;if(msg.from.id===this.card.id)return;const delivery={ack:()=>{},nak:()=>{},durable:false};this.emit("message",authenticatedMessage(msg,parsed),delivery,{historical:false,kind:kindFromParsed(parsed.kind)})}});this.chatSubs.set(channel,sub)}unsubscribeChat(channel){const sub=this.chatSubs.get(channel);if(sub){try{sub.unsubscribe()}catch{}this.chatSubs.delete(channel)}this.chatSubDenied.delete(channel)}async confirmChatSub(){if(!this.nc)throw new Error("connection not established");await this.nc.flush();await new Promise(r=>setTimeout(r,50))}async consumerInfo(stream,durable){if(!this.jsm)throw new Error(this.notLiveMsg());try{return await this.jsm.consumers.info(stream,durable)}catch(e){if(isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.ConsumerNotFound))return null;throw e}}async deleteConsumerIfPresent(stream,durable){if(!this.jsm)throw new Error(this.notLiveMsg());try{await this.jsm.consumers.delete(stream,durable)}catch(e){if(!isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.ConsumerNotFound,import_jetstream13.JetStreamApiCodes.StreamNotFound))throw e}}async chatFrontier(){const jsm=await this.manager();return(await jsm.streams.info(chatStream(this.space))).state.last_seq}async storedBytes(){return(await(await this.manager()).getAccountInfo()).storage}async armJoin(channels){const frontiers=new Map;for(const ch of channels){frontiers.set(ch,await this.chatFrontier())}return frontiers}async backfillArmed(frontiers,floorSeq){let total=0;for(const[ch,frontier]of frontiers){const policy=await this.joinPolicyFresh(ch);if(policy.replay)total+=await this.backfillChannel(ch,frontier,policy.windowMs,floorSeq)}return total}async joinPolicyFresh(channel){if(!this.channelKv)return{replay:effectiveReplay(void 0,void 0)};const[cfg,defaults]=await Promise.all([isConcreteChannel(channel)?readChannelConfig(this.channelKv,channel):Promise.resolve(void 0),readChannelDefaults(this.channelKv)]);return{replay:effectiveReplay(cfg,defaults),windowMs:effectiveReplayWindowMs(cfg,defaults)}}async collectHistory(subject,start,opts={}){const run=this.histLock.then(()=>this.collectHistoryInner(subject,start,opts));this.histLock=run.catch(()=>{});return run}async collectHistoryInner(subject,start,opts={}){if(!this.jsm||!this.js)throw new Error(this.notLiveMsg());const stream=chatStream(this.space);const name=chatHistDurable(this.owner,this.actor,this.requireLifecycleUid("chat history reads"));const out=[];await this.deleteConsumerIfPresent(stream,name);await this.jsm.consumers.add(stream,{name,filter_subject:subject,ack_policy:import_jetstream13.AckPolicy.None,mem_storage:true,inactive_threshold:(0,import_transport_node13.nanos)(3e4),..."time"in start?{deliver_policy:import_jetstream13.DeliverPolicy.StartTime,opt_start_time:start.time.toISOString()}:{deliver_policy:import_jetstream13.DeliverPolicy.StartSequence,opt_start_seq:start.seq}});try{const consumer=await this.js.consumers.get(stream,name);let pending=(await consumer.info()).num_pending;while(pending>0){const want=Math.min(pending,256);const iter=await consumer.fetch({max_messages:want,expires:5e3});let got=0;for await(const m of iter){got++;if(opts.untilSeq!==void 0&&m.seq>opts.untilSeq)return out;if(!subjectMatches(subject,m.subject))continue;out.push(m);if(opts.limit!==void 0&&out.length>=opts.limit)return out}if(got<want)break;pending-=got}}finally{await this.deleteConsumerIfPresent(stream,name)}return out}async backfillChannel(channel,upToSeq,sinceMs,floorSeq){if(floorSeq!==void 0&&floorSeq>=upToSeq)return 0;const subject=chatSubject(this.space,"*","*",channel);const start=floorSeq!==void 0?{seq:floorSeq+1}:sinceMs===void 0?{seq:1}:{time:new Date(Date.now()-sinceMs)};let msgs;try{msgs=await this.collectHistory(subject,start,{untilSeq:upToSeq})}catch(e){this.emit("error",e);if(isPermissionDenied(e))throw e;return 0}const noop={ack:()=>{},nak:()=>{},durable:false};let n=0;for(const sm of msgs){let msg;try{msg=sm.json()}catch{continue}if(!isRecord(msg)||!isUsableMessageId(msg.id))continue;const parsed=parseSubject(sm.subject);if(!parsed||!isFromSubjectSender(msg,parsed)||msg.from.id===this.card.id)continue;this.emit("message",authenticatedMessage(msg,parsed),noop,{historical:true,kind:"channel"});n++}return n}async recallChannel(channel,sinceSeq){if(!this.jsm)throw new Error(this.notLiveMsg());if(!isConcreteChannel(channel))return{messages:[],seqs:[],dropped:false,unanswered:true};const policy=await this.joinPolicyFresh(channel);if(!policy.replay)return{messages:[],seqs:[],dropped:true,unanswered:true};const subject=chatSubject(this.space,"*","*",channel);let raw;try{raw=await this.collectHistory(subject,{seq:sinceSeq+1})}catch(e){this.emit("error",e);if(isPermissionDenied(e))throw e;return{messages:[],seqs:[],dropped:true,unanswered:true}}const collected=[];const seqs=[];for(const sm of raw){let msg;try{msg=sm.json()}catch{continue}if(!isRecord(msg)||!isUsableMessageId(msg.id))continue;const parsed=parseSubject(sm.subject);if(!parsed||!isFromSubjectSender(msg,parsed)||msg.from.id===this.card.id)continue;collected.push(authenticatedMessage(msg,parsed));seqs.push(sm.seq)}let dropped;try{dropped=await this.chatMayHaveLost(subject,sinceSeq)}catch(e){this.emit("error",e);if(isPermissionDenied(e))throw e;return{messages:[],seqs:[],dropped:true,unanswered:true}}return{messages:collected,seqs,dropped,unanswered:false}}async chatMayHaveLost(subject,sinceSeq){if(!this.jsm)throw new Error(this.notLiveMsg());const info=await this.jsm.streams.info(chatStream(this.space),{subjects_filter:subject});if(info.state.first_seq>sinceSeq+1)return true;const cap=info.config.max_msgs_per_subject;let maxPerSubject=0;for(const count of Object.values(info.state.subjects??{}))maxPerSubject=Math.max(maxPerSubject,count);if(cap<1||maxPerSubject<cap)return false;const oldest=(await this.collectHistory(subject,{seq:1},{limit:1}))[0]?.seq;return oldest!==void 0&&oldest>sinceSeq+1}async publishPresence(){if(!this.doRegister||!this.kv)return;const p={card:this.card,...this.ownLifecycleUid!==void 0?{lifecycleUid:this.ownLifecycleUid}:{},runtime:processRuntime(this.ownLifecycleUid),status:this.status,condition:this.condition,environment:this.environment,activity:this.activity,statusSince:this.statusSince,activitySince:this.activitySince,activeAt:this.activeAt,attention:this.attentionMode,channelModes:this.channelModes,ts:Date.now()};const record3=this.status==="offline"?this.toOffline(p):p;assertPresenceRow(record3,this.card.id);const epoch=this.presenceEpoch;const conditionRevision=this.conditionRevision;const generation=++this.presencePutGeneration;try{await this.kv.put(this.card.id,JSON.stringify(record3))}catch(e){const superseded2=(this.presencePutSettled??0)>generation;this.presencePutSettled=Math.max(this.presencePutSettled??0,generation);if(epoch===this.presenceEpoch&&!this.stopped&&!superseded2){this.presenceWriteFailingSince??=Date.now();this.lastPresenceWriteError=e?.message??String(e);this.presenceWriteFailures++;this.escalatePresenceWriteFailureIfStuck()}if(e instanceof import_transport_node13.TimeoutError)throw new Error(`${e.message}. The presence write outcome is unknown: the broker may have stored the update. Read the roster before retrying.`,{cause:e});throw e}const superseded=(this.presencePutSettled??0)>generation;this.presencePutSettled=Math.max(this.presencePutSettled??0,generation);if(epoch!==this.presenceEpoch||this.stopped||superseded)return;if(conditionRevision!==this.conditionRevision){await this.publishPresence();return}this.clearPresenceWriteFailure()}clearPresenceWriteFailure(){this.presenceWriteFailingSince=void 0;this.lastPresenceWriteError=void 0;this.presenceWriteFailures=0;this.presenceWriteEscalated=false}escalatePresenceWriteFailureIfStuck(){if(this.presenceWriteEscalated||this.presenceWriteFailingSince===void 0||this.presenceWriteFailures<2||Date.now()-this.presenceWriteFailingSince<this.ttlMs)return;this.presenceWriteEscalated=true;this.emitRecoverable(new PresenceWriteStuckError(presenceBucket(this.space),this.presenceWriteFailingSince,this.presenceWriteFailures,this.ttlMs,this.lastPresenceWriteError))}presenceWriteFailure(){if(this.presenceWriteFailingSince===void 0)return void 0;return{since:this.presenceWriteFailingSince,forMs:Date.now()-this.presenceWriteFailingSince,error:this.lastPresenceWriteError,bucket:presenceBucket(this.space),consecutiveFailures:this.presenceWriteFailures,stuck:this.presenceWriteEscalated}}async startPresenceWatch(){if(!this.kv)return void 0;let hydrated;this.presenceSnapshot=new Promise(resolve=>{hydrated=resolve});const bound=await this.bindKvWatch(this.kv);if(!bound){hydrated();return void 0}const{iter,info}=bound;this.presenceWatchIter=iter;const empty=info.num_pending===0&&!this.doRegister;if(empty){this.presenceSnapshotPopulated=true;hydrated();this.markPresenceBucketEmpty()}void(async()=>{let ready=empty;for await(const e of iter){if(this.presenceWatchIter!==iter)break;this.handleKvEntry(e);if(!ready&&e.isUpdate){ready=true;this.presenceSnapshotPopulated=true;hydrated();this.emitPresenceViewIfChanged()}}hydrated()})().catch(e=>this.emit("error",e));return info}async readPresenceOnce(){if(!this.kv)return;for(const e of await lastKvEntries(this.kv))this.handleKvEntry(e);this.presenceSnapshotPopulated=true;if(this.lastPresenceWatchAt===0)this.markPresenceBucketEmpty();else this.emitPresenceViewIfChanged()}rebindStalePresenceWatch(now){if(this.stopped||this.reconnecting||!this.kv||!this.nc||this.nc.isClosed())return;if(this.presenceRebind||now-this.presenceRebindAt<this.ttlMs)return;this.presenceRebindAt=now;const old=this.presenceWatchIter;const epoch=this.presenceEpoch;this.presenceRebind=(async()=>{try{const silentMs=now-this.lastPresenceWatchAt;const info=await this.startPresenceWatch();if(!info)return;if(old&&old!==this.presenceWatchIter)this.retireKvWatch(old);if(info.num_pending===0)await this.onPresenceBucketEmpty();this.emit("warning",new Error(`presence watch silent for ${silentMs}ms with the connection up; rebound it from the bucket's current state`))}catch(e){if(epoch===this.presenceEpoch)this.emit("error",e)}finally{if(epoch===this.presenceEpoch)this.presenceRebind=void 0}})()}async startChannelWatch(){if(!this.channelKv)return;const bound=await this.bindKvWatch(this.channelKv);if(!bound)return;const{iter}=bound;this.channelWatchIter=iter;void(async()=>{for await(const e of iter)this.handleChannelEntry(e)})().catch(e=>this.emit("error",e))}async readChannelsOnce(){if(!this.channelKv)return;for(const e of await lastKvEntries(this.channelKv))this.handleChannelEntry(e)}handleChannelEntry(e){const isDefaults=e.key===CHANNEL_DEFAULTS_KEY;if(isDefaults)this.channelDefaults={};else this.channelConfigs.delete(e.key);if(e.operation==="DEL"||e.operation==="PURGE")return;try{if(isDefaults)this.channelDefaults=decodeChannelEntry(e);else this.channelConfigs.set(e.key,decodeChannelEntry(e))}catch(err3){this.emitRecoverable(new Error(`dropped channel registry entry for key ${JSON.stringify(e.key)}: ${err3.message}`))}}async onPresenceBucketEmpty(){if(this.doRegister){await this.publishPresence();return}this.markPresenceBucketEmpty()}markPresenceBucketEmpty(){this.presenceWatchEmpty=true;this.lastPresenceWatchAt=0;let changed=false;for(const[id2,p]of this.roster){if(p.status==="offline")continue;const offline=this.toOffline(p);this.roster.set(id2,offline);this.emit("presence",{type:"offline",presence:offline});changed=true}if(changed)this.emit("roster",this.getRoster());this.emitPresenceViewIfChanged()}handleKvEntry(e){if(e.key===TTL_RECONCILE_CANARY_KEY)return;this.lastPresenceWatchAt=Date.now();this.presenceWatchEmpty=false;if(e.operation==="DEL"||e.operation==="PURGE"){this.markOffline(e.key);return}const p=this.decodePresence(e);if(p)this.applyPresence(e.key,p)}decodePresence(e){let p;try{p=e.json()}catch{return void 0}if(!isPresenceRow(p,e.key)){this.presenceBindingDrops++;this.emitRecoverable(new Error(`dropped presence entry for key ${JSON.stringify(e.key)}: not a usable presence row (a record with card.id equal to its KV key, a string card.name, a known status, a finite ts, string display fields and a condition with a string code)`));return void 0}return p}applyPresence(id2,raw){const prev=this.roster.get(id2);const stale=Date.now()-raw.ts>this.ttlMs;if(stale&&raw.status!=="offline"){if(prev)return;this.roster.set(id2,this.toOffline(raw));this.emit("roster",this.getRoster());return}if(this.presenceSnapshotPopulated)this.emitPresenceViewIfChanged();const p=stale||raw.status==="offline"?this.toOffline(raw):raw;if(!prev&&p.status==="offline"){this.roster.set(id2,p);this.emit("roster",this.getRoster());return}if(prev&&prev.status!=="offline"&&p.status!=="offline"&&prev.lifecycleUid===p.lifecycleUid&&sameRuntime(prev.runtime,p.runtime)&&prev.status===p.status&&prev.activity===p.activity&&sameCondition(prev.condition,p.condition)&&prev.environment===p.environment&&prev.attention===p.attention&&sameChannelModes(prev.channelModes,p.channelModes)){this.roster.set(id2,p);return}this.roster.set(id2,p);const type=p.status==="offline"?"offline":!prev||prev.status==="offline"?"join":"update";this.emit("presence",{type,presence:p});this.emit("roster",this.getRoster())}toOffline(p){return{...p,status:"offline",statusSince:void 0,attention:void 0,channelModes:void 0}}markOffline(id2){const prev=this.roster.get(id2);if(!prev||prev.status==="offline")return;const offline=this.toOffline(prev);this.roster.set(id2,offline);this.emit("presence",{type:"offline",presence:offline});this.emit("roster",this.getRoster())}emitPresenceViewIfChanged(){const view=this.presenceView();if(view.state===this.presenceViewState)return;this.presenceViewState=view.state;this.emit("presence-view",view)}sweep(){const now=Date.now();if(this.lastPresenceWatchAt!==0&&now-this.lastPresenceWatchAt>this.ttlMs){this.emitPresenceViewIfChanged();this.rebindStalePresenceWatch(now);return}let changed=false;for(const[id2,p]of this.roster){if(p.status!=="offline"&&now-p.ts>this.ttlMs&&this.lastPresenceWatchAt-p.ts>this.ttlMs){const offline=this.toOffline(p);this.roster.set(id2,offline);this.emit("presence",{type:"offline",presence:offline});changed=true}}if(changed)this.emit("roster",this.getRoster())}};function subjectLabel(subjects){return subjects.length===1?subjects[0]:`${subjects.length} filtered subjects`}function isUsableMessageId(id2){return typeof id2==="string"}function kindFromParsed(kind){switch(kind){case"chat":return"channel";case"inst":return"dm";case"svc":return"anycast";default:throw new Error(`cannot derive a message kind from subject kind "${kind}"`)}}function isFromSubjectSender(msg,parsed){return isRecord(msg)&&isRecord(msg.from)&&msg.from.id===parsed.sender&&isPrincipalOwnerToken(parsed.owner)}function authenticatedMessage(msg,parsed){if(parsed.kind==="chat")return authenticatedChannelMessage(msg,parsed.rest);if(parsed.kind==="inst")return authenticatedDmMessage(msg,parsed.rest);if(parsed.kind==="svc")return authenticatedAnycastMessage(msg,parsed.rest);return msg}function authenticatedChannelMessage(msg,channel){if(msg.channel===channel&&msg.to===void 0&&msg.toService===void 0)return msg;const{to:_to,toService:_toService,...base}=msg;return{...base,channel}}function authenticatedDmMessage(msg,to){if(msg.to===to&&msg.channel===void 0&&msg.toService===void 0)return msg;const{channel:_channel,toService:_toService,...base}=msg;return{...base,to}}function authenticatedAnycastMessage(msg,toService){if(msg.toService===toService&&msg.to===void 0&&msg.channel===void 0)return msg;const{to:_to,channel:_channel,...base}=msg;return{...base,toService}}async function ackWaitOf(consumer){const{config:config2}=await consumer.info(true);if(config2.ack_wait===void 0)throw new Error(`consumer ${config2.durable_name} reports no ack wait`);return(0,import_transport_node13.millis)(config2.ack_wait)}function durableDelivery(m,ackWaitMs){return{ack:()=>m.ack(),nak:()=>m.nak(),durable:true,redelivery:{deliveryCount:m.info.deliveryCount,ackWaitMs,working:()=>m.working()}}}function dmOnlyDelivery(m,ackWaitMs,nc){const open5=what=>{if(!nc||nc.isClosed())throw new Error(`DM-only ${what} refused: the connection that delivered this copy is closed; the broker will redeliver it`)};return{ack:()=>{open5("ack");m.ack()},nak:()=>{open5("nak");m.nak()},durable:true,redelivery:{deliveryCount:m.info.deliveryCount,ackWaitMs,working:()=>{open5("in-progress signal");m.working()}}}}function historyMessageFromDelivery(m){let raw;try{raw=m.json()}catch{return void 0}if(!isHistoryDrainEnvelope(raw))return void 0;if(!isVerifiedHistoryRow(raw))return void 0;const parsed=parseSubject(m.subject);if(!parsed||!isFromSubjectSender(raw,parsed))return void 0;return authenticatedMessage(raw,parsed)}function isVerifiedHistoryRow(row){if(typeof row.from.name!=="string")return false;if(row.from.role!==void 0&&typeof row.from.role!=="string")return false;if(typeof row.ts!=="number"||!Number.isFinite(row.ts))return false;if(typeof row.space!=="string")return false;if(!Array.isArray(row.parts)||!row.parts.every(isReadableMessagePart))return false;if(row.mentions!==void 0&&(!Array.isArray(row.mentions)||!row.mentions.every(name=>typeof name==="string")))return false;if(row.replyTo!==void 0&&typeof row.replyTo!=="string")return false;if(row.contextId!==void 0&&typeof row.contextId!=="string")return false;return true}function isReadableMessagePart(value){return isRecord(value)&&typeof value.kind==="string"}function isHistoryDrainEnvelope(value){return isRecord(value)&&isUsableMessageId(value.id)&&isRecord(value.from)}function isPlane3DeliveryFrame(value){if(!isRecord(value))return false;const keys=Object.keys(value);if(keys.length!==3||!keys.includes("version")||!keys.includes("channel")||!keys.includes("msg"))return false;if(value.version!==1||typeof value.channel!=="string"||!isConcreteChannel(value.channel))return false;return isCotalMessage(value.msg)&&value.msg.channel===value.channel}function isCotalMessage(value){if(!isRecord(value))return false;const routes=["channel","to","toService"].filter(key=>key in value);if(routes.length!==1||typeof value[routes[0]]!=="string")return false;if(typeof value.id!=="string"||typeof value.ts!=="number"||!Number.isFinite(value.ts)||typeof value.space!=="string"||!isEndpointRef(value.from)||!Array.isArray(value.parts)||!value.parts.every(isMessagePart))return false;if(value.mentions!==void 0&&(!Array.isArray(value.mentions)||!value.mentions.every(name=>typeof name==="string")))return false;if(value.replyTo!==void 0&&typeof value.replyTo!=="string")return false;if(value.contextId!==void 0&&typeof value.contextId!=="string")return false;return true}function isEndpointRef(value){return isRecord(value)&&typeof value.id==="string"&&typeof value.name==="string"&&(value.role===void 0||typeof value.role==="string")}function isMessagePart(value){if(!isRecord(value)||typeof value.kind!=="string")return false;if(value.kind==="text")return typeof value.text==="string";if(value.kind==="data")return Object.prototype.hasOwnProperty.call(value,"data");if(value.kind===ARTIFACT_PART_KIND)return isArtifactPart(value);return/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/.test(value.kind)}function isRecord(value){return!!value&&typeof value==="object"&&!Array.isArray(value)}function jsonPathProblem(path,value,seen){if(value===null)return void 0;const t=typeof value;if(t==="boolean"||t==="string")return void 0;if(t==="number")return Number.isFinite(value)?void 0:`${path} is not a finite number`;if(t==="undefined"||t==="function"||t==="symbol"||t==="bigint")return`${path} is not a JSON value`;if(typeof value==="object"){if(seen.has(value))return`${path} is cyclic`;seen.add(value);let problem;if(Array.isArray(value)){for(let i=0;i<value.length;i++){problem=jsonPathProblem(`${path}[${i}]`,value[i],seen);if(problem)return problem}}else{const proto=Object.getPrototypeOf(value);if(proto!==null&&proto!==Object.prototype){seen.delete(value);return`${path} is not a plain object`}for(const key of Object.keys(value)){if(value[key]===void 0)continue;problem=jsonPathProblem(`${path}.${key}`,value[key],seen);if(problem)return problem}}seen.delete(value);return void 0}return`${path} is not a JSON value`}function assertPartsSerializable(parts){for(const p of parts){if(p.kind!=="data")continue;const problem=jsonPathProblem("data",p.data,new Set);if(problem!==void 0){throw new Error(`cannot publish a data part carrying a non-JSON value (SPEC \xA75) - ${problem}`)}}}function sameChannelModes(a,b){const ak=a?Object.keys(a):[];const bk=b?Object.keys(b):[];if(ak.length!==bk.length)return false;return ak.every(k=>a[k]===b?.[k])}function sameRuntime(a,b){return a?.id===b?.id&&a?.startedAt===b?.startedAt&&a?.source===b?.source}function sameCondition(a,b){return a?.code===b?.code&&a?.source===b?.source&&a?.message===b?.message&&a?.since===b?.since}function authOpts(a){const tls=a.tls?{}:void 0;if(a.bearer){if(a.creds||a.token||a.user||a.pass)throw new Error("bearer (user-mode auth) is mutually exclusive with creds/token/user/pass");if(!a.sentinelCreds)throw new Error("user-mode bearer requires sentinelCreds");return{authenticator:[nativeCredsAuthenticator(a.sentinelCreds),(0,import_transport_node13.tokenAuthenticator)(a.bearer)],tls}}if(a.creds){if(a.token||a.user||a.pass)throw new Error("creds are mutually exclusive with token/user/pass auth");const creds=a.creds;const authenticator=nonce3=>{const presented=typeof creds==="function"?creds():creds;const authenticated=nativeCredsAuthenticator(presented)(nonce3);a.onCreds?.(presented);return authenticated};return{authenticator,tls}}return{token:a.token,user:a.user,pass:a.pass,tls}}function bearerExpiryMs(bearer){return bearerLifetimeMs(bearer,0).expiresAtMs}function bearerLifetimeMs(bearer,adoptedAtMs){const payload=bearer.split(".")[1];if(!payload)throw new Error("user-mode bearer is not a JWT (no payload segment)");let claims2;try{claims2=JSON.parse(Buffer.from(payload,"base64url").toString("utf8"))}catch{throw new Error("user-mode bearer payload is not valid base64url JSON")}if(typeof claims2.exp!=="number")throw new Error("user-mode bearer is missing a numeric exp claim");const expiresAtMs=claims2.exp*1e3;return{issuedAtMs:Math.min(typeof claims2.iat==="number"?claims2.iat*1e3:adoptedAtMs,expiresAtMs),expiresAtMs}}function bearerRenewalDeadlineMs(bearer,adoptedAtMs){const{issuedAtMs,expiresAtMs}=bearerLifetimeMs(bearer,adoptedAtMs);return renewalDeadlineMs(issuedAtMs,expiresAtMs)}var RepeatedRefusal=class extends Error{};function decodeBearerPrincipal(bearer){const payload=bearer.split(".")[1];if(!payload)throw new Error("user-mode bearer is not a JWT (no payload segment)");let claims2;try{claims2=JSON.parse(Buffer.from(payload,"base64url").toString("utf8"))}catch{throw new Error("user-mode bearer payload is not valid base64url JSON")}const owner2=claims2.sub,actor2=claims2.act?.actor;if(typeof owner2!=="string"||typeof actor2!=="string")throw new Error("user-mode bearer is missing a string sub (owner) / act.actor claim");return{owner:owner2,actor:actor2}}function describeStatusError(err3){if(err3 instanceof import_transport_node13.PermissionViolationError){return new Error(`NATS permission denied: cannot ${err3.operation} "${err3.subject}" - check this endpoint's ACLs (a denied peer looks "absent" rather than blocked)`,{cause:err3})}return err3}function kvWatchConsumer(iter){const consumer=iter._data;if(!consumer)throw new Error("KV watch carries no consumer - the pinned nats.js changed shape");return consumer}function membershipConsumerReleased(err3){return isJetStreamMissing(err3,import_jetstream13.JetStreamApiCodes.ConsumerNotFound,import_jetstream13.JetStreamApiCodes.StreamNotFound)||isPublishPermissionDenied(err3)}function abortReason(signal){return signal?.reason instanceof Error?signal.reason:new DOMException("This operation was aborted","AbortError")}function isPublishPermissionDenied(e){const typed=e instanceof import_transport_node13.PermissionViolationError?e:e?.cause instanceof import_transport_node13.PermissionViolationError?e.cause:void 0;return typed?.operation==="publish"}function wsServers(servers){return/^wss?:\/\//i.test((servers.split(",")[0]??"").trim())}function defaultProbeTimeoutMs(servers){return wsServers(servers)?5e3:1e3}function dialerFor(servers){if(!wsServers(servers))return(opts=>(0,import_transport_node13.connect)(withDialedTlsHost(servers,opts)));return(opts=>{const{tls,...rest}=opts??{};const targets=Array.isArray(rest.servers)?rest.servers:String(rest.servers??servers).split(",");if(tls&&targets.some(target2=>!/^wss:\/\//i.test(String(target2).trim())))return Promise.reject(new Error("TLS-required WebSocket connections must use wss:// for every server"));return(0,import_nats_core6.wsconnect)(rest)})}function withDialedTlsHost(servers,opts){const urls=servers.split(",").map(url2=>url2.trim()).filter(Boolean);const tls=opts?.tls;if(urls.length!==1||tls===null||tls===void 0&&!/^tls:\/\//i.test(urls[0]))return opts;let host;try{({host}=hostPort(urls[0]))}catch{return opts}return(0,import_node_net.isIP)(host)?{...opts,tls:{host,...tls}}:opts}function hostPort(server){const raw=(server.split(",")[0]??"").trim();const scheme=raw.match(/^([a-z][a-z0-9+.-]*):\/\//i)?.[1]?.toLowerCase();const first=raw.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"");const u=new URL(`http://${first}`);const fallback=scheme==="wss"?443:scheme==="ws"?80:4222;return{host:u.hostname,port:u.port?Number(u.port):fallback}}function tcpInfoProbe(server,timeoutMs){return new Promise(resolve=>{let socket;let done=false;let connected=false;const finish=live=>{if(done)return;done=true;try{socket?.destroy()}catch{}resolve(live)};let host,port;try{({host,port}=hostPort(server))}catch{return resolve(false)}socket=(0,import_node_net.createConnection)({host,port});socket.setTimeout(timeoutMs);let buf="";socket.on("data",chunk=>{buf+=chunk.toString("utf8");const nl=buf.indexOf("\r\n");if(nl===-1){if(buf.length>4096)finish(false);return}const line=buf.slice(0,nl);const brace=line.indexOf("{");if(!/^INFO\b/.test(line)||brace===-1)return finish(false);try{finish({authRequired:JSON.parse(line.slice(brace))?.auth_required===true})}catch{finish(false)}});socket.on("connect",()=>{connected=true});socket.on("timeout",()=>finish(connected?"silent":false));socket.on("error",()=>finish(false));socket.on("close",()=>finish(false))})}function tcpDialable(server,timeoutMs){return new Promise(resolve=>{let socket;let done=false;const finish=dialable=>{if(done)return;done=true;try{socket?.destroy()}catch{}resolve(dialable)};let host,port;try{({host,port}=hostPort(server))}catch{return resolve(false)}socket=(0,import_node_net.createConnection)({host,port});socket.setTimeout(timeoutMs);socket.on("connect",()=>finish(true));socket.on("timeout",()=>finish(false));socket.on("error",()=>finish(false));socket.on("close",()=>finish(false))})}function isAuthRejection(e){return e instanceof import_transport_node13.AuthorizationError||e instanceof import_transport_node13.UserAuthenticationExpiredError}function retryAfterMs(e){const seconds=e?.retryAfterSeconds;return typeof seconds==="number"&&Number.isFinite(seconds)&&seconds>0?seconds*1e3:0}async function probeConnect(server=DEFAULT_SERVER,opts={}){const timeoutMs=opts.timeoutMs??defaultProbeTimeoutMs(server);const started=Date.now();const gate=opts.tls||wsServers(server)?tcpDialable:tcpInfoProbe;const greeting=await gate(server,timeoutMs);if(!greeting)return classifyProbeFailure(void 0,opts);if(greeting==="silent")return classifyProbeFailure(void 0,opts,false,"timeout");try{const nc=await dialerFor(server)({servers:server,timeout:Math.max(1,timeoutMs-(Date.now()-started)),reconnect:false,maxReconnectAttempts:0,...authOpts(opts)});await nc.close();return{ok:true}}catch(e){return classifyProbeFailure(e,opts,greeting!==true&&greeting.authRequired)}}function classifyProbeFailure(e,opts,authRequired=false,otherwise="unreachable"){if(typeof opts.creds==="string"){try{if(inspectCredHealth(opts.creds).state==="expired")return{ok:false,reason:"stale-auth"}}catch{}}if(e instanceof import_transport_node13.UserAuthenticationExpiredError)return{ok:false,reason:"stale-auth"};if(e instanceof import_transport_node13.AuthorizationError)return{ok:false,reason:"auth-required"};if(e instanceof import_transport_node13.TimeoutError)return{ok:false,reason:"timeout"};if(e instanceof import_transport_node13.ConnectionError&&e.message==="server does not support 'tls'")return{ok:false,reason:"tls-unsupported"};if(authRequired&&e?.code==="ECONNRESET")return{ok:false,reason:"auth-required",inferred:true};return{ok:false,reason:otherwise}}var EVICT_PRINCIPALS_MAX=256;var SOURCE_CHAIN_ID="[A-Za-z0-9_-]{1,64}";var SOURCE_CHAIN_ELEMENT=new RegExp(`^(root|handle\\.${SOURCE_CHAIN_ID}\\.${SOURCE_CHAIN_ID}|session\\.${SOURCE_CHAIN_ID})$`);async function fetchClusterDocument(store,closureDigest,walk){const{manifest,artifacts}=await fetchContractClosure(store,closureDigest,()=>[],walk);const rootBytes=artifacts.get(contractRefToHex(manifest.root));if(rootBytes===void 0)throw new EpEnvelopeError("failed-precondition",`the cluster manifest ${closureDigest} names root ${manifest.root} but the root artifact is absent from the fetched closure (SPEC 13.7)`);return parseClusterDocument(JSON.parse(dec3.decode(rootBytes)))}async function recompileClosure(store,closureDigest,walk){const{manifest,artifacts}=await fetchContractClosure(store,closureDigest,bytes=>extractSchemaRefs(bytes),walk);const members={};for(const[hex3,bytes]of artifacts)members[`sha256:${hex3}`]=JSON.parse(dec3.decode(bytes));const rootRef=manifest.root;const root=members[rootRef];if(root===void 0)throw new EpEnvelopeError("failed-precondition",`schema closure ${closureDigest} is missing its root ${rootRef} (SPEC 13.7)`);const bundleMembers={};for(const[ref,value]of Object.entries(members))if(ref!==rootRef)bundleMembers[ref]=value;const compiled=compileContract({root,members:bundleMembers});if(compiled.closureDigest!==closureDigest)throw new EpEnvelopeError("internal",`the recompiled schema closure hashes to ${compiled.closureDigest}, not the fetched ${closureDigest}; a store that served the wrong bytes never authorizes (SPEC 13.7)`);return compiled}function extractSchemaRefs(bytes){const refs=[];const walk=v=>{if(typeof v==="string"){const m=/^cotal:(sha256:[0-9a-f]{64})$/.exec(v);if(m)refs.push(m[1])}else if(Array.isArray(v)){for(const c of v)walk(c)}else if(v!==null&&typeof v==="object"){for(const c of Object.values(v))walk(c)}};walk(JSON.parse(dec3.decode(bytes)));return refs}var RESOLVE_MAX_INFLIGHT_READS=32;async function pooled(items,limit,work){const out=new Array(items.length);let next=0;const worker=async()=>{for(;;){const i=next++;if(i>=items.length)return;try{out[i]=await work(items[i])}catch(e){next=items.length;throw e}}};await Promise.all(Array.from({length:Math.min(limit,items.length)},worker));return out}async function resolveService(nc,space2,endpoint,caller,opts={}){if(opts.commands!==void 0){if(!Array.isArray(opts.commands)||opts.commands.length===0)throw new EpEnvelopeError("failed-precondition","commands must be a non-empty array when a resolve is narrowed");for(const command of opts.commands){try{assertCommandToken(command)}catch(e){throw new EpEnvelopeError("failed-precondition",`invalid requested command: ${e.message}`)}}}if(opts.optionalCommands!==void 0){if(!Array.isArray(opts.optionalCommands)||opts.optionalCommands.length===0)throw new EpEnvelopeError("failed-precondition","optionalCommands must be a non-empty array when supplied");for(const command of opts.optionalCommands){try{assertCommandToken(command)}catch(e){throw new EpEnvelopeError("failed-precondition",`invalid optional command: ${e.message}`)}}}const startedAt2=performance.now();const deadlineMs=opts.deadlineMs??1e4;const{answer,responder}=await describeEndpoint(nc,space2,endpoint,caller,{...opts,deadlineMs});const store=await contractStoreContext(nc,space2);const visible=new Set(answer.descriptor.clusters.flatMap(cl=>cl.commands));const requested=opts.commands===void 0?visible:new Set(opts.commands);const optional2=new Set(opts.optionalCommands);for(const command of requested){if(visible.has(command))continue;if(optional2.has(command)){requested.delete(command);continue}throw new EpEnvelopeError("not-found",`command "${command}" is not in ${endpoint}'s visible surface; describe lists ${[...visible].sort().join(", ")||"(none)"}`)}const artifactMemo=new Map;const walk=()=>{const walkBudgetMs=Math.floor(deadlineMs-(performance.now()-startedAt2));if(walkBudgetMs<=0)throw new EpEnvelopeError("deadline-exceeded",`resolving ${endpoint} exhausted its ${deadlineMs}ms deadline before a contract-store read`);return{artifactMemo,walkBudgetMs,...opts.signal?{signal:opts.signal}:{}}};const clusters=answer.descriptor.clusters.filter(cl=>cl.commands.some(command=>requested.has(command)));const docs=await pooled(clusters,RESOLVE_MAX_INFLIGHT_READS,cl=>{opts.signal?.throwIfAborted();return fetchClusterDocument(store,cl.digest,walk())});const declared=docs.flatMap(doc=>doc.commands).filter(cmd=>requested.has(cmd.name));const resolved=await pooled(declared,Math.max(1,RESOLVE_MAX_INFLIGHT_READS>>1),async cmd=>{opts.signal?.throwIfAborted();const[input,output]=await Promise.all([recompileClosure(store,cmd.inputDigest,walk()),recompileClosure(store,cmd.outputDigest,walk())]);return{command:cmd.name,contract:{input,output},class:cmd.class,targeted:cmd.targeted,modes:cmd.modes??[],capability:cmd.capability,...cmd.action?{action:true}:{}}});opts.signal?.throwIfAborted();const commands=new Map;for(const rc of resolved)commands.set(rc.command,rc);return{endpoint:answer.descriptor.endpoint,owner:answer.descriptor.owner,caller,responder,commands,...opts.instanceId!==void 0?{pinnedInstanceId:opts.instanceId}:{}}}function submitAndFollowGoal(nc,space2,endpoint,caller,deadlineMs,submit,opts){return submitAndFollowGoalWith(parseGoalResultFact,nc,space2,endpoint,caller,deadlineMs,submit,opts)}async function registryListingCaller(nc,space2,caller,credential){if(isIssuedCaller(caller))return caller;if(credential.exp===void 0)return void 0;try{return await issuedCallerOfToken(nc,space2,listingAcceptedToken(credential.connId,credential.exp),caller)}catch(e){if(isPermissionDenied(e))return void 0;throw e}}async function listRegistryEndpoints(space2,describe3,ask,input,opts={}){const deadline=Date.now()+(opts.deadlineMs??1e4);const ours=REGISTRY_CONTRACTS[REGISTRY_ENDPOINTS_COMMAND];let reply;for(let attempt=0;attempt<=BIND_SPLIT_REISSUES&&Date.now()<deadline;attempt++){const service=await describe3(deadline-Date.now(),opts.signal);const theirs=service.commands.get(REGISTRY_ENDPOINTS_COMMAND).contract;if(theirs.input.closureDigest!==ours.input.closureDigest||theirs.output.closureDigest!==ours.output.closureDigest)throw new EpEnvelopeError("contract-mismatch",`the registry serves a version of "${REGISTRY_ENDPOINTS_COMMAND}" this client does not implement; upgrade the client (SPEC 13.20)`);try{reply=await invokeCommand(ask.nc,space2,service,REGISTRY_ENDPOINTS_COMMAND,{...input},{deadlineMs:deadline-Date.now(),signal:opts.signal,...ask.caller?{caller:ask.caller}:{}})}catch(e){if(ask.caller!==void 0&&e instanceof EpEnvelopeError&&e.code==="permission-denied"&&e.outcome==="not-executed")return{unbound:true};throw e}if(reply.reply.ok!==false||!replyRefusedBeforeEffect(reply.reply.error))break}if(reply===void 0)throw new EpEnvelopeError("deadline-exceeded","the registry was not reached before the deadline");return{reply,...reply.reply.ok===true?{page:reply.reply.data}:{}}}var dec5=new TextDecoder;var enc5=new TextEncoder;var import_jetstream16=__toESM(require_mod4(),1);var import_kv8=__toESM(require_mod6(),1);var import_transport_node15=__toESM(require_transport_node(),1);var import_jetstream17=__toESM(require_mod4(),1);var import_transport_node16=__toESM(require_transport_node(),1);var import_kv9=__toESM(require_mod6(),1);var DEFAULT_FIELDS={replay:true,replayWindow:true,deliveryClass:true};var CHANNEL_FIELDS={...DEFAULT_FIELDS,description:true,instructions:true};var import_jetstream18=__toESM(require_mod4(),1);var enc6=new TextEncoder;var dec6=new TextDecoder;var mintGuardClearance=claimGuardClearanceMint();var TRAIT_SELECTORS=Object.freeze(["cluster","command","attribute","event"]);var import_jetstream19=__toESM(require_mod4(),1);var import_transport_node17=__toESM(require_transport_node(),1);var import_jetstream20=__toESM(require_mod4(),1);var import_transport_node18=__toESM(require_transport_node(),1);var COMMON_FIELDS=["v","executor","attemptId","ts","phase"];var PHASE_FIELDS={claimed:COMMON_FIELDS,launching:[...COMMON_FIELDS,"addr"],launched:[...COMMON_FIELDS,"addr"],settled:[...COMMON_FIELDS,"addr"]};var BASE=["v","ts","state","claimant"];var STATE_FIELDS={claimed:BASE,launching:[...BASE,"lifecycleUid","launchAttemptId","executor"],live:[...BASE,"lifecycleUid","runtimeOwner"],preserved:[...BASE,"lifecycleUid","runtimeOwner"],relaunching:[...BASE,"lifecycleUid","launchAttemptId","executor"],draining:[...BASE,"lifecycleUid","runtimeOwner","enteredAt"],released:BASE};var HANDLE_MAX_LIVE_TTL_MS=24*60*60*1e3;var HANDLE_MAX_STURDY_TTL_MS=30*24*60*60*1e3;var HANDLE_MAX_BYTES=64*1024;var SESSION_GRANT_MAX_TTL_MS=24*60*60*1e3;var SESSION_GRANT_MAX_BYTES=16*1024;var SESSION_TERMINAL_STATES=Object.freeze(["closed","expired","superseded","retired"]);var TERMINAL_STATE_SNAP=new Set(SESSION_TERMINAL_STATES);var MAX_B64_CHARS=4*1024*1024;var B64_ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var B64_INV=(()=>{const m=new Int16Array(128).fill(-1);for(let i=0;i<B64_ALPHABET.length;i++)m[B64_ALPHABET.charCodeAt(i)]=i;return m})();var import_jetstream21=__toESM(require_mod4(),1);var RENEW_AT_FRACTION=1/3;var OVERLAP_MS=10*60*1e3;function presenceAges(p,now){return{conditionSince:ageAt(now,p.condition?.since),statusSince:ageAt(now,p.statusSince),activitySince:p.activity?ageAt(now,p.activitySince):void 0,activeAt:ageAt(now,p.activeAt)}}function formatAge(ms){const s=Math.floor(ms/1e3);if(s<60)return`${s}s`;if(s<3600)return`${Math.floor(s/60)}m`;if(s<86400)return`${Math.floor(s/3600)}h`;return`${Math.floor(s/86400)}d`}function ageAt(now,at){if(typeof at!=="number"||!Number.isFinite(at))return void 0;return Math.max(0,now-at)}function oneLine(text2){return text2.replace(/[\p{Cc}\p{Cf}\p{Default_Ignorable_Code_Point}\p{Zl}\p{Zp}]/gu,c=>{let escaped="";for(let i=0;i<c.length;i++)escaped+=`\\u${c.charCodeAt(i).toString(16).padStart(4,"0")}`;return escaped})}var PRESENCE_TEXT_MAX=200;function presenceText(text2){const shown=Array.from(text2,oneLine);const width=s=>[...s].length;if(shown.reduce((n2,s)=>n2+width(s),0)<=PRESENCE_TEXT_MAX)return shown.join("");let kept="";let n=0;for(const s of shown){n+=width(s);if(n>PRESENCE_TEXT_MAX-1)break;kept+=s}return`${kept}\u2026`}function parseJoinLink(link){const tls=link.startsWith("cotals://");if(!tls&&!link.startsWith("cotal://"))throw new Error(`not a Cotal link (expected cotal:// or cotals://): ${link}`);const u=new URL(link.replace(/^cotals?:\/\//,tls?"https://":"http://"));if(!u.hostname)throw new Error(`Cotal link has no host: ${link}`);const space2=decodeURIComponent(u.pathname.replace(/^\/+/,"").split("/")[0]??"");if(!space2)throw new Error(`Cotal link has no space (cotal://host/<space>): ${link}`);const chParam=u.searchParams.get("channels")??u.searchParams.get("channel");const channels=chParam?chParam.split(",").map(s=>s.trim()).filter(Boolean):void 0;const user=u.username?decodeURIComponent(u.username):void 0;const pass=u.password?decodeURIComponent(u.password):void 0;return{servers:`nats://${u.hostname}:${u.port||"4222"}`,space:space2,channels,tls,token:user&&!pass?user:void 0,user:pass?user:void 0,pass:pass||void 0}}function brokerUrlHasUserinfo(servers){return servers.split(",").some(entry=>/^[^:/?#]+:\/\/[^/?#]*@/.test(entry.includes("://")?entry.trim():`nats://${entry.trim()}`))}var import_nkeys10=__toESM(require_mod(),1);var import_nkeys11=__toESM(require_mod(),1);var import_transport_node19=__toESM(require_transport_node(),1);var import_kv10=__toESM(require_mod6(),1);var import_node_fs5=require("node:fs");var import_node_path3=require("node:path");function ensureDirNoSymlink(parent,...segments){let dir=parent;for(const seg of segments){dir=(0,import_node_path3.join)(dir,seg);let st;try{st=(0,import_node_fs5.lstatSync)(dir)}catch(e){if(e.code==="ENOENT"){(0,import_node_fs5.mkdirSync)(dir,{mode:448});continue}throw e}if(st.isSymbolicLink())throw new Error(`refusing to write under "${dir}": it is a symlink`);if(!st.isDirectory())throw new Error(`refusing to write under "${dir}": not a directory`)}return dir}var import_node_fs6=require("node:fs");var LAUNCH_MATERIAL_ENV="COTAL_LAUNCH_MATERIAL";function readLaunchMaterial(path){let raw;try{if(process.platform!=="win32"){const mode=(0,import_node_fs6.statSync)(path).mode&511;if(mode&63)throw new Error(`is readable beyond its owner (mode ${mode.toString(8)}) - refusing to read connection material out of a file other local users can open`)}raw=(0,import_node_fs6.readFileSync)(path,"utf8")}catch(e){throw new Error(`launch material: cannot read ${path} (${e instanceof Error?e.message:String(e)})`)}let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error(`launch material: ${path} is not valid JSON`)}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))throw new Error(`launch material: ${path} must contain a JSON object`);return validate(parsed,path)}function validate(raw,path){const material={};const str2=key=>{const v=raw[key];if(v===void 0)return;if(typeof v!=="string"||!v.trim())throw new Error(`launch material: ${path} has a ${key} that is not a non-empty string`);material[key]=v};str2("servers");str2("creds");str2("token");str2("controlToken");if(raw.eventsRequired!==void 0){if(raw.eventsRequired!==true)throw new Error(`launch material: ${path} has eventsRequired that is not exactly true`);material.eventsRequired=true}if(raw.userAuth!==void 0){const u=raw.userAuth;if(typeof u!=="object"||u===null||Array.isArray(u))throw new Error(`launch material: ${path} has a userAuth that is not an object`);const{owner:owner2,actor:actor2,sentinelCredsPath,bearerCmd}=u;const named={owner:owner2,actor:actor2,sentinelCredsPath};for(const[k,v]of Object.entries(named))if(typeof v!=="string"||!v.trim())throw new Error(`launch material: ${path} has a userAuth.${k} that is not a non-empty string`);if(!Array.isArray(bearerCmd)||bearerCmd.length===0||!bearerCmd.every(a=>typeof a==="string"&&a))throw new Error(`launch material: ${path} has a userAuth.bearerCmd that is not a non-empty array of strings`);material.userAuth={owner:owner2,actor:actor2,sentinelCredsPath,bearerCmd}}if(Object.keys(material).length===0)throw new Error(`launch material: ${path} carries nothing this reader recognises. A launch that references material and supplies none is a broken launcher, not an open-mode launch, so it is refused rather than defaulted.`);return material}var import_transport_node20=__toESM(require_transport_node(),1);var import_jetstream22=__toESM(require_mod4(),1);var import_kv11=__toESM(require_mod6(),1);var import_node_net2=require("node:net");var LOOPBACK=new import_node_net2.BlockList;LOOPBACK.addSubnet("127.0.0.0",8,"ipv4");LOOPBACK.addAddress("::1","ipv6");var TARGET_FIELDS=["space","owner","actor","lifecycleUid"];var STRING_FIELDS=[...TARGET_FIELDS,"kind","server","authProvider","exchangeUrl","sentinelCreds","actorToken"];var LIST_FIELDS=["subscribe","allowSubscribe","allowPublish"];var FIELDS=new Set([...STRING_FIELDS,...LIST_FIELDS,"tlsRequired","idp","policy"]);var import_node_async_hooks=require("node:async_hooks");function claims(ext){return[ext.name,...ext.aliases??[]].map(word=>`${ext.kind}:${word}`)}var Registry=class{#byKey=new Map;#providers=new Map;#aliases=new Map;#stage=new import_node_async_hooks.AsyncLocalStorage;register(...exts){const stage=this.#stage.getStore();const taken=this.#claimed();for(const staged of stage?.values()??[])for(const key of claims(staged))taken.add(key);for(const ext of exts){for(const key of claims(ext)){if(taken.has(key))throw new Error(`extension already registered: ${key}`);taken.add(key)}}if(stage)for(const ext of exts)stage.set(`${ext.kind}:${ext.name}`,ext);else this.#publish(exts)}#claimed(){return new Set([...this.#byKey.keys(),...this.#aliases.keys()])}#publish(exts){for(const ext of exts){const key=`${ext.kind}:${ext.name}`;this.#byKey.set(key,ext);for(const alias of claims(ext).slice(1))this.#aliases.set(alias,key)}}unregister(kind,name){const key=`${kind}:${name}`;const ext=this.#byKey.get(key);if(!ext)return false;for(const alias of claims(ext).slice(1))this.#aliases.delete(alias);return this.#byKey.delete(key)}async runStaged(load){const stage=new Map;const value=await this.#stage.run(stage,load);return{value,staged:[...stage.values()]}}commitStaged(staged){const taken=this.#claimed();for(const ext of staged)for(const key of claims(ext))if(taken.has(key))throw new Error(`extension already registered: ${key}`);this.#publish(staged)}has(kind,name){return this.#byKey.has(this.#canonical(kind,name))}#canonical(kind,word){const key=`${kind}:${word}`;return this.#aliases.get(key)??key}resolve(kind,name){const ext=this.#byKey.get(this.#canonical(kind,name));if(!ext){if(this.#providers.has(`${kind}:${name}`))throw new Error(`${kind} "${name}" is declared by a provider this process has not loaded`);throw new Error(`no ${kind} registered for "${name}"`)}return ext}provide(provider){const keys=provider.provides.map(ref=>`${ref.kind}:${ref.name}`);for(const key of keys)if(this.#providers.has(key))throw new Error(`extension provider already declared: ${key}`);const entry={provider};for(const key of keys)this.#providers.set(key,entry)}provides(kind,name){return this.#providers.has(`${kind}:${name}`)}async load(kind,name){const entry=this.#providers.get(`${kind}:${name}`);if(entry){entry.loading??=entry.provider.load();await entry.loading;if(!this.#byKey.has(this.#canonical(kind,name)))throw new Error(`the provider declared for ${kind} "${name}" loaded without registering it`)}return this.resolve(kind,name)}all(kind){const values=[...this.#byKey.values()];return kind===void 0?values:values.filter(e=>e.kind===kind)}};var registry3=new Registry;var import_node_child_process2=require("node:child_process");function bearerCommandFailure(err3,stderr,timeoutMs,stdout=""){const said=stderr.trim();const retryAfter=/^retry-after (\d+)$/.exec(stdout.trim());if(said)return Object.assign(new Error(said),retryAfter?{retryAfterSeconds:Number(retryAfter[1])}:{});if(err3.killed)return new Error(`the bearer command timed out after ${timeoutMs}ms`);if(err3.signal)return new Error(`the bearer command was killed by ${err3.signal}`);if(typeof err3.code==="number")return new Error(`the bearer command exited with code ${err3.code} and printed nothing`);return new Error(err3.message)}function runAgentBearer(argv,opts={}){const timeoutMs=opts.timeoutMs??3e4;return new Promise((resolve,reject)=>{(0,import_node_child_process2.execFile)(argv[0],argv.slice(1),{timeout:timeoutMs,maxBuffer:64*1024,env:opts.env,signal:opts.signal},(err3,stdout,stderr)=>err3?reject(bearerCommandFailure(err3,stderr,timeoutMs,stdout)):resolve(stdout.trim()))})}var EVENT_CHANNEL_PREFIX="events.";function eventChannel(principal){return`${EVENT_CHANNEL_PREFIX}${principalKey(principal.owner,principal.actor).key}`}function eventChannelPrincipal(channel){if(typeof channel!=="string"||!channel.startsWith(EVENT_CHANNEL_PREFIX))return null;const principal=parsePrincipalKey(channel.slice(EVENT_CHANNEL_PREFIX.length));if(principal===null)return null;return eventChannel(principal)===channel?principal:null}var SELECTION_MAX_ITEMS=32;var order=(a,b)=>a<b?-1:a>b?1:0;function fail2(message){throw new Error(`conversation selection: ${message}`)}function record2(value,keys,what){if(!value||typeof value!=="object"||Array.isArray(value))fail2(`${what} must be an object`);const found=Object.keys(value);if(found.length!==keys.length||keys.some(k=>!found.includes(k)))fail2(`${what} must have exactly ${keys.join(", ")}`);return value}function list(value,what,max=Infinity){if(!Array.isArray(value))fail2(`${what} must be an array`);if(value.length>max)fail2(`${what} has ${value.length} entries; at most ${max} are allowed`);return value}function checkConversationSelection(value){const s=record2(value,["v","channels","role","capabilities","endpoints"],"selection");if(s.v!==1)fail2("v must be 1");const channels=list(s.channels,"channels",SELECTION_MAX_ITEMS).map(raw=>{const c=record2(raw,["channel","access"],"a channel entry");if(typeof c.channel!=="string")fail2("a channel must be a string");assertValidChannel(c.channel);if(c.access!=="read"&&c.access!=="read-post")fail2(`channel "${c.channel}" access must be "read" or "read-post"`);return{channel:c.channel,access:c.access}});if(s.role!==null&&typeof s.role!=="string")fail2("role must be a role token or null");const role=s.role===null?null:assertValidRole(s.role);const capabilities=list(s.capabilities,"capabilities").map(item=>{if(item!=="run"&&item!=="spawn"&&!(typeof item==="string"&&item.startsWith("role:")))fail2(`capability ${JSON.stringify(item)} is not run, spawn or role:<role>`);const capability=item;if(capability.startsWith("role:"))assertValidRole(capability.slice(5));return capability});const roles=capabilities.filter(c=>c.startsWith("role:"));if(role===null?roles.length!==0:roles.length!==1||roles[0]!==`role:${role}`)fail2("role must be set exactly when its role:<role> capability is selected, and no other role:<r> is allowed");if(list(s.endpoints,"endpoints").length)fail2("endpoint selection is not available in selection v1, so endpoints must be empty");const ascending=(keys,what)=>{for(let i=1;i<keys.length;i++)if(order(keys[i-1],keys[i])>=0)fail2(`${what} must be unique and in ascending order`)};ascending(channels.map(c=>c.channel),"channels");ascending(capabilities,"capabilities");if(!channels.length&&!capabilities.length)fail2("it selects nothing; leave it out to connect with only your own event channel");return{v:1,channels,role,capabilities,endpoints:[]}}function conversationSelection(input){const capabilities=[...input.capabilities??[],...input.role!==void 0?[`role:${input.role}`]:[]];return checkConversationSelection({v:1,channels:[...input.channels??[]].sort((a,b)=>order(a.channel,b.channel)),role:input.role??null,capabilities:capabilities.sort(order),endpoints:[]})}var EMPTY_CONVERSATION_SELECTION=Object.freeze({v:1,channels:Object.freeze([]),role:null,capabilities:Object.freeze([]),endpoints:Object.freeze([])});function managerCallerBinding(bearer,expected){let payload;try{const parts=bearer.split(".");if(parts.length!==3)throw new Error("invalid JWT");payload=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(fromBase64url(parts[1])))}catch{throw new Error("manager control exchange returned an invalid bearer")}const act=payload?.act;if(!act||act.view!=="manager-caller"||payload.sub!==expected.owner||act.owner!==expected.owner||act.actor!==expected.actor||act.lifecycleUid!==expected.lifecycleUid||!(payload.aud===expected.space||Array.isArray(payload.aud)&&payload.aud.length===1&&payload.aud[0]===expected.space))throw new Error("manager control exchange returned different space, principal, lifecycle or view coordinates");if(typeof act.managerInstanceId!=="string")throw new Error("manager control exchange returned no concrete manager instance");const instanceId=assertLifecycleToken(act.managerInstanceId,"managerInstanceId");if(expected.instanceId!==void 0&&instanceId!==expected.instanceId)throw new Error("manager control exchange selected a different manager instance");return{caller:{owner:expected.owner,actor:expected.actor,uid:expected.lifecycleUid},instanceId,...typeof act.credentialId==="string"?{credentialId:act.credentialId}:{}}}var DELEGATED_RECOVERY_REASONS=Object.freeze(["provider-unknown","store-unavailable","authority-unavailable","identity-unverified","descriptor-incomplete","retiring","authority-drift","identity-changed","scope-changed"]);function partText(p){if(p.kind==="text")return p.text;if(p.kind==="artifact")return`[artifact ${p.name} (${p.mediaType}, ${p.size} bytes) ${p.digest}]`;if(p.kind==="data"){const encoded=JSON.stringify(p.data);return encoded===void 0?`[empty data part]`:encoded}if(registry3.has("part-renderer",p.kind)){const renderer=registry3.resolve("part-renderer",p.kind);try{return renderer.render(p)}catch(e){return`[part renderer for ${JSON.stringify(p.kind)} failed: ${e.message}]`}}return`[unrenderable part kind ${JSON.stringify(p.kind)} \u2014 no renderer for it on this surface]`}function partsToText(parts){return parts.map(partText).join(" ")}var AGUI_FRAME_KIND="ag-ui.frame";var AGUI_EVENT_TYPE=Object.freeze({RUN_STARTED:"RUN_STARTED",RUN_FINISHED:"RUN_FINISHED",RUN_ERROR:"RUN_ERROR",TEXT_MESSAGE_START:"TEXT_MESSAGE_START",TEXT_MESSAGE_CONTENT:"TEXT_MESSAGE_CONTENT",TEXT_MESSAGE_END:"TEXT_MESSAGE_END",TOOL_CALL_START:"TOOL_CALL_START",TOOL_CALL_ARGS:"TOOL_CALL_ARGS",TOOL_CALL_END:"TOOL_CALL_END",TOOL_CALL_RESULT:"TOOL_CALL_RESULT",REASONING_MESSAGE_START:"REASONING_MESSAGE_START",REASONING_MESSAGE_CONTENT:"REASONING_MESSAGE_CONTENT",REASONING_MESSAGE_END:"REASONING_MESSAGE_END",CUSTOM:"CUSTOM"});function isAguiFramePart(part){if(typeof part!=="object"||part===null)return false;try{return part.kind===AGUI_FRAME_KIND}catch{return false}}var TURN_INPUT_SCHEMA=deepFreeze({type:"object",additionalProperties:false,required:["payload"],oneOf:[{required:["deadlineMs"]},{required:["deadlineAt"]}],properties:{payload:{type:"string",minLength:1,maxLength:65536},deadlineMs:{type:"integer",minimum:1},deadlineAt:{type:"integer",minimum:1},handoffFrom:{type:"string",minLength:1,maxLength:200}}});var TURN_OUTPUT_SCHEMA=deepFreeze({type:"object",additionalProperties:false,required:["name","owner","actor","uid","goalId","fingerprint","deadlineAt","executor"],properties:{name:{type:"string"},owner:{type:"string"},actor:{type:"string"},uid:{type:"string"},goalId:{type:"string"},fingerprint:{type:"string"},deadlineAt:{type:"integer",minimum:1},executor:{type:"object",additionalProperties:false,required:["lifecycleUid","epoch"],properties:{lifecycleUid:{type:"string"},epoch:{type:"integer",minimum:0}}}}});var TURN_YIELD_OUTPUT_SCHEMA=deepFreeze({type:"object",additionalProperties:false,required:["goalId","state"],properties:{goalId:{type:"string"},state:{enum:["succeeded","failed","cancelled","expired","uncertain"]}}});var CANCEL_INPUT_SCHEMA=deepFreeze({type:"object",additionalProperties:false,required:["goalId"],properties:{goalId:{type:"string",minLength:1},mode:{enum:["graceful","terminate"]}}});function deepFreeze(v){if(v!==null&&typeof v==="object"){for(const child of Object.values(v))deepFreeze(child);Object.freeze(v)}return v}var TURN_NOTICE_NONCE="turn-pending-notice-v1";function turnNoticeFilter(space2,instanceId,seat){return[spacePrefix(space2),...epPlaneTokens(seat),"reply",endpointToken("manager"),assertLifecycleToken(instanceId,"instanceId"),"*",...callerRailTokens(seat),TURN_NOTICE_NONCE].join(".")}function renderOnceTask(t){let context=t.payload;try{const p=JSON.parse(t.payload);if(typeof p.context==="string")context=p.context}catch{}const from=t.spawner??"your spawner";const deadline=t.deadlineAt!==void 0?`, or at ${new Date(t.deadlineAt).toISOString()} if you are still working then`:"";return`\u{1F3AF} Cotal \u2014 ${from} started this seat for one task (goal ${t.goalId}):
|
|
116
|
+
`}}function tryAcquireOnce({path,nonce:nonce3,content}){if(publishAtomic(path,content)){let released=false;return{kind:"acquired",held:{nonce:nonce3,release(){if(released)return;released=true;const found=readOwner(path);if(found?.owner?.nonce===nonce3){try{(0,import_node_fs2.unlinkSync)(path)}catch{}}}}}}const inspection=inspectLockSnapshot(path);if(inspection.state==="absent")return{kind:"retry"};if(inspection.state==="stale"){const reclaimer=reclaimStale(path,inspection.ino);return reclaimer?{kind:"reclaiming",owner:reclaimer}:{kind:"retry"}}return{kind:"held",owner:inspection.owner}}function reclaimPollMs(pollMs){return Math.min(pollMs,50)}function acquireLock(path,opts={}){const waitMs=opts.waitMs??3e5;const pollMs=opts.pollMs??200;const attempt=newAttempt(path,opts);const deadline=Date.now()+waitMs;for(;;){const result=tryAcquireOnce(attempt);if(result.kind==="acquired")return result.held;if(result.kind==="retry")continue;const left=deadline-Date.now();if(left<=0)throw lockTimeoutError(path,opts,result.owner,waitMs);sleepSync(Math.min(result.kind==="reclaiming"?reclaimPollMs(pollMs):pollMs,left))}}function lockTimeoutError(path,opts,owner2,waitMs){return opts.onTimeout?.(owner2)??new Error(`${opts.label??"a lock"} is held by a live process (pid ${owner2.pid}) and did not release within ${Math.round(waitMs/1e3)}s - retry, or if it is wedged, remove ${path}`)}var import_node_crypto3=require("node:crypto");var import_node_fs3=require("node:fs");var import_node_os=require("node:os");var import_node_path2=require("node:path");var LocalConsumerHeldError=class extends Error{};function localConsumerClaimPath(servers,space2,owner2,actor2,lifecycleUid){const user=(0,import_node_os.userInfo)();const root=process.platform==="linux"?`/tmp/cotal-consumers-${user.uid}`:(0,import_node_path2.join)(user.homedir,".cotal-consumers");(0,import_node_fs3.mkdirSync)(root,{recursive:true,mode:448});const st=(0,import_node_fs3.lstatSync)(root);if(!st.isDirectory()||st.isSymbolicLink()||process.platform!=="win32"&&(st.uid!==user.uid||(st.mode&63)!==0))throw new Error("local consumer custody directory is not private to this OS user");const targets=[...new Set(servers.split(",").map(s=>{const u=new URL(s.trim().includes("://")?s.trim():`nats://${s.trim()}`);u.username="";u.password="";if(!u.port)u.port=u.protocol==="nats:"?"4222":u.protocol==="wss:"?"443":"80";return u.href}))].sort();const key=(0,import_node_crypto3.createHash)("sha256").update(JSON.stringify([targets,space2,owner2,actor2,lifecycleUid])).digest("hex");const path=(0,import_node_path2.join)(root,`${key}.lock`);try{const file2=(0,import_node_fs3.lstatSync)(path);if(!file2.isFile()||file2.isSymbolicLink()||process.platform!=="win32"&&(file2.uid!==user.uid||(file2.mode&63)!==0))throw new Error("local consumer custody file is not private to this OS user")}catch(error51){if(error51.code!=="ENOENT")throw error51}return path}function acquireLocalConsumer(servers,space2,owner2,actor2,lifecycleUid){return acquireLock(localConsumerClaimPath(servers,space2,owner2,actor2,lifecycleUid),{waitMs:0,label:"local inbox consumer",onTimeout:()=>new LocalConsumerHeldError(`local inbox already has a consuming session for ${owner2}.${actor2} in space "${space2}"; preserve that session and choose a distinct actor for a new launch`)})}var import_nkeys2=__toESM(require_mod(),1);var ILLEGAL=/[^A-Za-z0-9_-]/g;function token(s){const t=s.trim().replace(ILLEGAL,"_");return t.length>0?t:"_"}var ROOT="cotal";function spacePrefix(space2){return`${ROOT}.${token(space2)}`}function normalizeMentions(mentions){if(!mentions?.length)return void 0;const out=[...new Set(mentions.map(m=>m.trim().toLowerCase()).filter(m=>m.length>0))];return out.length?out:void 0}function channelPath(channel){const segs=channel.split(".").map(s=>s.trim()).filter(s=>s.length>0);if(segs.length===0)return"_";return segs.map((s,i)=>{if(s===">"){if(i!==segs.length-1)throw new Error(`channel "${channel}": '>' is only valid as the last segment`);return">"}return s==="*"?"*":token(s)}).join(".")}function assertValidRole(role){if(typeof role!=="string"||!/^[A-Za-z0-9_-]+$/.test(role))throw new Error(`invalid role "${role}": must be a single NATS-safe token ([A-Za-z0-9_-]) - a role is an address, so it is rejected rather than silently rewritten`);return role}function routeToken(s){return s==="*"?"*":assertValidRole(s)}function ownerToken(s){return s==="*"?"*":assertValidOwnerToken(s)}function chatSubject(space2,owner2,actor2,channel){return`${spacePrefix(space2)}.chat.${ownerToken(owner2)}.${ownerToken(actor2)}.${channelPath(channel)}`}function isConcreteChannel(channel){return!channel.split(".").some(s=>s.trim()==="*"||s.trim()===">")}function isChannelFamily(channel){const segs=channel.split(".");return channel.length<=MAX_CHANNEL_LENGTH&&segs.length>=2&&segs[segs.length-1]===">"&&segs.slice(0,-1).every(s=>/^[A-Za-z0-9_-]+$/.test(s))}function familiesCovering(channel){const segs=channel.split(".");return segs.slice(1).map((_,i)=>`${segs.slice(0,i+1).join(".")}.>`)}function subjectMatches(pattern,subject){const p=pattern.split(".");const s=subject.split(".");for(let i=0;i<p.length;i++){if(p[i]===">")return i<s.length;if(i>=s.length)return false;if(p[i]==="*")continue;if(p[i]!==s[i])return false}return p.length===s.length}function assertValidChannel(channel){if(channel.length>MAX_CHANNEL_LENGTH)throw new Error(`invalid channel "${channel.slice(0,32)}\u2026": ${channel.length} characters exceeds the ${MAX_CHANNEL_LENGTH}-character limit (every grant line a channel mints rides the CONNECT line)`);const segs=channel.split(".");if(!channel.length||segs.some(s=>s.length===0))throw new Error(`invalid channel "${channel}": empty segment (no leading/trailing/double dots)`);segs.forEach((s,i)=>{if(s===">"){if(i!==segs.length-1)throw new Error(`invalid channel "${channel}": '>' is only valid as the last segment`);return}if(s==="*")return;if(!/^[A-Za-z0-9_-]+$/.test(s))throw new Error(`invalid channel "${channel}": segment "${s}" must be a NATS-safe token ([A-Za-z0-9_-])${/[*>]/.test(s)?", '*', or '>'":""} - policy channel names can't contain characters the wire layer would rewrite`)});return channel}var MAX_CHANNEL_LENGTH=4096;function assertValidOwnerToken(owner2){if(typeof owner2!=="string"||!/^[A-Za-z0-9_]+$/.test(owner2))throw new Error(`invalid owner/actor token "${owner2}": must be a single NATS-safe token ([A-Za-z0-9_]) - no dots, '*', '>', or '-'. A separator or wildcard in an id is lane breakout or aliasing, and '-' is reserved as the principal name-form separator, so it is rejected rather than silently rewritten.`);return owner2}function principalKey(owner2,actor2){assertValidOwnerToken(owner2);assertValidOwnerToken(actor2);return{key:`${owner2}.${actor2}`,name:`${owner2}-${actor2}`}}var LIFECYCLE_TOKEN=/^[a-z0-9]{26,32}$/;function assertLifecycleToken(v,what="lifecycleUid"){if(!LIFECYCLE_TOKEN.test(v))throw new Error(`${what} "${v}" is not a valid lifecycle token ([a-z0-9]{26,32})`);return v}function mintLifecycleUid(){return assertLifecycleToken(BigInt(`0x${Array.from(globalThis.crypto.getRandomValues(new Uint8Array(20)),b=>b.toString(16).padStart(2,"0")).join("")}`).toString(36).padStart(26,"0"))}function lifecycleNameKey(owner2,actor2,lifecycleUid){return`${principalKey(owner2,actor2).name}-${assertLifecycleToken(lifecycleUid)}`}function parseLifecycleSubjectKey(key){if(typeof key!=="string")return null;const parts=key.split(".");if(parts.length!==3)return null;const[owner2,actor2,uid2]=parts;if(!/^[A-Za-z0-9_]+$/.test(owner2)||!/^[A-Za-z0-9_]+$/.test(actor2)||!LIFECYCLE_TOKEN.test(uid2))return null;return{owner:owner2,actor:actor2,lifecycleUid:uid2}}function parsePrincipalKey(key){if(typeof key!=="string")return null;const dot=key.indexOf(".");if(dot<=0||dot>=key.length-1)return null;const owner2=key.slice(0,dot);const actor2=key.slice(dot+1);if(!/^[A-Za-z0-9_]+$/.test(owner2)||!/^[A-Za-z0-9_]+$/.test(actor2))return null;return{owner:owner2,actor:actor2}}function assertInboxConnId(connId){if(typeof connId!=="string"||!/^[A-Za-z0-9_-]{8,120}$/.test(connId))throw new Error(`invalid connId/inbox nonce ${JSON.stringify(connId)} - must match [A-Za-z0-9_-]{8,120} (no subject metacharacters; guards the _INBOX_<connId>.> grant against wildcard escalation)`);return connId}var DEV_OWNER="local";var DERIVED_OWNER_PREFIX="u_";function assertDerivedOwnerToken(owner2){if(typeof owner2!=="string"||!/^u_[a-z2-7]{26}$/.test(owner2))throw new Error(`invalid derived owner token "${owner2}": expected "${DERIVED_OWNER_PREFIX}" + 26 lowercase base32 chars ([a-z2-7]). Owner tokens are derived server-side at the auth callout and are structurally disjoint from nkeys; anything else at an owner boundary is rejected, not rewritten.`);return owner2}function assertPrincipalOwnerToken(owner2,opts={}){if(opts.allowLocal&&owner2===DEV_OWNER)return owner2;if(opts.allowPlatform&&/^p_[a-z2-7]{26}$/.test(owner2))return owner2;try{return assertDerivedOwnerToken(owner2)}catch{throw new Error(`invalid principal owner "${owner2}" at a trust boundary: expected a derived owner (u_\u2026)${opts.allowLocal?` or the reserved dev owner "${DEV_OWNER}"`:""}${opts.allowPlatform?" or a platform owner (p_\u2026)":""} - an nkey-shaped or arbitrary token is not a real owner (flip criterion 2: owners are nkey-disjoint).`)}}function isPrincipalOwnerToken(owner2,opts={allowLocal:true}){try{assertPrincipalOwnerToken(owner2,{allowLocal:opts.allowLocal??true,allowPlatform:opts.allowPlatform??false});return true}catch{return false}}function channelInAllow(allow,channel){return allow.some(a=>subjectMatches(a,channel))}function resolveReadAcl(subscribe,allowSubscribe){const allow=allowSubscribe?.length?allowSubscribe:subscribe;for(const ch of subscribe)if(!(isConcreteChannel(ch)?channelInAllow:patternInAllow)(allow,ch))throw new Error(`subscribe "${ch}" is not within allowSubscribe [${allow.join(", ")}]`);return allow}function patternCovers(cap,pattern){const c=cap.split(".");const p=pattern.split(".");if(c.slice(0,-1).includes(">")||p.slice(0,-1).includes(">"))return false;for(let i=0;i<c.length;i++){if(c[i]===">")return p.length>i;if(i>=p.length)return false;if(p[i]===">")return false;if(c[i]==="*")continue;if(p[i]==="*")return false;if(c[i]!==p[i])return false}return c.length===p.length}function patternInAllow(allow,pattern){return allow.some(a=>patternCovers(a,pattern))}function membershipInAllow(allow,channel){return isChannelFamily(channel)?patternInAllow(allow,channel):channelInAllow(allow,channel)}function unicastSubject(space2,recipOwner,recipActor,sndOwner,sndActor){return`${spacePrefix(space2)}.inst.${ownerToken(recipOwner)}.${ownerToken(recipActor)}.${ownerToken(sndOwner)}.${ownerToken(sndActor)}`}function unicastRecvFilter(space2,owner2,actor2){return`${spacePrefix(space2)}.inst.${ownerToken(owner2)}.${ownerToken(actor2)}.>`}function anycastSubject(space2,service,owner2,actor2){return`${spacePrefix(space2)}.svc.${routeToken(service)}.${ownerToken(owner2)}.${ownerToken(actor2)}`}function anycastServeFilter(space2,service){return`${spacePrefix(space2)}.svc.${routeToken(service)}.>`}var TAKE_ROUTE="take";function takeSubject(space2,role,owner2,actor2){return`${spacePrefix(space2)}.${TAKE_ROUTE}.${routeToken(role)}.${ownerToken(owner2)}.${ownerToken(actor2)}`}function takeServeFilter(space2){return`${spacePrefix(space2)}.${TAKE_ROUTE}.*.*.*`}function parseTakeSubject(subject){const parts=subject.split(".");if(parts.length!==6||parts[0]!==ROOT||parts[2]!==TAKE_ROUTE)return null;return{role:parts[3],owner:parts[4],actor:parts[5],sender:`${parts[4]}.${parts[5]}`}}function controlServiceSubject(space2,service,owner2,actor2){return`${spacePrefix(space2)}.ctl.${routeToken(service)}.${ownerToken(owner2)}.${ownerToken(actor2)}`}var CONTROL_DELIVERY="delivery";var CONTROL_DELIVERY_ADMIN="delivery-admin";var LIVENESS_ROUTE="live";function livenessSubject(space2,plane,owner2,actor2){return`${spacePrefix(space2)}.${LIVENESS_ROUTE}.${routeToken(plane)}.${ownerToken(owner2)}.${ownerToken(actor2)}`}function livenessServeFilter(space2,plane){return`${spacePrefix(space2)}.${LIVENESS_ROUTE}.${routeToken(plane)}.*.*`}function spaceWildcard(space2){return`${spacePrefix(space2)}.>`}function chatWildcard(space2){return`${spacePrefix(space2)}.chat.>`}function parseSubject(subject){const parts=subject.split(".");if(parts[0]!==ROOT)return null;const kind=parts[2];const mk=(kind2,owner2,actor2,rest)=>({kind:kind2,owner:owner2,actor:actor2,sender:`${owner2}.${actor2}`,rest});if(kind==="chat"){if(parts.length<6)return null;return mk(kind,parts[3],parts[4],parts.slice(5).join("."))}if(kind==="inst"){if(parts.length!==7)return null;return mk(kind,parts[5],parts[6],`${parts[3]}.${parts[4]}`)}if(kind==="svc"||kind==="ctl"){if(parts.length!==6)return null;return mk(kind,parts[4],parts[5],parts[3])}return null}function presenceBucket(space2){return`cotal_presence_${token(space2)}`}var PRESENCE_STATUSES={idle:true,waiting:true,working:true,offline:true};function presenceRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function presenceOptionalString(value){return value===void 0||typeof value==="string"}function isPresenceRow(value,key){return presenceRowProblem(value,key)===void 0}function presenceRowProblem(value,key){if(!presenceRecord(value))return"row";if(!presenceRecord(value.card))return"card";const card=value.card;if(typeof card.id!=="string"||card.id.length===0||card.id!==key)return"card.id";if(typeof card.name!=="string")return"card.name";if(!presenceOptionalString(card.role))return"card.role";if(typeof value.status!=="string"||!Object.hasOwn(PRESENCE_STATUSES,value.status))return"status";if(typeof value.ts!=="number"||!Number.isFinite(value.ts))return"ts";if(!presenceOptionalString(value.activity))return"activity";if(!presenceOptionalString(value.attention))return"attention";if(value.condition!==void 0){if(!presenceRecord(value.condition))return"condition";if(typeof value.condition.code!=="string")return"condition.code"}return void 0}function assertPresenceRow(value,key){const field=presenceRowProblem(value,key);if(field!==void 0)throw new TypeError(`invalid presence ${field}`)}function channelBucket(space2){return`cotal_channels_${token(space2)}`}var CHANNEL_DEFAULTS_KEY="=defaults";function membersBucket(space2){return`cotal_members_${token(space2)}`}function memberKey(channel,principal,lifecycleUid){const family=isChannelFamily(channel);if(!family&&!isConcreteChannel(assertValidChannel(channel)))throw new Error(`member key: "${channel}" must be a concrete channel or a family such as review.>`);return`${family?`${channel.slice(0,-1)}=`:channel}/${principal}.${assertLifecycleToken(lifecycleUid)}`}function parseMemberKey(key){const i=key.indexOf("/");if(i<=0||i>=key.length-1)return null;let channel=key.slice(0,i);const eq=channel.indexOf("=");if(eq!==-1){if(eq!==channel.length-1||!channel.endsWith(".="))return null;channel=`${channel.slice(0,-1)}>`}const tail=key.slice(i+1);const dot=tail.lastIndexOf(".");if(dot<=0||dot>=tail.length-1)return null;const principal=tail.slice(0,dot);const uid2=tail.slice(dot+1);if(!LIFECYCLE_TOKEN.test(uid2)||parsePrincipalKey(principal)===null)return null;return{channel,principal,lifecycleUid:uid2}}function aclBucket(space2){return`cotal_acl_${token(space2)}`}function aclKey(principal,lifecycleUid){return`${principal}.${assertLifecycleToken(lifecycleUid)}`}function aclAliasFilter(principal){return`${principal}.*`}function membershipBucket(space2){return`cotal_membership_${token(space2)}`}var MEMBERSHIP_FEED_KEY="=feed";function deliveryBucket(space2){return`cotal_delivery_${token(space2)}`}function anycastBucket(space2){return`cotal_anycast_${token(space2)}`}function leaseKey(shardIndex){return`lease.${shardIndex}`}function managerBucket(space2){return`cotal_manager_${token(space2)}`}var MANAGER_LEASE_KEY="lease";function managerLeaseKey(instanceId){return`${MANAGER_LEASE_KEY}.${instanceId}`}var MANAGER_RENEWAL_LEASE_KEY="renewal";function chatStream(space2){return`CHAT_${token(space2)}`}function dmStream(space2){return`DM_${token(space2)}`}function taskStream(space2){return`TASK_${token(space2)}`}function inboxStream(space2){return`INBOX_${token(space2)}`}function dlvStream(space2){return`DLV_${token(space2)}`}function dinboxSubject(space2,owner2,actor2,lifecycleUid){return`${spacePrefix(space2)}.dinbox.${ownerToken(owner2)}.${ownerToken(actor2)}.${assertLifecycleToken(lifecycleUid)}`}function dlvSubject(space2,owner2,actor2,lifecycleUid){return`${spacePrefix(space2)}.dlv.${ownerToken(owner2)}.${ownerToken(actor2)}.${assertLifecycleToken(lifecycleUid)}`}function parseDinboxPrincipal(subject){const parts=subject.split(".");return parts.length===6&&parts[0]===ROOT&&parts[2]==="dinbox"&&LIFECYCLE_TOKEN.test(parts[5])?{owner:parts[3],actor:parts[4],lifecycleUid:parts[5]}:null}function dlvDurable(owner2,actor2,lifecycleUid){return`dlv_${lifecycleNameKey(owner2,actor2,lifecycleUid)}`}var FANOUT_DURABLE="fanout";var INBOX_READER_DURABLE="reader";function fanoutDurable(shard=0,shards=1){return shards<=1?FANOUT_DURABLE:`${FANOUT_DURABLE}_${shard}`}function readerDurable(shard=0,shards=1){return shards<=1?INBOX_READER_DURABLE:`${INBOX_READER_DURABLE}_${shard}`}function chatHistDurable(owner2,actor2,lifecycleUid){return`chathist_${lifecycleNameKey(owner2,actor2,lifecycleUid)}`}var HISTORY_READERS=8;function historyReaderConsumer(readerId,slot){if(typeof readerId!=="string"||!/^[A-Za-z0-9_-]{1,120}$/.test(readerId))throw new Error(`history reader id ${JSON.stringify(readerId)} must match [A-Za-z0-9_-]{1,120}`);if(!Number.isInteger(slot)||slot<0||slot>=HISTORY_READERS)throw new Error(`history reader slot must be an integer in [0, ${HISTORY_READERS}), received ${slot}`);return`hist_${readerId}_${slot}`}function calloutReaderId(serverId,clientId){if(typeof serverId!=="string"||!/^N[A-Z2-7]{55}$/.test(serverId))throw new Error(`history reader server id ${JSON.stringify(serverId)} is not a server public key`);if(!Number.isSafeInteger(clientId)||clientId<1)throw new Error(`history reader client id must be a positive integer, received ${JSON.stringify(clientId)}`);return`${serverId}_${clientId}`}function dmDurable(owner2,actor2,lifecycleUid){return`dm_${lifecycleNameKey(owner2,actor2,lifecycleUid)}`}function taskDurable(service){return`svc_${assertValidRole(service)}`}var RESERVED_COMMANDS=Object.freeze(["describe","cancel"]);var ENDPOINT_LABEL=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;var COMMAND=/^[a-z0-9-]{1,32}$/;var NONCE=/^[A-Za-z0-9_-]{22,64}$/;var ID=/^[A-Za-z0-9_-]{1,64}$/;var DIGEST_HEX=/^[a-f0-9]{64}$/;var EPOCH=/^(0|[1-9][0-9]*)$/;var GENERATION=/^[a-f0-9]{32}$/;function assertGeneration(generation,what="generation"){if(typeof generation!=="string"||!GENERATION.test(generation))throw new Error(`${what} is not an issued generation (32 lowercase hex characters)`);return generation}var MAX_EP_SUBJECT_BYTES=1024;function endpointToken(name){const labels=name.split(".");for(const l of labels){if(!ENDPOINT_LABEL.test(l))throw new Error(`endpoint name label "${l}" in "${name}" is not DNS-shaped ([a-z0-9]([a-z0-9-]*[a-z0-9])?)`)}const tok=labels.join("_");if(tok.length>64)throw new Error(`endpoint name token "${tok}" exceeds 64 characters`);return tok}function endpointNameOf(token2){return token2.split("_").join(".")}function assertCommandToken(command){if(!COMMAND.test(command))throw new Error(`command "${command}" is not a valid command token ([a-z0-9-]{1,32})`);return command}function assertNonce(nonce3){if(!NONCE.test(nonce3))throw new Error(`nonce is not a valid nonce token ([A-Za-z0-9_-]{22,64}; >=128 bits of CSPRNG entropy)`);return nonce3}function assertIdToken(v,what="id"){if(!ID.test(v))throw new Error(`${what} "${v}" is not a valid id token ([A-Za-z0-9_-]{1,64})`);return v}function assertPoolToken(pool){if(!COMMAND.test(pool))throw new Error(`pool "${pool}" is not a valid pool token ([a-z0-9-]{1,32})`);return pool}function assertBoundedOwner(v,what){assertValidOwnerToken(v);if(v.length>64)throw new Error(`${what} "${v}" exceeds 64 characters`);return v}function assertSized(subject){if(new TextEncoder().encode(subject).length>MAX_EP_SUBJECT_BYTES)throw new Error(`subject exceeds ${MAX_EP_SUBJECT_BYTES} bytes: ${subject.slice(0,80)}\u2026`);return subject}var EP_AUTHZ_MODES=Object.freeze(["self","owner","any","child","ledger","handle","exact"]);var AUTHZ_SET=new Set(EP_AUTHZ_MODES);function isEpAuthzMode(m){return AUTHZ_SET.has(m)}var TARGET_ARITY={self:0,owner:1,any:1,child:1,ledger:1,handle:3,exact:3};function targetTokens(target2){if(target2.mode==="self")return["self"];if(target2.mode==="handle"||target2.mode==="exact")return[target2.mode,assertBoundedOwner(target2.tOwner,"target owner"),assertBoundedOwner(target2.tActor,"target actor"),assertLifecycleToken(target2.tUid,"target lifecycleUid")];return[target2.mode,assertBoundedOwner(target2.tOwner,"target owner")]}function callerTokens(caller){return[assertBoundedOwner(caller.owner,"caller owner"),assertBoundedOwner(caller.actor,"caller actor"),assertLifecycleToken(caller.uid,"caller lifecycleUid")]}function epGoalProgressGrantRow(space2,endpoint,caller){return`${spacePrefix(space2)}.epe.${endpointToken(endpoint)}.*.*.goal.${callerTokens(caller).join(".")}.>`}function isIssuedCaller(caller){return typeof caller.generation==="string"}function callerRailTokens(caller){return isIssuedCaller(caller)?[...callerTokens(caller),assertGeneration(caller.generation,"caller generation")]:callerTokens(caller)}function epPlaneTokens(caller){return isIssuedCaller(caller)?["ep",EP_RAIL_V1]:["ep"]}var EP_RAIL_V1="v1";function requestHead(space2,plane,route,endpoint,command){const parts=[spacePrefix(space2),...plane,route.mode,endpointToken(endpoint)];if(route.mode==="inst")parts.push(route.instanceId);parts.push(assertCommandToken(command));return parts}function epRequestSubject(space2,req){const route=req.route.mode==="inst"?{mode:"inst",instanceId:assertLifecycleToken(req.route.instanceId,"instanceId")}:req.route;const parts=requestHead(space2,epPlaneTokens(req.caller),route,req.endpoint,req.command);if(req.target)parts.push(...targetTokens(req.target));parts.push(...callerRailTokens(req.caller),assertNonce(req.nonce));return assertSized(parts.join("."))}function epCallerReplyFilter(space2,caller){return`${spacePrefix(space2)}.${epPlaneTokens(caller).join(".")}.reply.*.*.*.${callerRailTokens(caller).join(".")}.*`}function epcSubject(space2,digestHex){if(!DIGEST_HEX.test(digestHex))throw new Error(`contract digest "${digestHex}" is not 64 lowercase hex chars`);return`${spacePrefix(space2)}.epc.${digestHex}`}function parseTail(parts,i,withNonce,issued=false){let target2=null;const disc=parts[i];if(disc!==void 0&&AUTHZ_SET.has(disc)){const mode=disc;const arity=TARGET_ARITY[mode];const t=parts.slice(i+1,i+1+arity);if(t.length!==arity)return null;target2=mode==="self"?{mode}:mode==="handle"||mode==="exact"?{mode,tOwner:t[0],tActor:t[1],tUid:t[2]}:{mode,tOwner:t[0]};i+=1+arity}const want=i+3+(issued?1:0)+(withNonce?1:0);if(parts.length!==want)return null;let caller={owner:parts[i],actor:parts[i+1],uid:parts[i+2]};if(issued){const generation=parts[i+3];try{assertGeneration(generation)}catch{return null}caller={...caller,generation};i+=1}return withNonce?{target:target2,caller,nonce:parts[i+3]}:{target:target2,caller}}function parseEpoch(tok){if(!EPOCH.test(tok))return null;const n=Number(tok);return Number.isSafeInteger(n)?n:null}function parseEpSubject(subject){if(new TextEncoder().encode(subject).length>MAX_EP_SUBJECT_BYTES)return null;const parts=subject.split(".");if(parts[0]!==ROOT||parts.length<4)return null;const plane=parts[2];if(plane==="ep"){const issued=parts[3]===EP_RAIL_V1;const o=issued?1:0;const route=parts[3+o];const rail=issued?{rail:EP_RAIL_V1}:{};if(route==="one"||route==="all"){if(parts.length<10+o)return null;const tail=parseTail(parts,6+o,true,issued);if(!tail)return null;return{plane:"request",...rail,route,endpoint:endpointNameOf(parts[4+o]),command:parts[5+o],target:tail.target,caller:tail.caller,nonce:tail.nonce}}if(route==="inst"){if(parts.length<11+o)return null;const tail=parseTail(parts,7+o,true,issued);if(!tail)return null;return{plane:"request",...rail,route,endpoint:endpointNameOf(parts[4+o]),instanceId:parts[5+o],command:parts[6+o],target:tail.target,caller:tail.caller,nonce:tail.nonce}}if(route==="reply"){if(parts.length!==11+2*o)return null;const epoch=parseEpoch(parts[6+o]);if(epoch===null)return null;const triple={owner:parts[7+o],actor:parts[8+o],uid:parts[9+o]};if(!issued)return{plane:"reply",endpoint:endpointNameOf(parts[4]),instanceId:parts[5],epoch,caller:triple,nonce:parts[10]};const generation=parts[11];try{assertGeneration(generation)}catch{return null}return{plane:"reply",rail:EP_RAIL_V1,endpoint:endpointNameOf(parts[5]),instanceId:parts[6],epoch,caller:{...triple,generation},nonce:parts[12]}}return null}if(plane==="epe"){if(parts.length<7)return null;const epoch=parseEpoch(parts[5]);if(epoch===null)return null;return{plane:"event",endpoint:endpointNameOf(parts[3]),instanceId:parts[4],epoch,topic:parts.slice(6)}}if(plane==="epf"){if(parts.length<5)return null;return{plane:"fact",endpoint:endpointNameOf(parts[3]),topic:parts.slice(4)}}if(plane==="epj"){if(parts.length<8)return null;const tail=parseTail(parts,5,false);if(!tail)return null;return{plane:"journal",endpoint:endpointNameOf(parts[3]),command:parts[4],target:tail.target,caller:tail.caller}}if(plane==="ept"){if(parts.length!==8)return null;const epoch=parseEpoch(parts[5]);const phase=parts[7];if(epoch===null||phase!=="schedule"&&phase!=="armed"&&phase!=="fire")return null;return{plane:"timer",endpoint:endpointNameOf(parts[3]),instanceId:parts[4],epoch,timerId:parts[6],phase}}if(plane==="epr"){if(parts.length<7)return null;const epoch=parseEpoch(parts[5]);if(epoch===null)return null;return{plane:"record",endpoint:endpointNameOf(parts[3]),instanceId:parts[4],epoch,kind:parts[6],qualifier:parts.slice(7)}}if(plane==="epc"){if(parts.length!==4||!DIGEST_HEX.test(parts[3]))return null;return{plane:"contract",digestHex:parts[3]}}if(plane==="epw"){if(parts.length!==9)return null;return{plane:"work",endpoint:endpointNameOf(parts[3]),pool:parts[4],acceptance:{owner:parts[5],actor:parts[6],uid:parts[7],id:parts[8]}}}if(plane==="eps"){if(parts.length!==7)return null;const epoch=parseEpoch(parts[5]);const dir=parts[6];if(epoch===null||dir!=="in"&&dir!=="out")return null;return{plane:"session",endpoint:endpointNameOf(parts[3]),sessionId:parts[4],epoch,dir}}return null}var import_node_crypto4=require("node:crypto");var import_json_canonicalize=__toESM(require_index_umd(),1);var DIGEST_PREFIX="sha256:";var DIGEST_RE=/^sha256:[0-9a-f]{64}$/;function isContractDigest(v){return typeof v==="string"&&DIGEST_RE.test(v)}function isWellFormedUnicode(s){return!hasLoneSurrogate(s)}function hasLoneSurrogate(s){for(let i=0;i<s.length;i++){const c=s.charCodeAt(i);if(c>=55296&&c<=56319){const n=s.charCodeAt(i+1);if(!(n>=56320&&n<=57343))return true;i++}else if(c>=56320&&c<=57343){return true}}return false}function interchangeableCopy(v,path){if(v===null)return null;switch(typeof v){case"string":if(hasLoneSurrogate(v))throw new Error(`canonicalJson: lone surrogate in string at ${path} (I-JSON violation)`);return v;case"number":if(!Number.isFinite(v))throw new Error(`canonicalJson: non-finite number at ${path}`);return v;case"boolean":return v;case"undefined":throw new Error(`canonicalJson: undefined at ${path} (strict mode never coerces to null)`);case"object":{if(Array.isArray(v)){if(Object.getPrototypeOf(v)!==Array.prototype)throw new Error(`canonicalJson: non-ordinary array at ${path} (a subclassed/exotic array canonicalizes through projections)`);const length=Object.getOwnPropertyDescriptor(v,"length")?.value;if(typeof length!=="number"||!Number.isInteger(length)||length<0)throw new Error(`canonicalJson: invalid array length at ${path} (refusing the projection)`);for(const k of Reflect.ownKeys(v)){if(typeof k!=="string")throw new Error(`canonicalJson: symbol-keyed own property on array at ${path} (invisible to canonicalization; refusing the projection)`);if(k==="length")continue;if(!/^(0|[1-9][0-9]*)$/.test(k)||Number(k)>=length)throw new Error(`canonicalJson: non-index own property "${k}" on array at ${path} (invisible to canonicalization; refusing the projection)`)}const copy2=[];for(let i=0;i<length;i++){const d=Object.getOwnPropertyDescriptor(v,i);if(d===void 0)throw new Error(`canonicalJson: hole at ${path}[${i}] (a hole would be coerced to null; refusing the projection)`);if(!d.enumerable||d.get!==void 0||d.set!==void 0)throw new Error(`canonicalJson: non-enumerable or accessor element at ${path}[${i}] (refusing the projection)`);copy2.push(interchangeableCopy(d.value,`${path}[${i}]`))}return copy2}const proto=Object.getPrototypeOf(v);if(proto!==Object.prototype&&proto!==null)throw new Error(`canonicalJson: non-plain object at ${path} (a class/exotic instance canonicalizes through projections like toJSON; only plain data objects are interchangeable)`);const copy=Object.create(null);for(const k of Reflect.ownKeys(v)){if(typeof k!=="string")throw new Error(`canonicalJson: symbol-keyed own property at ${path} (invisible to canonicalization; refusing the projection)`);if(hasLoneSurrogate(k))throw new Error(`canonicalJson: lone surrogate in key at ${path}.${k}`);const d=Object.getOwnPropertyDescriptor(v,k);if(!d.enumerable)throw new Error(`canonicalJson: non-enumerable own property "${k}" at ${path} (invisible to canonicalization; refusing the projection)`);if(d.get!==void 0||d.set!==void 0)throw new Error(`canonicalJson: accessor property "${k}" at ${path} (a getter is code, not data; refusing the projection)`);copy[k]=interchangeableCopy(d.value,`${path}.${k}`)}return copy}default:throw new Error(`canonicalJson: unsupported ${typeof v} at ${path}`)}}function canonicalJson(value){return(0,import_json_canonicalize.canonicalizeEx)(interchangeableCopy(value,"$"),{undefinedInArrayToNull:false})}function contractDigest(value){return DIGEST_PREFIX+(0,import_node_crypto4.createHash)("sha256").update(canonicalJson(value),"utf8").digest("hex")}var EP_ERROR_CODES=Object.freeze(["bad-request","unsupported-version","op-mismatch","class-mismatch","target-mismatch","sender-mismatch","unauthenticated","permission-denied","not-found","already-exists","conflict","contract-mismatch","contract-invalid","failed-precondition","deadline-exceeded","cancelled","expired","unavailable","unimplemented","resource-exhausted","internal"]);var EP_UNBOUND_RESPONDER="ai.cotal.ep.unbound-responder";function respondedButUnbound(e){return e instanceof EpEnvelopeError&&(e.details??[]).some(d=>d.kind===EP_UNBOUND_RESPONDER)}var EP_UNANSWERED="ai.cotal.ep.unanswered";function unansweredRequest(e){return e instanceof EpEnvelopeError&&(e.details??[]).some(d=>d.kind===EP_UNANSWERED)}var EP_UNDECLARED_ARG="ai.cotal.ep.undeclared-arg";var EP_BIND_REFUSED="ai.cotal.ep.bind-refused";function bindRefusalMarked(e){return(e?.details??[]).some(d=>d.kind===EP_BIND_REFUSED)}function replyRefusedBeforeEffect(e){if(!bindRefusalMarked(e))return false;return e?.outcome==="not-executed"}var EP_TARGET_UNMAPPED="ai.cotal.ep.target-unmapped";function replyTargetUnmapped(e){return e?.outcome==="not-executed"&&(e.details??[]).some(d=>d.kind===EP_TARGET_UNMAPPED)}var EP_LIFECYCLE_BLOCKED="ai.cotal.ep.lifecycle-blocked";function detailsOf(source){if(source instanceof EpEnvelopeError)return source.details;if(source&&typeof source==="object"&&Array.isArray(source.details))return source.details;return void 0}function lifecycleBlockedFrom(source){return detailsOf(source)?.find(d=>d.kind===EP_LIFECYCLE_BLOCKED)}function renderLifecycleBlocked(message,source){const d=lifecycleBlockedFrom(source);if(!d)return message;const parts=[`blockedOp=${d.blockedOp}`];for(const k of["headState","gateState","opId","remedy"]){const v=d[k];if(typeof v==="string"&&v.length>0)parts.push(`${k}=${v}`)}const suffix=`[lifecycle ${parts.join(" ")}]`;return message.includes(suffix)?message:`${message} ${suffix}`}var EpEnvelopeError=class extends Error{code;details;outcome;constructor(code,message,details,outcome){super(message);this.code=code;this.details=details;this.outcome=outcome;this.name="EpEnvelopeError"}toEpError(){return{code:this.code,message:this.message,...this.details?{details:this.details}:{},...this.outcome?{outcome:this.outcome}:{}}}};var import_jetstream2=__toESM(require_mod4(),1);var import_transport_node2=__toESM(require_transport_node(),1);var import_kv=__toESM(require_mod6(),1);var SCHEMA_PROFILE=Object.freeze({maxDocumentBytes:256*1024,maxClosureBytes:1024*1024,maxDepth:32,maxRefChain:32,compileBudgetMs:100,maxPatternChars:256,validateBudgetMs:10,compiledCacheEntries:256});var EP_ENVELOPE_V=1;var EP_ERROR_SET=new Set(EP_ERROR_CODES);var UTF8=new TextEncoder;var utf8Bytes=s=>UTF8.encode(s).length;var LABEL="[a-z0-9]([a-z0-9-]*[a-z0-9])?";var EXTENSION_CODE=new RegExp(`^${LABEL}(\\.${LABEL}){2,}$`);function isEpErrorCode(code){if(typeof code!=="string"||utf8Bytes(code)>64)return false;return EP_ERROR_SET.has(code)||EXTENSION_CODE.test(code)}function fail(code,message,outcome){throw new EpEnvelopeError(code,message,void 0,outcome)}function controlReplyFrom(reply){if(reply.ok)return{ok:true,...reply.data!==void 0?{data:reply.data}:{}};const{error:error51}=reply;return{ok:false,error:renderLifecycleBlocked(error51.message,error51),code:error51.code,...reply.data!==void 0?{data:reply.data}:{},...error51.details?{details:error51.details}:{},...error51.outcome!==void 0?{outcome:error51.outcome}:{}}}function controlReplyFromThrown(e,message){return{ok:false,error:renderLifecycleBlocked(message,e),code:e.code,...e.details?{details:e.details}:{},...e.outcome!==void 0?{outcome:e.outcome}:{}}}function asRecord(v,what){if(v===null||typeof v!=="object"||Array.isArray(v))fail("bad-request",`${what} is not a JSON object`);return v}function asString(v,what){if(typeof v!=="string"||v.length===0)fail("bad-request",`${what} is not a non-empty string`);return v}function grammar(fn){try{return fn()}catch(e){fail("bad-request",e.message)}}function assertVersion(o,what){if(o.v!==EP_ENVELOPE_V)fail("unsupported-version",`${what} envelope version ${JSON.stringify(o.v)} is not ${EP_ENVELOPE_V}`)}function pickError(v){const e=asRecord(v,"error");const code=asString(e.code,"error.code");if(!isEpErrorCode(code))fail("bad-request",`error.code ${JSON.stringify(code)} is neither a catalog token nor a reverse-DNS extension token within 64 bytes`);const message=typeof e.message==="string"?e.message:fail("bad-request","error.message is not a string");let details;if(e.details!==void 0){if(!Array.isArray(e.details))fail("bad-request","error.details is not an array");details=e.details.map((d,i)=>{const o=asRecord(d,`error.details[${i}]`);const kind=asString(o.kind,`error.details[${i}].kind`);if(!EXTENSION_CODE.test(kind))fail("bad-request",`error.details[${i}].kind "${kind}" is not reverse-DNS namespaced`);return o})}let outcome;if(e.outcome!==void 0){if(e.outcome!=="executed"&&e.outcome!=="not-executed"&&e.outcome!=="unknown")fail("bad-request",`error.outcome ${JSON.stringify(e.outcome)} is not one of executed, not-executed, unknown (SPEC 13.3)`);outcome=e.outcome}return{code,message,...details?{details}:{},...outcome?{outcome}:{}}}function parseEndpointReply(raw){const o=asRecord(raw,"reply");assertVersion(o,"reply");const id2=grammar(()=>assertIdToken(asString(o.id,"id"),"id"));if(typeof o.ok!=="boolean")fail("bad-request","ok is not a boolean");if(o.ok&&o.error!==void 0)fail("bad-request","an ok reply must not carry an error");if(!o.ok&&o.data!==void 0)fail("bad-request","a failed reply must not carry data");const reply=o.ok?{v:EP_ENVELOPE_V,id:id2,ok:true,...o.data!==void 0?{data:o.data}:{}}:{v:EP_ENVELOPE_V,id:id2,ok:false,error:pickError(o.error)};const receipt2=o.receipt===void 0?void 0:asString(o.receipt,"receipt");return{...reply,...receipt2!==void 0?{receipt:receipt2}:{}}}var cpuNow=()=>typeof process==="undefined"?void 0:process.cpuUsage();function reportValidateBudget(what,startedCpu,startedMs){if(startedCpu===void 0)return;const cpu=process.cpuUsage(startedCpu);const cpuMs=Math.round((cpu.user+cpu.system)/1e3);if(cpuMs<=SCHEMA_PROFILE.validateBudgetMs)return;console.error(`! schema: ${what} validation took ~${cpuMs}ms of process CPU (\xA713.8 reference budget ${SCHEMA_PROFILE.validateBudgetMs}ms; ${Date.now()-startedMs}ms elapsed). Approximate - process-wide CPU includes JIT/Worker threads. Not a refusal - and note that refusing HERE would not have helped: this fires after validate() completed, so the cost is already paid. Validation cost on this path is bounded by nothing pre-emptively; a byte/item bound before validate is owed.`)}function firstErrorDetail(first){if(!first)return"";const extra=typeof first.params?.additionalProperty==="string"?`: ${JSON.stringify(first.params.additionalProperty)}`:"";return`: ${first.instancePath||"/"} ${first.message??""}${extra}`}function assertArgsValid(validate2,args){const value=args===void 0?null:args;const startedCpu=cpuNow();const started=Date.now();const okValid=validate2(value);reportValidateBudget("args",startedCpu,started);if(!okValid){const first=validate2.errors?.[0];fail("bad-request",`args do not validate against the input schema${firstErrorDetail(first)}`,"not-executed")}return value}function assertOutputValid(validate2,data){const value=data===void 0?null:data;const startedCpu=cpuNow();const started=Date.now();const okValid=validate2(value);reportValidateBudget("output",startedCpu,started);if(!okValid){const first=validate2.errors?.[0];fail("internal",`output does not validate against the pinned output schema; an invalid reply is a responder bug, never success (SPEC 13.7)${firstErrorDetail(first)}`)}}function recordsBucket(space2){return`cotal_records_${token(space2)}`}var qEndpoint={name:"endpoint",assert:v=>endpointToken(v)};var qOwner=name=>({name,assert:v=>assertBoundedOwner(v,name)});var qUid=name=>({name,assert:v=>assertLifecycleToken(v,name)});var qId=name=>({name,assert:v=>assertIdToken(v,name)});var LIFECYCLE_HEAD={kind:"lifecycle",qualifiers:[qOwner("owner"),qOwner("actor")],split:false,writers:{spec:"minting-manager-commit",status:"minting-manager-commit"},mediation:"mediated"};var UID_RESERVATION={kind:"uid",qualifiers:[qUid("lifecycleUid")],split:false,writers:{spec:"minting-authority",status:"minting-authority"},mediation:"mediated"};var OBLIGATION_EP_SENTINEL="ep";var OBLIGATION={kind:"oblig",qualifiers:[{name:"targetUid",assert:v=>v===OBLIGATION_EP_SENTINEL?v:assertLifecycleToken(v,"targetUid")},qEndpoint,qOwner("cOwner"),qOwner("cActor"),qUid("cUid"),qId("id")],split:false,writers:{spec:"admission-mediator",status:"admission-mediator"},mediation:"mediated"};var POLICY_VERSION={kind:"policy",qualifiers:[qEndpoint,{name:"digestHex",assert:v=>{if(!/^[0-9a-f]{64}$/.test(v))throw new Error(`policy digest ${JSON.stringify(v)} is not 64 lowercase hex chars (SPEC 13.7)`);return v}}],split:false,writers:{spec:"provisioner-registration",status:"provisioner-registration"},mediation:"mediated"};var RETIREMENT_FRONTIER={kind:"frontier",qualifiers:[qUid("lifecycleUid")],split:false,writers:{spec:"minting-authority",status:"minting-authority"},mediation:"mediated"};var GOVERN_HEAD={kind:"govern",qualifiers:[qEndpoint],split:false,writers:{spec:"provisioner-registration",status:"provisioner-registration"},mediation:"mediated"};var RECORD_KINDS={svc:{kind:"svc",qualifiers:[qEndpoint,qUid("instanceId")],split:true,writers:{spec:"provisioner-registration",status:"instance-commit-epoch-fenced"},mediation:"mediated"},signer:{kind:"signer",qualifiers:[qId("keyId")],split:true,writers:{spec:"operator-registry",status:"operator-registry"},mediation:"mediated"},handle:{kind:"handle",qualifiers:[qId("issuerKeyId"),qId("id")],split:true,writers:{spec:"issuer-create-only",status:"issuer-or-operator-monotonic"},mediation:"mediated"},contracts:{kind:"contracts",qualifiers:[qEndpoint],split:true,writers:{spec:"instance",status:"instance"},mediation:"direct"},goal:{kind:"goal",qualifiers:[qEndpoint,qOwner("cOwner"),qOwner("cActor"),qUid("cUid"),qId("goalId")],split:true,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},goalidx:{kind:"goalidx",qualifiers:[qEndpoint,qOwner("cOwner"),qOwner("cActor"),qUid("cUid"),qId("goalId")],split:false,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},goaleff:{kind:"goaleff",qualifiers:[qEndpoint,qOwner("cOwner"),qOwner("cActor"),qUid("cUid"),qId("goalId"),qId("gen")],split:false,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},epname:{kind:"epname",qualifiers:[qEndpoint,qId("nameToken")],split:false,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},epmig:{kind:"epmig",qualifiers:[qEndpoint],split:false,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},cp:{kind:"cp",qualifiers:[qEndpoint,qId("token")],split:true,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},lease:{kind:"lease",qualifiers:[qEndpoint,{name:"pool",assert:assertPoolToken},qOwner("cOwner"),qOwner("cActor"),qUid("cUid"),qId("id")],split:true,writers:{spec:"pool-owner-lease-command",status:"pool-owner-lease-command"},mediation:"mediated"},run:{kind:"run",qualifiers:[qEndpoint,qId("runId")],split:true,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},answer:{kind:"answer",qualifiers:[qEndpoint,qId("token"),qId("answerId")],split:false,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},notice:{kind:"notice",qualifiers:[qEndpoint,qId("runId"),qId("addresseeId"),qId("noticeId")],split:true,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},program:{kind:"program",qualifiers:[qEndpoint,qId("runId")],split:false,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},migration:{kind:"migration",qualifiers:[qEndpoint,qId("runId"),qId("migrationId")],split:true,writers:{spec:"commit-path",status:"commit-path"},mediation:"mediated"},lifecycle:{kind:"lifecycle",qualifiers:[qOwner("owner"),qOwner("actor"),qUid("lifecycleUid")],split:true,writers:{spec:"minting-manager-commit",status:"minting-manager-commit"},mediation:"mediated"}};var AUTHORITY_KIND_DEFS=[LIFECYCLE_HEAD,UID_RESERVATION,GOVERN_HEAD,OBLIGATION,POLICY_VERSION,RETIREMENT_FRONTIER];function freezeDef(def){for(const q of def.qualifiers)Object.freeze(q);Object.freeze(def.qualifiers);Object.freeze(def.writers);return Object.freeze(def)}var registry2=new Map;for(const def of[...Object.values(RECORD_KINDS),...AUTHORITY_KIND_DEFS]){freezeDef(def);const list2=registry2.get(def.kind)??[];list2.push(def);registry2.set(def.kind,list2)}Object.freeze(AUTHORITY_KIND_DEFS);Object.freeze(RECORD_KINDS);var AUTHORITY_DEF_SET=new Set(AUTHORITY_KIND_DEFS);function isCasLoss(e){const code=e?.code;return code===10071||code===10164}var import_transport_node=__toESM(require_transport_node(),1);var IDEMPOTENCY_HORIZON_MS_DEFAULT=24*60*60*1e3;var RESULT_RETENTION_MS_DEFAULT=24*60*60*1e3;var RECEIPT_RETENTION_MS_DEFAULT=90*24*60*60*1e3;var import_node_crypto5=require("node:crypto");var import_jetstream=__toESM(require_mod4(),1);var dec=new TextDecoder("utf-8",{fatal:true});function assertIssuedSpace(space2){if(typeof space2!=="string"||space2.length===0||token(space2)!==space2)throw new Error("issued space must be a nonempty canonical subject token ([A-Za-z0-9_-])")}function refSnapshot(value){closed(value,["space","owner","actor","uid","generation"],"issued reference");assertIssuedSpace(value.space);callerTokens(value);assertGeneration(value.generation);return Object.freeze({space:value.space,owner:value.owner,actor:value.actor,uid:value.uid,generation:value.generation})}function closed(value,keys,label){if(value===null||typeof value!=="object"||Array.isArray(value)||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null)throw new Error(`${label} must be a plain record`);for(const key of Reflect.ownKeys(value)){if(typeof key!=="string"||!keys.includes(key))throw new Error(`${label} carries an unsupported field ${String(key)}`);if(!Object.hasOwn(Object.getOwnPropertyDescriptor(value,key),"value"))throw new Error(`${label} cannot carry accessors`)}return value}function acceptedBucket(space2){return`cotal_accepted_${token(space2)}`}function acceptedKey(acceptedToken){return`accepted.v1.${assertGeneration(acceptedToken,"accepted token")}`}async function readAcceptedRow(nc,space2,acceptedToken,timeoutMs=3e3){const bucket=acceptedBucket(space2);const response=await nc.request(`$JS.API.DIRECT.GET.KV_${bucket}.$KV.${bucket}.${acceptedKey(acceptedToken)}`,new Uint8Array(0),{timeout:timeoutMs});const status2=response.headers?.get("Status");if(status2)throw new EpEnvelopeError("permission-denied",`no accepted row for this token (${status2}); the connection holds no issued authority (SPEC 13.15)`);const row=closed(JSON.parse(dec.decode(response.data)),["version","ref"],"accepted row");if(row.version!==1)throw new Error("unsupported accepted-row version");const ref=refSnapshot(row.ref);if(ref.space!==space2)throw new EpEnvelopeError("permission-denied","the accepted row names a foreign space");return ref}async function issuedCallerOfToken(nc,space2,acceptedToken,expected){const ref=await readAcceptedRow(nc,space2,acceptedToken);if(ref.owner!==expected.owner||ref.actor!==expected.actor||ref.uid!==expected.uid)throw new EpEnvelopeError("permission-denied",`this connection's accepted row names ${ref.owner}.${ref.actor}/${ref.uid}, not the caller ${expected.owner}.${expected.actor}/${expected.uid}; refused (SPEC 13.15)`);return{owner:ref.owner,actor:ref.actor,uid:ref.uid,generation:ref.generation}}var STATIC_GENERATION_HORIZON_SEC=30*24*60*60;function subjectToken(value,pattern){if(typeof value!=="string"||value.length===0||/\s/u.test(value)||[...value].some(ch=>ch.charCodeAt(0)<32||ch.charCodeAt(0)===127))throw new Error("a subject must be nonempty without whitespace or control characters; queue-qualified forms are not a ceiling entry");const parts=value.split(".");for(let i=0;i<parts.length;i++){const part=parts[i];if(!part||part.includes("*")&&(!pattern||part!=="*")||part.includes(">")&&(!pattern||part!==">"||i!==parts.length-1))throw new Error(`subject "${value}" has an invalid token or wildcard`)}return value}function patterns(value){if(!Array.isArray(value))throw new Error("subject patterns must be an explicit array");return Object.freeze(value.map(entry=>subjectToken(entry,true)))}function permission(allow,deny){return Object.freeze({allow:Object.freeze(allow),deny})}function readIssuedSubjectPermission(value){const raw=closed(value,["allow","deny"],"subject permission");const allow=closed(raw.allow,["mode","patterns"],"subject allow");const deny=patterns(raw.deny);if(allow.mode==="all"||allow.mode==="none"){if(Object.hasOwn(allow,"patterns"))throw new Error("only patterns mode carries a patterns field");return permission({mode:allow.mode},deny)}if(allow.mode!=="patterns")throw new Error("unsupported subject allow mode");const listed=patterns(allow.patterns);if(listed.length===0)throw new Error("patterns mode requires a nonempty list");return permission({mode:"patterns",patterns:listed},deny)}function importNativeSubjectPermissions(value){const raw=closed(value,["pub","sub"],"native permissions");const direction=v=>{if(v===void 0)return permission({mode:"all"},Object.freeze([]));const r=closed(v,["allow","deny"],"native subject permission");const allow=Object.hasOwn(r,"allow")?patterns(r.allow):Object.freeze([]);const deny=Object.hasOwn(r,"deny")?patterns(r.deny):Object.freeze([]);return permission(allow.length?{mode:"patterns",patterns:allow}:{mode:"all"},deny)};for(const key of["pub","sub"])if(Object.hasOwn(raw,key)&&raw[key]===void 0)throw new Error("an explicit native direction must not be undefined");return Object.freeze({publish:direction(raw.pub),subscribe:direction(raw.sub)})}function issuedPermitsSubject(value,concrete){const parsed=readIssuedSubjectPermission(value);subjectToken(concrete,false);if(parsed.deny.some(pattern=>subjectMatches(pattern,concrete)))return false;if(parsed.allow.mode==="none")return false;return parsed.allow.mode==="all"||parsed.allow.patterns.some(pattern=>subjectMatches(pattern,concrete))}var AUTHORITY_STORE_IMMUTABLE_FLAGS=Object.freeze({allow_rollup_hdrs:false,deny_delete:true,deny_purge:true});var WRITE_ONCE_PER_KEY=Object.freeze({max_msgs_per_subject:1,discard:import_jetstream.DiscardPolicy.New,discard_new_per_subject:true});var APPEND_ONLY_PER_KEY=Object.freeze({max_msgs_per_subject:-1});var ROW_TTL_RETENTION=Object.freeze({allow_msg_ttl:true});var enc=new TextEncoder;function connectionAcceptedToken(connId){if(typeof connId!=="string"||connId.length===0)throw new Error("connectionAcceptedToken: a connection nonce is required");return(0,import_node_crypto5.createHash)("sha256").update(`cotal.accepted.v1\0${connId}`).digest("hex").slice(0,32)}function listingAcceptedToken(connId,horizon){if(typeof connId!=="string"||connId.length===0)throw new Error("listingAcceptedToken: a connection id is required");if(!Number.isSafeInteger(horizon)||horizon<=0)throw new Error("listingAcceptedToken: the horizon must be a positive unix-seconds integer");return(0,import_node_crypto5.createHash)("sha256").update(`cotal.listing.v1\0${connId}\0${horizon}`).digest("hex").slice(0,32)}async function issuedUserCaller(nc,space2,connId,expected){return issuedCallerOfToken(nc,space2,connectionAcceptedToken(connId),expected)}function admissionBucket(space2){return`cotal_admission_${token(space2)}`}var enc2=new TextEncoder;var dec2=new TextDecoder("utf-8",{fatal:true});function admissionStoreDefinition(space2){return{bucket:admissionBucket(space2),createOptions:{allow_direct:false},hardenAfterCreate:{...AUTHORITY_STORE_IMMUTABLE_FLAGS,...WRITE_ONCE_PER_KEY}}}function epcStreamName(space2){return`EPC_${token(space2)}`}function wfjStreamName(space2){return`WFJ_${token(space2)}`}function epAuthBucket(space2){return`cotal_auth_${token(space2)}`}var EP_SUBMISSION_MAX_AGE_MS=24*60*60*1e3;var EP_EVENT_MAX_AGE_MS=24*60*60*1e3;var EP_INGRESS_MAX_AGE_MS=24*60*60*1e3;var EP_TIMER_MAX_AGE_MS=31*24*60*60*1e3;var EP_AUTH_MARKER_TTL_MS=60*60*1e3;function endpointAuthorityStoreDefinitions(space2){return{records:{bucket:recordsBucket(space2),createOptions:{allow_direct:true},hardenAfterCreate:AUTHORITY_STORE_IMMUTABLE_FLAGS},auth:{bucket:epAuthBucket(space2),createOptions:{allow_direct:false,markerTTL:EP_AUTH_MARKER_TTL_MS}}}}var AUTHORITY_HEAD_ARITY=new Map(AUTHORITY_KIND_DEFS.map(d=>[d.kind,1+d.qualifiers.length]));function recordsKvStreamName(space2){return`KV_${recordsBucket(space2)}`}var BASELINE_DELIVERY_ENDPOINT="delivery";var BASELINE_DELIVERY_COMMANDS=Object.freeze(["join","leave","list"]);var BASELINE_LIFECYCLE_ENDPOINT="manager";var BASELINE_SELF_LIFECYCLE_COMMANDS=Object.freeze(["stop","turn-participate","turn-pending","turn-yield","turn-unconfirmed","run-answer"]);var SPAWN_CREATE_COMMANDS=Object.freeze(["spawn","resolve-agent"]);var SPAWN_OWNER_LIFECYCLE_COMMANDS=Object.freeze(["despawn","attach"]);var OPERATOR_SEAT_COMMANDS=Object.freeze(["input","turn"]);var SPAWN_SERVICE_COMMANDS=Object.freeze(["define-persona","remove-persona","inspect","list-personas","show-persona","goal-result"]);var RUN_WRITE_COMMANDS=Object.freeze(["run-start","run-resume","run-start-keyed","run-submission-status","run-cancel"]);var RUN_READ_COMMANDS=Object.freeze(["run-status","run-ps"]);var CHAT_SESSION_COMMANDS=Object.freeze(["chat-session-open","chat-session-retire"]);var MANAGER_READ_COMMANDS=Object.freeze(["status","ps","slots","inspect","models","list-personas","show-persona","goal-result"]);var MANAGER_ADMIN_COMMANDS=Object.freeze(["purge","launch","resume-preserved","commit-resume","finalize-resume","prepare-preservation","commit-preservation","abort-preservation","transcript-receive"]);var GOAL_BEARING_COMMANDS=Object.freeze(["spawn","launch"]);var GOAL_BEARING_SET=new Set(GOAL_BEARING_COMMANDS);var REPEAT_SAFE_COMMANDS=Object.freeze({[BASELINE_LIFECYCLE_ENDPOINT]:Object.freeze(["status","ps","slots","inspect","list-personas","show-persona","run-status","run-ps","goal-result"]),[BASELINE_DELIVERY_ENDPOINT]:Object.freeze(["list"])});var REPEAT_SAFE_ANY_ENDPOINT="describe";var REPEAT_SAFE_SNAP=new Map(Object.entries(REPEAT_SAFE_COMMANDS).map(([endpoint,commands])=>[endpoint,new Set(commands)]));function isRepeatSafeCommand(endpoint,command){if(command===REPEAT_SAFE_ANY_ENDPOINT)return true;return REPEAT_SAFE_SNAP.get(endpoint)?.has(command)===true}var DELIVERY_COMMANDS_SNAP=Object.freeze([...BASELINE_DELIVERY_COMMANDS]);var SELF_LIFECYCLE_SNAP=Object.freeze([...BASELINE_SELF_LIFECYCLE_COMMANDS]);var SPAWN_CREATE_SNAP=Object.freeze([...SPAWN_CREATE_COMMANDS]);var SPAWN_OWNER_SNAP=Object.freeze([...SPAWN_OWNER_LIFECYCLE_COMMANDS]);var OPERATOR_SEAT_SNAP=Object.freeze([...OPERATOR_SEAT_COMMANDS]);var SPAWN_SERVICE_SNAP=Object.freeze([...SPAWN_SERVICE_COMMANDS]);var RUN_WRITE_SNAP=Object.freeze([...RUN_WRITE_COMMANDS]);var RUN_READ_SNAP=Object.freeze([...RUN_READ_COMMANDS]);var CHAT_SESSION_SNAP=Object.freeze([...CHAT_SESSION_COMMANDS]);var MANAGER_READ_SNAP=Object.freeze([...MANAGER_READ_COMMANDS]);var MANAGER_ADMIN_SNAP=Object.freeze([...MANAGER_ADMIN_COMMANDS]);var HEX64=/^[0-9a-f]{64}$/;function contractRefToHex(ref){const hex3=ref.startsWith("sha256:")?ref.slice("sha256:".length):ref;if(!HEX64.test(hex3))throw new EpEnvelopeError("contract-invalid",`contract reference ${JSON.stringify(ref)} is not a sha256 digest; a garbled reference never resolves (SPEC 13.7)`);return hex3}var sha256Ref=hex3=>`sha256:${hex3}`;function buildContractClosureManifest(rootRef,memberRefs){const root=sha256Ref(contractRefToHex(rootRef));const members=[...new Set(memberRefs.map(r=>sha256Ref(contractRefToHex(r))))].sort();return{v:1,root,members}}var CONTRACT_CLOSURE_MAX_ARTIFACTS=64;function assertManifestDigest(ref,what){if(typeof ref!=="string"||!isContractDigest(ref))throw new EpEnvelopeError("contract-invalid",`${what} must be exactly "sha256:<64-hex>" (SPEC 13.7); a bare-hex or otherwise-spelled digest gives one closure two identities and never names it`)}function parseClosureManifest(value,what){if(value===null||typeof value!=="object"||Array.isArray(value))throw new EpEnvelopeError("contract-invalid",`${what} is not a manifest object (SPEC 13.7)`);const o=value;for(const k of Object.keys(o))if(!["v","root","members"].includes(k))throw new EpEnvelopeError("contract-invalid",`${what} carries the unknown field "${k}"; the manifest schema is closed (SPEC 13.7)`);if(o.v!==1||typeof o.root!=="string"||!Array.isArray(o.members))throw new EpEnvelopeError("contract-invalid",`${what} is not { v: 1, root, members } (SPEC 13.7)`);assertManifestDigest(o.root,`${what} root`);if(o.members.length>CONTRACT_CLOSURE_MAX_ARTIFACTS)throw new EpEnvelopeError("contract-invalid",`${what} names ${o.members.length} members, above the ${CONTRACT_CLOSURE_MAX_ARTIFACTS}-artifact ceiling (SPEC 13.7)`);for(let i=0;i<o.members.length;i++){const m=o.members[i];assertManifestDigest(m,`${what} member ${i}`);if(i>0&&o.members[i-1]>=m)throw new EpEnvelopeError("contract-invalid",`${what} members are not strictly sorted/deduplicated at index ${i}; a noncanonical manifest never names a closure (SPEC 13.7)`)}return{v:1,root:o.root,members:o.members}}var import__=__toESM(require__(),1);var FULL={neg:true,ranges:[]};var EMPTY={neg:false,ranges:[]};var set2=(...ranges)=>({neg:false,ranges});var single=c=>set2([c,c]);function rangesOverlap(a,b){for(const[al,ah]of a)for(const[bl,bh]of b)if(al<=bh&&bl<=ah)return true;return false}function rangesCover(outer,[lo,hi]){return outer.some(([ol,oh])=>ol<=lo&&hi<=oh)}function intersects(a,b){if(!a.neg&&!b.neg)return rangesOverlap(a.ranges,b.ranges);if(a.neg&&b.neg)return true;const pos=a.neg?b:a;const neg=a.neg?a:b;return!pos.ranges.every(r=>rangesCover(neg.ranges,r))}function union2(a,b){if(!a.neg&&a.ranges.length===0)return b;if(!b.neg&&b.ranges.length===0)return a;if(a.neg||b.neg)return FULL;return{neg:false,ranges:[...a.ranges,...b.ranges]}}var PatternRefused=class extends Error{};var refuse=reason2=>{throw new PatternRefused(reason2)};var Parser=class{src;i=0;constructor(src){this.src=src}peek(){return this.src[this.i]}next(){return this.src[this.i++]}eof(){return this.i>=this.src.length}parse(){const node=this.alternation();if(!this.eof())refuse(`unexpected "${this.peek()}" at ${this.i}`);return node}alternation(){const branches=[this.sequence()];while(this.peek()==="|"){this.next();branches.push(this.sequence())}return branches.length===1?branches[0]:{kind:"alt",branches}}sequence(){const items=[];while(!this.eof()&&this.peek()!=="|"&&this.peek()!==")")items.push(this.quantified());return{kind:"seq",items}}quantified(){let node=this.atom();for(;;){const c=this.peek();let min,max;if(c==="*"){min=0;max=Infinity}else if(c==="+"){min=1;max=Infinity}else if(c==="?"){min=0;max=1}else if(c==="{"){const m=/^\{(\d+)(?:,(\d*))?\}/.exec(this.src.slice(this.i));if(!m)break;min=parseInt(m[1],10);max=m[2]===void 0?min:m[2]===""?Infinity:parseInt(m[2],10);if(max<min)refuse(`quantifier {${min},${max}} is inverted`);this.i+=m[0].length-1}else break;this.next();if(this.peek()==="?")this.next();node={kind:"quant",body:node,min,max}}return node}atom(){const c=this.next();if(c==="("){if(this.peek()==="?"){const ahead=this.src.slice(this.i,this.i+3);if(/^\?(:|<[a-zA-Z_])/.test(ahead)){this.next();if(this.peek()==="<"){while(this.next()!==">"){if(this.eof())refuse("unterminated group name")}}else this.next()}else{refuse("lookarounds and special groups are outside the profile's safe subset")}}const body=this.alternation();if(this.next()!==")")refuse("unterminated group");return body}if(c==="[")return{kind:"atom",set:this.charClass()};if(c===".")return{kind:"atom",set:FULL};if(c==="^")return{kind:"anchor",at:"start"};if(c==="$")return{kind:"anchor",at:"end"};if(c==="\\")return{kind:"atom",set:this.escape(false)};if(c===")"||c===void 0)refuse("unbalanced group");return{kind:"atom",set:single(this.codePoint())}}codePoint(){const cp=this.src.codePointAt(this.i-1);if(cp>65535)this.i++;return cp}charClass(){let neg=false;if(this.peek()==="^"){this.next();neg=true}const ranges=[];let approx=false;while(this.peek()!=="]"){if(this.eof())refuse("unterminated character class");let lo;const c=this.next();if(c==="\\"){if(this.peek()==="b"){this.next();lo=8}else{const s=this.escape(true);if(s.neg||s.ranges.length!==1||s.ranges[0][0]!==s.ranges[0][1]){approx=true;for(const r of s.neg?[[0,1114111]]:s.ranges)ranges.push(r)}else lo=s.ranges[0][0]}}else lo=this.codePoint();if(lo!==void 0){if(this.peek()==="-"&&this.src[this.i+1]!=="]"&&this.src[this.i+1]!==void 0){this.next();const hiC=this.next();const hi=hiC==="\\"?(()=>{const s=this.escape(true);if(s.neg||s.ranges.length!==1){approx=true;return 1114111}return s.ranges[0][0]})():this.codePoint();ranges.push([lo,hi])}else ranges.push([lo,lo])}}this.next();if(neg&&approx)return FULL;return{neg,ranges}}escape(inClass){const c=this.next();if(c===void 0)refuse("dangling escape");if(!inClass&&c>="1"&&c<="9")refuse(`backreference \\${c} is outside the profile's safe subset`);if(c==="k")refuse("named backreferences are outside the profile's safe subset");if(c==="b"||c==="B")return EMPTY;switch(c){case"d":return set2([48,57]);case"D":return{neg:true,ranges:[[48,57]]};case"w":return set2([48,57],[65,90],[95,95],[97,122]);case"W":return{neg:true,ranges:[[48,57],[65,90],[95,95],[97,122]]};case"s":return set2([9,13],[32,32],[160,160],[8232,8233]);case"S":return{neg:true,ranges:[[9,13],[32,32],[160,160],[8232,8233]]};case"n":return single(10);case"r":return single(13);case"t":return single(9);case"f":return single(12);case"v":return single(11);case"0":return single(0);case"x":{const m=/^[0-9a-fA-F]{2}/.exec(this.src.slice(this.i));if(!m)refuse("malformed \\x escape");this.i+=2;return single(parseInt(m[0],16))}case"u":{const braced=/^\{([0-9a-fA-F]{1,6})\}/.exec(this.src.slice(this.i));if(braced){this.i+=braced[0].length;const cp2=parseInt(braced[1],16);if(cp2>=55296&&cp2<=57343)refuse("surrogate code point escapes are outside the safe subset");return single(cp2)}const m=/^[0-9a-fA-F]{4}/.exec(this.src.slice(this.i));if(!m)refuse("malformed \\u escape");this.i+=4;const cp=parseInt(m[0],16);if(cp>=55296&&cp<=57343)refuse("surrogate escapes are outside the safe subset (write the character or \\u{\u2026})");return single(cp)}case"p":case"P":{const m=/^\{[^}]*\}/.exec(this.src.slice(this.i));if(!m)refuse("malformed \\p escape");this.i+=m[0].length;return FULL}default:if(/[A-Za-z0-9]/.test(c))refuse(`escape \\${c} is outside the profile's safe subset`);return single(c.codePointAt(0))}}};var CHOICE_BUDGET=64;var CHOICE_SAT=1<<20;var mulSat=(a,b)=>Math.min(a*b,CHOICE_SAT);function powSat(base,exp){let out=1;for(let i=0;i<exp&&out<CHOICE_SAT;i++)out=mulSat(out,base);return out}function edgeRepeat(facts,pick2){const deeper=new Array(facts.length+1);deeper[facts.length]=EMPTY;for(let i=facts.length-1;i>=0;i--)deeper[i]=union2(pick2(facts[i]),deeper[i+1]);let acc=EMPTY;for(let i=0;i<facts.length;i++){acc=union2(acc,pick2(facts[i]));if(!facts[i].nullable&&!intersects(facts[i].set,deeper[i+1]))break}return acc}function assertStartAnchored(node){switch(node.kind){case"anchor":if(node.at!=="start")refuse("a top-level branch must begin with a '^' start anchor (Ajv tests patterns unanchored)");return;case"seq":if(node.items.length===0)refuse("an empty top-level branch is not start-anchored");assertStartAnchored(node.items[0]);return;case"alt":for(const b of node.branches)assertStartAnchored(b);return;default:refuse("a top-level branch must begin with a '^' start anchor (Ajv tests patterns unanchored)")}}function analyze(node){switch(node.kind){case"anchor":return{set:EMPTY,nullable:true,variable:false,ambiguousAlt:false,choices:1,leadRep:EMPTY,trailRep:EMPTY};case"atom":return{set:node.set,nullable:node.set.ranges.length===0&&!node.set.neg,variable:false,ambiguousAlt:false,choices:1,leadRep:EMPTY,trailRep:EMPTY};case"seq":{const facts=node.items.map(analyze);for(let i=0;i<facts.length;i++){const T=facts[i].trailRep;if(T.ranges.length===0&&!T.neg)continue;for(let j=i+1;j<facts.length;j++){if(intersects(T,facts[j].leadRep))refuse("two overlapping variable repetitions in sequence (polynomial backtracking class)");if(!facts[j].nullable&&!intersects(facts[j].set,T))break}}return{set:facts.reduce((s,f)=>union2(s,f.set),EMPTY),nullable:facts.every(f=>f.nullable),variable:facts.some(f=>f.variable),ambiguousAlt:facts.some(f=>f.ambiguousAlt),choices:facts.reduce((n,f)=>mulSat(n,f.choices),1),leadRep:edgeRepeat(facts,f=>f.leadRep),trailRep:edgeRepeat([...facts].reverse(),f=>f.trailRep)}}case"alt":{const facts=node.branches.map(analyze);let ambiguous=facts.some(f=>f.ambiguousAlt);if(facts.filter(f=>f.nullable).length>1)ambiguous=true;for(let i=0;i<facts.length&&!ambiguous;i++){for(let j=i+1;j<facts.length;j++){if(intersects(facts[i].set,facts[j].set)){ambiguous=true;break}}}return{set:facts.reduce((s,f)=>union2(s,f.set),EMPTY),nullable:facts.some(f=>f.nullable),variable:facts.some(f=>f.variable),ambiguousAlt:ambiguous,choices:ambiguous?facts.reduce((n,f)=>Math.min(n+f.choices,CHOICE_SAT),0):facts.reduce((n,f)=>Math.max(n,f.choices),1),leadRep:facts.reduce((s,f)=>union2(s,f.leadRep),EMPTY),trailRep:facts.reduce((s,f)=>union2(s,f.trailRep),EMPTY)}}case"quant":{const body=analyze(node.body);const repeats=node.max>1||node.max===Infinity;if(repeats){if(body.variable)refuse("repeats a group that itself contains a quantifier (exponential backtracking class)");if(body.nullable)refuse("repeats a nullable body (unbounded ambiguity on empty matches)");if(body.ambiguousAlt)refuse("repeats an ambiguous alternation (branches overlap; exponential backtracking class)")}const nondet=node.max>node.min;return{set:body.set,nullable:body.nullable||node.min===0,variable:body.variable||nondet||repeats,ambiguousAlt:body.ambiguousAlt,choices:node.max===node.min?powSat(body.choices,node.min):node.min===0&&node.max===1?Math.min(body.choices+1,CHOICE_SAT):body.choices,leadRep:nondet?union2(body.set,body.leadRep):body.leadRep,trailRep:nondet?union2(body.set,body.trailRep):body.trailRep}}}}function assertSafePattern(pattern,maxChars){if(pattern.length>maxChars)throw new Error(`pattern of ${pattern.length} characters exceeds the profile complexity bound (${maxChars})`);try{const ast=new Parser(pattern).parse();assertStartAnchored(ast);const facts=analyze(ast);if(facts.choices>CHOICE_BUDGET)refuse(`aggregate alternation ambiguity of ${facts.choices>=CHOICE_SAT?"at least ":""}${facts.choices} paths exceeds the ${CHOICE_BUDGET}-path budget (the fixed-alternation exponential class)`)}catch(e){if(e instanceof PatternRefused)throw new Error(`pattern ${JSON.stringify(pattern)} is outside the profile's safe subset: ${e.message}`);throw new Error(`pattern ${JSON.stringify(pattern)} did not parse under the profile's safe subset: ${e.message}`)}}var AJV_PROFILE_OPTIONS=Object.freeze({strict:false,allErrors:true,ownProperties:true,validateFormats:false,loadSchema:void 0,validateSchema:true,meta:true,unicodeRegExp:true,inlineRefs:false});var sharedMeta;var ProfileAjv=class extends import__.Ajv2020{validateSchema(schema,throwOrLogError){if(schema===null||typeof schema!=="object")return super.validateSchema(schema,throwOrLogError);if(!sharedMeta){const ajv=new import__.Ajv2020(AJV_PROFILE_OPTIONS);sharedMeta={ajv,keys:new Set([...Object.keys(ajv.schemas),...Object.keys(ajv.refs)])}}if(schema.$schema!==void 0&&!sharedMeta.keys.has(schema.$schema))return super.validateSchema(schema,throwOrLogError);try{return sharedMeta.ajv.validateSchema(schema,throwOrLogError)}finally{this.errors=sharedMeta.ajv.errors}}};function singleDocumentClosure(root){const manifest=buildContractClosureManifest(contractDigest(root),[]);return{manifest,closureDigest:contractDigest(manifest)}}var VOID_SCHEMA=Object.freeze({type:"null"});var VOID_SCHEMA_ARTIFACT_DIGEST=contractDigest(VOID_SCHEMA);var VOID_SCHEMA_DIGEST=singleDocumentClosure(VOID_SCHEMA).closureDigest;var STORE_REF=/^cotal:(sha256:[0-9a-f]{64})(#.*)?$/;var ContractInvalidError=class extends Error{code="contract-invalid";constructor(message){super(message);this.name="ContractInvalidError"}};function canonicalOrInvalid(v,label){try{return canonicalJson(v)}catch(e){throw new ContractInvalidError(`${label}: ${e.message}`)}}function digestOrInvalid(v,label){try{return contractDigest(v)}catch(e){throw new ContractInvalidError(`${label}: ${e.message}`)}}function structuralDepth(v,depth=0){if(depth>SCHEMA_PROFILE.maxDepth)return depth;if(v===null||typeof v!=="object")return depth;let max=depth;const children=Array.isArray(v)?v:Object.values(v);for(const c of children){const d=structuralDepth(c,depth+1);if(d>max)max=d;if(max>SCHEMA_PROFILE.maxDepth)return max}return max}function assertBoundedPattern(p,label,where){try{assertSafePattern(p,SCHEMA_PROFILE.maxPatternChars)}catch(e){throw new ContractInvalidError(`${label}: ${where} refused: ${e.message}`)}}function collectRefs(v,label,out=[]){if(v===null||typeof v!=="object")return out;if(Array.isArray(v)){for(const c of v)collectRefs(c,label,out);return out}for(const[k,c]of Object.entries(v)){if((k==="$ref"||k==="$dynamicRef")&&typeof c==="string")out.push(c);if(k==="pattern"&&typeof c==="string")assertBoundedPattern(c,label,"a pattern");if(k==="patternProperties"&&c!==null&&typeof c==="object"&&!Array.isArray(c)){for(const p of Object.keys(c))assertBoundedPattern(p,label,"a patternProperties key")}collectRefs(c,label,out)}return out}var SCHEMA_VALUED_KEYS=["not","if","then","else","items","contains","additionalProperties","propertyNames","unevaluatedItems","unevaluatedProperties","contentSchema","additionalItems"];var SCHEMA_VALUED_MAP_KEYS=["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"];var SCHEMA_VALUED_LIST_KEYS=["allOf","anyOf","oneOf","prefixItems"];var SCALAR_KEYS=["type","enum","const","multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","maxItems","minItems","uniqueItems","maxContains","minContains","maxProperties","minProperties","required","dependentRequired","format","contentEncoding","contentMediaType","title","description","default","deprecated","readOnly","writeOnly","examples","$comment","$id","$schema","$ref","$anchor","$dynamicRef","$dynamicAnchor","$vocabulary"];var ADMITTED=new Set([...SCHEMA_VALUED_KEYS,...SCHEMA_VALUED_MAP_KEYS,...SCHEMA_VALUED_LIST_KEYS,...SCALAR_KEYS]);function assertAdmittedVocabulary(doc,label){const atSchema=(d,path)=>{if(typeof d==="boolean")return;if(d===null||typeof d!=="object"||Array.isArray(d))return;for(const[k,v]of Object.entries(d)){if(!ADMITTED.has(k))throw new ContractInvalidError(`${label}: keyword ${JSON.stringify(k)} at ${path||"/"} is not in the profile's admitted vocabulary; an unrecognised keyword is REFUSED rather than ignored, because this profile cannot count what it does not recognise`);const here=`${path}/${k}`;if(SCHEMA_VALUED_KEYS.includes(k))atSchema(v,here);else if(SCHEMA_VALUED_MAP_KEYS.includes(k)&&v&&typeof v==="object"&&!Array.isArray(v))for(const[name,sub]of Object.entries(v))atSchema(sub,`${here}/${name}`);else if(SCHEMA_VALUED_LIST_KEYS.includes(k)&&Array.isArray(v))v.forEach((sub,i)=>atSchema(sub,`${here}/${i}`))}};atSchema(doc,"")}function assertDocumentProfile(doc,label){const canonical=canonicalOrInvalid(doc,label);const bytes=Buffer.byteLength(canonical,"utf8");if(bytes>SCHEMA_PROFILE.maxDocumentBytes)throw new ContractInvalidError(`${label}: document is ${bytes} bytes (profile max ${SCHEMA_PROFILE.maxDocumentBytes})`);if(structuralDepth(doc)>SCHEMA_PROFILE.maxDepth)throw new ContractInvalidError(`${label}: nesting exceeds profile depth ${SCHEMA_PROFILE.maxDepth}`);assertAdmittedVocabulary(doc,label);const storeRefs=[];for(const ref of collectRefs(doc,label)){if(ref.startsWith("#"))continue;const m=STORE_REF.exec(ref);if(!m)throw new ContractInvalidError(`${label}: external $ref ${JSON.stringify(ref)}; only local '#\u2026' or digest-pinned 'cotal:sha256:<hex>' references are permitted (no ambient resolution)`);storeRefs.push(m[1])}return storeRefs}var COMPILED=new WeakSet;function makeCompiled(validate2,closureDigest){const compiled=Object.freeze({validate:validate2,closureDigest});COMPILED.add(compiled);return compiled}function assertClosureProfile(bundle){const members=bundle.members??{};for(const d of Object.keys(members)){if(!isContractDigest(d))throw new ContractInvalidError(`bundle member key ${JSON.stringify(d)} is not a sha256 digest`)}const seen=new Set;let closureBytes=0;let frontier=assertDocumentProfile(bundle.root,"root schema");closureBytes+=Buffer.byteLength(canonicalOrInvalid(bundle.root,"root schema"),"utf8");for(let chain=0;frontier.length>0;chain++){if(chain>=SCHEMA_PROFILE.maxRefChain)throw new ContractInvalidError(`reference chain exceeds profile depth ${SCHEMA_PROFILE.maxRefChain}`);const next=[];for(const digest of frontier){if(seen.has(digest))continue;seen.add(digest);const member=members[digest];if(member===void 0)throw new ContractInvalidError(`unresolved digest reference ${digest}: not present in the bundle (schemas are closed; nothing is fetched)`);if(digestOrInvalid(member,`member ${digest}`)!==digest)throw new ContractInvalidError(`bundle member under ${digest} does not hash to its key (content is ${digestOrInvalid(member,`member ${digest}`)})`);closureBytes+=Buffer.byteLength(canonicalOrInvalid(member,`member ${digest}`),"utf8");if(closureBytes>SCHEMA_PROFILE.maxClosureBytes)throw new ContractInvalidError(`closure is ${closureBytes} bytes (profile max ${SCHEMA_PROFILE.maxClosureBytes})`);next.push(...assertDocumentProfile(member,`member ${digest}`))}frontier=next}const extras=Object.keys(members).filter(d=>!seen.has(d));if(extras.length>0)throw new ContractInvalidError(`bundle carries ${extras.length} member(s) unreachable from the root (${extras.slice(0,3).join(", ")}${extras.length>3?", \u2026":""})`);return contractDigest(buildContractClosureManifest(digestOrInvalid(bundle.root,"root schema"),[...seen]))}function widestMapKeywordSize(doc,max=0){if(doc===null||typeof doc!=="object"||Array.isArray(doc))return max;for(const[k,v]of Object.entries(doc)){if(SCHEMA_VALUED_MAP_KEYS.includes(k)&&v&&typeof v==="object"&&!Array.isArray(v)){const size=Object.keys(v).length;if(size>max)max=size;for(const sub of Object.values(v))max=widestMapKeywordSize(sub,max)}else if(SCHEMA_VALUED_KEYS.includes(k)){max=widestMapKeywordSize(v,max)}else if(SCHEMA_VALUED_LIST_KEYS.includes(k)&&Array.isArray(v)){for(const sub of v)max=widestMapKeywordSize(sub,max)}}return max}function widestClosurePropertyCount(bundle){let max=widestMapKeywordSize(bundle.root);for(const member of Object.values(bundle.members??{}))max=widestMapKeywordSize(member,max);return max}function compileWithinBudget(bundle){const ajv=new ProfileAjv(AJV_PROFILE_OPTIONS);let validate2;try{for(const[digest,member]of Object.entries(bundle.members??{}))ajv.addSchema(member,`cotal:${digest}`);validate2=ajv.compile(bundle.root)}catch(e){if(e instanceof RangeError){const width=widestClosurePropertyCount(bundle);throw new ContractInvalidError(`schema does not compile under the 2020-12 profile: the generated validator's code shape overflowed the call stack (${e.message}) compiling a ${width}-property object, which every profile ceiling (document/closure bytes, depth, ref-chain, pattern length, admitted vocabulary) had already admitted; this is the compiler's generated-code shape running out of stack, not a defect in the schema`)}throw new ContractInvalidError(`schema does not compile under the 2020-12 profile: ${e.message}`)}return validate2}function compileContract(bundle){const closureDigest=assertClosureProfile(bundle);return makeCompiled(compileWithinBudget(bundle),closureDigest)}function serviceContractTable(rows){const contracts=Object.create(null);for(const row of rows){let pair2;Object.defineProperty(contracts,row.name,{enumerable:true,get:()=>{if(!pair2){pair2=Object.freeze({input:compileContract({root:row.input}),output:compileContract({root:row.output})})}return pair2}})}return{contracts:Object.freeze(contracts),artifactValues:()=>{const values=[];const seen=new Set;for(const r of rows){for(const source of[r.input,r.output]){const{manifest}=singleDocumentClosure(source);if(seen.has(manifest.root))continue;seen.add(manifest.root);values.push(source,manifest)}}return values}}}var isRec=v=>v!==null&&typeof v==="object"&&!Array.isArray(v);var URN=/^[a-z0-9][a-z0-9-]{0,62}(\.[a-z0-9][a-z0-9-]{0,62}){1,15}$/;var TRAIT_GUARDED="ai.cotal.guarded";var TRAIT_PRICED="ai.cotal.priced";var GOVERNED_TRAIT_URNS=Object.freeze([TRAIT_GUARDED,TRAIT_PRICED]);var CAPABILITY=/^[a-z][a-z0-9._-]{0,63}$/;function invalid(what){throw new ContractInvalidError(`cluster document does not validate: ${what}`)}function parseClusterDocument(raw){const o=isRec(raw)?raw:invalid("not an object");if(typeof o.urn!=="string"||!URN.test(o.urn))invalid(`urn ${JSON.stringify(o.urn)} is not a reverse-DNS cluster type URN`);if(typeof o.revision!=="number"||!Number.isSafeInteger(o.revision)||o.revision<0)invalid("revision is not an unsigned integer");if(!Array.isArray(o.attributes))invalid("attributes is not an array");if(!Array.isArray(o.events))invalid("events is not an array");if(!Array.isArray(o.commands)||o.commands.length===0)invalid("commands must be a non-empty array");const seen=new Set;const commands=o.commands.map((c,i)=>{const cmd=isRec(c)?c:invalid(`commands[${i}] is not an object`);const name=typeof cmd.name==="string"?cmd.name:invalid(`commands[${i}].name is not a string`);try{assertCommandToken(name)}catch(e){invalid(`commands[${i}].name: ${e.message}`)}if(name==="describe")invalid(`commands[${i}] declares "describe": reserved, served by the machinery, never a cluster command (SPEC 13.7)`);if(seen.has(name))invalid(`command "${name}" is declared twice`);seen.add(name);if(cmd.class!=="ephemeral"&&cmd.class!=="journal")invalid(`command "${name}" class ${JSON.stringify(cmd.class)} is not "ephemeral" | "journal"`);if(typeof cmd.targeted!=="boolean")invalid(`command "${name}" must declare targeted as a boolean (SPEC 13.7)`);let modes;if(cmd.targeted){if(!Array.isArray(cmd.modes)||cmd.modes.length===0)invalid(`targeted command "${name}" must declare its admitted authorization modes (SPEC 13.7)`);const uniq=new Set;for(const m of cmd.modes){if(typeof m!=="string"||!isEpAuthzMode(m))invalid(`command "${name}" admits unknown mode ${JSON.stringify(m)}`);if(uniq.has(m))invalid(`command "${name}" admits mode "${m}" twice`);uniq.add(m)}modes=[...cmd.modes]}else if(cmd.modes!==void 0){invalid(`untargeted command "${name}" must not declare authorization modes`)}if(typeof cmd.capability!=="string"||!CAPABILITY.test(cmd.capability))invalid(`command "${name}" capability is not a bounded capability token`);if(!isContractDigest(cmd.inputDigest))invalid(`command "${name}" inputDigest is not a sha256 closure digest`);if(!isContractDigest(cmd.outputDigest))invalid(`command "${name}" outputDigest is not a sha256 closure digest`);let traits;if(cmd.traits!==void 0){if(!Array.isArray(cmd.traits))invalid(`command "${name}" traits is not an array`);const tSeen=new Set;for(const t of cmd.traits){if(typeof t!=="string"||!URN.test(t))invalid(`command "${name}" trait ${JSON.stringify(t)} is not a reverse-DNS trait URN (SPEC 13.7)`);if(tSeen.has(t))invalid(`command "${name}" declares trait "${t}" twice`);tSeen.add(t)}traits=[...cmd.traits]}let action;if(cmd.action!==void 0){if(cmd.action!==true)invalid(`command "${name}" action ${JSON.stringify(cmd.action)} is not true (the action composite is present or absent; "false" is a second way to say absent)`);if(cmd.class!=="journal")invalid(`command "${name}" declares the action composite but class "${cmd.class}": an action command's submissions are journal-class (SPEC 13.7)`);action=true}let admissionCeiling;if(cmd.class==="journal"){const ceil=isRec(cmd.admissionCeiling)?cmd.admissionCeiling:invalid(`journal-class command "${name}" must declare admissionCeiling {maxBytes, maxDepth, maxItems}: the canonicalizer reads its ceilings from the digest-verified surface, never from a constant`);const nums={};for(const f of["maxBytes","maxDepth","maxItems"]){const v=ceil[f];if(typeof v!=="number"||!Number.isSafeInteger(v)||v<=0)invalid(`command "${name}" admissionCeiling.${f} ${JSON.stringify(v)} is not a positive safe integer`);nums[f]=v}admissionCeiling={maxBytes:nums.maxBytes,maxDepth:nums.maxDepth,maxItems:nums.maxItems}}else if(cmd.admissionCeiling!==void 0){invalid(`ephemeral command "${name}" declares admissionCeiling: an ephemeral command receives no journal submissions, so a ceiling on it is unreadable by anything`)}let readinessDeadlineMs;if(cmd.readinessDeadlineMs!==void 0){if(!action)invalid(`command "${name}" declares readinessDeadlineMs without the action composite: readiness is goal state and only an action command has a goal`);if(typeof cmd.readinessDeadlineMs!=="number"||!Number.isSafeInteger(cmd.readinessDeadlineMs)||cmd.readinessDeadlineMs<0)invalid(`command "${name}" readinessDeadlineMs ${JSON.stringify(cmd.readinessDeadlineMs)} is not a non-negative safe integer (SPEC 13.11)`);readinessDeadlineMs=cmd.readinessDeadlineMs}return{name,class:cmd.class,targeted:cmd.targeted,...modes?{modes}:{},capability:cmd.capability,inputDigest:cmd.inputDigest,outputDigest:cmd.outputDigest,...traits?{traits}:{},...action?{action}:{},...admissionCeiling?{admissionCeiling}:{},...readinessDeadlineMs!==void 0?{readinessDeadlineMs}:{}}});return{urn:o.urn,revision:o.revision,attributes:[...o.attributes],commands,events:[...o.events]}}var REGISTRY_ENDPOINT="registry";var REGISTRY_ENDPOINTS_COMMAND="endpoints";var REGISTRY_ENDPOINTS_CAPABILITY="registry.endpoints";var REGISTRY_PAGE_LIMIT=100;var REGISTRY_ENDPOINTS_GRANT=Object.freeze({endpoint:REGISTRY_ENDPOINT,command:REGISTRY_ENDPOINTS_COMMAND});var NAME={type:"string",minLength:1,maxLength:128};var TOKEN={type:"string",minLength:1,maxLength:64};var ENDPOINTS_INPUT={type:"object",additionalProperties:false,properties:{limit:{type:"integer",minimum:1,maximum:REGISTRY_PAGE_LIMIT},after:NAME}};var FORM={type:"object",additionalProperties:false,required:["rail","literals","covered"],properties:{rail:{enum:["ep","ep.v1","epj"]},route:{enum:["one","all","inst"]},mode:TOKEN,literals:{type:"object",additionalProperties:{type:"array",items:TOKEN}},covered:{type:"array",items:{type:"object",additionalProperties:{type:["string","null"],maxLength:64}}}}};var ENDPOINTS_OUTPUT={type:"object",additionalProperties:false,required:["rows","source"],properties:{rows:{type:"array",maxItems:REGISTRY_PAGE_LIMIT,items:{type:"object",additionalProperties:false,required:["endpoint","instances","commands"],properties:{endpoint:NAME,instances:{type:"array",items:{type:"object",additionalProperties:false,required:["instanceId","state","artifacts"],properties:{instanceId:TOKEN,state:{type:["string","null"],maxLength:64},artifacts:{enum:["verified","missing","invalid"]}}}},commands:{type:"array",items:{type:"object",additionalProperties:false,required:["name","class","forms"],properties:{name:TOKEN,class:{enum:["ephemeral","journal"]},forms:{type:"array",items:FORM},instances:{type:"array",items:TOKEN}}}},unprojected:{type:"array",items:TOKEN}}}},next:NAME,source:{enum:["recorded-ceiling","no-permission-system"]}}};var ROWS=[{name:REGISTRY_ENDPOINTS_COMMAND,capability:REGISTRY_ENDPOINTS_CAPABILITY,input:ENDPOINTS_INPUT,output:ENDPOINTS_OUTPUT,targeted:false}];var TABLE=serviceContractTable(ROWS);var REGISTRY_CONTRACTS=TABLE.contracts;var registryContractArtifactValues=TABLE.artifactValues;var import_jetstream15=__toESM(require_mod4(),1);var import_jetstream5=__toESM(require_mod4(),1);var import_transport_node5=__toESM(require_transport_node(),1);var GOAL_TERMINAL_STATES=Object.freeze(["succeeded","failed","cancelled","expired","uncertain"]);function assertClosedKeys(o,allowed,what){for(const k of Object.keys(o))if(!allowed.includes(k))throw new EpEnvelopeError("internal",`${what} carries unknown field ${JSON.stringify(k)}; a closed schema admits no extras - garbled state never authorizes (SPEC 13.4)`)}function assertGoalResultFactShape(raw,subject,ref){if(raw===null||typeof raw!=="object"||Array.isArray(raw))throw new EpEnvelopeError("internal",`goal result fact on ${subject} is not an object; garbled state never authorizes (SPEC 13.6)`);const o=raw;assertClosedKeys(o,["v","goalId","fingerprint","state","outcomeDigest","data","committer","ts"],`goal result fact on ${subject}`);if(o.committer!==void 0){const cm=o.committer;if(cm===null||typeof cm!=="object"||Array.isArray(cm))throw new EpEnvelopeError("internal",`goal result fact on ${subject} committer is not an object; garbled state never authorizes (SPEC 13.6)`);assertClosedKeys(cm,["instanceId","epoch"],`goal result fact on ${subject} committer`);if(typeof cm.instanceId!=="string"||cm.instanceId.length===0||typeof cm.epoch!=="number"||!Number.isSafeInteger(cm.epoch)||cm.epoch<0)throw new EpEnvelopeError("internal",`goal result fact on ${subject} carries a malformed committer; garbled state never authorizes (SPEC 13.6)`)}if(o.v!==1||typeof o.goalId!=="string"||typeof o.fingerprint!=="string"||o.fingerprint.length===0||typeof o.state!=="string"||!GOAL_TERMINAL_STATES.includes(o.state)||typeof o.outcomeDigest!=="string"||o.outcomeDigest.length===0||typeof o.ts!=="number"||!Number.isSafeInteger(o.ts)||o.ts<0)throw new EpEnvelopeError("internal",`goal result fact on ${subject} is malformed; garbled state never authorizes (SPEC 13.6)`);if(o.goalId!==ref.goalId)throw new EpEnvelopeError("internal",`goal result fact on ${subject} names goalId ${JSON.stringify(o.goalId)}, not its subject's ${ref.goalId}; a mis-subjected fact never authorizes (SPEC 13.4)`);return o}function goalOutcomeDigestMismatch(subject){return new EpEnvelopeError("internal",`goal result fact on ${subject} carries an outcomeDigest that does not match its payload; a digest-inconsistent fact never authorizes (SPEC 13.6)`)}async function withDeadline(p,ms,onTimeout){let timer;const timeout=new Promise((_,rej)=>{timer=setTimeout(()=>rej(onTimeout()),Math.max(1,ms))});try{return await Promise.race([p,timeout])}finally{clearTimeout(timer)}}var import_jetstream3=__toESM(require_mod4(),1);var import_transport_node3=__toESM(require_transport_node(),1);var MAX_SCHEDULE_MS=Date.UTC(9999,11,31,23,59,59,999);var import_jetstream4=__toESM(require_mod4(),1);var import_transport_node4=__toESM(require_transport_node(),1);var import_nkeys3=__toESM(require_mod(),1);var ANCHOR_ROLES=Object.freeze(["handles","traits","receipts","resume","sessions","authz-slots","obligations","payments","consents"]);var BRANDED_CONTEXTS=new WeakSet;function assertCtx(ctx){if(!BRANDED_CONTEXTS.has(ctx))throw new EpEnvelopeError("failed-precondition",`the action context was not constructed by actionContext(); a hand-assembled resource bundle never authorizes - the space bond is constructed, not asserted (SPEC 13.4)`)}var GUARD_CLEARANCES=new WeakMap;var clearanceMintClaimed=false;function claimGuardClearanceMint(){if(clearanceMintClaimed)throw new EpEnvelopeError("permission-denied","the guard-clearance mint is already claimed by THE gate; a guarded goal's edge into running opens only through it (SPEC 13.6)");clearanceMintClaimed=true;return(ctx,goalId)=>{assertCtx(ctx);const clearance=Object.freeze({goalId:assertIdToken(goalId,"goalId")});GUARD_CLEARANCES.set(clearance,ctx);return clearance}}var GOAL_STATES=Object.freeze(["accepted","running","waiting","cancelling","succeeded","failed","cancelled","expired","uncertain"]);function parseGoalResultFact(raw,subject,ref){const o=assertGoalResultFactShape(raw,subject,ref);if(contractDigest(o.data===void 0?null:o.data)!==o.outcomeDigest)throw goalOutcomeDigestMismatch(subject);return o}var import_nats_core2=__toESM(require_mod3(),1);function base64url3(bytes){let binary="";for(const b of bytes)binary+=String.fromCharCode(b);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function fromBase64url(text2){const b64=text2.replace(/-/g,"+").replace(/_/g,"/");const binary=atob(b64+"=".repeat((4-b64.length%4)%4));return Uint8Array.from(binary,ch=>ch.charCodeAt(0))}var import_nats_core=__toESM(require_mod3(),1);var BROKER_REFUSAL_CAUSE="either no grant covers it, or it was granted after this connection authenticated, which still has its earlier permissions: reconnect and retry (SPEC 13.2)";function openPublishDenialWatch(nc,subject,refusal,what){const statusStream=nc.status();if(typeof statusStream?.stop!=="function")throw new EpEnvelopeError("unavailable",`the NATS connection's status() stream does not expose stop(); the ${what} permission watch cannot be released and would leak a listener per call`);const statusIter=statusStream[Symbol.asyncIterator]();const denied=new Promise((_,reject)=>{void(async()=>{for(;;){const{value:s,done}=await statusIter.next();if(done===true||s===void 0)return;if(s.type!=="error")continue;if(s.error instanceof import_nats_core.PermissionViolationError&&s.error.subject===subject){reject(refusal(s.error));return}}})().catch(()=>{})});return{denied,release(){statusStream.stop();void statusIter.return?.(void 0)}}}var nonce=()=>base64url3(globalThis.crypto.getRandomValues(new Uint8Array(24)));function subjectTarget(t){if(t.mode==="self")return{mode:"self"};if(t.mode==="handle"||t.mode==="exact")return{mode:t.mode,tOwner:t.owner,tActor:t.actor,tUid:t.lifecycleUid};return{mode:t.mode,tOwner:t.owner}}function bodyTarget(t){if(t.mode==="self")return void 0;return{owner:assertBoundedOwner(t.owner,"target owner"),actor:t.actor,lifecycleUid:assertLifecycleToken(t.lifecycleUid,"target lifecycleUid"),...t.mappingRevision!==void 0?{mappingRevision:t.mappingRevision}:{}}}function buildRequest(space2,route,op,verb){let args;try{args=op.args===void 0?void 0:JSON.parse(JSON.stringify(op.args))}catch(e){throw new EpEnvelopeError("bad-request",`args cannot be sent as JSON: ${e instanceof Error?e.message:String(e)}`,void 0,"not-executed")}try{assertArgsValid(op.contract.input.validate,args)}catch(e){if(!(e instanceof EpEnvelopeError))throw e;const property=op.contract.input.validate.errors?.[0]?.params?.additionalProperty;throw new EpEnvelopeError(e.code,e.message,typeof property==="string"?[{kind:EP_UNDECLARED_ARG,property,...op.bind!==void 0?{instanceId:op.bind.instanceId}:{}}]:void 0,"not-executed")}if(op.bind!==void 0){if(op.command==="describe")throw new EpEnvelopeError("bad-request","describe carries no bind: it is the bootstrap that produces one (SPEC 13.3)");if(route.mode==="all")throw new EpEnvelopeError("bad-request","a scatter addresses every incarnation; a bind would make every member but one refuse (SPEC 13.5)");if(route.mode==="inst"&&op.bind.instanceId!==route.instanceId)throw new EpEnvelopeError("bad-request",`bind.instanceId "${op.bind.instanceId}" contradicts the inst-rail route's instance "${route.instanceId}" (SPEC 13.2)`)}const n=nonce();const subject=epRequestSubject(space2,{route,endpoint:op.endpoint,command:op.command,...op.target?{target:subjectTarget(op.target)}:{},caller:op.caller,nonce:n});const requestId=op.id!==void 0?assertIdToken(op.id,"pinned envelope id"):nonce();const env={v:1,id:requestId,op:{endpoint:op.endpoint,command:op.command,inputDigest:op.contract.input.closureDigest,outputDigest:op.contract.output.closureDigest},class:"ephemeral",replyExpected:verb.replyExpected,...op.goalId!==void 0?{goalId:op.goalId}:{},...op.target&&op.target.mode!=="self"?{target:bodyTarget(op.target)}:{},...op.bind!==void 0?{bind:{instanceId:assertLifecycleToken(op.bind.instanceId,"bind instanceId"),epoch:op.bind.epoch}}:{},...args!==void 0?{args}:{},from:{id:`${op.caller.owner}.${op.caller.actor}`,name:op.name??op.caller.actor},...verb.deadlineMs!==void 0?{deadlineMs:verb.deadlineMs}:{},...op.correlation!==void 0?{correlation:op.correlation}:{},...op.auth!==void 0?{auth:op.auth}:{}};return{subject,requestId,n,body:new TextEncoder().encode(JSON.stringify(env))}}var MAX_TIMER_MS=2147483647;function assertDeadline(deadlineMs,what="deadlineMs"){if(!Number.isSafeInteger(deadlineMs)||deadlineMs<=0||deadlineMs>MAX_TIMER_MS)throw new EpEnvelopeError("bad-request",`${what} ${deadlineMs} must be a positive budget within the timer bound ${MAX_TIMER_MS}ms (SPEC 13.3: bounded, never unbounded; a larger setTimeout clamps to 1ms)`);return deadlineMs}function isNoRespondersMsg(msg){const h2=msg.headers;return h2!=null&&(h2.code===503||h2.status==="503")}async function raceBounded(read,ms,what,details){let t;try{return await Promise.race([(async()=>read())(),new Promise((_,reject)=>{t=setTimeout(()=>reject(new EpEnvelopeError("deadline-exceeded",`${what} did not settle within the ${ms}ms budget (SPEC 13.5)`,details)),ms)})])}finally{if(t!==void 0)clearTimeout(t)}}var unansweredDetail=op=>({kind:EP_UNANSWERED,endpoint:op.endpoint,command:op.command,rail:epPlaneTokens(op.caller).join(".")});function replySubjectFor(space2,caller,n){return`${spacePrefix(space2)}.${epPlaneTokens(caller).join(".")}.reply.*.*.*.${callerRailTokens(caller).join(".")}.${n}`}function noRespondersReplyTo(space2,caller,n){return`${spacePrefix(space2)}.${epPlaneTokens(caller).join(".")}.reply._nr._nr._nr.${callerRailTokens(caller).join(".")}.${n}`}function staleEpochRefusal(op,responder,held2,reference,rail){const who=`the ${op.endpoint} instance ${responder.instanceId}`;const ahead=responder.epoch>held2;const situation=reference==="bind"?ahead?`${who} answered at epoch ${responder.epoch}, but this handle resolved against it at epoch ${held2}: a SUCCESSOR of the bound incarnation answered (a restart or supersession), so the handle is the stale side; re-resolve to adopt it`:`${who} answered at epoch ${responder.epoch}, but this handle resolved against it at epoch ${held2}: a SUPERSEDED incarnation still connected answered, and its reply is rejected`:ahead?`${who} answered at epoch ${responder.epoch}, but a currency read of its registered epoch returned ${held2}: the responder is ahead of the registry read (the read lags a restart), so its reply is rejected until the read catches up; nothing of this caller's is stale`:`${who} answered at epoch ${responder.epoch}, but a currency read of its registered epoch returned ${held2}: a SUPERSEDED incarnation still connected answered, and its reply is rejected`;const detail={kind:EP_UNBOUND_RESPONDER,endpoint:op.endpoint,command:op.command,answeredBy:responder.instanceId,...reference==="bind"?{boundTo:responder.instanceId}:{},answeredEpoch:responder.epoch,heldEpoch:held2,reference,pinned:rail==="inst"};return new EpEnvelopeError("expired",`${situation}. THIS SAYS NOTHING ABOUT WHETHER THE COMMAND RAN: ${responder.instanceId} received the request and answered it, so if "${op.command}" mutates, that effect may already have landed; verify the outcome ('ps'/'inspect'/roster) before re-issuing (SPEC 13.2, the stale-reply rejection rule)`,[detail])}function parseAttributedReply(space2,subject,data,requestId,op,expect){const parsed=parseEpSubject(subject);if(!parsed||parsed.plane!=="reply")throw new EpEnvelopeError("internal",`a message on the caller's reply rail does not parse as a reply subject: ${subject}`);if(parsed.endpoint!==op.endpoint)throw new EpEnvelopeError("internal",`reply endpoint "${parsed.endpoint}" is not the invoked endpoint "${op.endpoint}" (SPEC 13.2: the caller binds a reply to the requested identity, never trusts the subject alone)`);if(expect?.instanceId!==void 0&&parsed.instanceId!==expect.instanceId)throw new EpEnvelopeError("internal",`reply instance "${parsed.instanceId}" is not the addressed instance "${expect.instanceId}" (SPEC 13.2)`);if(expect?.epoch!==void 0&&parsed.epoch!==expect.epoch)throw staleEpochRefusal(op,{instanceId:parsed.instanceId,epoch:parsed.epoch},expect.epoch,"bind","inst");let rawBody;try{rawBody=JSON.parse(new TextDecoder().decode(data))}catch(e){throw new EpEnvelopeError("internal",`the reply body on the caller's rail is not JSON (${e instanceof Error?e.message:String(e)}); an unparseable reply is a responder bug surfaced as the caller boundary's structured refusal (SPEC 13.3)`)}const reply=parseEndpointReply(rawBody);if(reply.id!==requestId)throw new EpEnvelopeError("internal",`reply id "${reply.id}" does not echo the request id "${requestId}" on its nonce-scoped rail (SPEC 13.3)`);if(reply.ok)assertOutputValid(op.contract.output.validate,reply.data);return{reply,responder:{endpoint:parsed.endpoint,instanceId:parsed.instanceId,epoch:parsed.epoch}}}async function epCall(nc,space2,route,op,opts){opts.signal?.throwIfAborted();const deadlineMs=assertDeadline(opts.deadlineMs);if(route.mode==="one"&&opts.currentEpoch===void 0)throw new EpEnvelopeError("bad-request","epCall on the `one` rail requires opts.currentEpoch: the queue winner is not implicitly current, and a superseded-but-connected member's reply must be rejected (SPEC 13.2, the stale-reply rejection rule)");const req=buildRequest(space2,route,op,{replyExpected:true,deadlineMs});const expect=route.mode==="inst"?{instanceId:route.instanceId,epoch:route.epoch}:void 0;const noRespReplyTo=noRespondersReplyTo(space2,op.caller,req.n);const started=Date.now();let sub;let timer;let denialWatch;let onAbort;let published=false;const cancelled=new Promise((_,reject)=>{onAbort=()=>reject(new EpEnvelopeError("unavailable",`${op.endpoint}.${op.command} observation cancelled; the request may have executed`,published?[{...unansweredDetail(op),requestId:req.requestId}]:void 0,"unknown"));opts.signal?.addEventListener("abort",onAbort,{once:true})});try{denialWatch=openPublishDenialWatch(nc,req.subject,()=>new EpEnvelopeError("permission-denied",`the call for ${op.endpoint}.${op.command} was REFUSED BY THE BROKER, not unanswered: this caller's credential does not authorize publishing to "${req.subject}"${route.mode==="inst"?` (the instance rail for ${route.instanceId})`:""}. The responder may be perfectly healthy. The current credential did not authorize this route, command or target, and the broker does not say which; ${BROKER_REFUSAL_CAUSE}`,void 0,"not-executed"),"call");const outcome=new Promise((resolve,reject)=>{sub=nc.subscribe(replySubjectFor(space2,op.caller,req.n),{callback:(err3,msg2)=>{if(err3){reject(new EpEnvelopeError("unavailable",`the caller's reply subscription failed: ${err3.message}`));return}if(msg2.subject===noRespReplyTo){if(isNoRespondersMsg(msg2)){reject(new EpEnvelopeError("unavailable",`no responder for ${op.endpoint}.${op.command} (SPEC 13.5)`,[unansweredDetail(op)],"not-executed"));return}reject(new EpEnvelopeError("internal",`a non-503 message reached the reserved no-responders sentinel for ${op.endpoint}.${op.command}; nothing but the broker control frame is addressable there`));return}resolve({subject:msg2.subject,data:msg2.data})}});opts.signal?.throwIfAborted();nc.publish(req.subject,req.body,{reply:noRespReplyTo});published=true});const timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new EpEnvelopeError("deadline-exceeded",`no reply to ${op.endpoint}.${op.command} within the ${deadlineMs}ms budget (SPEC 13.5)`,[{...unansweredDetail(op),requestId:req.requestId}],"unknown")),deadlineMs)});const msg=await Promise.race([outcome,timeout,denialWatch.denied,cancelled]);const attributed=parseAttributedReply(space2,msg.subject,msg.data,req.requestId,op,expect);if(attributed.reply.ok===false&&bindRefusalMarked(attributed.reply.error)){if(op.bind===void 0)throw new EpEnvelopeError("internal",`${op.endpoint}.${op.command} replied with a bind refusal to a request that carried no bind`);const r=attributed.responder;if(r.instanceId===op.bind.instanceId&&r.epoch===op.bind.epoch)throw new EpEnvelopeError("internal",`${op.endpoint} instance ${r.instanceId} refused ${op.command} as the wrong incarnation, but the reply subject attributes it to exactly the bound one (${op.bind.instanceId} epoch ${op.bind.epoch}); the body does not get to contradict its own attribution (SPEC 13.3)`);const refusal=(attributed.reply.error?.details??[]).find(d=>d.kind===EP_BIND_REFUSED);if(refusal===void 0)throw new EpEnvelopeError("internal",`${op.endpoint}.${op.command} came back marked ${EP_BIND_REFUSED} with no such detail to derive it from (SPEC 13.3)`);if(refusal.boundTo.instanceId!==op.bind.instanceId||refusal.boundTo.epoch!==op.bind.epoch)throw new EpEnvelopeError("internal",`${op.endpoint} refused ${op.command} against bind ${refusal.boundTo.instanceId} epoch ${refusal.boundTo.epoch}, but this request carried ${op.bind.instanceId} epoch ${op.bind.epoch}; a refusal computed from another request proves nothing about this one (SPEC 13.3)`);if(refusal.servedBy.instanceId!==r.instanceId||refusal.servedBy.epoch!==r.epoch)throw new EpEnvelopeError("internal",`${op.endpoint} refused ${op.command} claiming to be served by ${refusal.servedBy.instanceId} epoch ${refusal.servedBy.epoch}, but the reply subject attributes it to ${r.instanceId} epoch ${r.epoch}; the body does not get to contradict its own attribution (SPEC 13.3)`);return attributed}if(route.mode==="one"){const remaining=deadlineMs-(Date.now()-started);if(remaining<=0)throw new EpEnvelopeError("deadline-exceeded",`no budget left to verify the \`one\` responder's currency within ${deadlineMs}ms (SPEC 13.5)`);let cur;try{cur=await raceBounded(()=>opts.currentEpoch(attributed.responder.instanceId),remaining,`the \`one\` currency read for ${op.endpoint}.${op.command}`)}catch(e){if(e instanceof EpEnvelopeError)throw e;throw new EpEnvelopeError("internal",`the \`one\` currency read threw (${e instanceof Error?e.message:String(e)}); the documented error catalog holds at this boundary (SPEC 13.3)`)}if(!Number.isSafeInteger(cur)||cur<0)throw new EpEnvelopeError("failed-precondition",`the \`one\` currency read returned a non-integer/negative epoch ${String(cur)}; a garbled currency read is refused as the read's own failure, never reported as responder staleness (SPEC 13.2)`);if(attributed.responder.epoch!==cur)throw staleEpochRefusal(op,attributed.responder,cur,opts.currencyReference??"registry","one")}return attributed}finally{sub?.unsubscribe();if(timer!==void 0)clearTimeout(timer);denialWatch?.release();if(onAbort)opts.signal?.removeEventListener("abort",onAbort)}}var dec3=new TextDecoder;var enc3=new TextEncoder;var nonce2=()=>base64url3(globalThis.crypto.getRandomValues(new Uint8Array(24)));var DESCRIBE_RETRY_MS=250;function caughtText(e,fallback){try{return e instanceof Error?e.message:String(e)}catch{return fallback}}var GOAL_FOLLOW_MARGIN_MS=1e4;async function describeEndpoint(nc,space2,endpoint,caller,opts={}){opts.signal?.throwIfAborted();if(opts.classInstanceId!==void 0){assertLifecycleToken(opts.classInstanceId,"classInstanceId");if(opts.instanceId!==void 0)throw new EpEnvelopeError("bad-request","a describe cannot select both an instance route and a class responder")}const deadlineMs=opts.deadlineMs??1e4;const n=nonce2();const requestId=nonce2();const route=opts.instanceId!==void 0?{mode:"inst",instanceId:opts.instanceId}:{mode:"one"};const subject=epRequestSubject(space2,{route,endpoint,command:"describe",caller,nonce:n});const rail=epPlaneTokens(caller).join(".");const env={v:1,id:requestId,op:{endpoint,command:"describe"},class:"ephemeral",replyExpected:true,deadlineMs,from:{id:`${caller.owner}.${caller.actor}`,name:caller.actor}};let sub;let timer;let retryTimer;let denialWatch;let onAbort;const startedAt2=performance.now();const unanswered=ms=>new EpEnvelopeError("deadline-exceeded",`no describe reply from ${endpoint}${opts.instanceId!==void 0?` instance ${opts.instanceId}`:opts.classInstanceId!==void 0?` class responder ${opts.classInstanceId}`:""} within ${ms}ms on the ${rail} rail`,[{kind:EP_UNANSWERED,endpoint,command:"describe",rail}]);const cancelled=new Promise((_,reject)=>{onAbort=()=>reject(opts.signal?.reason?.name==="TimeoutError"?unanswered(Math.round(performance.now()-startedAt2)):opts.signal?.reason);opts.signal?.addEventListener("abort",onAbort,{once:true})});try{denialWatch=openPublishDenialWatch(nc,subject,()=>new EpEnvelopeError("permission-denied",`the describe for ${endpoint} was REFUSED BY THE BROKER, not unanswered: this caller's credential does not authorize publishing to "${subject}"${opts.instanceId!==void 0?` (the instance rail for ${opts.instanceId}: an instance-addressed call needs a credential minted with that instance, not a class-rail one)`:""}. The responder may be perfectly healthy; ${BROKER_REFUSAL_CAUSE}`,void 0,"not-executed"),"describe");const got=new Promise((resolve,reject)=>{sub=nc.subscribe(epCallerReplyFilter(space2,caller),{callback:(err3,msg)=>{if(err3){reject(new EpEnvelopeError("unavailable",`describe reply subscription failed: ${err3.message}`));return}const parsed=parseEpSubject(msg.subject);if(!parsed||parsed.plane!=="reply"||parsed.endpoint!==endpoint||parsed.nonce!==n)return;let reply2;try{reply2=parseEndpointReply(JSON.parse(dec3.decode(msg.data)))}catch{return}if(reply2.id!==requestId)return;if(opts.classInstanceId!==void 0&&parsed.instanceId!==opts.classInstanceId)return;resolve({body:reply2,responder:{instanceId:parsed.instanceId,epoch:parsed.epoch}})}});const request=enc3.encode(JSON.stringify(env));nc.publish(subject,request);retryTimer=setInterval(()=>{try{nc.publish(subject,request)}catch(e){reject(new EpEnvelopeError("unavailable",`the describe retry for ${endpoint} could not publish: ${caughtText(e,"unknown publish failure")}`))}},DESCRIBE_RETRY_MS)});const timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(unanswered(deadlineMs)),deadlineMs)});const{body:reply,responder}=await Promise.race([got,timeout,denialWatch.denied,cancelled]);if(reply.ok!==true){const e=reply.error;throw new EpEnvelopeError(e?.code??"unavailable",`describe(${endpoint}) failed: ${e?.message??"unknown"}`)}return{answer:reply.data,responder}}finally{sub?.unsubscribe();if(timer!==void 0)clearTimeout(timer);if(retryTimer!==void 0)clearInterval(retryTimer);if(onAbort)opts.signal?.removeEventListener("abort",onAbort);denialWatch?.release()}}var BIND_SPLIT_REISSUES=16;async function invokeCommand(nc,space2,service,command,args,opts){const resolved=service.commands.get(command);if(resolved===void 0)throw new EpEnvelopeError("not-found",`command "${command}" is not in ${service.endpoint}'s visible surface; describe lists ${[...service.commands.keys()].sort().join(", ")||"(none)"}`);if(resolved.targeted&&opts.target===void 0)throw new EpEnvelopeError("bad-request",`command "${command}" is targeted (modes: ${resolved.modes.join(", ")}); an invoke needs its target`);if(!resolved.targeted&&opts.target!==void 0)throw new EpEnvelopeError("bad-request",`command "${command}" is untargeted; an invoke must not carry a target`);const caller=opts.caller??service.caller;if(caller.owner!==service.caller.owner||caller.actor!==service.caller.actor||caller.uid!==service.caller.uid)throw new EpEnvelopeError("bad-request","a call's caller must name the triple its describe ran as");let sendArgs=args;if(sendArgs===void 0&&!resolved.contract.input.validate(null)&&resolved.contract.input.validate({}))sendArgs={};const describeBound=instanceId=>{if(instanceId!==service.responder.instanceId){throw new EpEnvelopeError("failed-precondition",service.pinnedInstanceId!==void 0?`the ${service.endpoint} instance ${instanceId} answered but this handle is PINNED to ${service.pinnedInstanceId}; a pinned call names its instance and never accepts another. ${instanceId} did receive and answer the request, so if "${command}" mutates, that effect may already have landed - verify before re-issuing (SPEC 13.2)`:`the ${service.endpoint} instance ${instanceId} won the class queue but this UNPINNED handle resolved against ${service.responder.instanceId}; the describe and the invoke are separate trips through the same queue, so in a multi-instance space this is an ordinary split and not necessarily a supersession - the handle cannot currently adopt a different winner. THIS SAYS NOTHING ABOUT WHETHER THE COMMAND RAN: ${instanceId} received the request and answered it, possibly after this error was raised. For a read that is harmless and re-issuing is safe; if "${command}" mutates, verify the outcome ('ps'/'inspect'/roster) before re-issuing, because a retry that assumes failure duplicates the effect. A call that addresses one instance does not split (SPEC 13.2)`,[{kind:EP_UNBOUND_RESPONDER,endpoint:service.endpoint,command,answeredBy:instanceId,boundTo:service.responder.instanceId,pinned:service.pinnedInstanceId!==void 0}])}return service.responder.epoch};const bind=opts.currentEpoch===void 0?{instanceId:service.pinnedInstanceId??service.responder.instanceId,epoch:service.responder.epoch}:void 0;const deadline=Date.now()+(opts.deadlineMs??1e4);const call=route=>epCall(nc,space2,route,{endpoint:service.endpoint,command,contract:resolved.contract,caller,...sendArgs!==void 0?{args:sendArgs}:{},...opts.target?{target:opts.target}:{},...bind!==void 0?{bind}:{},...opts.id!==void 0?{id:opts.id}:{}},{deadlineMs:deadline-Date.now(),signal:opts.signal,currentEpoch:opts.currentEpoch??describeBound,currencyReference:opts.currentEpoch?"registry":"bind"});if(service.pinnedInstanceId!==void 0)return call({mode:"inst",instanceId:service.pinnedInstanceId,epoch:service.responder.epoch});try{return await call({mode:"one"})}catch(e){if(!(e instanceof EpEnvelopeError)||e.code!=="permission-denied"||e.outcome!=="not-executed"||deadline<=Date.now())throw e;return call({mode:"inst",instanceId:service.responder.instanceId,epoch:service.responder.epoch})}}function goalFollowRefusal(service){if(service.commands.has("goal-result"))return void 0;return{reply:{v:1,id:globalThis.crypto.randomUUID(),ok:false,error:{code:"failed-precondition",outcome:"not-executed",message:`endpoint "${service.endpoint}" does not support "goal-result"; upgrade manager to enable durable goal following (SPEC 13.6)`}},responder:{endpoint:service.endpoint,instanceId:service.responder.instanceId,epoch:service.responder.epoch}}}function goalProgressOrigin(space2,endpoint,caller,subject){const head=`${spacePrefix(space2)}.epe.${endpointToken(endpoint)}.`;if(!subject.startsWith(head))return void 0;const[instanceId,epoch,...tail]=subject.slice(head.length).split(".");const triple=callerTokens(caller);if(tail.length!==6||tail[0]!=="goal"||tail[1]!==triple[0]||tail[2]!==triple[1]||tail[3]!==triple[2]||tail[5]!=="progress")return void 0;if(!instanceId||!epoch||!tail[4])return void 0;return{instanceId,epoch,goalId:tail[4]}}async function submitAndFollowGoalWith(verifyFact,nc,space2,endpoint,caller,deadlineMs,submit,opts){if(!Number.isSafeInteger(deadlineMs)||deadlineMs<=0)throw new EpEnvelopeError("bad-request","goal following requires a positive integer deadline",void 0,"not-executed");const acceptingCaller={...caller};const terminals=new Map;const terminalKey=(goalId,instanceId,epoch)=>`${goalId}\0${instanceId}\0${epoch}`;let terminalPromptedRead=false;const progressSubject=epGoalProgressGrantRow(space2,endpoint,acceptingCaller);const work=new AbortController;const timers=new Set;let activeNc=nc;let activeSub;let generation=0;let unbindReconnect;let completed=false;let stopped=opts?.signal?.aborted===true;let submitted=false;let subError;let observationError;let wake;let abortPhase;let needsReconcile=false;let reading=false;let progressReady=false;const aborted2=new Promise(resolve=>{abortPhase=resolve});const onAbort=()=>{stopped=true;work.abort();abortPhase?.();wake?.()};const phaseError=code=>new EpEnvelopeError(code,submitted?"the goal submission was interrupted while in flight; its outcome is unknown. It may have been accepted or executed; do NOT retry without inspecting 'ps'/'inspect' first (SPEC 13.6)":"goal observation stopped or exceeded its deadline before submission; the manager request WAS NOT RUN",void 0,submitted?"unknown":"not-executed");let deadline=Date.now()+deadlineMs;const bounded=async(operation,until)=>{if(stopped||completed)throw phaseError("unavailable");const remaining=until-Date.now();if(remaining<=0)throw phaseError("deadline-exceeded");let timer;try{return await Promise.race([operation(),aborted2.then(()=>{throw phaseError("unavailable")}),new Promise((_,reject)=>{timer=setTimeout(()=>reject(phaseError("deadline-exceeded")),Math.min(remaining,2147483647));timers.add(timer)})])}finally{if(timer!==void 0){clearTimeout(timer);timers.delete(timer)}}};const subscribe=next=>{if(completed||stopped)return;const mine=++generation;activeSub?.unsubscribe();activeNc=next;progressReady=false;subError=void 0;activeSub=next.subscribe(progressSubject,{callback:(err3,msg)=>{if(completed||stopped||mine!==generation)return;if(err3){subError??=err3;wake?.();return}const origin=goalProgressOrigin(space2,endpoint,acceptingCaller,msg.subject);if(!origin)return;let ev;try{ev=JSON.parse(dec3.decode(msg.data))}catch{return}if(ev?.phase==="terminal"&&ev.goalId===origin.goalId){terminals.set(terminalKey(origin.goalId,origin.instanceId,origin.epoch),{state:String(ev.state),data:ev.data});if(!terminalPromptedRead){terminalPromptedRead=true;needsReconcile=true}wake?.()}}})};const replaceConnection=next=>{if(completed||stopped)return;try{subscribe(next)}catch(err3){subError=err3 instanceof Error?err3:new Error(String(err3));wake?.();return}const mine=generation;void bounded(()=>next.flush(),deadline).then(()=>{if(completed||stopped||mine!==generation)return;progressReady=true;needsReconcile=true;wake?.()},err3=>{if(completed||stopped||mine!==generation)return;subError=err3 instanceof Error?err3:new Error(String(err3));wake?.()})};try{opts?.signal?.addEventListener("abort",onAbort,{once:true});if(stopped)throw phaseError("unavailable");if(opts?.prepare){let timer;try{await Promise.race([opts.prepare(work.signal,deadline),aborted2,new Promise(resolve=>{timer=setTimeout(()=>{work.abort(new DOMException("the goal follow's deadline passed","TimeoutError"));setTimeout(resolve,0)},Math.min(deadline-Date.now(),2147483647))})]);work.signal.throwIfAborted()}catch(err3){throw stopped?phaseError("unavailable"):work.signal.aborted&&!unansweredRequest(err3)?phaseError("deadline-exceeded"):err3}finally{clearTimeout(timer)}}subscribe(opts?.currentNc?.()??nc);unbindReconnect=opts?.onReconnect?.(replaceConnection);for(;;){const preparing=activeNc;try{await bounded(()=>preparing.flush(),deadline)}catch(err3){if(!stopped&&preparing!==activeNc)continue;throw err3}if(stopped)throw phaseError("unavailable");const current2=opts?.currentNc?.();if(current2&¤t2!==activeNc)subscribe(current2);if(preparing===activeNc){progressReady=true;break}}if(stopped)throw phaseError("unavailable");submitted=true;let attributed;let submission;try{attributed=await bounded(()=>submission=submit(work.signal),deadline)}catch(err3){work.abort();let turn;const cause=submission?await Promise.race([submission.then(()=>err3,failure2=>failure2),new Promise(resolve=>{turn=setTimeout(()=>resolve(err3),0)})]).finally(()=>clearTimeout(turn)):err3;if(cause instanceof EpEnvelopeError&&cause.outcome==="not-executed")throw cause;const failure=stopped?phaseError("unavailable"):err3;const message2=failure instanceof Error?failure.message:String(failure);throw new EpEnvelopeError(failure instanceof EpEnvelopeError?failure.code:"unavailable",failure instanceof EpEnvelopeError&&failure.outcome==="unknown"&&message2.includes("do NOT retry")?message2:`${message2}; the submission outcome is unknown. It may have been accepted or executed; do NOT retry without inspecting 'ps'/'inspect' first (SPEC 13.6)`,cause instanceof EpEnvelopeError?cause.details:void 0,"unknown")}if(attributed.reply.ok!==true)return attributed;const acceptance=attributed.reply.data;const goalId=acceptance?.goalId;if(typeof goalId!=="string")return attributed;const acceptedFingerprint=typeof acceptance?.fingerprint==="string"?acceptance.fingerprint:void 0;const acceptedBy=attributed.responder;const acceptedKey2=terminalKey(goalId,acceptedBy.instanceId,acceptedBy.epoch);const readinessDeadlineMs=acceptance?.readinessDeadlineMs;const followDeadlineMs=typeof readinessDeadlineMs==="number"&&Number.isSafeInteger(readinessDeadlineMs)&&readinessDeadlineMs>=0?Math.max(deadlineMs,readinessDeadlineMs+GOAL_FOLLOW_MARGIN_MS):deadlineMs;deadline=Date.now()+followDeadlineMs;const reconcileAt=deadline-Math.min(deadlineMs,followDeadlineMs/2);let finalReadRequested=false;const reconcile=async()=>{if(!opts?.reconcile||completed||stopped||reading||!progressReady)return;reading=true;needsReconcile=false;try{const result=await opts.reconcile(goalId,attributed,{caller:{...acceptingCaller},signal:work.signal,deadlineMs:Math.max(1,deadline-Date.now())});if(completed||stopped||Date.now()>=deadline)return;if(!result||typeof result!=="object"||result.goalId!==goalId)throw new EpEnvelopeError("internal","goal-result reply is malformed or names a different goal; it cannot authorize this outcome (SPEC 13.6)");if(result.result!==void 0){const ref={endpoint,caller:acceptingCaller,goalId};const fact=await verifyFact(result.result,"goal-result reply",ref);if(acceptedFingerprint!==void 0&&fact.fingerprint!==acceptedFingerprint)throw new EpEnvelopeError("internal","goal result fingerprint does not match the accepted goal (SPEC 13.6)");if(fact.committer!==void 0&&fact.committer.instanceId!==acceptedBy.instanceId)throw new EpEnvelopeError("internal",`goal result fact was committed by instance ${fact.committer.instanceId}, not ${acceptedBy.instanceId}, which accepted the goal; it cannot authorize this outcome (SPEC 13.6)`);terminals.set(acceptedKey2,{state:fact.state,data:fact.data})}}catch(err3){if(!completed&&!stopped&&Date.now()<deadline)observationError=err3 instanceof Error?err3:new Error(String(err3))}finally{reading=false;if(!completed&&!stopped)wake?.()}};const current=opts?.currentNc?.();if(current&¤t!==activeNc&&!stopped)replaceConnection(current);needsReconcile=true;while(!terminals.has(acceptedKey2)&&!stopped&&!observationError&&!subError&&Date.now()<deadline){if(!finalReadRequested&&Date.now()>=reconcileAt){finalReadRequested=true;needsReconcile=true}if(needsReconcile&&!reading)void reconcile();if(terminals.has(acceptedKey2)||stopped||observationError||subError)break;await new Promise(resolve=>{const until=finalReadRequested?deadline:reconcileAt;const timer=setTimeout(()=>{timers.delete(timer);wake=void 0;resolve()},Math.max(0,Math.min(until-Date.now(),2147483647)));timers.add(timer);wake=()=>{clearTimeout(timer);timers.delete(timer);wake=void 0;resolve()}})}const terminal=terminals.get(acceptedKey2);const observationFailure=(code,reason2)=>({...attributed,reply:{...attributed.reply,ok:false,data:void 0,error:{code,outcome:"unknown",message:`the goal "${goalId}" was accepted, but ${reason2}. THE GOAL IS UNAFFECTED - it may already have succeeded; this is not evidence the goal failed. Do NOT retry: another submission could duplicate the effect. Inspect 'ps'/'inspect' first (SPEC 13.6)`}}});if(stopped)return observationFailure("unavailable","the endpoint was stopped while awaiting its outcome");if(observationError)return observationFailure("unavailable",`following its outcome failed: ${observationError.message}`);if(!terminal&&subError)return subError instanceof import_nats_core2.PermissionViolationError?observationFailure("permission-denied",`this caller is NOT PERMITTED to hear its outcome: the broker refused the per-goal progress subscription "${progressSubject}" (${subError.message}); grant this caller the per-goal progress read row`):observationFailure("unavailable",`the per-goal progress subscription "${progressSubject}" FAILED (${subError.name}: ${subError.message}); this is NOT a grant refusal, so changing ACLs is the wrong remedy`);if(!terminal)return observationFailure("deadline-exceeded",`no terminal arrived within ${followDeadlineMs}ms; this is a timeout on the WAIT`);if(terminal.state==="succeeded")return{...attributed,reply:{...attributed.reply,ok:true,data:terminal.data,error:void 0}};const d=terminal.data??{};const raw=typeof d.error==="string"?d.error:typeof d.reason==="string"?d.reason:`the goal settled ${terminal.state}`;const details=Array.isArray(d.details)?d.details:void 0;const message=renderLifecycleBlocked(raw,details?{details}:void 0);const fromAccept=lifecycleBlockedFrom(attributed.reply.error);const merged=details??(fromAccept?[fromAccept]:void 0);return{...attributed,reply:{...attributed.reply,ok:false,error:{code:terminal.state,message,...merged?{details:merged}:{}}}}}finally{completed=true;opts?.signal?.removeEventListener("abort",onAbort);unbindReconnect?.();activeSub?.unsubscribe();for(const timer of timers)clearTimeout(timer);timers.clear();wake=void 0;work.abort();abortPhase?.()}}var import_jetstream6=__toESM(require_mod4(),1);var import_transport_node6=__toESM(require_transport_node(),1);var import_node_crypto6=require("node:crypto");var CONTRACT_ARTIFACT_MAX_BYTES=256*1024;var CONTRACT_CLOSURE_MAX_BYTES=1024*1024;var CONTRACT_CLOSURE_MAX_REF_DEPTH=32;var STORE_RESOURCES=new WeakMap;async function contractStoreContext(nc,space2){if(nc===null||typeof nc!=="object"||typeof nc.close!=="function")throw new EpEnvelopeError("failed-precondition","a contract-store context is constructed from ONE binding-layer connection; separate resources are never accepted (SPEC 13.4)");if(typeof space2!=="string"||space2.length===0)throw new EpEnvelopeError("failed-precondition","a contract-store context needs a space");const js=(0,import_jetstream6.jetstream)(nc);const jsm=await(0,import_jetstream6.jetstreamManager)(nc,{checkAPI:false});const ctx=Object.freeze({space:space2});STORE_RESOURCES.set(ctx,{js,jsm});return ctx}function resources(ctx){const r=ctx===null||typeof ctx!=="object"?void 0:STORE_RESOURCES.get(ctx);if(r===void 0)throw new EpEnvelopeError("failed-precondition",`the contract-store context was not constructed by contractStoreContext(); a hand-assembled resource bundle never authorizes - the space bond is constructed, not asserted (SPEC 13.4)`);return r}function contractArtifactDigestHex(bytes){return(0,import_node_crypto6.createHash)("sha256").update(bytes).digest("hex")}function assertCanonicalArtifactBytes(bytes,what){let text2;try{text2=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new EpEnvelopeError("contract-invalid",`${what} is not valid UTF-8; only strict canonical JSON is a contract artifact (SPEC 13.7)`)}let value;try{value=JSON.parse(text2)}catch(e){throw new EpEnvelopeError("contract-invalid",`${what} does not parse as JSON (${e.message}); only strict canonical JSON is a contract artifact (SPEC 13.7)`)}let canonical;try{canonical=canonicalJson(value)}catch(e){throw new EpEnvelopeError("contract-invalid",`${what} is not interchangeable I-JSON (${e.message}); only strict canonical JSON is a contract artifact (SPEC 13.7)`)}if(canonical!==text2)throw new EpEnvelopeError("contract-invalid",`${what} is not its own RFC 8785 canonical serialization; a noncanonical encoding never gets its own content identity (SPEC 13.7)`);return value}function verifyStored(data,digestHex,subject){if(data.length>CONTRACT_ARTIFACT_MAX_BYTES)return void 0;if(contractArtifactDigestHex(data)!==digestHex)return void 0;try{assertCanonicalArtifactBytes(data,`the artifact at ${subject}`)}catch{return void 0}return data}async function fetchContractArtifact(ctx,digestHex,opts={}){const{jsm}=resources(ctx);const stream=epcStreamName(ctx.space);const subject=epcSubject(ctx.space,digestHex);const read=async req=>{try{const stored=await jsm.direct.getMessage(stream,req);return stored===null?"absent":stored.data}catch(e){if(e?.code===10037)return"absent";throw new EpEnvelopeError("unavailable",`the contract-store read for ${digestHex} failed (a failed observation is never absence, SPEC 13.7): ${e?.message??String(e)}`)}};const last=await read({last_by_subj:subject});if(last==="absent")return void 0;const okLast=verifyStored(last,digestHex,subject);if(okLast!==void 0)return okLast;if(opts.lastOnly)throw new ContractStoreCorruptError(`the message at ${subject} does not recompute its digest as strict canonical JSON (SPEC 13.7)`);const first=await read({seq:0,next_by_subj:subject});if(first==="absent")return void 0;const okFirst=verifyStored(first,digestHex,subject);if(okFirst!==void 0)return okFirst;throw new ContractStoreCorruptError(`no message at ${subject} recomputes its digest as strict canonical JSON (checked both the last and the create-only winner); verify-on-read is the tamper boundary and a store with no verifying artifact never serves (SPEC 13.7)`)}var ContractStoreCorruptError=class extends EpEnvelopeError{constructor(message){super("internal",message)}};async function fetchContractClosure(ctx,closureDigestRef,extractRefs,opts={}){resources(ctx);const max=opts.maxArtifacts??CONTRACT_CLOSURE_MAX_ARTIFACTS;if(!Number.isSafeInteger(max)||max<=0||max>CONTRACT_CLOSURE_MAX_ARTIFACTS)throw new EpEnvelopeError("failed-precondition",`maxArtifacts must be a positive integer at or below the frozen ${CONTRACT_CLOSURE_MAX_ARTIFACTS}-artifact ceiling (a caller narrows, never widens); got ${JSON.stringify(opts.maxArtifacts)} (SPEC 13.7)`);const budgetMs=opts.walkBudgetMs??3e4;if(!Number.isSafeInteger(budgetMs)||budgetMs<=0)throw new EpEnvelopeError("failed-precondition",`walkBudgetMs must be a positive integer; got ${JSON.stringify(opts.walkBudgetMs)}`);if(typeof extractRefs!=="function")throw new EpEnvelopeError("failed-precondition","a closure fetch requires the reference-resolution seam (extractRefs); the store never guesses a document's reference shape (SPEC 13.7)");const startedAt2=performance.now();const overBudget=()=>performance.now()-startedAt2>budgetMs;const raceBudget=async(p,what)=>{opts.signal?.throwIfAborted();const rem=budgetMs-(performance.now()-startedAt2);if(rem<=0)throw new EpEnvelopeError("deadline-exceeded",`the closure walk exhausted its ${budgetMs}ms budget before ${what} (SPEC 13.7/13.8)`);let timer;let onAbort;const bound=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new EpEnvelopeError("deadline-exceeded",`the closure walk exceeded its ${budgetMs}ms budget during ${what}; a closure fetch is bounded and fails loud, never hangs (SPEC 13.7/13.8)`)),rem);onAbort=()=>reject(opts.signal?.reason);opts.signal?.addEventListener("abort",onAbort,{once:true})});try{return await Promise.race([p,bound])}finally{clearTimeout(timer);if(onAbort)opts.signal?.removeEventListener("abort",onAbort)}};const getArtifact=hex3=>{const memo=opts.artifactMemo;if(!memo)return fetchContractArtifact(ctx,hex3);const hit=memo.get(hex3);if(hit)return hit;const p=fetchContractArtifact(ctx,hex3);p.catch(()=>{});memo.set(hex3,p);return p};const closureHex=contractRefToHex(closureDigestRef);const manifestBytes=await raceBudget(getArtifact(closureHex),`the manifest fetch for ${closureHex}`);if(manifestBytes===void 0)throw new EpEnvelopeError("failed-precondition",`the closure manifest ${closureHex} is not published; a closure digest names its manifest artifact (SPEC 13.7)`);const manifest=parseClosureManifest(assertCanonicalArtifactBytes(manifestBytes,`the manifest ${closureHex}`),`the manifest ${closureHex}`);const rootHex=contractRefToHex(manifest.root);const out=new Map;let totalBytes=0;let rootReReached=false;const queue=[{hex:rootHex,depth:0}];while(queue.length>0){if(overBudget())throw new EpEnvelopeError("deadline-exceeded",`the closure walk for ${closureHex} exceeded its ${budgetMs}ms budget; a closure fetch is bounded and fails loud, never hangs (SPEC 13.7/13.8)`);const{hex:hex3,depth}=queue.shift();if(depth>CONTRACT_CLOSURE_MAX_REF_DEPTH)throw new EpEnvelopeError("contract-invalid",`the closure walk for ${closureHex} exceeds the ${CONTRACT_CLOSURE_MAX_REF_DEPTH}-deep reference chain bound (SPEC 13.7)`);if(out.has(hex3))continue;if(out.size>=max)throw new EpEnvelopeError("failed-precondition",`the contract closure exceeds the ${max}-artifact bound; a truncated closure never verifies as complete (SPEC 13.7)`);const bytes=await raceBudget(getArtifact(hex3),`the fetch of ${hex3}`);if(bytes===void 0)throw new EpEnvelopeError("failed-precondition",`the closure references artifact ${hex3} but it is not published; a closure is fetched all-or-nothing (SPEC 13.7)`);totalBytes+=bytes.length;if(totalBytes>CONTRACT_CLOSURE_MAX_BYTES)throw new EpEnvelopeError("contract-invalid",`the closure for ${closureHex} exceeds the ${CONTRACT_CLOSURE_MAX_BYTES}-byte bound (SPEC 13.7)`);out.set(hex3,bytes);const refs=extractRefs(new Uint8Array(bytes),hex3);if(!Array.isArray(refs)||!refs.every(r=>typeof r==="string"))throw new EpEnvelopeError("internal",`the reference-resolution seam returned a non-string-array for ${hex3}; a garbled resolution never extends a closure (SPEC 13.7)`);if(refs.length>CONTRACT_CLOSURE_MAX_ARTIFACTS)throw new EpEnvelopeError("contract-invalid",`artifact ${hex3} names ${refs.length} references, above the ${CONTRACT_CLOSURE_MAX_ARTIFACTS}-reference cap; an unbounded reference list never extends a closure (SPEC 13.7)`);if(overBudget())throw new EpEnvelopeError("deadline-exceeded",`the closure walk for ${closureHex} exceeded its ${budgetMs}ms budget resolving references for ${hex3} (SPEC 13.7/13.8)`);for(const r of refs){const rHex=contractRefToHex(r);if(rHex===rootHex)rootReReached=true;queue.push({hex:rHex,depth:depth+1})}}const walked=new Set;for(const hex3 of out.keys())if(hex3!==rootHex||rootReReached)walked.add(sha256Ref(hex3));const memberSet=new Set(manifest.members);for(const m of walked)if(!memberSet.has(m))throw new EpEnvelopeError("contract-invalid",`the closure walk reached ${m} but the manifest ${closureHex} does not name it; an under-naming manifest never verifies (SPEC 13.7)`);for(const m of memberSet)if(!walked.has(m))throw new EpEnvelopeError("contract-invalid",`the manifest ${closureHex} names ${m} but the walk never reached it; an over-naming manifest never verifies (SPEC 13.7)`);return{manifest,artifacts:out}}var SERVICE_RENEWAL_TTL_SECONDS=24*60*60;var SERVICE_AUTHORITY_MAX_BYTES=2*1024*1024;var SERVICE_CALLER_PAYLOAD_OVERHEAD=1024;var SERVICE_CALLER_PAYLOAD_FLOOR=SERVICE_AUTHORITY_MAX_BYTES+SERVICE_CALLER_PAYLOAD_OVERHEAD;var MANAGER_START_PAYLOAD_FLOOR=CONTRACT_ARTIFACT_MAX_BYTES+SERVICE_CALLER_PAYLOAD_OVERHEAD;var import_nkeys4=__toESM(require_mod(),1);var import_node_crypto7=require("node:crypto");var Types;(function(Types2){Types2["Operator"]="operator";Types2["Account"]="account";Types2["User"]="user";Types2["Activation"]="activation";Types2["AuthorizationResponse"]="authorization_response"})(Types||(Types={}));(function(nacl2){"use strict";var u64=function(h2,l){this.hi=h2|0>>>0;this.lo=l|0>>>0};var gf=function(init){var i,r=new Float64Array(16);if(init)for(i=0;i<init.length;i++)r[i]=init[i];return r};var randombytes=function(){throw new Error("no PRNG")};var _0=new Uint8Array(16);var _9=new Uint8Array(32);_9[0]=9;var gf0=gf(),gf1=gf([1]),_121665=gf([56129,1]),D=gf([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),D2=gf([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),X=gf([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),Y=gf([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),I=gf([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function L32(x,c){return x<<c|x>>>32-c}function ld32(x,i){var u=x[i+3]&255;u=u<<8|x[i+2]&255;u=u<<8|x[i+1]&255;return u<<8|x[i+0]&255}function dl64(x,i){var h2=x[i]<<24|x[i+1]<<16|x[i+2]<<8|x[i+3];var l=x[i+4]<<24|x[i+5]<<16|x[i+6]<<8|x[i+7];return new u64(h2,l)}function st32(x,j,u){var i;for(i=0;i<4;i++){x[j+i]=u&255;u>>>=8}}function ts64(x,i,u){x[i]=u.hi>>24&255;x[i+1]=u.hi>>16&255;x[i+2]=u.hi>>8&255;x[i+3]=u.hi&255;x[i+4]=u.lo>>24&255;x[i+5]=u.lo>>16&255;x[i+6]=u.lo>>8&255;x[i+7]=u.lo&255}function vn(x,xi,y,yi,n){var i,d=0;for(i=0;i<n;i++)d|=x[xi+i]^y[yi+i];return(1&d-1>>>8)-1}function crypto_verify_16(x,xi,y,yi){return vn(x,xi,y,yi,16)}function crypto_verify_32(x,xi,y,yi){return vn(x,xi,y,yi,32)}function core(out,inp,k,c,h2){var w=new Uint32Array(16),x=new Uint32Array(16),y=new Uint32Array(16),t=new Uint32Array(4);var i,j,m;for(i=0;i<4;i++){x[5*i]=ld32(c,4*i);x[1+i]=ld32(k,4*i);x[6+i]=ld32(inp,4*i);x[11+i]=ld32(k,16+4*i)}for(i=0;i<16;i++)y[i]=x[i];for(i=0;i<20;i++){for(j=0;j<4;j++){for(m=0;m<4;m++)t[m]=x[(5*j+4*m)%16];t[1]^=L32(t[0]+t[3]|0,7);t[2]^=L32(t[1]+t[0]|0,9);t[3]^=L32(t[2]+t[1]|0,13);t[0]^=L32(t[3]+t[2]|0,18);for(m=0;m<4;m++)w[4*j+(j+m)%4]=t[m]}for(m=0;m<16;m++)x[m]=w[m]}if(h2){for(i=0;i<16;i++)x[i]=x[i]+y[i]|0;for(i=0;i<4;i++){x[5*i]=x[5*i]-ld32(c,4*i)|0;x[6+i]=x[6+i]-ld32(inp,4*i)|0}for(i=0;i<4;i++){st32(out,4*i,x[5*i]);st32(out,16+4*i,x[6+i])}}else{for(i=0;i<16;i++)st32(out,4*i,x[i]+y[i]|0)}}function crypto_core_salsa20(out,inp,k,c){core(out,inp,k,c,false);return 0}function crypto_core_hsalsa20(out,inp,k,c){core(out,inp,k,c,true);return 0}var sigma=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k){var z2=new Uint8Array(16),x=new Uint8Array(64);var u,i;if(!b)return 0;for(i=0;i<16;i++)z2[i]=0;for(i=0;i<8;i++)z2[i]=n[i];while(b>=64){crypto_core_salsa20(x,z2,k,sigma);for(i=0;i<64;i++)c[cpos+i]=(m?m[mpos+i]:0)^x[i];u=1;for(i=8;i<16;i++){u=u+(z2[i]&255)|0;z2[i]=u&255;u>>>=8}b-=64;cpos+=64;if(m)mpos+=64}if(b>0){crypto_core_salsa20(x,z2,k,sigma);for(i=0;i<b;i++)c[cpos+i]=(m?m[mpos+i]:0)^x[i]}return 0}function crypto_stream_salsa20(c,cpos,d,n,k){return crypto_stream_salsa20_xor(c,cpos,null,0,d,n,k)}function crypto_stream(c,cpos,d,n,k){var s=new Uint8Array(32);crypto_core_hsalsa20(s,n,k,sigma);return crypto_stream_salsa20(c,cpos,d,n.subarray(16),s)}function crypto_stream_xor(c,cpos,m,mpos,d,n,k){var s=new Uint8Array(32);crypto_core_hsalsa20(s,n,k,sigma);return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,n.subarray(16),s)}function add1305(h2,c){var j,u=0;for(j=0;j<17;j++){u=u+(h2[j]+c[j]|0)|0;h2[j]=u&255;u>>>=8}}var minusp=new Uint32Array([5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252]);function crypto_onetimeauth(out,outpos,m,mpos,n,k){var s,i,j,u;var x=new Uint32Array(17),r=new Uint32Array(17),h2=new Uint32Array(17),c=new Uint32Array(17),g=new Uint32Array(17);for(j=0;j<17;j++)r[j]=h2[j]=0;for(j=0;j<16;j++)r[j]=k[j];r[3]&=15;r[4]&=252;r[7]&=15;r[8]&=252;r[11]&=15;r[12]&=252;r[15]&=15;while(n>0){for(j=0;j<17;j++)c[j]=0;for(j=0;j<16&&j<n;++j)c[j]=m[mpos+j];c[j]=1;mpos+=j;n-=j;add1305(h2,c);for(i=0;i<17;i++){x[i]=0;for(j=0;j<17;j++)x[i]=x[i]+h2[j]*(j<=i?r[i-j]:320*r[i+17-j]|0)|0|0}for(i=0;i<17;i++)h2[i]=x[i];u=0;for(j=0;j<16;j++){u=u+h2[j]|0;h2[j]=u&255;u>>>=8}u=u+h2[16]|0;h2[16]=u&3;u=5*(u>>>2)|0;for(j=0;j<16;j++){u=u+h2[j]|0;h2[j]=u&255;u>>>=8}u=u+h2[16]|0;h2[16]=u}for(j=0;j<17;j++)g[j]=h2[j];add1305(h2,minusp);s=-(h2[16]>>>7)|0;for(j=0;j<17;j++)h2[j]^=s&(g[j]^h2[j]);for(j=0;j<16;j++)c[j]=k[j+16];c[16]=0;add1305(h2,c);for(j=0;j<16;j++)out[outpos+j]=h2[j];return 0}function crypto_onetimeauth_verify(h2,hpos,m,mpos,n,k){var x=new Uint8Array(16);crypto_onetimeauth(x,0,m,mpos,n,k);return crypto_verify_16(h2,hpos,x,0)}function crypto_secretbox(c,m,d,n,k){var i;if(d<32)return-1;crypto_stream_xor(c,0,m,0,d,n,k);crypto_onetimeauth(c,16,c,32,d-32,c);for(i=0;i<16;i++)c[i]=0;return 0}function crypto_secretbox_open(m,c,d,n,k){var i;var x=new Uint8Array(32);if(d<32)return-1;crypto_stream(x,0,32,n,k);if(crypto_onetimeauth_verify(c,16,c,32,d-32,x)!==0)return-1;crypto_stream_xor(m,0,c,0,d,n,k);for(i=0;i<32;i++)m[i]=0;return 0}function set25519(r,a){var i;for(i=0;i<16;i++)r[i]=a[i]|0}function car25519(o){var c;var i;for(i=0;i<16;i++){o[i]+=65536;c=Math.floor(o[i]/65536);o[(i+1)*(i<15?1:0)]+=c-1+37*(c-1)*(i===15?1:0);o[i]-=c*65536}}function sel25519(p,q,b){var t,c=~(b-1);for(var i=0;i<16;i++){t=c&(p[i]^q[i]);p[i]^=t;q[i]^=t}}function pack25519(o,n){var i,j,b;var m=gf(),t=gf();for(i=0;i<16;i++)t[i]=n[i];car25519(t);car25519(t);car25519(t);for(j=0;j<2;j++){m[0]=t[0]-65517;for(i=1;i<15;i++){m[i]=t[i]-65535-(m[i-1]>>16&1);m[i-1]&=65535}m[15]=t[15]-32767-(m[14]>>16&1);b=m[15]>>16&1;m[14]&=65535;sel25519(t,m,1-b)}for(i=0;i<16;i++){o[2*i]=t[i]&255;o[2*i+1]=t[i]>>8}}function neq25519(a,b){var c=new Uint8Array(32),d=new Uint8Array(32);pack25519(c,a);pack25519(d,b);return crypto_verify_32(c,0,d,0)}function par25519(a){var d=new Uint8Array(32);pack25519(d,a);return d[0]&1}function unpack25519(o,n){var i;for(i=0;i<16;i++)o[i]=n[2*i]+(n[2*i+1]<<8);o[15]&=32767}function A(o,a,b){var i;for(i=0;i<16;i++)o[i]=a[i]+b[i]|0}function Z(o,a,b){var i;for(i=0;i<16;i++)o[i]=a[i]-b[i]|0}function M(o,a,b){var i,j,t=new Float64Array(31);for(i=0;i<31;i++)t[i]=0;for(i=0;i<16;i++){for(j=0;j<16;j++){t[i+j]+=a[i]*b[j]}}for(i=0;i<15;i++){t[i]+=38*t[i+16]}for(i=0;i<16;i++)o[i]=t[i];car25519(o);car25519(o)}function S(o,a){M(o,a,a)}function inv25519(o,i){var c=gf();var a;for(a=0;a<16;a++)c[a]=i[a];for(a=253;a>=0;a--){S(c,c);if(a!==2&&a!==4)M(c,c,i)}for(a=0;a<16;a++)o[a]=c[a]}function pow2523(o,i){var c=gf();var a;for(a=0;a<16;a++)c[a]=i[a];for(a=250;a>=0;a--){S(c,c);if(a!==1)M(c,c,i)}for(a=0;a<16;a++)o[a]=c[a]}function crypto_scalarmult(q,n,p){var z2=new Uint8Array(32);var x=new Float64Array(80),r,i;var a=gf(),b=gf(),c=gf(),d=gf(),e=gf(),f=gf();for(i=0;i<31;i++)z2[i]=n[i];z2[31]=n[31]&127|64;z2[0]&=248;unpack25519(x,p);for(i=0;i<16;i++){b[i]=x[i];d[i]=a[i]=c[i]=0}a[0]=d[0]=1;for(i=254;i>=0;--i){r=z2[i>>>3]>>>(i&7)&1;sel25519(a,b,r);sel25519(c,d,r);A(e,a,c);Z(a,a,c);A(c,b,d);Z(b,b,d);S(d,e);S(f,a);M(a,c,a);M(c,b,e);A(e,a,c);Z(a,a,c);S(b,a);Z(c,d,f);M(a,c,_121665);A(a,a,d);M(c,c,a);M(a,d,f);M(d,b,x);S(b,e);sel25519(a,b,r);sel25519(c,d,r)}for(i=0;i<16;i++){x[i+16]=a[i];x[i+32]=c[i];x[i+48]=b[i];x[i+64]=d[i]}var x32=x.subarray(32);var x16=x.subarray(16);inv25519(x32,x32);M(x16,x16,x32);pack25519(q,x16);return 0}function crypto_scalarmult_base(q,n){return crypto_scalarmult(q,n,_9)}function crypto_box_keypair(y,x){randombytes(x,32);return crypto_scalarmult_base(y,x)}function crypto_box_beforenm(k,y,x){var s=new Uint8Array(32);crypto_scalarmult(s,x,y);return crypto_core_hsalsa20(k,_0,s,sigma)}var crypto_box_afternm=crypto_secretbox;var crypto_box_open_afternm=crypto_secretbox_open;function crypto_box(c,m,d,n,y,x){var k=new Uint8Array(32);crypto_box_beforenm(k,y,x);return crypto_box_afternm(c,m,d,n,k)}function crypto_box_open(m,c,d,n,y,x){var k=new Uint8Array(32);crypto_box_beforenm(k,y,x);return crypto_box_open_afternm(m,c,d,n,k)}function add64(){var a=0,b=0,c=0,d=0,m16=65535,l,h2,i;for(i=0;i<arguments.length;i++){l=arguments[i].lo;h2=arguments[i].hi;a+=l&m16;b+=l>>>16;c+=h2&m16;d+=h2>>>16}b+=a>>>16;c+=b>>>16;d+=c>>>16;return new u64(c&m16|d<<16,a&m16|b<<16)}function shr64(x,c){return new u64(x.hi>>>c,x.lo>>>c|x.hi<<32-c)}function xor64(){var l=0,h2=0,i;for(i=0;i<arguments.length;i++){l^=arguments[i].lo;h2^=arguments[i].hi}return new u64(h2,l)}function R(x,c){var h2,l,c1=32-c;if(c<32){h2=x.hi>>>c|x.lo<<c1;l=x.lo>>>c|x.hi<<c1}else if(c<64){h2=x.lo>>>c|x.hi<<c1;l=x.hi>>>c|x.lo<<c1}return new u64(h2,l)}function Ch(x,y,z2){var h2=x.hi&y.hi^~x.hi&z2.hi,l=x.lo&y.lo^~x.lo&z2.lo;return new u64(h2,l)}function Maj(x,y,z2){var h2=x.hi&y.hi^x.hi&z2.hi^y.hi&z2.hi,l=x.lo&y.lo^x.lo&z2.lo^y.lo&z2.lo;return new u64(h2,l)}function Sigma0(x){return xor64(R(x,28),R(x,34),R(x,39))}function Sigma1(x){return xor64(R(x,14),R(x,18),R(x,41))}function sigma0(x){return xor64(R(x,1),R(x,8),shr64(x,7))}function sigma1(x){return xor64(R(x,19),R(x,61),shr64(x,6))}var K=[new u64(1116352408,3609767458),new u64(1899447441,602891725),new u64(3049323471,3964484399),new u64(3921009573,2173295548),new u64(961987163,4081628472),new u64(1508970993,3053834265),new u64(2453635748,2937671579),new u64(2870763221,3664609560),new u64(3624381080,2734883394),new u64(310598401,1164996542),new u64(607225278,1323610764),new u64(1426881987,3590304994),new u64(1925078388,4068182383),new u64(2162078206,991336113),new u64(2614888103,633803317),new u64(3248222580,3479774868),new u64(3835390401,2666613458),new u64(4022224774,944711139),new u64(264347078,2341262773),new u64(604807628,2007800933),new u64(770255983,1495990901),new u64(1249150122,1856431235),new u64(1555081692,3175218132),new u64(1996064986,2198950837),new u64(2554220882,3999719339),new u64(2821834349,766784016),new u64(2952996808,2566594879),new u64(3210313671,3203337956),new u64(3336571891,1034457026),new u64(3584528711,2466948901),new u64(113926993,3758326383),new u64(338241895,168717936),new u64(666307205,1188179964),new u64(773529912,1546045734),new u64(1294757372,1522805485),new u64(1396182291,2643833823),new u64(1695183700,2343527390),new u64(1986661051,1014477480),new u64(2177026350,1206759142),new u64(2456956037,344077627),new u64(2730485921,1290863460),new u64(2820302411,3158454273),new u64(3259730800,3505952657),new u64(3345764771,106217008),new u64(3516065817,3606008344),new u64(3600352804,1432725776),new u64(4094571909,1467031594),new u64(275423344,851169720),new u64(430227734,3100823752),new u64(506948616,1363258195),new u64(659060556,3750685593),new u64(883997877,3785050280),new u64(958139571,3318307427),new u64(1322822218,3812723403),new u64(1537002063,2003034995),new u64(1747873779,3602036899),new u64(1955562222,1575990012),new u64(2024104815,1125592928),new u64(2227730452,2716904306),new u64(2361852424,442776044),new u64(2428436474,593698344),new u64(2756734187,3733110249),new u64(3204031479,2999351573),new u64(3329325298,3815920427),new u64(3391569614,3928383900),new u64(3515267271,566280711),new u64(3940187606,3454069534),new u64(4118630271,4000239992),new u64(116418474,1914138554),new u64(174292421,2731055270),new u64(289380356,3203993006),new u64(460393269,320620315),new u64(685471733,587496836),new u64(852142971,1086792851),new u64(1017036298,365543100),new u64(1126000580,2618297676),new u64(1288033470,3409855158),new u64(1501505948,4234509866),new u64(1607167915,987167468),new u64(1816402316,1246189591)];function crypto_hashblocks(x,m,n){var z2=[],b=[],a=[],w=[],t,i,j;for(i=0;i<8;i++)z2[i]=a[i]=dl64(x,8*i);var pos=0;while(n>=128){for(i=0;i<16;i++)w[i]=dl64(m,8*i+pos);for(i=0;i<80;i++){for(j=0;j<8;j++)b[j]=a[j];t=add64(a[7],Sigma1(a[4]),Ch(a[4],a[5],a[6]),K[i],w[i%16]);b[7]=add64(t,Sigma0(a[0]),Maj(a[0],a[1],a[2]));b[3]=add64(b[3],t);for(j=0;j<8;j++)a[(j+1)%8]=b[j];if(i%16===15){for(j=0;j<16;j++){w[j]=add64(w[j],w[(j+9)%16],sigma0(w[(j+1)%16]),sigma1(w[(j+14)%16]))}}}for(i=0;i<8;i++){a[i]=add64(a[i],z2[i]);z2[i]=a[i]}pos+=128;n-=128}for(i=0;i<8;i++)ts64(x,8*i,z2[i]);return n}var iv=new Uint8Array([106,9,230,103,243,188,201,8,187,103,174,133,132,202,167,59,60,110,243,114,254,148,248,43,165,79,245,58,95,29,54,241,81,14,82,127,173,230,130,209,155,5,104,140,43,62,108,31,31,131,217,171,251,65,189,107,91,224,205,25,19,126,33,121]);function crypto_hash(out,m,n){var h2=new Uint8Array(64),x=new Uint8Array(256);var i,b=n;for(i=0;i<64;i++)h2[i]=iv[i];crypto_hashblocks(h2,m,n);n%=128;for(i=0;i<256;i++)x[i]=0;for(i=0;i<n;i++)x[i]=m[b-n+i];x[n]=128;n=256-128*(n<112?1:0);x[n-9]=0;ts64(x,n-8,new u64(b/536870912|0,b<<3));crypto_hashblocks(h2,x,n);for(i=0;i<64;i++)out[i]=h2[i];return 0}function add(p,q){var a=gf(),b=gf(),c=gf(),d=gf(),e=gf(),f=gf(),g=gf(),h2=gf(),t=gf();Z(a,p[1],p[0]);Z(t,q[1],q[0]);M(a,a,t);A(b,p[0],p[1]);A(t,q[0],q[1]);M(b,b,t);M(c,p[3],q[3]);M(c,c,D2);M(d,p[2],q[2]);A(d,d,d);Z(e,b,a);Z(f,d,c);A(g,d,c);A(h2,b,a);M(p[0],e,f);M(p[1],h2,g);M(p[2],g,f);M(p[3],e,h2)}function cswap(p,q,b){var i;for(i=0;i<4;i++){sel25519(p[i],q[i],b)}}function pack(r,p){var tx=gf(),ty=gf(),zi=gf();inv25519(zi,p[2]);M(tx,p[0],zi);M(ty,p[1],zi);pack25519(r,ty);r[31]^=par25519(tx)<<7}function scalarmult(p,q,s){var b,i;set25519(p[0],gf0);set25519(p[1],gf1);set25519(p[2],gf1);set25519(p[3],gf0);for(i=255;i>=0;--i){b=s[i/8|0]>>(i&7)&1;cswap(p,q,b);add(q,p);add(p,p);cswap(p,q,b)}}function scalarbase(p,s){var q=[gf(),gf(),gf(),gf()];set25519(q[0],X);set25519(q[1],Y);set25519(q[2],gf1);M(q[3],X,Y);scalarmult(p,q,s)}function crypto_sign_keypair(pk,sk,seeded){var d=new Uint8Array(64);var p=[gf(),gf(),gf(),gf()];var i;if(!seeded)randombytes(sk,32);crypto_hash(d,sk,32);d[0]&=248;d[31]&=127;d[31]|=64;scalarbase(p,d);pack(pk,p);for(i=0;i<32;i++)sk[i+32]=pk[i];return 0}var L=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function modL(r,x){var carry,i,j,k;for(i=63;i>=32;--i){carry=0;for(j=i-32,k=i-12;j<k;++j){x[j]+=carry-16*x[i]*L[j-(i-32)];carry=Math.floor((x[j]+128)/256);x[j]-=carry*256}x[j]+=carry;x[i]=0}carry=0;for(j=0;j<32;j++){x[j]+=carry-(x[31]>>4)*L[j];carry=x[j]>>8;x[j]&=255}for(j=0;j<32;j++)x[j]-=carry*L[j];for(i=0;i<32;i++){x[i+1]+=x[i]>>8;r[i]=x[i]&255}}function reduce(r){var x=new Float64Array(64),i;for(i=0;i<64;i++)x[i]=r[i];for(i=0;i<64;i++)r[i]=0;modL(r,x)}function crypto_sign(sm,m,n,sk){var d=new Uint8Array(64),h2=new Uint8Array(64),r=new Uint8Array(64);var i,j,x=new Float64Array(64);var p=[gf(),gf(),gf(),gf()];crypto_hash(d,sk,32);d[0]&=248;d[31]&=127;d[31]|=64;var smlen=n+64;for(i=0;i<n;i++)sm[64+i]=m[i];for(i=0;i<32;i++)sm[32+i]=d[32+i];crypto_hash(r,sm.subarray(32),n+32);reduce(r);scalarbase(p,r);pack(sm,p);for(i=32;i<64;i++)sm[i]=sk[i];crypto_hash(h2,sm,n+64);reduce(h2);for(i=0;i<64;i++)x[i]=0;for(i=0;i<32;i++)x[i]=r[i];for(i=0;i<32;i++){for(j=0;j<32;j++){x[i+j]+=h2[i]*d[j]}}modL(sm.subarray(32),x);return smlen}function unpackneg(r,p){var t=gf(),chk=gf(),num=gf(),den=gf(),den2=gf(),den4=gf(),den6=gf();set25519(r[2],gf1);unpack25519(r[1],p);S(num,r[1]);M(den,num,D);Z(num,num,r[2]);A(den,r[2],den);S(den2,den);S(den4,den2);M(den6,den4,den2);M(t,den6,num);M(t,t,den);pow2523(t,t);M(t,t,num);M(t,t,den);M(t,t,den);M(r[0],t,den);S(chk,r[0]);M(chk,chk,den);if(neq25519(chk,num))M(r[0],r[0],I);S(chk,r[0]);M(chk,chk,den);if(neq25519(chk,num))return-1;if(par25519(r[0])===p[31]>>7)Z(r[0],gf0,r[0]);M(r[3],r[0],r[1]);return 0}function crypto_sign_open(m,sm,n,pk){var i;var t=new Uint8Array(32),h2=new Uint8Array(64);var p=[gf(),gf(),gf(),gf()],q=[gf(),gf(),gf(),gf()];if(n<64)return-1;if(unpackneg(q,pk))return-1;for(i=0;i<n;i++)m[i]=sm[i];for(i=0;i<32;i++)m[i+32]=pk[i];crypto_hash(h2,m,n);reduce(h2);scalarmult(p,q,h2);scalarbase(q,sm.subarray(32));add(p,q);pack(t,p);n-=64;if(crypto_verify_32(sm,0,t,0)){for(i=0;i<n;i++)m[i]=0;return-1}for(i=0;i<n;i++)m[i]=sm[i+64];return n}var crypto_secretbox_KEYBYTES=32,crypto_secretbox_NONCEBYTES=24,crypto_secretbox_ZEROBYTES=32,crypto_secretbox_BOXZEROBYTES=16,crypto_scalarmult_BYTES=32,crypto_scalarmult_SCALARBYTES=32,crypto_box_PUBLICKEYBYTES=32,crypto_box_SECRETKEYBYTES=32,crypto_box_BEFORENMBYTES=32,crypto_box_NONCEBYTES=crypto_secretbox_NONCEBYTES,crypto_box_ZEROBYTES=crypto_secretbox_ZEROBYTES,crypto_box_BOXZEROBYTES=crypto_secretbox_BOXZEROBYTES,crypto_sign_BYTES=64,crypto_sign_PUBLICKEYBYTES=32,crypto_sign_SECRETKEYBYTES=64,crypto_sign_SEEDBYTES=32,crypto_hash_BYTES=64;nacl2.lowlevel={crypto_core_hsalsa20,crypto_stream_xor,crypto_stream,crypto_stream_salsa20_xor,crypto_stream_salsa20,crypto_onetimeauth,crypto_onetimeauth_verify,crypto_verify_16,crypto_verify_32,crypto_secretbox,crypto_secretbox_open,crypto_scalarmult,crypto_scalarmult_base,crypto_box_beforenm,crypto_box_afternm,crypto_box,crypto_box_open,crypto_box_keypair,crypto_hash,crypto_sign,crypto_sign_keypair,crypto_sign_open,crypto_secretbox_KEYBYTES,crypto_secretbox_NONCEBYTES,crypto_secretbox_ZEROBYTES,crypto_secretbox_BOXZEROBYTES,crypto_scalarmult_BYTES,crypto_scalarmult_SCALARBYTES,crypto_box_PUBLICKEYBYTES,crypto_box_SECRETKEYBYTES,crypto_box_BEFORENMBYTES,crypto_box_NONCEBYTES,crypto_box_ZEROBYTES,crypto_box_BOXZEROBYTES,crypto_sign_BYTES,crypto_sign_PUBLICKEYBYTES,crypto_sign_SECRETKEYBYTES,crypto_sign_SEEDBYTES,crypto_hash_BYTES,gf,D,L,pack25519,unpack25519,M,A,S,Z,pow2523,add,set25519,modL,scalarmult,scalarbase};function checkLengths(k,n){if(k.length!==crypto_secretbox_KEYBYTES)throw new Error("bad key size");if(n.length!==crypto_secretbox_NONCEBYTES)throw new Error("bad nonce size")}function checkBoxLengths(pk,sk){if(pk.length!==crypto_box_PUBLICKEYBYTES)throw new Error("bad public key size");if(sk.length!==crypto_box_SECRETKEYBYTES)throw new Error("bad secret key size")}function checkArrayTypes(){for(var i=0;i<arguments.length;i++){if(!(arguments[i]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}}function cleanup(arr){for(var i=0;i<arr.length;i++)arr[i]=0}nacl2.randomBytes=function(n){var b=new Uint8Array(n);randombytes(b,n);return b};nacl2.secretbox=function(msg,nonce3,key){checkArrayTypes(msg,nonce3,key);checkLengths(key,nonce3);var m=new Uint8Array(crypto_secretbox_ZEROBYTES+msg.length);var c=new Uint8Array(m.length);for(var i=0;i<msg.length;i++)m[i+crypto_secretbox_ZEROBYTES]=msg[i];crypto_secretbox(c,m,m.length,nonce3,key);return c.subarray(crypto_secretbox_BOXZEROBYTES)};nacl2.secretbox.open=function(box,nonce3,key){checkArrayTypes(box,nonce3,key);checkLengths(key,nonce3);var c=new Uint8Array(crypto_secretbox_BOXZEROBYTES+box.length);var m=new Uint8Array(c.length);for(var i=0;i<box.length;i++)c[i+crypto_secretbox_BOXZEROBYTES]=box[i];if(c.length<32)return null;if(crypto_secretbox_open(m,c,c.length,nonce3,key)!==0)return null;return m.subarray(crypto_secretbox_ZEROBYTES)};nacl2.secretbox.keyLength=crypto_secretbox_KEYBYTES;nacl2.secretbox.nonceLength=crypto_secretbox_NONCEBYTES;nacl2.secretbox.overheadLength=crypto_secretbox_BOXZEROBYTES;nacl2.scalarMult=function(n,p){checkArrayTypes(n,p);if(n.length!==crypto_scalarmult_SCALARBYTES)throw new Error("bad n size");if(p.length!==crypto_scalarmult_BYTES)throw new Error("bad p size");var q=new Uint8Array(crypto_scalarmult_BYTES);crypto_scalarmult(q,n,p);return q};nacl2.scalarMult.base=function(n){checkArrayTypes(n);if(n.length!==crypto_scalarmult_SCALARBYTES)throw new Error("bad n size");var q=new Uint8Array(crypto_scalarmult_BYTES);crypto_scalarmult_base(q,n);return q};nacl2.scalarMult.scalarLength=crypto_scalarmult_SCALARBYTES;nacl2.scalarMult.groupElementLength=crypto_scalarmult_BYTES;nacl2.box=function(msg,nonce3,publicKey,secretKey){var k=nacl2.box.before(publicKey,secretKey);return nacl2.secretbox(msg,nonce3,k)};nacl2.box.before=function(publicKey,secretKey){checkArrayTypes(publicKey,secretKey);checkBoxLengths(publicKey,secretKey);var k=new Uint8Array(crypto_box_BEFORENMBYTES);crypto_box_beforenm(k,publicKey,secretKey);return k};nacl2.box.after=nacl2.secretbox;nacl2.box.open=function(msg,nonce3,publicKey,secretKey){var k=nacl2.box.before(publicKey,secretKey);return nacl2.secretbox.open(msg,nonce3,k)};nacl2.box.open.after=nacl2.secretbox.open;nacl2.box.keyPair=function(){var pk=new Uint8Array(crypto_box_PUBLICKEYBYTES);var sk=new Uint8Array(crypto_box_SECRETKEYBYTES);crypto_box_keypair(pk,sk);return{publicKey:pk,secretKey:sk}};nacl2.box.keyPair.fromSecretKey=function(secretKey){checkArrayTypes(secretKey);if(secretKey.length!==crypto_box_SECRETKEYBYTES)throw new Error("bad secret key size");var pk=new Uint8Array(crypto_box_PUBLICKEYBYTES);crypto_scalarmult_base(pk,secretKey);return{publicKey:pk,secretKey:new Uint8Array(secretKey)}};nacl2.box.publicKeyLength=crypto_box_PUBLICKEYBYTES;nacl2.box.secretKeyLength=crypto_box_SECRETKEYBYTES;nacl2.box.sharedKeyLength=crypto_box_BEFORENMBYTES;nacl2.box.nonceLength=crypto_box_NONCEBYTES;nacl2.box.overheadLength=nacl2.secretbox.overheadLength;nacl2.sign=function(msg,secretKey){checkArrayTypes(msg,secretKey);if(secretKey.length!==crypto_sign_SECRETKEYBYTES)throw new Error("bad secret key size");var signedMsg=new Uint8Array(crypto_sign_BYTES+msg.length);crypto_sign(signedMsg,msg,msg.length,secretKey);return signedMsg};nacl2.sign.open=function(signedMsg,publicKey){checkArrayTypes(signedMsg,publicKey);if(publicKey.length!==crypto_sign_PUBLICKEYBYTES)throw new Error("bad public key size");var tmp=new Uint8Array(signedMsg.length);var mlen=crypto_sign_open(tmp,signedMsg,signedMsg.length,publicKey);if(mlen<0)return null;var m=new Uint8Array(mlen);for(var i=0;i<m.length;i++)m[i]=tmp[i];return m};nacl2.sign.detached=function(msg,secretKey){var signedMsg=nacl2.sign(msg,secretKey);var sig=new Uint8Array(crypto_sign_BYTES);for(var i=0;i<sig.length;i++)sig[i]=signedMsg[i];return sig};nacl2.sign.detached.verify=function(msg,sig,publicKey){checkArrayTypes(msg,sig,publicKey);if(sig.length!==crypto_sign_BYTES)throw new Error("bad signature size");if(publicKey.length!==crypto_sign_PUBLICKEYBYTES)throw new Error("bad public key size");var sm=new Uint8Array(crypto_sign_BYTES+msg.length);var m=new Uint8Array(crypto_sign_BYTES+msg.length);var i;for(i=0;i<crypto_sign_BYTES;i++)sm[i]=sig[i];for(i=0;i<msg.length;i++)sm[i+crypto_sign_BYTES]=msg[i];return crypto_sign_open(m,sm,sm.length,publicKey)>=0};nacl2.sign.keyPair=function(){var pk=new Uint8Array(crypto_sign_PUBLICKEYBYTES);var sk=new Uint8Array(crypto_sign_SECRETKEYBYTES);crypto_sign_keypair(pk,sk);return{publicKey:pk,secretKey:sk}};nacl2.sign.keyPair.fromSecretKey=function(secretKey){checkArrayTypes(secretKey);if(secretKey.length!==crypto_sign_SECRETKEYBYTES)throw new Error("bad secret key size");var pk=new Uint8Array(crypto_sign_PUBLICKEYBYTES);for(var i=0;i<pk.length;i++)pk[i]=secretKey[32+i];return{publicKey:pk,secretKey:new Uint8Array(secretKey)}};nacl2.sign.keyPair.fromSeed=function(seed){checkArrayTypes(seed);if(seed.length!==crypto_sign_SEEDBYTES)throw new Error("bad seed size");var pk=new Uint8Array(crypto_sign_PUBLICKEYBYTES);var sk=new Uint8Array(crypto_sign_SECRETKEYBYTES);for(var i=0;i<32;i++)sk[i]=seed[i];crypto_sign_keypair(pk,sk,true);return{publicKey:pk,secretKey:sk}};nacl2.sign.publicKeyLength=crypto_sign_PUBLICKEYBYTES;nacl2.sign.secretKeyLength=crypto_sign_SECRETKEYBYTES;nacl2.sign.seedLength=crypto_sign_SEEDBYTES;nacl2.sign.signatureLength=crypto_sign_BYTES;nacl2.hash=function(msg){checkArrayTypes(msg);var h2=new Uint8Array(crypto_hash_BYTES);crypto_hash(h2,msg,msg.length);return h2};nacl2.hash.hashLength=crypto_hash_BYTES;nacl2.verify=function(x,y){checkArrayTypes(x,y);if(x.length===0||y.length===0)return false;if(x.length!==y.length)return false;return vn(x,0,y,0,x.length)===0?true:false};nacl2.setPRNG=function(fn){randombytes=fn};(function(){var crypto2=typeof globalThis!=="undefined"?globalThis.crypto||globalThis.msCrypto:null;if(crypto2&&crypto2.getRandomValues){var QUOTA=65536;nacl2.setPRNG(function(x,n){var i,v=new Uint8Array(n);for(i=0;i<n;i+=QUOTA){crypto2.getRandomValues(v.subarray(i,i+Math.min(n-i,QUOTA)))}for(i=0;i<n;i++)x[i]=v[i];cleanup(v)})}else if(typeof require!=="undefined"){crypto2=require("crypto");if(crypto2&&crypto2.randomBytes){nacl2.setPRNG(function(x,n){var i,v=crypto2.randomBytes(n);for(i=0;i<n;i++)x[i]=v[i];cleanup(v)})}}})()})(typeof module!=="undefined"&&module.exports?module.exports:globalThis.nacl=globalThis.nacl||{});var nacl=typeof module!=="undefined"&&module.exports?module.exports:globalThis.nacl;var denoHelper={fromSeed:nacl.sign.keyPair.fromSeed,sign:nacl.sign.detached,verify:nacl.sign.detached.verify,randomBytes:nacl.randomBytes,scalarBaseMultiply:nacl.scalarMult.base,seal:nacl.box,open:nacl.box.open};var helper;function setEd25519Helper(lib){helper=lib}var crc16tab=new Uint16Array([0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920]);var NKeysErrorCode2;(function(NKeysErrorCode3){NKeysErrorCode3["InvalidPrefixByte"]="nkeys: invalid prefix byte";NKeysErrorCode3["InvalidKey"]="nkeys: invalid key";NKeysErrorCode3["InvalidPublicKey"]="nkeys: invalid public key";NKeysErrorCode3["InvalidSeedLen"]="nkeys: invalid seed length";NKeysErrorCode3["InvalidSeed"]="nkeys: invalid seed";NKeysErrorCode3["InvalidCurveSeed"]="nkeys: invalid curve seed";NKeysErrorCode3["InvalidCurveKey"]="nkeys: not a valid curve key";NKeysErrorCode3["InvalidCurveOperation"]="nkeys: curve key is not valid for sign/verify";NKeysErrorCode3["InvalidNKeyOperation"]="keys: only curve key can seal/open";NKeysErrorCode3["InvalidEncoding"]="nkeys: invalid encoded key";NKeysErrorCode3["InvalidRecipient"]="nkeys: not a valid recipient public curve key";NKeysErrorCode3["InvalidEncrypted"]="nkeys: encrypted input is not valid";NKeysErrorCode3["CannotSign"]="nkeys: cannot sign, no private key available";NKeysErrorCode3["PublicKeyOnly"]="nkeys: no seed or private key available";NKeysErrorCode3["InvalidChecksum"]="nkeys: invalid checksum";NKeysErrorCode3["SerializationError"]="nkeys: serialization error";NKeysErrorCode3["ApiError"]="nkeys: api error";NKeysErrorCode3["ClearedPair"]="nkeys: pair is cleared"})(NKeysErrorCode2||(NKeysErrorCode2={}));var Prefix2;(function(Prefix3){Prefix3[Prefix3["Unknown"]=-1]="Unknown";Prefix3[Prefix3["Seed"]=144]="Seed";Prefix3[Prefix3["Private"]=120]="Private";Prefix3[Prefix3["Operator"]=112]="Operator";Prefix3[Prefix3["Server"]=104]="Server";Prefix3[Prefix3["Cluster"]=16]="Cluster";Prefix3[Prefix3["Account"]=0]="Account";Prefix3[Prefix3["User"]=160]="User";Prefix3[Prefix3["Curve"]=184]="Curve"})(Prefix2||(Prefix2={}));setEd25519Helper(denoHelper);var Algorithms;(function(Algorithms2){Algorithms2["v1"]="ed25519";Algorithms2["v2"]="ed25519-nkey"})(Algorithms||(Algorithms={}));var import_nats_core3=__toESM(require_mod3(),1);var import_nkeys5=__toESM(require_mod(),1);function idFromCreds(creds){return identityFromCreds(creds).id}function jwtFromCreds(creds){return creds.match(/BEGIN NATS USER JWT-----\s*([\s\S]*?)\s*------END NATS USER JWT/)?.[1].trim()}function credsFingerprint(creds){const jwt2=jwtFromCreds(creds);if(!jwt2)throw new Error("creds: no NATS user JWT block found - cannot fingerprint");return(0,import_node_crypto7.createHash)("sha256").update(jwt2).digest("hex")}function credsClaims(creds){const payload=jwtFromCreds(creds)?.split(".")[1];if(!payload)throw new Error("creds: no NATS user JWT block found");try{return JSON.parse(Buffer.from(payload,"base64url").toString("utf8"))}catch{throw new Error("creds: undecodable user JWT payload")}}function credsRenewalDelayMs(creds){const claims2=credsClaims(creds);if(typeof claims2.exp!=="number")throw new Error("creds source returned a cred without a numeric exp - a standing-renewal endpoint requires bounded creds (mint with a lifetime, or pass a static string instead of a source)");const iatMs=(typeof claims2.iat==="number"?claims2.iat:Date.now()/1e3)*1e3;const expMs=claims2.exp*1e3;return iatMs+.75*(expMs-iatMs)-Date.now()}function identityFromCreds(creds){const seedM=creds.match(/BEGIN USER NKEY SEED-----\s*([\s\S]*?)\s*------END USER NKEY SEED/);if(!seedM)throw new Error("creds: no user nkey seed block found");const seed=seedM[1].trim();const signer=nativeNkeySigner(new TextEncoder().encode(seed));const id2=signer.getPublicKey();signer.clear();const payload=jwtFromCreds(creds)?.split(".")[1];const sub=payload?JSON.parse(Buffer.from(payload,"base64url").toString("utf8")).sub:void 0;if(sub&&sub!==id2)throw new Error(`creds: seed identity ${id2} != JWT subject ${sub}`);return{id:id2,seed}}var ED25519_P=(1n<<255n)-19n;async function drainAndClose(nc,graceMs=1e3){let timer;try{if(!nc.isClosed()){await Promise.race([nc.drain().catch(()=>{}),nc.closed(),new Promise(resolve=>{timer=setTimeout(resolve,graceMs)})])}}finally{clearTimeout(timer);await nc.close()}}var import_nkeys9=__toESM(require_mod(),1);var import_transport_node14=__toESM(require_transport_node(),1);var import_node_events=require("node:events");var import_node_crypto10=require("node:crypto");var import_promises=require("node:timers/promises");var import_node_net=require("node:net");var import_transport_node13=__toESM(require_transport_node(),1);var import_nats_core6=__toESM(require_mod3(),1);var LIVENESS_PLANES=Object.freeze(["manager","delivery"]);function isLivenessPlane(plane){return LIVENESS_PLANES.includes(plane)}function responderFromLease(lease,expectedHolder){if(lease===void 0)return"unbound";if(lease.ready!==true)return"unbound";if(expectedHolder!==void 0&&lease.holder!==expectedHolder)return"stale";return"bound"}function responderFromProbe(outcome,answered){if(outcome==="replied")return answered??"unknown";if(outcome==="noResponders")return"unbound";return"unknown"}function parseLivenessAnswer(body,expectPlane){if(typeof body!=="object"||body===null)return void 0;const{plane,responder,instance}=body;if(typeof plane!=="string"||!isLivenessPlane(plane)||plane!==expectPlane)return void 0;if(responder!=="bound"&&responder!=="unbound"&&responder!=="stale"&&responder!=="unknown")return void 0;if(instance!==void 0&&(typeof instance!=="string"||instance===""))return void 0;return instance===void 0?{plane,responder}:{plane,responder,instance}}var import_node_crypto8=require("node:crypto");var startedAt=Math.floor(performance.timeOrigin);var scopes=new Map;function processRuntime(lifecycleUid){let own=scopes.get(lifecycleUid);if(!own){own=Object.freeze({id:(0,import_node_crypto8.randomUUID)(),startedAt,source:"endpoint-process"});scopes.set(lifecycleUid,own)}return own}var import_nkeys6=__toESM(require_mod(),1);function nativeCredsAuthenticator(creds){return nonce3=>{const blocks=/\s*(?:(?:[-]{3,}[^\n]*[-]{3,}\n)(.+)(?:\n\s*[-]{3,}[^\n]*[-]{3,}\n))/ig;const text2=typeof creds==="function"?creds():creds;const jwtBlock=blocks.exec(text2);if(!jwtBlock)throw new Error("unable to parse credentials");const seedBlock=blocks.exec(text2);if(!seedBlock)throw new Error("unable to parse credentials");const seed=new TextEncoder().encode(seedBlock[1].trim());let signer;try{signer=nativeNkeySigner(seed);return{jwt:jwtBlock[1].trim(),nkey:signer.getPublicKey(),sig:nonce3?(0,import_nkeys6.encode)(signer.sign(new TextEncoder().encode(nonce3))):""}}finally{seed.fill(0);signer?.clear()}}}var RENEWAL_WINDOW=Object.freeze({from:.5,to:.8});var RENEWAL_SPACING_MS=1e3;var MAX_TIMER_MS2=2147483647;var armed=new Map;function pickFree(taken,from,to){const free=[];let lo=from;for(const t of[...taken].sort((a,b)=>a-b)){if(t-RENEWAL_SPACING_MS>lo)free.push([lo,Math.min(to,t-RENEWAL_SPACING_MS)]);lo=Math.max(lo,t+RENEWAL_SPACING_MS);if(lo>=to)break}if(lo<=to)free.push([lo,to]);const total=free.reduce((sum,[a,b])=>sum+(b-a),0);if(free.length===0)return from+Math.random()*(to-from);let r=Math.random()*total;for(const[a,b]of free){if(r<=b-a)return a+r;r-=b-a}return free[free.length-1][1]}function armRenewal(space2,issuedAtMs,expiresAtMs,renew,minDelayMs=0){const now=Date.now();const life=Math.max(0,expiresAtMs-issuedAtMs);const from=Math.max(issuedAtMs+RENEWAL_WINDOW.from*life,now+minDelayMs);const to=Math.max(issuedAtMs+RENEWAL_WINDOW.to*life,from);const taken=armed.get(space2)??new Set;armed.set(space2,taken);const at=pickFree([...taken],from,to);taken.add(at);const release=()=>{taken.delete(at);if(taken.size===0&&armed.get(space2)===taken)armed.delete(space2)};let timer;const wait=()=>{const left=at-Date.now();timer=setTimeout(left>MAX_TIMER_MS2?wait:()=>{release();renew()},Math.min(Math.max(0,left),MAX_TIMER_MS2));timer.unref?.()};wait();return()=>{clearTimeout(timer);release()}}function renewalDeadlineMs(issuedAtMs,expiresAtMs){return issuedAtMs+RENEWAL_WINDOW.to*Math.max(0,expiresAtMs-issuedAtMs)}function jitteredBackoffMs(attempt,baseMs,capMs){const step=Math.min(capMs,baseMs*2**attempt);return step/2+Math.random()*(step/2)}var BROKER_FLOOR=Object.freeze({major:2,minor:12});function parseServerVersion(v){const m=/^(\d+)\.(\d+)\.(\d+)/.exec(v.trim());if(!m)return null;return{major:Number(m[1]),minor:Number(m[2]),patch:Number(m[3])}}function meetsBrokerFloor(version2){const p=parseServerVersion(version2);if(!p)return false;if(p.major!==BROKER_FLOOR.major)return p.major>BROKER_FLOOR.major;return p.minor>=BROKER_FLOOR.minor}function requireBrokerFloor(nc){const version2=nc.info?.version;if(!version2)throw new Error("control surface: connected broker reports no server version; refusing to start (floor is nats-server >= 2.12)");if(!meetsBrokerFloor(version2))throw new Error(`control surface: nats-server ${version2} is below the required floor 2.12; upgrade the broker (no degraded mode exists)`)}var import_jetstream10=__toESM(require_mod4(),1);var import_node_crypto9=require("node:crypto");var import_transport_node8=__toESM(require_transport_node(),1);var import_kv4=__toESM(require_mod6(),1);var import_obj=__toESM(require_mod7(),1);var import_jetstream7=__toESM(require_mod4(),1);function isJetStreamMissing(e,...codes){return e instanceof import_jetstream7.JetStreamApiError&&codes.includes(e.code)}function isConsumerNotFound(e){return isJetStreamMissing(e,import_jetstream7.JetStreamApiCodes.ConsumerNotFound)}function isStreamNotFound(e){return isJetStreamMissing(e,import_jetstream7.JetStreamApiCodes.StreamNotFound)}function isConsumerAlreadyExists(e){return isJetStreamMissing(e,10148)}var import_kv2=__toESM(require_mod6(),1);var import_internal=__toESM(require_internal_mod3(),1);var import_jetstream8=__toESM(require_mod4(),1);var IncompleteKvScan=class extends Error{bucket;received;expected;constructor(bucket,received,expected){super(`reading ${bucket} ended after ${received} of ~${expected} entries without reaching the end of the bucket - the connection or consumer died mid-pass. Refusing to return a partial view (a short or empty result here is indistinguishable from a real answer). Retry; if it persists, the link to the broker is dropping.`);this.bucket=bucket;this.received=received;this.expected=expected;this.name="IncompleteKvScan"}};async function liveKvEntries(kv,filterOrOptions,options){let filter;let opts;if(typeof filterOrOptions==="string"||Array.isArray(filterOrOptions)){filter=filterOrOptions;opts=options}else if(filterOrOptions&&typeof filterOrOptions==="object"){if(options!==void 0){throw new TypeError("liveKvEntries does not accept a third argument when the second argument is options")}opts=filterOrOptions}else{opts=options}if(opts?.signal?.aborted){throw opts.signal.reason??new Error("scan aborted")}if(!(kv instanceof import_internal.Bucket))throw new Error(`liveKvEntries needs the @nats-io/kv Bucket implementation to bind its own consumer (got ${kv?.constructor?.name??typeof kv}). Refusing to fall back to history(), whose hidden bind-time pending count is exactly the ambiguity this exists to remove.`);const bucket=kv;const cc=bucket._buildCC(filter??">",import_internal.KvWatchInclude.AllHistory,{headers_only:false});cc.mem_storage=true;const oc=await bucket.js.consumers.getPushConsumer(bucket.stream,cc);const own=oc;const api=own.api;const owned=[{name:own.name,answered:Promise.resolve(true)}];own.api=Object.assign(Object.create(api),{add:(...args)=>{const created=api.add(...args);owned.push({name:args[1].name,answered:created.then(()=>true,e=>e instanceof import_jetstream8.JetStreamApiError)});return created}});const latest=new Map;let received=0;let sawTerminal=false;let bucketName=bucket.bucket;let expected=0;let complete=false;try{const initialInfo=await oc.info(true);opts?.onConsumer?.(initialInfo);expected=initialInfo.num_pending;if(opts?.signal?.aborted){throw opts.signal.reason??new Error("scan aborted")}if(expected!==0){const iter=await oc.consume();const onAbort=()=>{iter.stop(opts?.signal?.reason??new Error("scan aborted"))};opts?.signal?.addEventListener("abort",onAbort,{once:true});try{for await(const m of iter){if(opts?.signal?.aborted)break;const e=bucket.jmToWatchEntry(m,false);received++;bucketName=e.bucket;const prior=latest.get(e.key);if(prior===void 0||e.revision>=prior.revision)latest.set(e.key,e);if(m.info.pending===0){sawTerminal=true;break}}}finally{opts?.signal?.removeEventListener("abort",onAbort);await iter.close()}}complete=expected===0||sawTerminal}finally{try{const answered=await Promise.all(owned.map(c=>c.answered));if(owned.at(-1).name!==own.name)throw new Error(`scan consumer ${own.name} was not created through the scan's consumer API - the pinned nats.js changed shape`);const deleteOwn=opts?.deleteOwnConsumer??((_stream,_name,del)=>del());let unanswered;for(let i=owned.length-1;i>=0;i--){const target2=owned[i].name;try{await deleteOwn(bucket.stream,target2,()=>bucket.jsm.consumers.delete(bucket.stream,target2))}catch(e){if(isPublishPermissionDenied(e))break;if(!isConsumerNotFound(e))throw e;if(!answered[i])unanswered??=target2}}if(unanswered)throw new Error(`the broker never answered the create of scan consumer ${unanswered}, so it can land after its delete and live until its inactive_threshold`)}catch(e){if(complete&&!opts?.signal?.aborted)throw e}}if(opts?.signal?.aborted){throw opts.signal.reason??new Error("scan aborted")}if(expected===0)return[];if(!sawTerminal)throw new IncompleteKvScan(bucketName,received,expected);const out=[];for(const e of latest.values())if(e.operation!=="DEL"&&e.operation!=="PURGE")out.push(e);return out}var DIRECT_BATCH=1024;async function lastKvEntries(kv){if(!(kv instanceof import_internal.Bucket))throw new Error(`lastKvEntries needs the @nats-io/kv Bucket implementation to address its backing stream (got ${kv?.constructor?.name??typeof kv})`);const bucket=kv;const nc=bucket.jsm.getConnection?.();if(nc===void 0)throw new Error("lastKvEntries needs the bucket's JetStream manager to expose its connection, to tell a denied Direct Get from a slow one");const watch=openPublishDenialWatch(nc,`${bucket.jsm.getOptions().apiPrefix||"$JS.API"}.DIRECT.GET.${bucket.stream}`,err3=>err3,"Direct Get");let page;try{const read=(async()=>{const latest=new Map;for(let seq=1;;){let last=0,pending=-1;try{await new Promise((resolve,reject)=>{bucket.jsm.direct.getBatch(bucket.stream,{seq,batch:DIRECT_BATCH,next_by_subj:`${bucket.prefix}.>`,callback:(done,sm)=>{if(done){done.err?reject(done.err):resolve();return}try{const e=bucket.smToEntry(sm);const prior=latest.get(e.key);if(prior===void 0||e.revision>=prior.revision)latest.set(e.key,e);last=sm.seq;pending=sm.pending}catch(e){page?.stop(e);reject(e)}}}).then(iter=>{page=iter},reject)})}catch(e){if(last===0&&e?.code===404)break;throw e}if(pending===0)break;if(last===0)throw new IncompleteKvScan(bucket.bucket,latest.size,latest.size+Math.max(pending,1));seq=last+1}return[...latest.values()]})();read.catch(()=>{});return await Promise.race([read,watch.denied.catch(err3=>{page?.stop(err3);throw err3})])}finally{watch.release()}}async function openAclRegistry(nc,space2,opts={}){const kvm=new import_kv2.Kvm(nc);return opts.create?kvm.create(aclBucket(space2)):kvm.open(aclBucket(space2))}async function readAcl(kv,owner2,lifecycleUid){const e=await kv.get(aclKey(owner2,lifecycleUid));if(!e||e.operation==="DEL"||e.operation==="PURGE")return void 0;try{const record3=e.json();if(!Array.isArray(record3.allowSubscribe))return void 0;return{record:record3,revision:e.revision}}catch{return void 0}}async function aclRetired(kv,owner2,lifecycleUid){const e=await kv.get(aclKey(owner2,lifecycleUid));return e?.operation==="DEL"||e?.operation==="PURGE"}var AmbiguousAclAlias=class extends Error{principal;lifecycleUids;constructor(principal,lifecycleUids){super(`read-ACL alias "${principal}" resolves to ${lifecycleUids.length} live lifecycle rows (${lifecycleUids.join(", ")}); at most one lifecycle may be live per alias (SPEC 13.1) - refusing to authorize on a first-match guess`);this.principal=principal;this.lifecycleUids=lifecycleUids}};async function readAclForAlias(kv,principal){const first=await enumerateLiveAclRows(kv,principal);if(first.length>1)throw new AmbiguousAclAlias(principal,first.map(l=>l.lifecycleUid).sort());const second=await enumerateLiveAclRows(kv,principal);if(second.length>1)throw new AmbiguousAclAlias(principal,second.map(l=>l.lifecycleUid).sort());if(second.length===0)return void 0;if(first.length===1&&first[0].lifecycleUid!==second[0].lifecycleUid)throw new AmbiguousAclAlias(principal,[first[0].lifecycleUid,second[0].lifecycleUid].sort());return{record:second[0].record,revision:second[0].revision,lifecycleUid:second[0].lifecycleUid}}async function enumerateLiveAclRows(kv,principal){const live=[];for(const e of await liveKvEntries(kv,aclAliasFilter(principal))){const parsed=parseLifecycleSubjectKey(e.key);if(!parsed||`${parsed.owner}.${parsed.actor}`!==principal)continue;let record3;try{record3=e.json()}catch{continue}if(!Array.isArray(record3.allowSubscribe))continue;live.push({lifecycleUid:parsed.lifecycleUid,record:record3,revision:e.revision})}return live}async function reissueAcl(kv,owner2,lifecycleUid,allowSubscribe){return writeAcl(kv,owner2,lifecycleUid,allowSubscribe,{reissue:true})}async function commitAcl(kv,owner2,lifecycleUid,allowSubscribe){return writeAcl(kv,owner2,lifecycleUid,allowSubscribe,{reissue:false})}async function writeAcl(kv,owner2,lifecycleUid,allowSubscribe,opts){const key=aclKey(owner2,lifecycleUid);let lastErr;for(let attempt=0;attempt<5;attempt++){const cur=await readAcl(kv,owner2,lifecycleUid);let issued;if(opts.reissue||!cur){issued=[...allowSubscribe]}else{issued=[...cur.record.issuedAllowSubscribe??cur.record.allowSubscribe];const excess=allowSubscribe.filter(a=>!patternInAllow(issued,a));if(excess.length>0){throw new Error(`commitAcl: cannot raise ACL above mint-time ceiling without reissue (entries [${excess.join(", ")}] not within ceiling [${issued.join(", ")}]); use reissueAcl from the provisioning path that also remints the JWT`)}}const next={allowSubscribe:[...allowSubscribe],issuedAllowSubscribe:issued,revision:(cur?.record.revision??0)+1,updatedAt:Date.now()};const data=new TextEncoder().encode(JSON.stringify(next));if(!cur){try{await kv.create(key,data);return next}catch(e){lastErr=e;try{const raw=await kv.get(key);if(raw){await kv.update(key,data,raw.revision);return next}}catch(e2){lastErr=e2}continue}}try{await kv.update(key,data,cur.revision);return next}catch(e){lastErr=e;continue}}throw new Error(`acl CAS exhausted retries for ${owner2}${lastErr?` - last error: ${lastErr instanceof Error?lastErr.message:String(lastErr)}`:""}`,lastErr instanceof Error?{cause:lastErr}:void 0)}var import_kv3=__toESM(require_mod6(),1);var StaleMembershipWrite=class extends Error{constructor(channel,owner2,attempted,current){super(`stale membership write for ${channel}/${owner2}: generation ${attempted} < current ${current}`);this.name="StaleMembershipWrite"}};async function openMembersRegistry(nc,space2,opts={}){const kvm=new import_kv3.Kvm(nc);return opts.create?kvm.create(membersBucket(space2)):kvm.open(membersBucket(space2))}async function readMember(kv,channel,owner2,lifecycleUid){const e=await kv.get(memberKey(channel,owner2,lifecycleUid));if(!e||e.operation==="DEL"||e.operation==="PURGE")return void 0;try{return{record:e.json(),revision:e.revision}}catch{return void 0}}async function commitMemberRevision(kv,next){const key=memberKey(next.channel,next.owner,next.lifecycleUid);const data=new TextEncoder().encode(JSON.stringify(next));for(let attempt=0;attempt<5;attempt++){const cur=await readMember(kv,next.channel,next.owner,next.lifecycleUid);if(!cur){try{return{record:next,revision:await kv.create(key,data)}}catch{continue}}if(next.generation<cur.record.generation)throw new StaleMembershipWrite(next.channel,next.owner,next.generation,cur.record.generation);try{return{record:next,revision:await kv.update(key,data,cur.revision)}}catch{continue}}throw new Error(`members CAS exhausted retries for ${key}`)}async function tombstoneMember(kv,channel,owner2,lifecycleUid,leaveCursor,writerIdentity,expectedGeneration){const key=memberKey(channel,owner2,lifecycleUid);let generation=expectedGeneration;for(let attempt=0;attempt<5;attempt++){const cur=await readMember(kv,channel,owner2,lifecycleUid);if(!cur)return void 0;generation??=cur.record.generation;if(cur.record.generation!==generation)throw new StaleMembershipWrite(channel,owner2,generation,cur.record.generation);if(cur.record.leaveCursor!==void 0&&cur.record.leaveCursor<=leaveCursor)return cur.record;const next={...cur.record,state:"live-confirmed",leaveCursor,writerIdentity,updatedAt:Date.now()};try{await kv.update(key,new TextEncoder().encode(JSON.stringify(next)),cur.revision);return next}catch{continue}}throw new Error(`members CAS exhausted retries for ${key}`)}async function activateMember(kv,channel,owner2,lifecycleUid,expectedGeneration,expectedJoinCursor){const key=memberKey(channel,owner2,lifecycleUid);for(let attempt=0;attempt<5;attempt++){const cur=await readMember(kv,channel,owner2,lifecycleUid);if(!cur)return void 0;const r=cur.record;if(r.generation!==expectedGeneration||r.joinCursor!==expectedJoinCursor||r.leaveCursor!==void 0)return void 0;if(r.activated)return r;const next={...r,activated:true,updatedAt:Date.now()};try{await kv.update(key,new TextEncoder().encode(JSON.stringify(next)),cur.revision);return next}catch{continue}}return void 0}async function deleteMember(kv,channel,owner2,lifecycleUid){await kv.purge(memberKey(channel,owner2,lifecycleUid))}async function listMembers(kv,filter={}){const out=[];for(const e of await liveKvEntries(kv)){const parsed=parseMemberKey(e.key);if(!parsed)continue;if(filter.channel!==void 0&&parsed.channel!==filter.channel)continue;if(filter.covering!==void 0&&parsed.channel!==filter.covering&&!(isChannelFamily(parsed.channel)&&subjectMatches(parsed.channel,filter.covering)))continue;if(filter.owner!==void 0&&parsed.principal!==filter.owner)continue;try{out.push(e.json())}catch{}}return out}function durableEligible(rec,seq){if(seq<=rec.joinCursor)return false;if(rec.leaveCursor!==void 0&&seq>rec.leaveCursor)return false;return true}var inventoryPasses=new WeakMap;function inventoryPassAfterNow(kv){let passes=inventoryPasses.get(kv);if(passes===void 0)inventoryPasses.set(kv,passes={});const state=passes;if(state.next)return state.next;const next=(state.running??Promise.resolve([])).catch(()=>[]).then(()=>{state.next=void 0;const pass=liveKvEntries(kv);state.running=pass;const done=()=>{if(state.running===pass)state.running=void 0};pass.then(done,done);return pass});state.next=next;return next}async function listLifecycleMemberChannels(kv,principal,lifecycleUid){const pr=parsePrincipalKey(principal);if(!pr)throw new Error(`listLifecycleMemberChannels: invalid principal "${principal}"`);assertLifecycleToken(lifecycleUid);const channels=new Set;for(const e of await inventoryPassAfterNow(kv)){const parsed=parseMemberKey(e.key);if(!parsed)continue;if(parsed.principal!==principal||parsed.lifecycleUid!==lifecycleUid)continue;if(!isConcreteChannel(parsed.channel)&&!isChannelFamily(parsed.channel))continue;channels.add(parsed.channel)}return[...channels].sort()}var import_jetstream9=__toESM(require_mod4(),1);var import_transport_node7=__toESM(require_transport_node(),1);var DEFAULT_DUPLICATE_WINDOW_MS=2*60*1e3;var DEFAULT_DUPLICATE_WINDOW=(0,import_transport_node7.nanos)(DEFAULT_DUPLICATE_WINDOW_MS);var PLANE3_MAX_MSGS_PER_SUBJECT=1e3;var BACKUP_PLANE3_DEDUP_WINDOW_MS=2*60*60*1e3;var PLANE3_DUPLICATE_WINDOW=(0,import_transport_node7.nanos)(BACKUP_PLANE3_DEDUP_WINDOW_MS);var DELIVERY_LIMIT_HEADER="Cotal-Delivery-Limit";var HISTORY_NO_COUNT=-1;var CHAT_HISTORY_DEFAULT=Object.freeze({maxAgeMs:0,perSubject:1e3});var INBOX_HISTORY_DEFAULT=Object.freeze({maxAgeMs:0,perSubject:PLANE3_MAX_MSGS_PER_SUBJECT});var DM_HISTORY_DEFAULT=Object.freeze({maxAgeMs:0,perSubject:HISTORY_NO_COUNT});var HISTORY_MAX_AGE_MS=3650*864e5;function historyLimitDefault(stream){if(stream==="chat")return CHAT_HISTORY_DEFAULT;return stream==="dm"?DM_HISTORY_DEFAULT:INBOX_HISTORY_DEFAULT}function historyLimitStreamOf(space2,stream){if(stream===chatStream(space2))return"chat";if(stream===inboxStream(space2))return"inbox";if(stream===dlvStream(space2))return"dlv";if(stream===dmStream(space2))return"dm";return void 0}function baseConfig(name,subjects){return{name,subjects,retention:import_jetstream9.RetentionPolicy.Limits,storage:import_jetstream9.StorageType.File,max_consumers:-1,max_msgs:-1,max_bytes:-1,max_age:0,max_msgs_per_subject:-1,max_msg_size:-1,discard:import_jetstream9.DiscardPolicy.Old,num_replicas:1,no_ack:false,duplicate_window:DEFAULT_DUPLICATE_WINDOW,compression:import_jetstream9.StoreCompression.None,allow_direct:false,mirror_direct:false,discard_new_per_subject:false,allow_rollup_hdrs:false,deny_delete:false,deny_purge:false,sealed:false,consumer_limits:{}}}function canonicalBackupStreamConfig(space2,stream,limit){const p=spacePrefix(space2);const target2=historyLimitStreamOf(space2,stream);const limits=target2&&{max_age:(0,import_transport_node7.nanos)((limit??historyLimitDefault(target2)).maxAgeMs),max_msgs_per_subject:(limit??historyLimitDefault(target2)).perSubject};if(target2==="chat")return{...baseConfig(stream,[`${p}.chat.>`]),...limits,allow_direct:true};if(target2==="dm")return{...baseConfig(stream,[`${p}.inst.>`]),...limits};if(stream===taskStream(space2)){return{...baseConfig(stream,[`${p}.svc.>`]),retention:import_jetstream9.RetentionPolicy.Workqueue}}if(target2==="inbox")return{...baseConfig(stream,[`${p}.dinbox.>`]),...limits,duplicate_window:PLANE3_DUPLICATE_WINDOW};if(target2==="dlv")return{...baseConfig(stream,[`${p}.dlv.>`]),...limits,duplicate_window:PLANE3_DUPLICATE_WINDOW};if(stream===wfjStreamName(space2))return baseConfig(stream,[`${p}.wfj.*`]);if(stream===recordsKvStreamName(space2))return{...kvStoreConfig(stream,recordsBucket(space2)),allow_direct:true,...endpointAuthorityStoreDefinitions(space2).records.hardenAfterCreate};if(stream===`KV_${admissionBucket(space2)}`)return{...kvStoreConfig(stream,admissionBucket(space2)),...admissionStoreDefinition(space2).hardenAfterCreate};for(const bucket of[channelBucket(space2),aclBucket(space2),membersBucket(space2)]){if(stream===`KV_${bucket}`){return{...baseConfig(stream,[`$KV.${bucket}.>`]),max_msgs_per_subject:1,discard:import_jetstream9.DiscardPolicy.New,allow_direct:true,allow_rollup_hdrs:true}}}throw new Error(`stream ${JSON.stringify(stream)} is not a backed-up stream for space ${JSON.stringify(space2)}`)}function kvStoreConfig(name,bucket){return{...baseConfig(name,[`$KV.${bucket}.>`]),max_msgs_per_subject:1,discard:import_jetstream9.DiscardPolicy.New,allow_rollup_hdrs:true}}var PRESENCE_STORAGE=import_jetstream10.StorageType.Memory;var DINBOX_MAX_ACK_PENDING=1e3;var MANAGER_LEASE_TTL_MS=1e4;var MANAGER_LEASE_RENEW_MS=MANAGER_LEASE_TTL_MS/4;var MANAGER_LEASE_ATTEMPT_MS=2e3;var LEGACY_MEMBERSHIP_MAX_BYTES=64*1024*1024;var MEMBERSHIP_MAX_VALUE_SIZE=256*1024;var ANYCAST_RECORD_MAX_VALUE_SIZE=64*1024;var LEGACY_ARTIFACT_STORE_MAX_BYTES=4*1024*1024*1024;function standaloneConnectOpts(auth){if(auth?.tls===void 0)throw new Error("standaloneConnectOpts requires an explicit `tls` boolean: pass `tls: true` to REQUIRE TLS, or `tls: false` for a plaintext broker. It has no default, because defaulting it would silently connect without the requirement that protects the credentials being passed.");const tlsOpt=auth.tls?{tls:{}}:{};if(auth.bearer!==void 0){if(!auth.sentinelCreds)throw new Error("user-mode standalone connect requires sentinelCreds alongside the bearer");if(auth.creds)throw new Error("standalone connect takes creds OR bearer+sentinelCreds, never both");const nonce3=`ibx${(0,import_node_crypto9.randomUUID)().replace(/-/g,"")}`;return{name:nonce3,inboxPrefix:`_INBOX_${nonce3}`,authenticator:[nativeCredsAuthenticator(auth.sentinelCreds),(0,import_transport_node8.tokenAuthenticator)(auth.bearer)],...tlsOpt}}const creds=auth.creds;if(!creds)return{...tlsOpt};return{authenticator:nativeCredsAuthenticator(creds),inboxPrefix:`_INBOX_${idFromCreds(typeof creds==="function"?creds():creds)}`,...tlsOpt}}function spaceMessageStreamConfigs(space2){return[chatStream(space2),dmStream(space2),taskStream(space2),inboxStream(space2),dlvStream(space2)].map(stream=>canonicalBackupStreamConfig(space2,stream))}function anycastStoreDefinition(space2){return{bucket:anycastBucket(space2),createOptions:{history:1,max_bytes:-1,maxValueSize:ANYCAST_RECORD_MAX_VALUE_SIZE}}}async function createSpaceStreams(jsm,space2){for(const definition of spaceMessageStreamConfigs(space2)){if(historyLimitStreamOf(space2,definition.name)){try{await jsm.streams.info(definition.name);continue}catch(e){if(!isStreamNotFound(e))throw e}}await jsm.streams.add(definition)}}function dmDurableConfig(space2,owner2,actor2,lifecycleUid,opts={}){const frontier=opts.activationFrontier??0;if(!Number.isInteger(frontier)||frontier<0)throw new Error(`dmDurableConfig activationFrontier must be a non-negative integer, got ${String(frontier)}`);const cfg={durable_name:dmDurable(owner2,actor2,lifecycleUid),filter_subject:unicastRecvFilter(space2,owner2,actor2),ack_policy:import_jetstream10.AckPolicy.Explicit,ack_wait:(0,import_transport_node8.nanos)(opts.ackWaitMs??6e4),...frontier>0?{deliver_policy:import_jetstream10.DeliverPolicy.StartSequence,opt_start_seq:frontier+1}:{deliver_policy:import_jetstream10.DeliverPolicy.All}};if(opts.inactiveThresholdMs)cfg.inactive_threshold=(0,import_transport_node8.nanos)(opts.inactiveThresholdMs);return cfg}function taskDurableConfig(space2,role,opts={}){return{durable_name:taskDurable(role),filter_subject:anycastServeFilter(space2,role),ack_policy:import_jetstream10.AckPolicy.Explicit,ack_wait:(0,import_transport_node8.nanos)(opts.ackWaitMs??6e4)}}function inboxReaderConfig(space2,opts={}){return{durable_name:readerDurable(opts.shard,opts.shards),filter_subject:`${spacePrefix(space2)}.dinbox.>`,ack_policy:import_jetstream10.AckPolicy.Explicit,ack_wait:(0,import_transport_node8.nanos)(opts.ackWaitMs??6e4),deliver_policy:import_jetstream10.DeliverPolicy.All,max_ack_pending:DINBOX_MAX_ACK_PENDING}}function dlvDurableConfig(space2,owner2,actor2,lifecycleUid,opts={}){const cfg={durable_name:dlvDurable(owner2,actor2,lifecycleUid),filter_subject:dlvSubject(space2,owner2,actor2,lifecycleUid),ack_policy:import_jetstream10.AckPolicy.Explicit,ack_wait:(0,import_transport_node8.nanos)(opts.ackWaitMs??6e4),deliver_policy:import_jetstream10.DeliverPolicy.All};if(opts.inactiveThresholdMs)cfg.inactive_threshold=(0,import_transport_node8.nanos)(opts.inactiveThresholdMs);return cfg}function fanoutDurableConfig(space2,opts={}){return{durable_name:fanoutDurable(opts.shard,opts.shards),filter_subject:chatWildcard(space2),ack_policy:import_jetstream10.AckPolicy.Explicit,ack_wait:(0,import_transport_node8.nanos)(opts.ackWaitMs??6e4),deliver_policy:import_jetstream10.DeliverPolicy.New}}var TTL_RECONCILE_CANARY_KEY="_cotal_ttl_reconcile";var import_transport_node9=__toESM(require_transport_node(),1);var import_nkeys8=__toESM(require_mod(),1);var enc4=new TextEncoder;var dec4=new TextDecoder("utf-8",{fatal:true});var PLACEMENT_COMMANDS=Object.freeze(["describe","resolve-cwd","spawn"]);var PLACED_LIFECYCLE_COMMANDS=Object.freeze(["turn"]);var import_nats_core4=__toESM(require_mod3(),1);var import_jetstream11=__toESM(require_mod4(),1);var import_obj2=__toESM(require_mod7(),1);var ARTIFACT_PART_KIND="artifact";function isArtifactPart(value){if(!value||typeof value!=="object")return false;const p=value;return p.kind===ARTIFACT_PART_KIND&&typeof p.name==="string"&&p.name.length>0&&typeof p.mediaType==="string"&&p.mediaType.length>0&&typeof p.digest==="string"&&isContractDigest(p.digest)&&typeof p.size==="number"&&Number.isSafeInteger(p.size)&&p.size>=0}var TRANSFER_CHUNK_MAX=128*1024;var HEADER_ROOM=4*1024;var import_nkeys7=__toESM(require_mod(),1);var REMOTE_MANAGER_AUTHORITY_OPERATIONS=Object.freeze(["prepare","activate","renew","session","retire","renewStandingBundle","renewRunDriver","transferReader"]);var REMOTE_MANAGER_MAINTENANCE_OPERATIONS=Object.freeze(["evict-family-principal","reconcile-registration"]);var MANAGED_AGENT_RUNTIME_STATES=Object.freeze(["reserved","creating","bound","create-unknown","closing","closed"]);var MANAGED_AGENT_RUNTIME_READINESS=Object.freeze(["ready","bound-not-ready","none"]);var MANAGED_AGENT_RETIREMENT_PHASES=Object.freeze(["intent","released","retired","deprovisioned","terminal"]);var REMOTE_MANAGER_IDENTITY_NAMES=Object.freeze(["supervisor","executor","serve","goalWriter","sessionLedger"]);var import_jetstream12=__toESM(require_mod4(),1);var import_transport_node10=__toESM(require_transport_node(),1);var DEFAULT_TRANSFER_TIMEOUT_MS=5*60*1e3;function principalFromDurable(name,prefix){if(!name.startsWith(prefix))return void 0;const match=/^([A-Za-z0-9_]+)-([A-Za-z0-9_]+)-([a-z0-9]+)$/.exec(name.slice(prefix.length));return match?{owner:match[1],actor:match[2],lifecycleUid:match[3]}:void 0}function expectedConsumerConfig(space2,stream,name){if(stream===chatStream(space2)&&name===FANOUT_DURABLE)return fanoutDurableConfig(space2);if(stream===inboxStream(space2)&&name===INBOX_READER_DURABLE)return inboxReaderConfig(space2);if(stream===dmStream(space2)){const principal=principalFromDurable(name,"dm_");if(principal)return dmDurableConfig(space2,principal.owner,principal.actor,principal.lifecycleUid)}if(stream===dlvStream(space2)){const principal=principalFromDurable(name,"dlv_");if(principal)return dlvDurableConfig(space2,principal.owner,principal.actor,principal.lifecycleUid)}if(stream===taskStream(space2)&&/^svc_[A-Za-z0-9_-]+$/.test(name))return{...taskDurableConfig(space2,name.slice("svc_".length)),deliver_policy:import_jetstream12.DeliverPolicy.All};throw new Error(`unsupported persistent consumer ${stream}/${name}`)}var CONSUMER_KEYS=new Set(["ack_policy","ack_wait","backoff","deliver_group","deliver_policy","deliver_subject","description","durable_name","filter_subject","filter_subjects","flow_control","headers_only","idle_heartbeat","inactive_threshold","max_ack_pending","max_batch","max_bytes","max_deliver","max_expires","max_waiting","mem_storage","metadata","name","num_replicas","opt_start_seq","opt_start_time","pause_until","priority_groups","priority_policy","priority_timeout","rate_limit_bps","replay_policy","sample_freq"]);function validatePersistentConsumer(space2,stream,info){const expected=expectedConsumerConfig(space2,stream,info.name);const config2=info.config;const unknown2=Object.keys(config2).filter(key=>!CONSUMER_KEYS.has(key));if(unknown2.length)throw new Error(`${stream}/${info.name} has unsupported consumer fields: ${unknown2.sort().join(", ")}`);if(config2.name!==void 0&&config2.name!==info.name)throw new Error(`${stream}/${info.name} has a mismatched name`);if(config2.durable_name!==info.name)throw new Error(`${stream}/${info.name} is not a canonical durable`);if(config2.deliver_subject||config2.deliver_group)throw new Error(`${stream}/${info.name} is a push consumer`);if(config2.filter_subject!==expected.filter_subject||(config2.filter_subjects?.length??0)!==0)throw new Error(`${stream}/${info.name} has a noncanonical filter`);if(config2.ack_policy!==import_jetstream12.AckPolicy.Explicit||config2.ack_wait!==expected.ack_wait)throw new Error(`${stream}/${info.name} has noncanonical ACK settings`);const task=stream===taskStream(space2);const migrated=!task&&config2.deliver_policy===import_jetstream12.DeliverPolicy.StartSequence;const implicitTaskAll=task&&config2.deliver_policy===void 0;if(config2.deliver_policy!==expected.deliver_policy&&!migrated&&!implicitTaskAll)throw new Error(`${stream}/${info.name} has a noncanonical delivery policy`);if(migrated){if(!Number.isSafeInteger(config2.opt_start_seq)||(config2.opt_start_seq??0)<1)throw new Error(`${stream}/${info.name} has an invalid creation lower bound`)}else if(config2.opt_start_seq!==void 0||config2.opt_start_time!==void 0){throw new Error(`${stream}/${info.name} has an unexpected start bound`)}const expectedMaxAck=expected.max_ack_pending??1e3;if((config2.max_ack_pending??1e3)!==expectedMaxAck)throw new Error(`${stream}/${info.name} has noncanonical max_ack_pending`);if((config2.max_deliver??-1)!==-1||(config2.max_waiting??512)!==512)throw new Error(`${stream}/${info.name} has noncanonical delivery limits`);if((config2.replay_policy??import_jetstream12.ReplayPolicy.Instant)!==import_jetstream12.ReplayPolicy.Instant||(config2.num_replicas??0)!==0)throw new Error(`${stream}/${info.name} has noncanonical replay/replica settings`);for(const key of["backoff","description","flow_control","headers_only","idle_heartbeat","inactive_threshold","max_batch","max_bytes","max_expires","mem_storage","metadata","pause_until","priority_groups","priority_policy","priority_timeout","rate_limit_bps","sample_freq"]){const value=config2[key];if(key==="metadata"&&value&&typeof value==="object"&&!Array.isArray(value)&&Object.entries(value).every(([metadataKey,metadataValue])=>metadataKey.startsWith("_nats.")&&typeof metadataValue==="string"))continue;if(value!==void 0&&value!==false&&value!==0&&value!==""&&!(Array.isArray(value)&&value.length===0)&&!(typeof value==="object"&&value!==null&&Object.keys(value).length===0))throw new Error(`${stream}/${info.name} has active unsupported setting ${key}`)}}function isRestoredConsumer(space2,stream,info,wanted){if(info.name!==wanted.durable_name||info.config.deliver_policy!==import_jetstream12.DeliverPolicy.StartSequence||info.config.ack_wait!==wanted.ack_wait)return false;try{validatePersistentConsumer(space2,stream,info)}catch{return false}return true}var FIVE_MINUTES=5*60;var MAX_CONTROL_LINE_BYTES=65536;var CONNECT_ENVELOPE_OVERHEAD_BYTES=512;var MAX_MINTED_JWT_BYTES=MAX_CONTROL_LINE_BYTES-CONNECT_ENVELOPE_OVERHEAD_BYTES;var STANDING_RENEWABLE_TTL_SEC=24*60*60;var ROTATION_RENEWED_TTL_SEC=30*24*60*60;var CREDENTIAL_LIFETIMES={agent:{class:"mixed",note:"manager children, foreground spawn/join, and `cotal mint` static outputs all use this profile; split or repair flow required before default exp"},"manager-caller":{class:"mixed",note:"short-lived user-auth view bound to the bearer expiry and one manager instance"},observer:{class:"static-operator-managed",note:"out-of-band dashboard/audit credential from `cotal mint`"},admin:{class:"static-operator-managed",note:"out-of-band elevated dashboard/audit credential from `cotal mint`"},supervisor:{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"manager's always-on endpoint; the manager holds the DATA seed and self-remints via the endpoint creds source"},delivery:{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"server-side Plane-3 daemon; seed-less - the manager re-signs .cotal/delivery.creds for the SAME nkey, requests delivery-admin reloadCreds for explicit adoption, and the endpoint source re-read is only a backstop"},"membership-rw":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"membership feed writer; seed-less - the manager re-signs the membership-rw.creds store key for the SAME nkey, the feed adopts it on a 75% preflight-proven renewal timer (its active self-heal), and delivery-admin reloadCreds is the explicit adoption on top"},provisioner:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"setup/spawn provisioning window only"},deprovisioner:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"target-pinned teardown window only"},"retirement-requester":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one despawn's retirement request window; request+reply only"},"lifecycle-executor":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one static lifecycle operation's 13.1 state-write window (activation / terminal / renewal ledger append)"},"endpoint-serve-executor":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one endpoint registration/serve-mint window (13.1 epgate CAS + epcred stage/revoke + eprepair cursor for one (endpoint, instanceId))"},operator:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"send/dm/join/probe-style operator command"},purger:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"history purge command"},backup:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"offline snapshot phase; exact stream and delivery subject, memory-only"},restore:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"offline restore initiation or exact-ID upload phase, memory-only"},probe:{class:"one-shot",defaultTtlSeconds:60,note:"connect-only preflight"},"channel-writer":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"channel registry mutation command"},"channel-purger":{class:"mixed",note:"one-shot for CLI, standing inside web; split or renewal required before default exp"},teardown:{class:"one-shot",note:"space teardown can be long/destructive; needs TTL budget/remint guard before default exp"},"issued-store-recreate":{class:"one-shot",defaultTtlSeconds:30*60,note:"one `up --recreate-issued-stores` step: snapshot and delete the two pre-retention issued-authority stores of one space; 30 minutes bounds a large store's snapshot"},"control-caller-privileged":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"ps/start control call"},"control-caller-admin":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"stop/attach admin control call"},deployer:{class:"one-shot",note:"manifest deploy spans planning/launch/ledger; needs near-expiry guard or remint before default exp"},"endpoint-serve":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"per-instance endpoint serve credential (SPEC 13.9); the managing authority re-mints on renewal and on takeover (new epoch), and the 13.1 barrier revokes the superseded one"},"goal-writer":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"self-mediated goal-writer for spawn-as-action; the manager re-mints for the SAME nkey on renewal, disjoint from the serve credential"},"session-caller":{class:"one-shot",defaultTtlSeconds:24*60*60,note:"per-session console/CLI caller cred: rails-only for ONE \xA713.6 session; TTL-BOUND to the session (the face mints with expiresAt = the session exp; the 24h default is the SESSION_GRANT_MAX_TTL ceiling, never a standing lifetime); NEVER renewed - a new session mints a new cred"},"dm-reader":{class:"mixed",note:"user-auth own-DM reader view: one dm_ durable's INFO/NEXT/ACK, bound to the bearer expiry (which the IdP proof bounds); renewed by re-exchange, never a standing credential"},"session-serving":{class:"one-shot",defaultTtlSeconds:24*60*60,note:"per-session SERVING cred: rails-only for ONE \xA713.6 session, the mirror of session-caller with the directions swapped; minted at redemption and TTL-BOUND to the session (the 24h default is the SESSION_GRANT_MAX_TTL ceiling, never a standing lifetime); NEVER renewed - a new session mints a new cred, and the session's terminal revokes this one by name"},"session-ledger":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"manager's session LEDGER: the dedicated sessions-bucket `session.<id>` rows and NOTHING else - no session rail of any shape. Standing because SPEC 13.6 makes it the durable revocation authority that must survive the serving endpoint; the manager re-mints for the SAME nkey on the half-TTL loop (the goal-writer precedent)"},"run-driver":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"one workflow run's driver, per takeover attempt (SPEC 14.6): the hosting manager mints it when it takes the run over and re-mints for the SAME nkey on renewal; a new takeover mints a new one"},"run-mediator":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"trusted workflow host operations, bound to one run and attempt; kept on the hosting process's connection"},"run-operator":{class:"one-shot",defaultTtlSeconds:60,note:"one served run-status / run-ps / run-answer call (SPEC 14.3): the hosting manager mints it per call on its own connection, never the serve rails; 60s bounds a copied cred to a minute"},"registry-reader":{class:"standing-renewable",defaultTtlSeconds:60*60,renewalOwner:"registry host",note:"the registry's reads (SPEC 13.20), no write of any shape; the evidence-store read is stream-scoped, so it can read every recorded ceiling in the space (a NAMED RESIDUAL), and one hour bounds a copied credential; the process hosting the registry re-mints it"},issuer:{class:"mixed",defaultTtlSeconds:FIVE_MINUTES,renewalOwner:"auth-service",note:"renewed as the auth plane's held session for connect-time issuance (re-minted before exp, closed with the plane); one-shot for every other issuance window and for a lifecycle terminal's issuance retirement (SPEC 13.15)"},"run-admitter":{class:"one-shot",defaultTtlSeconds:60,note:"one hosted run's admission record create, or its revocation marker (SPEC 14.8); 60s bounds a copied cred to a minute"},"transfer-writer":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one carried resume per CLI call: one object's chunk and meta subjects in one instance's transfer bucket"},"transfer-reader":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one transcript-receive or sweep over the minting instance's own transfer bucket"},"endpoint-evictor":{class:"one-shot",defaultTtlSeconds:60,note:"one re-registration's verify-evict window: a scoped delivery-admin caller that kicks+verifies the SUPERSEDED serve family before the epoch advances; 60s bounds a copied cred to a minute"},"remote-manager":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"auth-service",note:"the scoped remote manager lifecycle: own lease/presence plus same-owner agent provisioning; issued only by the typed supervise protocol, never by `cotal mint` or a raw view/profile string"},"environment-bootstrap":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one admitted environment's bootstrap caller; explicit expiry capped by admission and five minutes"},"environment-manager-supervisor":{class:"standing-renewable",renewalOwner:"environment-authority",note:"own lease/presence/liveness; explicit expiry capped by admission, no auth-store access"},"environment-manager-executor":{class:"standing-renewable",renewalOwner:"environment-authority",note:"own admitted authority instance RPC; explicit expiry capped by admission, no direct store access"},"environment-manager-goal-writer":{class:"standing-renewable",renewalOwner:"environment-authority",note:"manager goal rows without the auth-read belt; explicit expiry capped by admission"},"membership-observer":{class:"rotation-renewed",defaultTtlSeconds:ROTATION_RENEWED_TTL_SEC,renewalOwner:"system-account rotation",note:"$SYS-account CONNZ observer; NOT online-renewable ($SYS seed dies at `up`) - bounded exp, renewed only by rotateSystemAccount + broker restart; doctor warns near expiry"},"account-census":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"Host-only account CONNZ and account-qualified replies; at most five minutes, no KICK or client-side renewal"},"connection-evictor":{class:"rotation-renewed",defaultTtlSeconds:ROTATION_RENEWED_TTL_SEC,renewalOwner:"system-account rotation",note:"$SYS-account KICK-only live-eviction cred; same rotation-renewed posture as the observer"}};for(const p of Object.values(CREDENTIAL_LIFETIMES))Object.freeze(p);Object.freeze(CREDENTIAL_LIFETIMES);var LIFETIME_TTL_SNAP=new Map(Object.entries(CREDENTIAL_LIFETIMES).map(([k,p])=>[k,p.defaultTtlSeconds]));function inspectCredHealth(creds,nowSec=Math.floor(Date.now()/1e3)){let claims2;try{claims2=credsClaims(creds)}catch(e){return{state:"unreadable",error:e.message}}const{iat,exp}=claims2;if(typeof exp!=="number")return{state:"unbounded",iat};if(typeof iat!=="number")return{state:"unreadable",iat:void 0,exp,error:"user JWT carries exp but no iat - cannot place the renewal point"};const renewAt=Math.floor(iat+.75*(exp-iat));if(nowSec>=exp)return{state:"expired",iat,exp,renewAt};if(nowSec>=renewAt)return{state:"near-expiry",iat,exp,renewAt};return{state:"healthy",iat,exp,renewAt}}var BASE_LIMITS={subs:-1,conn:-1,leaf:-1,imports:-1,exports:-1,data:-1,payload:-1,wildcards:true};var DATA_LIMITS={...BASE_LIMITS,mem_storage:-1,disk_storage:-1};var SYS_LIMITS={...BASE_LIMITS,mem_storage:0,disk_storage:0};var SPAWN_VIEW_READS=Object.freeze(["status","models","resolve-cwd","list-dir","ps"]);function parseSecretStoreIdentity(raw){if(raw===null||typeof raw!=="object"||Array.isArray(raw))throw new Error("secret-store identity must be an object");const o=raw;const keys=Object.keys(o);if(o.kind==="fs"){if(keys.some(k=>k!=="kind"&&k!=="root"&&k!=="id"))throw new Error("secret-store identity of kind fs admits only {kind, root, id}");if(typeof o.root!=="string"||!o.root.trim())throw new Error("secret-store identity of kind fs requires a non-blank root");if(typeof o.id!=="string"||!o.id.trim())throw new Error("secret-store identity of kind fs requires a non-blank id");return{kind:"fs",root:o.root,id:o.id}}if(o.kind==="injected"){if(keys.some(k=>k!=="kind"&&k!=="coordinate"))throw new Error("secret-store identity of kind injected admits only {kind, coordinate}");if(typeof o.coordinate!=="string"||!o.coordinate.trim())throw new Error("secret-store identity of kind injected requires a non-blank coordinate");return{kind:"injected",coordinate:o.coordinate}}throw new Error('secret-store identity kind must be "fs" or "injected"')}var import_node_fs4=require("node:fs");var import_yaml=__toESM(require_dist2(),1);function peerLabel(card){return(card.role?`${card.name}/${card.role}`:card.name).replace(/[\p{Cc}\p{Zl}\p{Zp}[\]]+/gu," ")}var LINE_BREAK=/\r\n?|[\n\v\f\u0085\u2028\u2029]/;var AmbiguousPeerError=class extends Error{target;candidates;constructor(target2,candidates){super(`"${target2}" is ambiguous - ${candidates.length} peers share that name: `+candidates.map(c=>`${c.name} (${c.id}, ${c.status})`).join("; ")+`. Re-send to the exact instance id.`);this.target=target2;this.candidates=candidates;this.name="AmbiguousPeerError"}};function candidate(p){return{id:p.card.id,name:p.card.name,role:p.card.role,status:p.status,ts:p.ts}}function resolvePeer(roster,target2,opts={}){const peers=opts.selfId?roster.filter(p=>p.card.id!==opts.selfId):roster;const byId=peers.find(p=>p.card.id===target2);if(byId)return byId;const want=target2.trim().toLowerCase();if(!want)return void 0;const matches=peers.filter(p=>p.card.name.toLowerCase()===want);if(matches.length===0){const labelled=peers.find(p=>p.card.role&&peerLabel(p.card).trim().toLowerCase()===want);if(labelled)throw new Error(`"${target2}" is the roster label of ${labelled.card.name} (role ${labelled.card.role}), not an address: use the name "${labelled.card.name}" or its instance id`);return void 0}const live=matches.filter(p=>p.status!=="offline");const pool=live.length>0?live:matches;if(pool.length===1)return pool[0];throw new AmbiguousPeerError(target2,pool.map(candidate))}function sharedNameIds(roster,opts={}){const peers=opts.selfId?roster.filter(p=>p.card.id!==opts.selfId):roster;const groups=new Map;for(const p of peers){const key=p.card.name.trim().toLowerCase();const group=groups.get(key);if(group)group.push(p);else groups.set(key,[p])}const ids=new Set;for(const group of groups.values()){const live=group.filter(p=>p.status!=="offline");const pool=live.length>0?live:group;if(pool.length>1)for(const p of pool)ids.add(p.card.id)}return ids}var MAX_NAME_LENGTH=128;function assertValidName(name){if(name.length===0||name!==name.trim())throw new Error(`invalid name ${JSON.stringify(name)}: must be non-empty with no surrounding whitespace`);if(name.length>MAX_NAME_LENGTH)throw new Error(`invalid name ${JSON.stringify(name.slice(0,32))}\u2026: ${name.length} characters exceeds the ${MAX_NAME_LENGTH}-character limit (the CONNECT line budget that carries it)`);if(LINE_BREAK.test(name))throw new Error(`invalid name ${JSON.stringify(name)}: must be a single line`);if(name.includes("/"))throw new Error(`invalid name ${JSON.stringify(name)}: "/" is reserved (the owner/name separator)`);if(name.includes("\\"))throw new Error(`invalid name ${JSON.stringify(name)}: "\\" is reserved (a Windows path separator)`);if(!isWellFormedUnicode(name))throw new Error(`invalid name ${JSON.stringify(name)}: contains an unpaired UTF-16 surrogate. Such a name cannot survive UTF-8 encoding \u2014 it is replaced with U+FFFD \u2014 so distinct names would silently become one identity.`)}function utf16Problem(text2){return text2.startsWith("\uFFFD\uFFFD")||text2.includes("\0")?"it is saved as UTF-16, and Cotal reads only UTF-8":void 0}var PERSONA_ENDPOINT_MAX_COMMANDS=256;var ENTRY_KEYS=["endpoint","commands","instanceId"];function parsePersonaEndpoints(raw,where){if(raw===void 0||raw===null)return void 0;const fail3=detail=>{throw new Error(`${where}: "endpoints" ${detail}`)};if(!Array.isArray(raw))fail3("must be a list of { endpoint, commands, instanceId? } entries");const merged=new Map;let total=0;for(const item of raw){if(item===null||typeof item!=="object"||Array.isArray(item))fail3("entries must be mappings of endpoint, commands and an optional instanceId");const proto=Object.getPrototypeOf(item);if(proto!==Object.prototype&&proto!==null)fail3("entries must be plain mappings");const rec=item;const extra=Reflect.ownKeys(rec).find(k=>typeof k!=="string"||!ENTRY_KEYS.includes(k));if(extra!==void 0)fail3(`entry has unknown key ${String(extra)}; an entry takes endpoint, commands and instanceId`);const endpoint=rec.endpoint;if(typeof endpoint!=="string")fail3("entry needs an endpoint name");try{endpointToken(endpoint)}catch(e){fail3(`entry: ${e.message}`)}if(!endpoint.includes("."))fail3(`entry names "${endpoint}", a single-label endpoint; those are the reference endpoints, reached through the baseline and the spawn, run and admin capabilities. A persona hands on a reverse-DNS endpoint such as com.example.orders`);let instanceId;if(rec.instanceId!==void 0){if(typeof rec.instanceId!=="string")fail3(`entry for ${endpoint}: instanceId must be a string`);try{instanceId=assertLifecycleToken(rec.instanceId,"instanceId")}catch(e){fail3(`entry for ${endpoint}: ${e.message}`)}}const commands=rec.commands;if(!Array.isArray(commands)||commands.length===0)fail3(`entry for ${endpoint} needs a non-empty commands list`);const key=`${endpoint}\0${instanceId??""}`;const into=merged.get(key)??{endpoint,commands:[],...instanceId!==void 0?{instanceId}:{}};for(const c of commands){if(typeof c!=="string")fail3(`entry for ${endpoint}: commands must be strings`);try{assertCommandToken(c)}catch(e){fail3(`entry for ${endpoint}: ${e.message}`)}if(RESERVED_COMMANDS.includes(c))fail3(`entry for ${endpoint} names the reserved command "${c}"; describe is granted on every endpoint and cancel is not handed on`);if(!into.commands.includes(c)){into.commands.push(c);total++}}merged.set(key,into)}if(total>PERSONA_ENDPOINT_MAX_COMMANDS)fail3(`names ${total} commands; a persona may name at most ${PERSONA_ENDPOINT_MAX_COMMANDS}`);return[...merged.values()].map(e=>({...e,commands:[...e.commands].sort()})).sort((a,b)=>a.endpoint<b.endpoint?-1:a.endpoint>b.endpoint?1:(a.instanceId??"")<(b.instanceId??"")?-1:1)}function parseFrontmatter(src,path){let doc;try{doc=(0,import_yaml.parse)(src)}catch(e){throw new Error(`agent file ${path}: invalid YAML frontmatter; ${e.message}`)}if(doc===null||doc===void 0)return{};if(typeof doc!=="object"||Array.isArray(doc))throw new Error(`agent file ${path}: frontmatter must be a YAML mapping (key: value pairs)`);return doc}var AGENT_FILE_FENCE=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;var MODELED_KEYS=new Set(["name","role","kind","description","tags","subscribe","allowSubscribe","allowPublish","quiet","muted","agent","model","variant","launchOptions","capabilities","endpoints","owner"]);var RENAMED_KEYS=["channels","publish"];function assertLaunchSelectors(def,where){for(const k of["model","variant"]){const v=def[k];if(v!==void 0&&!v.trim())throw new Error(`${where}: "${k}" must not be empty`)}}function assertValidKind(kind,where){if(kind==="agent"||kind==="endpoint")return kind;throw new Error(`${where?`${where}: `:`invalid kind ${JSON.stringify(kind)}: `}"kind" must be "agent" or "endpoint"`)}function loadAgentFile(path){return parseAgentFileSource((0,import_node_fs4.readFileSync)(path,"utf8"),path)}function parseAgentFileSource(src,path){const encoding=utf16Problem(src);if(encoding)throw new Error(`agent file ${path}: ${encoding}; save it as UTF-8`);const m=AGENT_FILE_FENCE.exec(src.replace(/^\uFEFF/,"").replace(/\r\n/g,"\n"));if(!m)throw new Error(`agent file ${path}: missing "---" frontmatter block`);const fm=parseFrontmatter(m[1],path);const persona=m[2].trim();const str2=k=>{const v=fm[k];if(v===void 0||v===null)return void 0;if(typeof v==="object")throw new Error(`agent file ${path}: "${k}" must be a scalar`);return String(v)};const list2=k=>{const v=fm[k];if(v===void 0||v===null)return void 0;return(Array.isArray(v)?v:[v]).map(x=>{if(x===null||typeof x==="object")throw new Error(`agent file ${path}: "${k}" list items must be scalars`);return String(x)})};const name=str2("name");if(!name)throw new Error(`agent file ${path}: "name" is required`);assertValidName(name);const model=str2("model");const variant=str2("variant");assertLaunchSelectors({model,variant},`agent file ${path}`);const rawKind=str2("kind");const kind=rawKind!==void 0?assertValidKind(rawKind,`agent file ${path}`):void 0;for(const old of RENAMED_KEYS)if(old in fm)throw new Error(`agent file ${path}: "${old}" was renamed - use "subscribe"/"allowSubscribe" (read) and "allowPublish" (post)`);const subscribe=list2("subscribe");const allowSubscribe=list2("allowSubscribe");const allowPublish=list2("allowPublish");const quiet=list2("quiet");const muted=list2("muted");for(const ch of[...subscribe??[],...allowSubscribe??[],...allowPublish??[]])try{assertValidChannel(ch)}catch(e){throw new Error(`agent file ${path}: ${e.message}`)}let effAllow;try{effAllow=resolveReadAcl(subscribe??[],allowSubscribe)}catch(e){throw new Error(`agent file ${path}: ${e.message}`)}const both=(quiet??[]).filter(c=>(muted??[]).includes(c));if(both.length)throw new Error(`agent file ${path}: channel(s) [${both.join(", ")}] are in both quiet and muted - pick one`);for(const[field,chans]of[["quiet",quiet],["muted",muted]])for(const ch of chans??[]){try{assertValidChannel(ch)}catch(e){throw new Error(`agent file ${path}: ${e.message}`)}if(!isConcreteChannel(ch))throw new Error(`agent file ${path}: ${field} channel "${ch}" must be a concrete channel (no wildcard)`);if(!channelInAllow(effAllow,ch))throw new Error(`agent file ${path}: ${field} channel "${ch}" is not within your read ACL / allowSubscribe [${effAllow.join(", ")}]`)}const launchOptionsRaw=fm["launchOptions"];let launchOptions;if(launchOptionsRaw!==void 0&&launchOptionsRaw!==null){if(typeof launchOptionsRaw!=="object"||Array.isArray(launchOptionsRaw))throw new Error(`agent file ${path}: "launchOptions" must be a mapping of key: value pairs`);launchOptions=launchOptionsRaw}const meta3={};for(const[k,v]of Object.entries(fm))if(!MODELED_KEYS.has(k)&&v!==null&&typeof v!=="object")meta3[k]=String(v);return{name,role:str2("role"),kind,description:str2("description"),tags:list2("tags"),agent:str2("agent"),subscribe,allowSubscribe,allowPublish,quiet,muted,model,variant,launchOptions,capabilities:list2("capabilities"),endpoints:parsePersonaEndpoints(fm["endpoints"],`agent file ${path}`),owner:str2("owner"),meta:Object.keys(meta3).length?meta3:void 0,persona:persona||void 0}}function nextHeartbeat(phaseMs,intervalMs,lastBeat,nowMs){const beat=Math.max(lastBeat+1,Math.ceil((nowMs-phaseMs)/intervalMs));return{beat,delayMs:Math.max(0,phaseMs+beat*intervalMs-nowMs)}}var import_jetstream13=__toESM(require_mod4(),1);var import_jetstream14=__toESM(require_mod4(),1);var import_kv7=__toESM(require_mod6(),1);var import_internal2=__toESM(require_internal_mod3(),1);var import_kv5=__toESM(require_mod6(),1);var import_transport_node11=__toESM(require_transport_node(),1);async function openDeliveryRegistry(nc,space2){return new import_kv5.Kvm(nc).open(deliveryBucket(space2))}var import_kv6=__toESM(require_mod6(),1);var import_transport_node12=__toESM(require_transport_node(),1);var MAX_CHANNEL_DESCRIPTION=200;var MAX_CHANNEL_INSTRUCTIONS=2e3;function validateChannelConfig(cfg){validateChannelDefaults(cfg);validateText("description",cfg.description,MAX_CHANNEL_DESCRIPTION);validateText("instructions",cfg.instructions,MAX_CHANNEL_INSTRUCTIONS)}function validateText(field,text2,max){if(text2===void 0)return;if(typeof text2!=="string")throw new Error(`channel ${field} must be a string`);if(text2.length>max)throw new Error(`channel ${field} too long (${text2.length} > ${max} chars)`)}function validateChannelDefaults(d){if(d.replay!==void 0&&typeof d.replay!=="boolean")throw new Error(`invalid replay "${d.replay}" - expected true or false`);if(d.replayWindow!==void 0)parseDuration(d.replayWindow);if(d.deliveryClass!==void 0&&d.deliveryClass!=="live"&&d.deliveryClass!=="durable")throw new Error(`invalid deliveryClass "${d.deliveryClass}" - expected "live" or "durable"`)}function decodeChannelEntry(e){const value=e.json();if(typeof value!=="object"||value===null||Array.isArray(value))throw new Error("not a JSON object");if(e.key===CHANNEL_DEFAULTS_KEY)validateChannelDefaults(value);else validateChannelConfig(value);return value}function parseDuration(s){const m=/^(\d+)(s|m|h|d)$/.exec(s.trim());if(!m)throw new Error(`invalid duration "${s}" - expected <number><s|m|h|d>, e.g. "24h"`);const n=Number(m[1]);const unit={s:1e3,m:6e4,h:36e5,d:864e5}[m[2]];return n*unit}function effectiveReplay(cfg,defaults){return cfg?.replay??defaults?.replay??true}function effectiveReplayWindowMs(cfg,defaults){const w=cfg?.replayWindow??defaults?.replayWindow;return w===void 0?void 0:parseDuration(w)}function effectiveDeliveryClass(cfg,defaults){return cfg?.deliveryClass??defaults?.deliveryClass??"durable"}async function openChannelRegistry(nc,space2,opts={}){const kvm=new import_kv6.Kvm(nc);return opts.create?kvm.create(channelBucket(space2)):kvm.open(channelBucket(space2))}async function readChannelConfig(kv,channel){return decode4(kv,channel)}async function readChannelDefaults(kv){return decode4(kv,CHANNEL_DEFAULTS_KEY)}async function decode4(kv,key){return entryValue(await kv.get(key))}function entryValue(e){return entryDecode(e).value}function entryDecode(e){if(!e||e.operation==="DEL"||e.operation==="PURGE")return{};try{return{value:decodeChannelEntry(e)}}catch(err3){return{error:err3.message}}}var ANYCAST_RECORD_RETENTION_MS=24*60*60*1e3;var ANYCAST_STATUS_OP="anycastStatus";var ANYCAST_CANCEL_OP="anycastCancel";var ANYCAST_TAKES_OP="anycastTakes";var ANYCAST_RECORDS_CREDENTIAL_OUTDATED="this delivery daemon's credential was minted before anycast request records existed, so it records no takes and answers no status or cancel; restart the daemon on a credential minted at this version (`cotal up` mints one)";var ANYCAST_NOTICE_KEY="cotalAnycastNotice";function anycastRecordKey(epoch,seq){return`r.${epoch.replace(/[^0-9A-Za-z]/g,"")}.${seq}`}function isAnycastSeq(seq){return typeof seq==="number"&&Number.isSafeInteger(seq)&&seq>0}function holderOf(t){return{id:t.id,name:t.name}}function noticeEvent(row,notice){const{taker,previous,role,seq}=notice;const text2=notice.event==="taken"?`${taker.name} (${taker.id}) took your @${role} request (seq ${seq}).`:`${previous.name} (${previous.id}) did not confirm your @${role} request (seq ${seq}) before its ack wait ran out, and ${taker.name} (${taker.id}) took it. ${previous.name} may already have started it.`;return{key:`anycast.${anycastRecordKey(row.epoch,row.seq).slice(2)}.${row.rev}`,text:text2,notice}}function decideTake(row,stored,t){const taker={...holderOf(t.holder),count:t.count,at:t.now};if(!row){const next={v:1,epoch:t.epoch,seq:t.seq,id:stored.id,role:stored.role,sender:stored.sender,rev:1,state:"taken",taker,outbox:[]};next.outbox.push(noticeEvent(next,{seq:t.seq,role:stored.role,event:"taken",taker:holderOf(taker)}));return{reply:{ok:true},next}}if(row.state==="cancelled")return{reply:{ok:false,code:"cancelled",error:`request seq ${t.seq} was cancelled by its sender`}};const current=row.taker;if(current.id===t.holder.id&¤t.count===t.count)return{reply:{ok:true}};if(t.count>current.count){const moved=current.id!==t.holder.id;const next={...row,rev:row.rev+1,taker,previous:moved?{...holderOf(current),count:current.count}:row.previous,outbox:[...row.outbox]};if(moved)next.outbox.push(noticeEvent(next,{seq:t.seq,role:row.role,event:"redelivered",taker:holderOf(taker),previous:holderOf(current)}));return{reply:{ok:true},next}}return{reply:{ok:false,code:"taken",error:`request seq ${t.seq} was taken by ${current.name} (${current.id}) on delivery ${current.count}`}}}function statusFor(row,stored,q){if(row){if(row.sender!==q.caller||q.id!==void 0&&row.id!==q.id)return{state:"unknown",seq:q.seq};if(row.state==="cancelled")return{state:"cancelled",seq:q.seq,role:row.role,removal:row.removal??"pending"};const taker=row.taker;return{state:"taken",seq:q.seq,role:row.role,taker:holderOf(taker),at:taker.at,...row.previous?{previous:holderOf(row.previous)}:{}}}if(!stored||stored.sender!==q.caller||q.id!==void 0&&stored.id!==q.id)return{state:"unknown",seq:q.seq};return{state:"waiting",seq:q.seq,role:stored.role}}function decideCancel(row,stored,q){const status2=statusFor(row,stored,q);if(status2.state!=="waiting")return{status:status2};const s=stored;return{status:{state:"cancelled",seq:q.seq,role:s.role,removal:"pending"},next:{v:1,epoch:q.epoch,seq:q.seq,id:s.id,role:s.role,sender:s.sender,rev:1,state:"cancelled",removal:"pending",outbox:[]}}}function storedRequest(subject,data){const parsed=parseSubject(subject);if(!parsed||parsed.kind!=="svc")return void 0;let id2;try{id2=JSON.parse(new TextDecoder().decode(data)).id}catch{return void 0}if(typeof id2!=="string")return void 0;return{role:parsed.rest,sender:parsed.sender,id:id2}}function isNoMessageFound(e){return e?.code===10043||/no message found/i.test(String(e?.message??""))}var encoder=new TextEncoder;function readRow(e){if(!e||e.operation!=="PUT")return void 0;const row=e.json();if(row?.v!==1||typeof row.epoch!=="string"||!isAnycastSeq(row.seq)||!Array.isArray(row.outbox))throw new Error(`anycast record ${e.key} is not a version-1 record`);return row}var AnycastRequestAuthority=class{deps;flushing=new Map;constructor(deps){this.deps=deps}now(){return this.deps.now?.()??Date.now()}async queued(seq){for(let attempt=0;attempt<3;attempt++){const before=(await this.deps.jsm.streams.info(this.deps.stream)).created;const sm=await this.deps.jsm.streams.getMessage(this.deps.stream,{seq});const after=(await this.deps.jsm.streams.info(this.deps.stream)).created;if(before!==after)continue;return{epoch:before,stored:sm?storedRequest(sm.subject,sm.data):void 0}}throw new Error(`the ${this.deps.stream} stream was recreated during the read; retry`)}async take(role,req){for(let attempt=0;attempt<5;attempt++){const{epoch,stored}=await this.queued(req.seq);if(req.epoch!==epoch)return{ok:false,code:"mismatch",error:`the copy of seq ${req.seq} came from a ${this.deps.stream} stream that has since been recreated`};if(!stored){const row=readRow(await this.deps.kv.get(anycastRecordKey(epoch,req.seq)));if(row?.state==="cancelled"&&row.id===req.id)return{ok:false,code:"cancelled",error:`request seq ${req.seq} was cancelled by its sender`};return{ok:false,code:"gone",error:`request seq ${req.seq} is no longer on the queue`}}if(stored.role!==role||stored.id!==req.id)return{ok:false,code:"mismatch",error:`seq ${req.seq} on the queue is not the @${role} request ${req.id}`};const key=anycastRecordKey(epoch,req.seq);const entry=await this.deps.kv.get(key);const{reply,next}=decideTake(readRow(entry),stored,{epoch,seq:req.seq,holder:req.from,count:req.count,now:this.now()});if(!next)return reply;if(!this.deps.mayAct())return{ok:false,code:"busy",error:"the delivery daemon stopped serving while the take was in flight; retry"};if(!await this.write(key,next,entry))continue;if(next.outbox.length)this.flushSoon(key);return reply}return{ok:false,code:"busy",error:`request seq ${req.seq} changed under five takes in a row; retry`}}async status(caller,q){const{epoch,stored}=await this.queued(q.seq);const row=readRow(await this.deps.kv.get(anycastRecordKey(epoch,q.seq)));return statusFor(row,stored,{...q,caller})}async cancel(caller,q){for(let attempt=0;attempt<5;attempt++){const{epoch,stored}=await this.queued(q.seq);const key=anycastRecordKey(epoch,q.seq);const entry=await this.deps.kv.get(key);const row=readRow(entry);const{status:status2,next}=decideCancel(row,stored,{...q,epoch,caller,now:this.now()});if(!next){if(status2.state==="cancelled"&&status2.removal==="pending")return this.remove(key);return status2}if(!this.deps.mayAct())throw new Error("the delivery daemon stopped serving while the cancel was in flight; retry");if(!await this.write(key,next,entry))continue;return this.remove(key)}throw new Error(`request seq ${q.seq} changed under five cancels in a row; retry`)}async remove(key){let removal;for(let attempt=0;attempt<5;attempt++){const entry=await this.deps.kv.get(key);const row=readRow(entry);if(!row||row.state!=="cancelled")throw new Error(`anycast record ${key} is not a cancelled request`);if(row.removal!=="pending")return{state:"cancelled",seq:row.seq,role:row.role,removal:row.removal??"pending"};if(removal===void 0){const epoch=(await this.deps.jsm.streams.info(this.deps.stream)).created;if(epoch!==row.epoch)removal="already-gone";else{if(!this.deps.mayAct())return{state:"cancelled",seq:row.seq,role:row.role,removal:"pending"};try{await this.deps.jsm.streams.deleteMessage(this.deps.stream,row.seq,false);removal="deleted"}catch(e){if(!isNoMessageFound(e))throw e;removal="already-gone"}}}if(await this.write(key,{...row,removal},entry))return{state:"cancelled",seq:row.seq,role:row.role,removal}}throw new Error(`anycast record ${key} changed under five writes in a row; retry`)}async write(key,row,entry){try{const bytes=encoder.encode(JSON.stringify(row));if(entry&&entry.operation==="PUT")await this.deps.kv.update(key,bytes,entry.revision);else await this.deps.kv.create(key,bytes);return true}catch(e){if(isCasLoss(e))return false;throw e}}flushSoon(key){void this.flush(key).catch(e=>this.deps.onError(e))}flush(key){const prior=this.flushing.get(key)??Promise.resolve();const run=prior.then(async()=>{for(let attempt=0;attempt<16;attempt++){if(!this.deps.mayAct())return;const entry=await this.deps.kv.get(key);const row=readRow(entry);const event=row?.outbox[0];if(!row||!event)return;await this.deps.send(row.sender,event);await this.write(key,{...row,outbox:row.outbox.filter(e=>e.key!==event.key)},entry)}});const settled=run.finally(()=>{if(this.flushing.get(key)===settled)this.flushing.delete(key)});this.flushing.set(key,settled);return settled}async sweep(){const keys=[];for await(const k of await this.deps.kv.keys("r.>"))keys.push(k);for(const key of keys){if(!this.deps.mayAct())return;try{await this.maintain(key)}catch(e){this.deps.onError(e)}}}async maintain(key){let row=readRow(await this.deps.kv.get(key));if(!row)return;if(row.outbox.length)await this.flush(key);if(row.state==="cancelled"&&row.removal==="pending")await this.remove(key);const entry=await this.deps.kv.get(key);row=readRow(entry);if(!row||!this.deps.mayAct())return;if(row.leftAt===void 0){const{epoch,stored}=await this.queued(row.seq);if(epoch===row.epoch&&stored?.id===row.id)return;await this.write(key,{...row,leftAt:this.now()},entry)}else if(this.now()-row.leftAt>ANYCAST_RECORD_RETENTION_MS&&!row.outbox.length){try{await this.deps.kv.delete(key,{previousSeq:entry.revision})}catch(e){if(!isCasLoss(e))throw e}}}};var import_nats_core5=__toESM(require_mod3(),1);function isPermissionDenied(e){if(e instanceof import_nats_core5.PermissionViolationError)return true;if(e?.cause instanceof import_nats_core5.PermissionViolationError)return true;return/permissions?\s+violation/i.test(String(e?.message??""))}var DEFAULT_SERVER="nats://127.0.0.1:4222";var PLANE3_FRAME_HEADER="Cotal-Delivery-Frame";var ANYCAST_CONTROL_OPS=new Set([ANYCAST_STATUS_OP,ANYCAST_CANCEL_OP,ANYCAST_TAKES_OP]);var MAX_TAKES_IN_FLIGHT=64;var ANYCAST_SWEEP_MS=10*60*1e3;var ANYCAST_TAKE_TIMEOUT_MS=5e3;var DELIVERY_LIMIT_READ_MS=5e3;function deliveryLimitOf(value){if(value===void 0||value==="")return PLANE3_MAX_MSGS_PER_SUBJECT;if(value==="none")return null;if(!/^[1-9]\d*$/.test(value)||!Number.isSafeInteger(Number(value)))throw new Error(`plane-3 delivery: ${DELIVERY_LIMIT_HEADER} ${JSON.stringify(value)} is not a count`);return Number(value)}var MULTI_FILTER_BATCH=1e3;var MULTI_FILTER_READ_CONCURRENCY=4;var HISTORY_READER_INACTIVE_MS=5*6e4;var MAX_TIMER_MS3=2147483647;var DmDurableMissingError=class extends Error{stream;durable;code="dm-durable-missing";constructor(stream,durable){super(`dm-durable-missing: durable "${durable}" on stream "${stream}" does not exist; a DM-only endpoint binds an existing durable and never creates one`);this.stream=stream;this.durable=durable;this.name="DmDurableMissingError"}};var DmBindRefusedError=class extends Error{stream;durable;code="dm-bind-refused";constructor(stream,durable,cause){super(`dm-bind-refused: binding durable "${durable}" on stream "${stream}" was refused (${cause instanceof Error?cause.message:String(cause)})`,{cause});this.stream=stream;this.durable=durable;this.name="DmBindRefusedError"}};var PresenceWriteStuckError=class extends Error{bucket;since;consecutiveFailures;ttlMs;lastError;code="presence-write-stuck";transient=false;constructor(bucket,since,consecutiveFailures,ttlMs,lastError){super(`presence writes to bucket ${JSON.stringify(bucket)} have failed ${consecutiveFailures} consecutive times for at least one TTL (${ttlMs}ms); the presence view is not live until a write succeeds or the broker store is repaired${lastError?` (last refusal: ${lastError})`:""}`);this.bucket=bucket;this.since=since;this.consecutiveFailures=consecutiveFailures;this.ttlMs=ttlMs;this.lastError=lastError;this.name="PresenceWriteStuckError"}};var READER_MAX_REDELIVERIES=10;var READ_HISTORY_DEFAULT_LIMIT=100;var READ_HISTORY_MAX_LIMIT=200;function fitHistoryPage(items,budget){const enc7=new TextEncoder;let used=enc7.encode(JSON.stringify({ok:true,data:{items:[],complete:false}})).length;let first=items.length;for(let i=items.length-1;i>=0;i--){const size=enc7.encode(JSON.stringify(items[i])).length+1;if(used+size>budget)break;used+=size;first=i}return first===items.length?[]:items.slice(first)}function membershipChange(e,update){const operation=e.operation;if(e.key===MEMBERSHIP_FEED_KEY){let asOf;if(operation==="PUT"){try{asOf=e.json().observedAt}catch{}}return{type:"heartbeat",revision:e.revision,update,asOf}}let member;if(operation==="PUT"){try{const rec=e.json();member={id:e.key,live:rec.live??[],durable:rec.durable??[],observedAt:rec.observedAt}}catch{}}return{type:"member",id:e.key,operation,revision:e.revision,update,member}}var CotalEndpoint=class _CotalEndpoint extends import_node_events.EventEmitter{card;space;channels;servers;token;user;pass;credsSource;currentCreds;credsTimer;watchDeletePermissions=new WeakMap;userMode=false;bearerSource;currentBearer;presentedExp;cancelBearerRenewal;bearerRenewalFailures=0;bearerRefusalSurfaced=false;bearerAdoptedAtMs=0;authExpiryReconnectTimer;sentinelCreds;tls;transportPingIntervalMs;transportMaxPingOut;transportConnectTimeoutMs;heartbeatMs;ttlMs;doRegister;doWatch;doWatchChannels;readOnce;doConsume;dmOnly;dmOnlyInFlight;ackWaitMs;inactiveThresholdMs;nc;requestsAwaitingReply=new Map;onConnection;overlapOnConnectionRenewal;beforeBind;js;jsm;kv;channelKv;presenceWatchIter;channelWatchIter;kvWatchDeletes=new Set;kvWatchBinds=new Set;leaseWatchIntent;leaseWatchIter;leaseWatchDeletes=new Set;leaseWatchBinds=new Set;membersKv;aclKv;deliveryKv;managerLeaseKv;daemonRenewalLeaseRevision;membershipFeedKv;membershipFeedWatches=new Set;deliveryServeSub;deliveryAdminServeSub;takeServeSub;anycastAuthority;taskEpoch;anycastUnavailable;anycastSweep;takesInFlight=0;retiringLifecycles=new Map;membershipWrites=new Map;plane3Quiesced=false;plane3;channelConfigs=new Map;channelDefaults={};channelRead;channelReadGeneration=0;channelReadApplied=0;histLock=Promise.resolve();subs=[];taps=[];livenessResponders=new Map;streamMsgs=[];chatSubs=new Map;chatSubDenied=new Set;plane3Channels=new Map;pendingDurableLeave=new Map;pendingBootJoins=new Set;chatSubRefusals=new WeakSet;reportedSubRefusals=new WeakSet;ownWatchDeletePrefixes=new Set;historyReaderSlots=new Map;firstConnect=true;heartbeatTimer;sweepTimer;presenceWriteFailingSince;lastPresenceWriteError;presenceWriteFailures=0;presenceWriteEscalated=false;presencePutGeneration=0;presencePutSettled;roster=new Map;presenceRead;presenceReadGeneration=0;presenceReadApplied=0;presenceSnapshot=Promise.resolve();presenceSnapshotPopulated=false;lastPresenceWatchAt=0;presenceViewState="unpopulated";presenceRebind;presenceEpoch=0;presenceWatchEmpty=false;presenceRebindAt=0;status="idle";activity;statusSince=Date.now();activitySince;activeAt;condition;conditionRevision=0;environment;attentionMode;channelModes;stopped=false;stopPromise;startPromise;ownedConnections=new Set;rebuildPromise;reconnecting=false;reestablishing=false;backoffResolve;backoffTimer;retryMs=3e3;retryAttempt=0;connId;owner;actor;actorIsEphemeral;ownLifecycleUid;backfillFloor;acceptedToken;issuedGeneration;resolvedServices=new Map;serviceInvocations=new WeakMap;resolvedCommandServices=new Map;activeGoalFollowers=new Set;splitsRecovered=0;presenceBindingDrops=0;get principal(){return{owner:this.owner,actor:this.actor}}get splitRecoveryCount(){return this.splitsRecovered}get presenceBindingDropCount(){return this.presenceBindingDrops}requireLifecycleUid(what){if(!this.ownLifecycleUid)throw new Error(`${what} requires this endpoint's lifecycleUid (EndpointOptions.lifecycleUid): dm/dlv/chathist broker resources are lifecycle-keyed names (SPEC 13.1)`);return this.ownLifecycleUid}constructor(opts){super();let selfMintedConnId=false;this.space=opts.space;assertValidName(opts.card.name);assertValidKind(opts.card.kind);if(opts.card.role!==void 0)assertValidRole(opts.card.role);if(opts.bearer){if(opts.creds||opts.token||opts.user||opts.pass)throw new Error("bearer (user-mode auth) is mutually exclusive with creds/token/user/pass");if(!opts.sentinelCreds)throw new Error("user-mode bearer requires sentinelCreds (the shared auth-account creds presented alongside it)")}if(opts.bearer){this.userMode=true;if(typeof opts.bearer==="function"){if(!opts.card.owner||!opts.card.actor)throw new Error("a bearer source requires explicit card.owner + card.actor (no bearer to derive them from at construction)");this.owner=opts.card.owner;this.actor=opts.card.actor;this.bearerSource=opts.bearer}else{const claims2=decodeBearerPrincipal(opts.bearer);if(opts.card.owner&&opts.card.owner!==claims2.owner)throw new Error(`card.owner ${opts.card.owner} != bearer owner ${claims2.owner}`);if(opts.card.actor&&opts.card.actor!==claims2.actor)throw new Error(`card.actor ${opts.card.actor} != bearer actor ${claims2.actor}`);this.owner=claims2.owner;this.actor=claims2.actor;this.currentBearer=opts.bearer}this.connId=assertInboxConnId(`ibx${(0,import_node_crypto10.randomUUID)().replace(/-/g,"")}`);this.sentinelCreds=opts.sentinelCreds;this.actorIsEphemeral=false}else{if(typeof opts.creds==="function"){if(!opts.card.id)throw new Error("a creds source requires an explicit card.id (no cred to derive the identity from at construction)");this.credsSource=opts.creds;this.connId=opts.card.id;selfMintedConnId=false}else{const credId=opts.creds?idFromCreds(opts.creds):void 0;if(opts.card.id&&credId&&opts.card.id!==credId)throw new Error(`card.id ${opts.card.id} != creds identity ${credId} - they must be the same nkey`);this.currentCreds=opts.creds;selfMintedConnId=opts.card.id===void 0&&credId===void 0;this.connId=opts.card.id??credId??(0,import_node_crypto10.randomUUID)().replace(/-/g,"")}this.owner=opts.card.owner??DEV_OWNER;this.actor=opts.card.actor??this.connId;this.actorIsEphemeral=opts.card.actor===void 0&&selfMintedConnId}this.ownLifecycleUid=opts.lifecycleUid!==void 0?assertLifecycleToken(opts.lifecycleUid):this.authed?void 0:mintLifecycleUid();if(opts.backfillFloor!==void 0){if(!Number.isInteger(opts.backfillFloor)||opts.backfillFloor<0)throw new Error(`EndpointOptions.backfillFloor must be a non-negative integer stream sequence, got ${opts.backfillFloor}`);this.backfillFloor=opts.backfillFloor}if(opts.acceptedToken!==void 0){if(!opts.creds)throw new Error("EndpointOptions.acceptedToken names a static issuance and needs creds beside it (SPEC 13.15)");this.acceptedToken=assertGeneration(opts.acceptedToken,"acceptedToken")}const principal=principalKey(this.owner,this.actor);this.card={...opts.card,id:principal.key,owner:this.owner,actor:this.actor};this.environment=(opts.environment===void 0?process.env.COTAL_ENVIRONMENT:opts.environment)?.trim()||void 0;this.servers=opts.servers??DEFAULT_SERVER;this.token=opts.token;this.user=opts.user;this.pass=opts.pass;this.tls=opts.tls??false;for(const[label,value]of[["transportPingIntervalMs",opts.transportPingIntervalMs],["transportMaxPingOut",opts.transportMaxPingOut],["transportConnectTimeoutMs",opts.transportConnectTimeoutMs]]){if(value!==void 0&&(!Number.isSafeInteger(value)||value<=0))throw new Error(`EndpointOptions.${label} must be a positive safe integer`)}if(opts.transportPingIntervalMs===void 0!==(opts.transportMaxPingOut===void 0))throw new Error("EndpointOptions transportPingIntervalMs and transportMaxPingOut must be configured together");this.onConnection=opts.onConnection;this.overlapOnConnectionRenewal=opts.overlapOnConnectionRenewal===true;this.beforeBind=opts.beforeBind;this.transportPingIntervalMs=opts.transportPingIntervalMs??1e4;this.transportMaxPingOut=opts.transportMaxPingOut??2;this.transportConnectTimeoutMs=opts.transportConnectTimeoutMs;this.channels=opts.channels??[];this.heartbeatMs=opts.heartbeatMs??2e3;this.ttlMs=opts.ttlMs??6e3;this.doRegister=opts.registerPresence??true;this.doWatch=opts.watchPresence??true;this.doWatchChannels=opts.watchChannels??true;this.doConsume=opts.consume??true;this.readOnce=opts.readOnce??false;if(this.readOnce&&(this.doConsume||this.doRegister))throw new Error("EndpointOptions.readOnce requires consume and registerPresence false: a one-time read cannot keep a consumer's channel cache or its own presence current");if(opts.dmOnly!==void 0){if(typeof opts.dmOnly.handler!=="function")throw new Error("EndpointOptions.dmOnly.handler must be a function");const settle=opts.dmOnly.settleTimeoutMs;if(settle!==void 0&&(!Number.isSafeInteger(settle)||settle<=0))throw new Error("EndpointOptions.dmOnly.settleTimeoutMs must be a positive safe integer");if(!this.authed)throw new Error("EndpointOptions.dmOnly requires creds or a bearer: it binds a provisioned durable and never creates one");if(!this.doConsume||this.doRegister||this.doWatch||this.doWatchChannels||this.readOnce)throw new Error("EndpointOptions.dmOnly requires consume true and registerPresence, watchPresence, watchChannels and readOnce false");if(this.channels.length||opts.card.role||opts.acceptedToken!==void 0)throw new Error("EndpointOptions.dmOnly takes no channels, role or acceptedToken: the endpoint reads only its own DM durable");this.requireLifecycleUid("EndpointOptions.dmOnly");this.dmOnly=opts.dmOnly}this.channelModes=opts.channelModes&&Object.keys(opts.channelModes).length?opts.channelModes:void 0;this.ackWaitMs=opts.ackWaitMs??6e4;this.inactiveThresholdMs=opts.inactiveThresholdMs??6e5}ref(){return{id:this.card.id,name:this.card.name,role:this.card.role}}get authed(){return Boolean(this.currentCreds||this.credsSource)||this.userMode}start(){if(this.startPromise)return this.startPromise;const flight=this.startOnce().finally(()=>{if(this.startPromise===flight)this.startPromise=void 0});this.startPromise=flight;return flight}async startOnce(){try{await this.connectAndBind()}catch(error51){if(!this.stopped)throw error51}if(await this.tearDownIfStopped())return;this.superviseConnection()}static BEARER_MIN_RENEWAL_MS=5e3;static BEARER_RETRY_MS=5e3;static BEARER_RETRY_CAP_MS=6e4;emitRecoverable(err3){this.emit("warning",err3)}async refreshBearer(initial=false){try{const bearer=await this.bearerSource();const claims2=decodeBearerPrincipal(bearer);if(claims2.owner!==this.owner||claims2.actor!==this.actor)throw new Error(`bearer source returned principal ${claims2.owner}.${claims2.actor}, expected ${this.owner}.${this.actor}`);const expiryMs=bearerExpiryMs(bearer);const held2=this.currentBearer;if(held2!==void 0){if(expiryMs<=Date.now())throw new Error("the bearer source returned a token that has already expired - nothing adopted");if(bearer===held2&&Date.now()>=bearerRenewalDeadlineMs(held2,this.bearerAdoptedAtMs))throw new Error("the bearer source re-served the token already held and it cannot carry another cycle (the auth service has not issued a fresh one) - nothing adopted")}if(bearer!==held2)this.bearerAdoptedAtMs=Date.now();this.currentBearer=bearer;this.bearerRenewalFailures=0;const{issuedAtMs,expiresAtMs}=bearerLifetimeMs(bearer,this.bearerAdoptedAtMs);this.armBearerTimer(armRenewal(this.space,issuedAtMs,expiresAtMs,()=>void this.renewBearerOnTimer(),_CotalEndpoint.BEARER_MIN_RENEWAL_MS))}catch(e){if(initial)throw e;if(this.bearerRenewalFailures===0)this.emitRecoverable(new Error(`bearer refresh failed (${e instanceof Error?e.message:String(e)}) - retrying with backoff; this connection dies at its current token's expiry if the auth service stays down`));const named=retryAfterMs(e);const delay3=named>0?named:jitteredBackoffMs(this.bearerRenewalFailures,_CotalEndpoint.BEARER_RETRY_MS,_CotalEndpoint.BEARER_RETRY_CAP_MS);this.bearerRenewalFailures++;const timer=setTimeout(()=>void this.renewBearerOnTimer(),delay3);timer.unref?.();this.armBearerTimer(()=>clearTimeout(timer))}}armBearerTimer(cancel){this.cancelBearerRenewal?.();this.cancelBearerRenewal=cancel;if(this.stopped)cancel()}async renewBearerOnTimer(){const held2=this.currentBearer;await this.refreshBearer();if(this.stopped||this.currentBearer===held2)return;if(this.nc&&!this.nc.isClosed())await this.swapConnectionOntoFreshCreds();else this.kickBackoff()}bearerForWire(){const bearer=this.currentBearer;if(bearer!==void 0&&bearerExpiryMs(bearer)>Date.now())return bearer;throw new Error(this.bearerSource?"this endpoint's user bearer has expired and renewal through the auth exchange is failing - not presenting the expired token to the broker; retrying with backoff":"this endpoint's user bearer has expired and it holds no bearer source to renew it - re-authenticate and rebuild the endpoint (construct it with a bearer FUNCTION for standing renewal)")}static CREDS_RETRY_MS=6e4;static presentableCreds(creds,opts){const{exp}=credsClaims(creds);if(typeof exp==="number"&&exp*1e3<=Date.now())throw new Error(opts.renewable?"this endpoint's creds have expired and renewal is failing - not presenting the expired credential to the broker; retrying with backoff":"this endpoint's creds have expired and it holds no creds source to renew them - replace the credential and rebuild the endpoint (pass a creds FUNCTION for standing renewal)");return creds}presentCreds(){const creds=this.credsForWire();this.presentedExp=credsClaims(creds).exp;return creds}presentBearer(){const bearer=this.bearerForWire();this.presentedExp=bearerExpiryMs(bearer)/1e3;return bearer}credsForWire(){if(!this.currentCreds)throw new Error(this.credsSource?"this endpoint has no credential to present yet (the creds source has not returned one) - not dialing without auth material":"this endpoint was constructed with an empty creds string - not dialing without auth material (an empty credential is not anonymous access)");return _CotalEndpoint.presentableCreds(this.currentCreds,{renewable:Boolean(this.credsSource)})}wireCreds(){return this.credsForWire()}static assertRenewableGeneration(candidate2,current,delayMs){const{exp}=credsClaims(candidate2);if(typeof exp==="number"&&exp*1e3<=Date.now())throw new Error("the creds source returned an already-expired credential (its `exp` is in the past) - nothing adopted; the renewal owner has not re-signed it, or the store is serving a stale generation");if(current!==void 0&&credsFingerprint(candidate2)===credsFingerprint(current)&&delayMs<=0)throw new Error("the creds source still holds the previous generation past its renewal point (the renewal owner has not re-signed it) - nothing adopted")}static PREFLIGHT_MS=4e3;static RESIDENT_SWAP_DEFER_MS=250;static RESIDENT_SWAP_GATE_MS=5e3;residentSwap;static RELOAD_DEADLINE_MS=12e3;async fetchFreshCreds(){const creds=await this.credsSource();const id2=idFromCreds(creds);if(id2!==this.connId)throw new Error(`creds source returned identity ${id2}, expected ${this.connId} - renewal may not swap the connection's nkey`);const delay3=credsRenewalDelayMs(creds);_CotalEndpoint.assertRenewableGeneration(creds,this.currentCreds,delay3);this.currentCreds=creds;this.armCredsRefresh(delay3);const{iat,exp}=credsClaims(creds);return{iat,exp}}async swapConnectionOntoFreshCreds(){const nc=this.nc;if(!(nc&&!this.stopped))return;const overlap=this.overlapOnConnectionRenewal&&this.onConnection?await this.openRenewalOverlap().catch(()=>void 0):void 0;try{await nc.reconnect().catch(()=>{});if(overlap&&!nc.isClosed())await withDeadline(nc.flush(),1e4,()=>new Error("resident renewal flush did not finish")).catch(()=>{});if(this.nc===nc&&!this.stopped)this.armAuthExpiryReconnectFence(nc)}finally{if(overlap&&!overlap.isClosed())await this.closeWithoutLibraryReconnect(overlap).catch(()=>{})}}async openRenewalOverlap(){const overlap=await dialerFor(this.servers)({servers:this.servers,noAsyncTraces:true,name:`cotal:${this.card.name}:renewal`,inboxPrefix:`_INBOX_renew_${(0,import_node_crypto10.randomUUID)()}`,maxReconnectAttempts:0,...authOpts({token:this.token,user:this.user,pass:this.pass,creds:this.currentCreds!==void 0||this.credsSource?()=>this.presentCreds():void 0,bearer:this.userMode?()=>this.presentBearer():void 0,sentinelCreds:this.sentinelCreds,tls:this.tls})});this.ownedConnections.add(overlap);try{this.onConnection?.(overlap);await withDeadline(overlap.flush(),5e3,()=>new Error("renewal overlap flush did not finish"));return overlap}catch(error51){await this.closeWithoutLibraryReconnect(overlap).catch(()=>{});throw error51}}disableLibraryReconnect(nc){const protocol=nc.protocol;if(protocol?.options)protocol.options.reconnect=false}async closeWithoutLibraryReconnect(nc){if(!nc)return;this.disableLibraryReconnect(nc);await nc.close();if(!nc.isClosed())throw new Error("endpoint connection closure is unproved; consumer custody must be retained");this.ownedConnections.delete(nc)}armAuthExpiryReconnectFence(nc){clearTimeout(this.authExpiryReconnectTimer);this.authExpiryReconnectTimer=void 0;const credsExp=this.currentCreds&&credsClaims(this.currentCreds).exp;const expiryMs=this.userMode&&this.currentBearer?bearerExpiryMs(this.currentBearer):typeof credsExp==="number"?credsExp*1e3:void 0;if(expiryMs===void 0||this.stopped)return;const delay3=Math.max(0,expiryMs-Date.now()-500);this.authExpiryReconnectTimer=delay3>MAX_TIMER_MS3?setTimeout(()=>{if(this.nc===nc)this.armAuthExpiryReconnectFence(nc)},MAX_TIMER_MS3):setTimeout(()=>{if(this.nc===nc)this.disableLibraryReconnect(nc)},delay3);this.authExpiryReconnectTimer.unref?.()}async refreshCreds(initial=false){try{await this.fetchFreshCreds()}catch(e){if(initial)throw e;this.emitRecoverable(new Error(`creds refresh failed (${e instanceof Error?e.message:String(e)}) - retrying; this connection dies at its current JWT's expiry if renewal keeps failing`));this.armCredsRefresh(_CotalEndpoint.CREDS_RETRY_MS)}}credsTxn=Promise.resolve();runCredsTxn(fn){const next=this.credsTxn.then(fn,fn);this.credsTxn=next.then(()=>void 0,()=>void 0);return next}async adoptFreshCreds(opts={}){const deadline=opts.deadline??Date.now()+_CotalEndpoint.RELOAD_DEADLINE_MS;if(Date.now()>deadline)throw new Error("reloadCreds: the request deadline elapsed while queued behind another credential transaction; nothing adopted");const candidate2=await withDeadline(this.credsSource(),deadline-Date.now(),()=>new Error("reloadCreds: the creds source did not return before the daemon deadline; nothing adopted"));const id2=idFromCreds(candidate2);if(id2!==this.connId)throw new Error(`creds source returned identity ${id2}, expected ${this.connId} - renewal may not swap the connection's nkey`);if(opts.expected!==void 0&&credsFingerprint(candidate2)!==opts.expected)throw new Error("reloadCreds: re-read credential generation did not match the expected re-signed generation (a different store, or a torn/stale read); nothing adopted");const proven=_CotalEndpoint.presentableCreds(candidate2,{renewable:true});const probe=await probeConnect(this.servers,{creds:proven,tls:this.tls,timeoutMs:Math.max(500,Math.min(_CotalEndpoint.PREFLIGHT_MS,deadline-Date.now()))});if(!probe.ok)throw new Error(`reloadCreds: the broker did not accept the re-signed credential (${probe.reason}); nothing adopted`);if(Date.now()>deadline)throw new Error("reloadCreds: the proof exceeded the daemon deadline; nothing adopted");const delay3=credsRenewalDelayMs(candidate2);_CotalEndpoint.assertRenewableGeneration(candidate2,this.currentCreds,delay3);this.currentCreds=candidate2;this.armCredsRefresh(delay3);this.emit("creds-adopted",credsClaims(candidate2));return credsClaims(candidate2)}async renewCredsOnTimer(){const deadline=Date.now()+_CotalEndpoint.RELOAD_DEADLINE_MS;try{await this.runCredsTxn(()=>this.adoptFreshCreds({deadline}));await this.swapConnectionOntoFreshCreds()}catch(e){this.emitRecoverable(new Error(`creds refresh failed (${e instanceof Error?e.message:String(e)}) - retrying; this connection dies at its current JWT's expiry if renewal keeps failing`));this.armCredsRefresh(_CotalEndpoint.CREDS_RETRY_MS)}}async refreshCredsRequestSafe(){if(!this.credsSource)throw new Error("credential refresh requires a creds source");const nc=this.nc;if(!nc||this.stopped)throw new Error("credential refresh requires a running endpoint");const deadline=Date.now()+_CotalEndpoint.RELOAD_DEADLINE_MS;await this.runCredsTxn(async()=>{await this.adoptFreshCreds({deadline});if(this.nc!==nc||this.stopped)throw new Error("endpoint connection changed during credential refresh");await requestSafeReconnect(nc,()=>this.requestsAwaitingReply.get(nc)?.size??0);if(this.nc===nc&&!this.stopped)this.armAuthExpiryReconnectFence(nc)})}async reloadCreds(expected){if(!this.credsSource)throw new Error("reloadCreds: this endpoint has no creds source (a static cred cannot be renewed in place)");const deadline=Date.now()+_CotalEndpoint.RELOAD_DEADLINE_MS;const{iat,exp}=await this.runCredsTxn(()=>this.adoptFreshCreds({expected,deadline}));return{identity:this.connId,iat,exp}}scheduleResidentSwap(){if(this.stopped)return;const swap=new Promise(resolve=>{setTimeout(resolve,_CotalEndpoint.RESIDENT_SWAP_DEFER_MS).unref?.()}).then(async()=>{const back=this.transportBack(_CotalEndpoint.RESIDENT_SWAP_GATE_MS);await this.swapConnectionOntoFreshCreds();await back}).finally(()=>{if(this.residentSwap===swap)this.residentSwap=void 0});this.residentSwap=swap}transportBack(ms){return new Promise(resolve=>{const done=()=>{clearTimeout(timer);this.off("transport",seen);resolve()};const seen=state=>{if(state.connected)done()};const timer=setTimeout(done,ms);timer.unref?.();this.on("transport",seen)})}armCredsRefresh(delayMs){if(this.stopped)return;clearTimeout(this.credsTimer);this.credsTimer=delayMs>MAX_TIMER_MS3?setTimeout(()=>this.armCredsRefresh(delayMs-MAX_TIMER_MS3),MAX_TIMER_MS3):setTimeout(()=>void this.renewCredsOnTimer(),Math.max(1e3,delayMs));this.credsTimer.unref?.()}async connectAndBind(){try{await this.bindConnection()}catch(error51){await this.closeFailedBind();throw error51}}async bindConnection(){this.clearConnectionScoped();if(this.bearerSource){if(!this.currentBearer)await this.refreshBearer(true);else if(this.bearerRenewalFailures===0&&Date.now()>=bearerRenewalDeadlineMs(this.currentBearer,this.bearerAdoptedAtMs))await this.refreshBearer()}if(this.credsSource){const stale=!this.currentCreds||credsRenewalDelayMs(this.currentCreds)<=0;if(stale)await this.refreshCreds(!this.currentCreds)}if(this.userMode){try{this.bearerForWire();this.bearerRefusalSurfaced=false}catch(e){if(!this.bearerRefusalSurfaced){this.bearerRefusalSurfaced=true;throw e}throw new RepeatedRefusal(e.message)}}let watchDeletePermission;this.nc=await dialerFor(this.servers)({servers:this.servers,noAsyncTraces:true,name:this.userMode?this.connId:`cotal:${this.card.name}`,inboxPrefix:`_INBOX_${this.connId}`,...this.transportPingIntervalMs===void 0?{}:{pingInterval:this.transportPingIntervalMs},...this.transportMaxPingOut===void 0?{}:{maxPingOut:this.transportMaxPingOut},...this.transportConnectTimeoutMs===void 0?{}:{timeout:this.transportConnectTimeoutMs},...authOpts({token:this.token,user:this.user,pass:this.pass,creds:this.currentCreds!==void 0||this.credsSource?()=>this.presentCreds():void 0,bearer:this.userMode?()=>this.presentBearer():void 0,sentinelCreds:this.sentinelCreds,tls:this.tls,onCreds:creds=>{watchDeletePermission=void 0;try{const nats=credsClaims(creds).nats;if(nats?.pub!==void 0)watchDeletePermission=importNativeSubjectPermissions({pub:nats.pub}).publish}catch{}}})});this.watchDeletePermissions.set(this.nc,()=>watchDeletePermission);this.ownedConnections.add(this.nc);const owned=this.nc;void owned.closed().then(()=>this.ownedConnections.delete(owned));this.onConnection?.(this.nc);requireBrokerFloor(this.nc);this.armAuthExpiryReconnectFence(this.nc);this.watchStatus();this.js=(0,import_jetstream13.jetstream)(this.nc);if(this.dmOnly){await this.beforeBind?.();if(this.stopped)return;await this.bindDmOnly(this.dmOnly);if(this.stopped)return;this.emit("connection",{connected:true});return}if(this.acceptedToken!==void 0){const ref=await readAcceptedRow(this.nc,this.space,this.acceptedToken);const uid2=this.requireLifecycleUid("an issued endpoint");if(ref.owner!==this.owner||ref.actor!==this.actor||ref.uid!==uid2)throw new Error(`the accepted row names ${ref.owner}.${ref.actor} (uid ${ref.uid}), not this endpoint ${this.owner}.${this.actor} (uid ${uid2}); refusing to ride a foreign issuance (SPEC 13.15)`);this.issuedGeneration=ref.generation}await this.beforeBind?.();if(this.stopped)return;if(this.doWatch||this.doRegister){const kvm=new import_kv7.Kvm(this.nc);this.kv=this.authed?await kvm.open(presenceBucket(this.space)):await kvm.create(presenceBucket(this.space),{ttl:this.ttlMs,storage:PRESENCE_STORAGE})}if(this.doWatch&&this.readOnce)await this.readPresenceOnce();else if(this.doWatch){await this.startPresenceWatch();this.sweepTimer=setInterval(()=>this.sweep(),Math.max(500,Math.floor(this.ttlMs/3)))}const watchChannels=this.doWatch&&this.doWatchChannels;if(watchChannels||this.doConsume){this.channelKv=await openChannelRegistry(this.nc,this.space,{create:!this.authed});if(watchChannels)await(this.readOnce?this.readChannelsOnce():this.startChannelWatch());else if(this.readsChannelsOnDemand)await this.readChannels()}if(this.leaseWatchIntent)await this.bindDeliveryLeaseWatch();if(this.authed&&(this.doConsume||this.doRegister))this.requireLifecycleUid(this.doConsume?"an authed consuming endpoint":"an authed presence-registering endpoint");if(this.doConsume){this.jsm=await(0,import_jetstream13.jetstreamManager)(this.nc);if(!this.authed)await this.ensureStreams();await this.startConsumers()}if(this.doRegister&&!this.doConsume&&this.authed&&this.card.kind==="agent"){const jsm=this.jsm??(this.jsm=await(0,import_jetstream13.jetstreamManager)(this.nc));const uid2=this.requireLifecycleUid("an authed presence-registering agent");try{await jsm.consumers.info(dmStream(this.space),dmDurable(this.owner,this.actor,uid2))}catch(e){throw new Error(`lifecycle proof failed for ${this.card.id} (uid ${uid2}): its dm_ durable is not present at the broker, so this incarnation's uid does not match its provisioned resources - refusing to publish presence (SPEC 13.1 fail-before-presence): ${e?.message??String(e)}`)}}if(this.doRegister){try{await this.publishPresence()}catch(e){const detail=e?.message??String(e);throw new Error(`presence registration failed for ${this.card.id}: the space's presence KV bucket "${presenceBucket(this.space)}" did not accept this endpoint's first write (${detail}). The bucket can be OPENED and WATCHED while refusing every write, so a healthy-looking connection does not rule this out; a broker whose store has latched refuses until it is restarted, and no client can clear it (#1356).`)}const phase=Date.now();let beat=0;const arm=()=>{const next=nextHeartbeat(phase,this.heartbeatMs,beat,Date.now());beat=next.beat;const handle=setTimeout(()=>{this.publishPresence().catch(e=>this.emitRecoverable(e));if(this.heartbeatTimer===handle)arm()},next.delayMs);this.heartbeatTimer=handle};arm()}await this.rearmMembershipWatches();await this.armPlane3();for(const plane of this.livenessResponders.keys())this.bindLiveness(plane);for(const tap of this.taps)this.bindTap(tap);if(this.stopped)return;this.emit("connection",{connected:true});if(this.nc){for(const follower of this.activeGoalFollowers){follower.reconnected(this.nc)}}}clearConnectionScoped(){if(this.authExpiryReconnectTimer){clearTimeout(this.authExpiryReconnectTimer);this.authExpiryReconnectTimer=void 0}if(this.heartbeatTimer){clearInterval(this.heartbeatTimer);this.heartbeatTimer=void 0}if(this.sweepTimer){clearInterval(this.sweepTimer);this.sweepTimer=void 0}for(const msgs of this.streamMsgs){try{msgs.stop()}catch{}}this.streamMsgs.length=0;this.presenceEpoch++;this.presenceRebind=void 0;if(this.presenceWatchIter)this.retireKvWatch(this.presenceWatchIter);this.presenceWatchIter=void 0;if(this.channelWatchIter)this.retireKvWatch(this.channelWatchIter);this.channelWatchIter=void 0;this.stopDeliveryLeaseWatch();for(const sub of this.chatSubs.values()){try{sub.unsubscribe()}catch{}}this.chatSubs.clear();this.chatSubDenied.clear();this.ownWatchDeletePrefixes.clear();this.roster.clear();this.presenceRead=void 0;this.presenceReadGeneration++;this.presenceReadApplied=this.presenceReadGeneration;this.clearPresenceWriteFailure();this.lastPresenceWatchAt=0;this.presenceRebindAt=0;this.presenceWatchEmpty=false;this.presenceSnapshotPopulated=false;this.emitPresenceViewIfChanged();this.channelConfigs.clear();this.channelDefaults={};this.channelRead=void 0;this.channelReadGeneration++;this.channelReadApplied=this.channelReadGeneration;for(const watch of this.membershipFeedWatches)watch.arm=watch.arm.catch(()=>{}).then(()=>this.disarmMembershipWatch(watch)).catch(err3=>{this.emit("error",err3)})}async closeFailedBind(){const failedNc=this.nc;if(failedNc)this.disableLibraryReconnect(failedNc);this.clearConnectionScoped();this.nc=void 0;this.js=void 0;this.jsm=void 0;this.kv=void 0;this.channelKv=void 0;this.membersKv=void 0;this.aclKv=void 0;this.membershipFeedKv=void 0;this.deliveryKv=void 0;this.managerLeaseKv=void 0;this.daemonRenewalLeaseRevision=void 0;if(this.deliveryServeSub){try{this.deliveryServeSub.unsubscribe()}catch{}this.deliveryServeSub=void 0}if(this.deliveryAdminServeSub){try{this.deliveryAdminServeSub.unsubscribe()}catch{}this.deliveryAdminServeSub=void 0}this.dropAnycastRequests();for(const sub of this.subs){try{sub.unsubscribe()}catch{}}this.subs.length=0;if(!failedNc)return;this.emit("transport",{connected:false});this.emit("connection",{connected:false});try{await failedNc.close();return}catch{}if(!failedNc.isClosed?.()){try{await drainAndClose(failedNc);return}catch{}}const proto=failedNc.protocol;const transport=proto?.transport;if(transport&&!transport.isClosed){try{await transport.close?.()}catch{}if(!transport.isClosed){try{transport.disconnect?.()}catch{}}}}async tearDownIfStopped(){if(!this.stopped)return false;const nc=this.nc;if(nc)this.disableLibraryReconnect(nc);this.clearConnectionScoped();await this.closeWithoutLibraryReconnect(nc);this.nc=void 0;return true}superviseConnection(){const nc=this.nc;if(!nc)return;void nc.closed().then(err3=>{if(this.stopped)return;if(this.nc!==nc)return;this.emit("connection",{connected:false});this.emit("error",new Error(`mesh connection closed${err3?`: ${err3.message||err3.name}`:""} - re-establishing`));void this.reestablishLoop()})}rebuild(){if(this.rebuildPromise)return this.rebuildPromise;const p=this.doRebuild().finally(()=>{if(this.rebuildPromise===p)this.rebuildPromise=void 0});this.rebuildPromise=p;return p}async doRebuild(){const oldNc=this.nc;if(oldNc)this.disableLibraryReconnect(oldNc);this.reconnecting=true;try{this.clearConnectionScoped();if(oldNc&&!oldNc.isClosed())await Promise.all([...[...this.membershipFeedWatches].map(watch=>watch.arm),this.settleDeliveryLeaseWatches(),this.settleKvWatches()]);this.nc=void 0;this.js=void 0;this.jsm=void 0;this.kv=void 0;this.channelKv=void 0;this.membersKv=void 0;this.aclKv=void 0;this.membershipFeedKv=void 0;this.deliveryKv=void 0;this.managerLeaseKv=void 0;this.daemonRenewalLeaseRevision=void 0;this.emit("transport",{connected:false});this.emit("connection",{connected:false});await this.closeWithoutLibraryReconnect(oldNc);if(this.stopped)return;try{await this.connectAndBind()}catch(error51){if(!this.stopped)throw error51}if(await this.tearDownIfStopped())return;this.superviseConnection()}finally{this.reconnecting=false}}static RETRY_BACKOFF_CAP_MS=6e4;nextRetryDelayMs(){const delay3=Math.min(this.retryMs*2**this.retryAttempt,_CotalEndpoint.RETRY_BACKOFF_CAP_MS);this.retryAttempt++;return Math.round(delay3/2+Math.random()*(delay3/2))}async reestablishLoop(){if(this.reestablishing)return;this.reestablishing=true;try{while(!this.stopped){try{await this.rebuild();this.retryAttempt=0;return}catch(e){const delay3=this.nextRetryDelayMs();if(!this.stopped&&!(e instanceof RepeatedRefusal))this.emitRecoverable(this.userMode&&isAuthRejection(e)?new Error(`the broker refused this endpoint's bearer for ${this.owner}.${this.actor} - retrying in ${Math.ceil(delay3/1e3)}s; the space's auth service logs why`,{cause:e}):e);if(this.stopped)return;await new Promise(resolve=>{this.backoffResolve=resolve;this.backoffTimer=setTimeout(resolve,delay3)})}}}finally{this.reestablishing=false}}kickBackoff(){this.backoffResolve?.();if(this.backoffTimer){clearTimeout(this.backoffTimer);this.backoffTimer=void 0}}async reconnect(){if(this.stopped)throw new Error("endpoint stopped - cannot reconnect");this.kickBackoff();try{await this.rebuild()}catch(e){void this.reestablishLoop();throw e}}stop(){return this.stopPromise??=this.stopOnce()}async stopOnce(){if(this.nc)this.disableLibraryReconnect(this.nc);this.stopped=true;for(const follower of this.activeGoalFollowers){follower.cancel()}this.activeGoalFollowers.clear();this.presenceEpoch++;this.presenceRebind=void 0;this.kickBackoff();if(this.heartbeatTimer)clearInterval(this.heartbeatTimer);if(this.sweepTimer)clearInterval(this.sweepTimer);this.cancelBearerRenewal?.();if(this.credsTimer)clearTimeout(this.credsTimer);if(this.authExpiryReconnectTimer)clearTimeout(this.authExpiryReconnectTimer);for(const watch of this.membershipFeedWatches){watch.stopped=true;watch.arm=watch.arm.catch(()=>{}).then(async()=>{await this.disarmMembershipWatch(watch);await this.deleteRetainedMembershipConsumer(watch)})}await Promise.all([...this.membershipFeedWatches].map(watch=>watch.arm.catch(err3=>{if(this.nc&&!this.nc.isClosed())throw err3})));for(const watch of this.membershipFeedWatches){watch.resolveStop?.();watch.resolveStop=void 0;watch.rejectStop=void 0}this.membershipFeedWatches.clear();for(const msgs of this.streamMsgs){try{msgs.stop()}catch{}}if(this.presenceWatchIter)this.retireKvWatch(this.presenceWatchIter);this.presenceWatchIter=void 0;if(this.channelWatchIter)this.retireKvWatch(this.channelWatchIter);this.channelWatchIter=void 0;this.stopDeliveryLeaseWatch();try{if(this.doRegister){this.status="offline";await this.publishPresence()}}catch{}await Promise.all([this.settleDeliveryLeaseWatches(),this.settleKvWatches()]);let dmOnlyUnsettled=false;if(this.dmOnly&&this.dmOnlyInFlight){const settleMs=this.dmOnly.settleTimeoutMs??3e4;dmOnlyUnsettled=await withDeadline(this.dmOnlyInFlight.then(()=>false),settleMs,()=>new Error("unsettled")).catch(()=>true)}await this.closeWithoutLibraryReconnect(this.nc);this.clearPresenceWriteFailure();await this.rebuildPromise;await this.startPromise;if([...this.ownedConnections].some(nc=>!nc.isClosed()))throw new Error("endpoint stop could not prove its connection closed; local consumer custody must be retained");if(dmOnlyUnsettled)throw new Error(`endpoint stop closed the connection but the DM-only handler did not settle within ${this.dmOnly?.settleTimeoutMs??3e4}ms; its copy stays unacked and handler custody must be retained`)}async multicast(text2,opts){const channel=opts?.channel??this.channels.find(isConcreteChannel);if(channel===void 0)throw new Error("no default channel: this endpoint is not on any concrete channel, so there is nothing to broadcast to - name a channel explicitly, or join one first");if(!isConcreteChannel(channel))throw new Error(`cannot publish to wildcard channel "${channel}" - pick a concrete sub-channel`);const msg={id:(0,import_node_crypto10.randomUUID)(),ts:Date.now(),space:this.space,from:this.ref(),channel,mentions:normalizeMentions(opts?.mentions),parts:opts?.parts??[{kind:"text",text:text2}],replyTo:opts?.replyTo,contextId:opts?.contextId};await this.publishMsg(chatSubject(this.space,this.owner,this.actor,channel),msg);return msg}get maxPayload(){const max=this.nc?.info?.max_payload;if(typeof max!=="number"||!Number.isFinite(max)||max<=0)throw new Error(`${this.notLiveMsg()} - max_payload is only known while connected`);return max}async assertExpectationSemantics(){if(!this.jsm)throw new Error(this.notLiveMsg());const stream=chatStream(this.space);let replicas;try{replicas=(await this.jsm.streams.info(stream)).config.num_replicas}catch(e){throw new Error(`cannot verify expectation semantics: stream "${stream}" info unavailable (${e.message}). Serialized appends are refused rather than run on an unverified stream.`)}if(replicas!==1)throw new Error(`stream "${stream}" reports num_replicas=${String(replicas)}; serialized appends on THIS stream require 1 \u2014 a property of this one stream, not of the broker, so a clustered deployment is fine so long as this stream is R1, which a cluster can host. On a replicated stream the dedup cache is consulted before the subject expectation, so a retry returns a duplicate ack instead of a conflict and a lost message reads as success.`)}casEnvelope(opts){return{id:opts.id,ts:Date.now(),space:this.space,from:this.ref(),channel:opts.channel,mentions:normalizeMentions(opts.mentions),parts:opts.parts,replyTo:opts.replyTo,contextId:opts.contextId}}encodedSize(opts){if(!isConcreteChannel(opts.channel))throw new Error(`cannot publish to wildcard channel "${opts.channel}" - pick a concrete sub-channel`);assertIdToken(opts.id,"publish id");if(!Number.isSafeInteger(opts.expectedLastSubjectSeq)||opts.expectedLastSubjectSeq<0)throw new Error(`expectedLastSubjectSeq must be a non-negative safe integer, got ${JSON.stringify(opts.expectedLastSubjectSeq)}`);if(!Array.isArray(opts.parts)||opts.parts.length===0)throw new Error("encodedSize requires at least one part");const mh=(0,import_transport_node13.headers)();mh.set("Nats-Msg-Id",opts.id);mh.set("Nats-Expected-Last-Subject-Sequence",`${opts.expectedLastSubjectSeq}`);const headerBytes=mh.encode().length;return headerBytes+Buffer.byteLength(JSON.stringify(this.casEnvelope(opts)),"utf8")}async multicastExpecting(opts){if(!this.js)throw new Error(this.notLiveMsg());if(!isConcreteChannel(opts.channel))throw new Error(`cannot publish to wildcard channel "${opts.channel}" - pick a concrete sub-channel`);assertIdToken(opts.id,"publish id");const expected=opts.expectedLastSubjectSeq;if(!Number.isSafeInteger(expected)||expected<0)throw new Error(`expectedLastSubjectSeq must be a non-negative safe integer, got ${JSON.stringify(expected)}`);if(!Array.isArray(opts.parts)||opts.parts.length===0)throw new Error("multicastExpecting requires at least one part");const message=this.casEnvelope(opts);assertPartsSerializable(message.parts);const ack=await this.js.publish(chatSubject(this.space,this.owner,this.actor,opts.channel),JSON.stringify(message),{msgID:opts.id,expect:{lastSubjectSequence:expected}});return{message,ack:{seq:ack.seq,duplicate:ack.duplicate===true}}}async unicast(instanceId,text2,opts){const{msg}=await this.unicastAttributed(instanceId,text2,opts);return msg}async unicastAttributed(instanceId,text2,opts){if(!this.js)throw new Error(this.notLiveMsg());const msg={id:(0,import_node_crypto10.randomUUID)(),ts:Date.now(),space:this.space,from:this.ref(),to:instanceId,parts:opts?.parts??[{kind:"text",text:text2}],replyTo:opts?.replyTo,contextId:opts?.contextId};const recip=parsePrincipalKey(instanceId);if(!recip)throw new Error(`unicast: "${instanceId}" is not a valid recipient principal <owner>.<actor>`);assertPartsSerializable(msg.parts);const subject=unicastSubject(this.space,recip.owner,recip.actor,this.owner,this.actor);try{const ack=await this.js.publish(subject,JSON.stringify(msg),{msgID:msg.id});return{msg,ack:{seq:ack.seq,duplicate:ack.duplicate===true}}}catch(error51){if(error51 instanceof import_transport_node13.TimeoutError)throw new Error(`${error51.message} publishing to ${JSON.stringify(subject)}. The send outcome is unknown: the broker may have stored the message. Check before resending.`,{cause:error51});throw error51}}async anycast(service,text2,opts){const{msg}=await this.anycastAttributed(service,text2,opts);return msg}async anycastAttributed(service,text2,opts){if(!this.js)throw new Error(this.notLiveMsg());assertValidRole(service);const msg={id:(0,import_node_crypto10.randomUUID)(),ts:Date.now(),space:this.space,from:this.ref(),toService:service,parts:opts?.parts??[{kind:"text",text:text2}],replyTo:opts?.replyTo,contextId:opts?.contextId};assertPartsSerializable(msg.parts);const ack=await this.js.publish(anycastSubject(this.space,service,this.owner,this.actor),JSON.stringify(msg),{msgID:msg.id});return{msg,ack:{seq:ack.seq,duplicate:ack.duplicate===true}}}tap(handler,opts){const tap={handler,subject:opts?.subject??spaceWildcard(this.space)};this.taps.push(tap);this.bindTap(tap)}bindTap(tap){if(!this.nc)return;const sub=this.nc.subscribe(tap.subject);this.subs.push(sub);void(async()=>{for await(const m of sub){let decoded;try{decoded=m.json()}catch{decoded=void 0}const parsed=parseSubject(m.subject);if(decoded!==void 0&&(parsed?.kind==="chat"||parsed?.kind==="inst"||parsed?.kind==="svc")){if(!isFromSubjectSender(decoded,parsed))continue;decoded=authenticatedMessage(decoded,parsed)}tap.handler(m.subject,decoded)}})().catch(e=>this.emit("error",e))}serveControl(service,handler,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());const sub=this.nc.subscribe(controlServiceSubject(this.space,service,"*","*"),{queue:service});this.subs.push(sub);const inOwnTime=opts.concurrent;let inOrder=Promise.resolve();void(async()=>{for await(const m of sub){if(opts.boundReply&&(!m.reply||!m.reply.startsWith(`${m.subject}.reply.`))){this.emit("error",new Error(`rejected ${service} request on ${m.subject}: reply target "${m.reply??"(none)"}" is not under the sender's own reply subtree`));continue}const answer=()=>this.answerControl(service,handler,m);if(inOwnTime===void 0){await answer();continue}let own=false;try{own=inOwnTime(m.json())}catch{}if(own)void answer().catch(e=>this.emit("error",e));else inOrder=inOrder.then(answer).catch(e=>{this.emit("error",e)})}})().catch(e=>{if(!this.reportSubscriptionDenial(e))this.emit("error",e)});return sub}async answerControl(service,handler,m){let body;try{let reply;const req=m.json();const parsed=parseSubject(m.subject);if(!parsed||!isFromSubjectSender(req,parsed)){this.emit("error",new Error(`rejected control request on ${m.subject}: from ${req.from?.id??"(none)"} does not match subject sender ${parsed?.sender??"(unparseable)"}`));reply={ok:false,error:"sender mismatch - request rejected"}}else{reply=await handler(req)}body=JSON.stringify(reply)}catch(e){body=JSON.stringify({ok:false,error:e.message})}try{m.respond(body)}catch(e){const refused={ok:false,error:`the ${service} reply is ${Buffer.byteLength(body)} bytes and was not published: ${e.message}`};try{m.respond(JSON.stringify(refused))}catch(err3){this.emit("error",new Error(`could not answer ${service} request on ${m.subject}: ${refused.error}, and the refusal failed too: ${err3.message}`))}}}async requestBoundReply(nc,subject,body,reply,timeoutMs){let pending=this.requestsAwaitingReply.get(nc);if(!pending){const waiting=new Set;this.requestsAwaitingReply.set(nc,waiting);void nc.closed().then(error51=>{this.requestsAwaitingReply.delete(nc);const failure=error51??new import_transport_node13.ClosedConnectionError;for(const reject of waiting)reject(failure);waiting.clear()});pending=waiting}let rejectClosed;const closed3=new Promise((_resolve,reject)=>{rejectClosed=reject;pending.add(reject)});try{return await Promise.race([nc.request(subject,body,{timeout:timeoutMs,noMux:true,reply}),closed3])}finally{pending.delete(rejectClosed)}}async requestControl(service,req,timeoutMs=5e3){if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=controlServiceSubject(this.space,service,this.owner,this.actor);const reply=`${reqSubject}.reply.${(0,import_node_crypto10.randomUUID)()}`;const body={...req,from:req.from??this.ref()};const m=await this.requestBoundReply(this.nc,reqSubject,JSON.stringify(body),reply,timeoutMs);return m.json()}serviceRailCaller(){return this.serviceCaller()}serviceCaller(){const triple={owner:this.owner,actor:this.actor,uid:this.requireLifecycleUid("invokeService")};if(this.acceptedToken===void 0)return triple;if(this.issuedGeneration===void 0)throw new Error("invokeService: the issued generation is not yet discovered on this connection");return{...triple,generation:this.issuedGeneration}}async followServiceGoal(endpoint,submit,deadlineMs=1e4,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());if(this.stopped)throw new Error("endpoint stopped - cannot follow goal");const abortController=new AbortController;const onAbort=()=>abortController.abort();if(opts.signal?.aborted)onAbort();else opts.signal?.addEventListener("abort",onAbort,{once:true});let reconnectHandler;const entry={cancel:()=>abortController.abort(),reconnected:nc=>reconnectHandler?.(nc)};this.activeGoalFollowers.add(entry);try{const reconcile=opts.reconcile??(async(goalId,_attributed,context)=>{const current=this.serviceCaller();if(current.owner!==context.caller.owner||current.actor!==context.caller.actor||current.uid!==context.caller.uid)throw new Error("the renewed goal reader no longer has the accepting caller's full identity");const q=await this.invokeService(endpoint,"goal-result",{goalId},{deadlineMs:Math.min(deadlineMs,context.deadlineMs),signal:context.signal});if(q.reply.ok!==true)throw new Error(q.reply.error.message);return q.reply.data});return await submitAndFollowGoal(this.nc,this.space,endpoint,this.serviceCaller(),deadlineMs,submit,{reconcile,currentNc:()=>this.nc,onReconnect:cb=>{reconnectHandler=cb;return()=>{reconnectHandler=void 0}},signal:abortController.signal,prepare:opts.prepare})}finally{opts.signal?.removeEventListener("abort",onAbort);this.activeGoalFollowers.delete(entry)}}clearResolvedService(endpoint){this.resolvedServices.delete(endpoint);this.resolvedCommandServices.delete(endpoint)}beginServiceInvocation(nc){let pending=this.serviceInvocations.get(nc);if(!pending){pending=new Set;this.serviceInvocations.set(nc,pending)}let settle;const request=new Promise(resolve=>{settle=resolve});pending.add(request);return()=>{pending.delete(request);settle()}}async waitServiceRecovery(recovery,deadline,signal,timeout){let onAbort;const cancelled=new Promise((_,reject)=>{onAbort=()=>reject(signal?.reason);if(signal?.aborted)onAbort();else signal?.addEventListener("abort",onAbort,{once:true})});try{await withDeadline(Promise.race([recovery,cancelled]),deadline-Date.now(),timeout)}finally{if(onAbort)signal?.removeEventListener("abort",onAbort)}signal?.throwIfAborted();if(deadline<=Date.now())throw timeout()}async describeService(endpoint,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());if(opts.refresh)this.clearResolvedService(endpoint);const cached2=opts.instanceId===void 0?this.resolvedServices.get(endpoint):void 0;if(cached2)return cached2;const svc=await resolveService(this.nc,this.space,endpoint,this.serviceCaller(),{deadlineMs:opts.deadlineMs??1e4,signal:opts.signal,...opts.instanceId!==void 0?{instanceId:opts.instanceId}:{}});if(opts.instanceId===void 0)this.resolvedServices.set(endpoint,svc);return svc}async listingCaller(){if(!this.nc)throw new Error(this.notLiveMsg());return registryListingCaller(this.nc,this.space,this.serviceCaller(),{connId:this.connId,...this.presentedExp!==void 0?{exp:this.presentedExp}:{}})}async listEndpoints(input,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());const nc=this.nc;const listing=this.authed?await this.listingCaller():void 0;if(this.authed&&listing===void 0)return{unbound:true};return this.listEndpointsOver(nc,listing,input,opts)}async listEndpointsOver(nc,listing,input,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());const own=this.nc;const result=await listRegistryEndpoints(this.space,(deadlineMs,signal)=>resolveService(own,this.space,REGISTRY_ENDPOINT,this.serviceCaller(),{deadlineMs,signal,commands:[REGISTRY_ENDPOINTS_COMMAND]}),{nc,...listing?{caller:listing}:{}},input,opts);if(result.unbound)return result;for(const row of result.page?.rows??[])this.clearResolvedService(row.endpoint);return result}async invokeService(endpoint,command,args,opts={}){const deadline=Date.now()+(opts.deadlineMs??1e4);const rebuilding=this.rebuildPromise;if(rebuilding){await this.waitServiceRecovery(rebuilding,deadline,opts.signal,()=>new EpEnvelopeError("deadline-exceeded","the invocation deadline elapsed waiting for connection recovery",void 0,"not-executed"));opts={...opts,deadlineMs:deadline-Date.now()}}const nc=this.nc;if(!nc)throw new Error(this.notLiveMsg());try{return await this.invokeServiceOnce(endpoint,command,args,opts,rebuilding?deadline:void 0)}catch(e){if(!(e instanceof EpEnvelopeError)||e.code!=="permission-denied"||e.outcome!=="not-executed"||deadline<=Date.now())throw e;opts.signal?.throwIfAborted();const recovery=(async()=>{for(;;){opts.signal?.throwIfAborted();if(deadline<=Date.now())throw e;const pending=this.serviceInvocations.get(nc);if(!pending?.size)break;await Promise.allSettled([...pending])}if(this.nc===nc)await this.reconnect();else await this.rebuildPromise})();await this.waitServiceRecovery(recovery,deadline,opts.signal,()=>e);this.clearResolvedService(endpoint);return this.invokeServiceOnce(endpoint,command,args,{...opts,deadlineMs:deadline-Date.now()},deadline)}}async invokeServiceOnce(endpoint,command,args,opts={},retryDeadline){if(!this.nc)throw new Error(this.notLiveMsg());const nc=this.nc;const caller=this.serviceCaller();const resolve=async(signal=opts.signal,deadlineMs=opts.deadlineMs??1e4)=>{signal?.throwIfAborted();if(retryDeadline!==void 0)deadlineMs=Math.min(deadlineMs,retryDeadline-Date.now());if(deadlineMs<=0)throw new EpEnvelopeError("deadline-exceeded","the invocation deadline elapsed before resolve",void 0,"not-executed");const needed=opts.follow?[command,"goal-result"]:[command];const classSelected=opts.instanceId===void 0&&opts.classInstanceId===void 0;const full=classSelected?this.resolvedServices.get(endpoint):void 0;if(full&&needed.every(name=>full.commands.has(name)))return full;const cacheKey=[...needed].sort().join("\0");const commandCache=classSelected?this.resolvedCommandServices.get(endpoint):void 0;const cached2=commandCache?.get(cacheKey);if(cached2)return cached2;const svc=await resolveService(nc,this.space,endpoint,caller,{deadlineMs,signal,commands:needed,...opts.follow&&command!=="goal-result"?{optionalCommands:["goal-result"]}:{},...opts.instanceId!==void 0?{instanceId:opts.instanceId}:{},...opts.classInstanceId!==void 0?{classInstanceId:opts.classInstanceId}:{}});if(classSelected){let byCommand=this.resolvedCommandServices.get(endpoint);if(!byCommand){byCommand=new Map;this.resolvedCommandServices.set(endpoint,byCommand)}byCommand.set(cacheKey,svc)}return svc};const invokeOpts={...opts.target?{target:opts.target}:{},...opts.deadlineMs!==void 0?{deadlineMs:opts.deadlineMs}:{}};const invokeResolved=(service,signal)=>{signal?.throwIfAborted();const unfollowable=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable)return Promise.resolve(unfollowable);const deadlineMs=retryDeadline===void 0?invokeOpts.deadlineMs:retryDeadline-Date.now();if(deadlineMs!==void 0&&deadlineMs<=0)throw new EpEnvelopeError("deadline-exceeded","the invocation deadline elapsed before publish",void 0,"not-executed");return invokeCommand(nc,this.space,service,command,args,{...invokeOpts,deadlineMs,signal})};const resolveFirst=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{try{return await resolve(signal,deadline-Date.now())}catch(e){if(!(e instanceof EpEnvelopeError)||e.code!=="failed-precondition")throw e;const left=deadline-Date.now();if(left<=0)throw e;return await resolve(signal,left)}};const doInvoke=async(service,signal=opts.signal)=>{signal?.throwIfAborted();try{let r=await invokeResolved(service,signal);const unmappedHere=x=>opts.instanceId===void 0&&replyTargetUnmapped(x.reply.error);let unmapped=unmappedHere(r)?r:void 0;for(let reissues=0;reissues<BIND_SPLIT_REISSUES&&r.reply.ok===false&&(replyRefusedBeforeEffect(r.reply.error)||unmappedHere(r));reissues++){this.splitsRecovered++;this.emit("split-recovered",{endpoint,command,servedBy:r.responder,splitsRecovered:this.splitsRecovered,boundTo:(r.reply.error.details??[]).find(d=>d.kind===EP_BIND_REFUSED)?.boundTo});this.clearResolvedService(endpoint);const raw=r.reply.error.code;const refusalCode=raw==="expired"?"expired":raw==="failed-precondition"?"failed-precondition":void 0;if(refusalCode===void 0)throw new EpEnvelopeError("internal",`${endpoint}.${command} came back marked as refused before it ran, but with code ${String(raw)}; the fence produces only failed-precondition or expired (SPEC 13.2)`,r.reply.error.details);let reissueTarget;try{reissueTarget=await resolve(signal);const unfollowable=opts.follow?goalFollowRefusal(reissueTarget):void 0;if(unfollowable)throw new Error(unfollowable.reply.error.message)}catch(reissue){throw new EpEnvelopeError(refusalCode,`${endpoint}.${command} WAS NOT RUN - the incarnation that received it refused it before any effect, and the re-issue could not be resolved: ${reissue instanceof Error?reissue.message:String(reissue)}. Re-resolve and re-issue when the endpoint is reachable (SPEC 13.2)`,r.reply.error.details,"not-executed")}r=await invokeResolved(reissueTarget,signal);if(unmappedHere(r))unmapped=r}return replyRefusedBeforeEffect(r.reply.error)?unmapped??r:r}catch(e){if(respondedButUnbound(e)){this.clearResolvedService(endpoint);if(!isRepeatSafeCommand(endpoint,command))throw e;return await invokeResolved(await resolve(signal),signal)}throw e}};const release=this.beginServiceInvocation(nc);try{if(!opts.follow)return await doInvoke(await resolveFirst());let service;return await this.followServiceGoal(endpoint,async signal=>{try{return await doInvoke(service,signal)}finally{release()}},opts.deadlineMs??1e4,{signal:opts.signal,prepare:async(signal,deadline)=>{service=await resolveFirst(signal,deadline)}})}finally{release()}}async requestDelivery(op,args,timeoutMs=5e3){if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=controlServiceSubject(this.space,CONTROL_DELIVERY,this.owner,this.actor);const reply=`${reqSubject}.reply.${(0,import_node_crypto10.randomUUID)()}`;const body={op,args,from:this.ref()};const m=await this.requestBoundReply(this.nc,reqSubject,JSON.stringify(body),reply,timeoutMs);return m.json()}async requestDeliveryAdmin(op,args,timeoutMs=5e3){if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=controlServiceSubject(this.space,CONTROL_DELIVERY_ADMIN,this.owner,this.actor);const reply=`${reqSubject}.reply.${(0,import_node_crypto10.randomUUID)()}`;const body={op,args,from:this.ref()};const m=await this.requestBoundReply(this.nc,reqSubject,JSON.stringify(body),reply,timeoutMs);return m.json()}getRoster(){return[...this.roster.values()].sort((a,b)=>a.card.name.localeCompare(b.card.name))}async readPresence(){if(this.doWatch&&!this.readOnce)throw new Error("readPresence is for an endpoint that does not watch presence; this one keeps its roster live (getRoster)");const kv=this.kv;if(!kv)throw new Error(this.nc?"readPresence needs the presence bucket open (registerPresence or watchPresence)":this.notLiveMsg());if(this.presenceRead)return this.presenceRead;const generation=++this.presenceReadGeneration;const roster=(async()=>{let entries;try{entries=await lastKvEntries(kv)}catch(e){if(!isPublishPermissionDenied(e))throw e;throw new Error(`presence read refused for ${this.card.id}: this credential may not publish $JS.API.DIRECT.GET.KV_${presenceBucket(this.space)}, the on-demand roster read (SPEC Appendix B). A credential minted by an older issuer can lack this grant even when newly minted; upgrade the manager or auth service that issues credentials, then mint a new credential. Reusing credentials or reconnecting does not add the grant.`,{cause:e})}const at=Date.now();const read=new Map;for(const e of entries){if(e.key===TTL_RECONCILE_CANARY_KEY||e.operation==="DEL"||e.operation==="PURGE")continue;const p=this.decodePresence(e);if(p)read.set(e.key,p.status==="offline"||at-p.ts>this.ttlMs?this.toOffline(p):p)}if(generation>this.presenceReadApplied){this.presenceReadApplied=generation;for(const[id2,p]of this.roster)if(!read.has(id2))read.set(id2,p.status==="offline"?p:this.toOffline(p));this.roster.clear();for(const[id2,p]of read)this.roster.set(id2,p)}return this.getRoster()})();this.presenceRead=roster;const settled=()=>{if(this.presenceRead===roster)this.presenceRead=void 0};roster.then(settled,settled);return roster}presenceView(){if(!this.doWatch)return{state:"current",fresh:true};if(!this.presenceSnapshotPopulated)return{state:"unpopulated",fresh:false};if(this.presenceWatchEmpty)return{state:"current",fresh:true};const staleSince=this.lastPresenceWatchAt+this.ttlMs;if(Date.now()<staleSince)return{state:"current",fresh:true};return{state:"stale",fresh:false,staleSince}}async waitForPresenceSnapshot(timeoutMs=1e3){let timer;try{return await Promise.race([this.presenceSnapshot.then(()=>"snapshot"),new Promise(resolve=>{timer=setTimeout(()=>resolve("timeout"),timeoutMs)})])}finally{if(timer)clearTimeout(timer)}}assertPresenceUpdate(update){assertPresenceRow({card:this.card,status:this.status,activity:this.activity,condition:this.condition,attention:this.attentionMode,ts:Date.now(),...update},this.card.id)}async setActivity(activity){this.assertPresenceUpdate({activity});if(activity!==this.activity)this.statusSince=this.activitySince=Date.now();this.activity=activity;await this.publishPresence()}async setStatus(status2,activity){this.assertPresenceUpdate({status:status2,...activity===void 0?{}:{activity}});if(activity!==void 0&&activity!==this.activity)this.statusSince=this.activitySince=Date.now();if(activity!==void 0)this.activity=activity;if(status2!==this.status)this.statusSince=Date.now();this.status=status2;await this.publishPresence()}noteActivity(at=Date.now()){if(Number.isFinite(at)&&at>(this.activeAt??0))this.activeAt=at}async setCondition(condition){this.assertPresenceUpdate({condition:condition??void 0});this.condition=condition??void 0;this.conditionRevision++;await this.publishPresence()}async setAttention(attention){this.assertPresenceUpdate({attention});this.attentionMode=attention;await this.publishPresence()}async setChannelModes(modes){this.channelModes=Object.keys(modes).length?modes:void 0;await this.publishPresence()}async setCardModel(model,variant,provider){const m=model.trim();const v=variant?.trim();const p=provider?.trim();if(!m||this.card.meta?.model===m&&this.card.meta.variant===v&&(p===void 0||this.card.meta?.provider===p))return;const meta3={...this.card.meta??{},model:m};if(v)meta3.variant=v;else delete meta3.variant;if(p)meta3.provider=p;this.card.meta=meta3;await this.publishPresence()}async setCardCwd(cwd){if(!cwd||this.card.meta?.cwd===cwd)return;this.card.meta={...this.card.meta??{},cwd};await this.publishPresence()}get readsChannelsOnDemand(){return this.doConsume&&this.doWatchChannels&&!this.doWatch}async readChannels(){if(!this.readsChannelsOnDemand)throw new Error("readChannels is for a consumer that reads presence on demand; this endpoint watches the channel registry or keeps no cache of it");const kv=this.channelKv;if(!kv)throw new Error(this.notLiveMsg());if(this.channelRead)return this.channelRead;const generation=++this.channelReadGeneration;const read=(async()=>{let entries;try{entries=await lastKvEntries(kv)}catch(e){if(!isPublishPermissionDenied(e))throw e;throw new Error(`channel registry read refused for ${this.card.id}: this credential may not publish $JS.API.DIRECT.GET.KV_${channelBucket(this.space)}, the on-demand registry read (SPEC Appendix B). A credential minted by an older issuer can lack this grant even when newly minted; upgrade the manager or auth service that issues credentials, then mint a new credential. Reusing credentials or reconnecting does not add the grant.`,{cause:e})}if(generation<=this.channelReadApplied)return;this.channelReadApplied=generation;this.channelConfigs.clear();this.channelDefaults={};for(const e of entries)this.handleChannelEntry(e)})();this.channelRead=read;const settled=()=>{if(this.channelRead===read)this.channelRead=void 0};read.then(settled,settled);return read}getChannelConfig(channel){return this.channelConfigs.get(channel)}channelReplay(channel){return effectiveReplay(this.channelConfigs.get(channel),this.channelDefaults)}channelReplayWindow(channel){return this.channelConfigs.get(channel)?.replayWindow??this.channelDefaults.replayWindow}async channelReplayPolicy(channel){if(!this.nc)throw new Error(this.notLiveMsg());const kv=this.channelKv??await openChannelRegistry(this.nc,this.space,{create:false});let cfg;let defaults;try{[cfg,defaults]=await Promise.all([isConcreteChannel(channel)?readChannelConfig(kv,channel):Promise.resolve(void 0),readChannelDefaults(kv)])}catch(e){if(!isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.StreamNotFound))throw e}return{replay:effectiveReplay(cfg,defaults),window:cfg?.replayWindow??defaults?.replayWindow??null,registered:cfg!==void 0}}channelDeliveryClass(channel){return effectiveDeliveryClass(this.channelConfigs.get(channel),this.channelDefaults)}joinedChannels(){return[...this.channels]}async joinChannel(channel){if(!this.jsm)throw new Error(this.notLiveMsg());if(this.channels.includes(channel))return{joined:false,backfilled:0,durable:this.plane3Channels.has(channel)};if(this.readsChannelsOnDemand)await this.readChannels();const armed2=await this.armJoin([channel]);this.subscribeChat(channel);try{await this.confirmChatSub()}catch(e){this.unsubscribeChat(channel);throw new Error(`cannot join "${channel}": live subscription could not be confirmed (${e.message})`)}if(this.chatSubDenied.has(channel)){this.unsubscribeChat(channel);throw new Error(`cannot join "${channel}": not within this agent's read ACL (allowSubscribe)`)}this.channels.push(channel);let durable=false;let reason2;const family=isChannelFamily(channel);if(!family&&!isConcreteChannel(channel))reason2="a pattern with * or the root > has no stored copies; follow a concrete channel or a family such as review.>";else if(family||effectiveDeliveryClass(this.channelConfigs.get(channel),this.channelDefaults)==="durable"){try{const r=await this.durableJoinChannel(channel);if(r.durable){this.plane3Channels.set(channel,r.generation??0);durable=true}else{reason2=r.reason??"durable backstop unavailable"}}catch(e){reason2=`durable backstop unavailable (${e.message})`}}const backfilled=await this.backfillArmed(armed2);return{joined:true,backfilled,durable,...reason2!==void 0?{reason:reason2}:{}}}async leaveChannel(channel){if(!this.jsm)throw new Error(this.notLiveMsg());if(!this.channels.includes(channel))return{left:false};if(this.readsChannelsOnDemand)await this.readChannels();if(this.authed&&(isChannelFamily(channel)||effectiveDeliveryClass(this.channelConfigs.get(channel),this.channelDefaults)==="durable")){let generation=this.plane3Channels.get(channel);if(generation===void 0)generation=(await this.fetchMemberships())?.find(m=>m.channel===channel)?.generation;if(generation!==void 0){await this.durableLeaveChannel(channel,generation);this.plane3Channels.delete(channel)}}this.unsubscribeChat(channel);const i=this.channels.indexOf(channel);if(i>=0)this.channels.splice(i,1);return{left:true}}async chatRetention(){if(!this.nc)throw new Error(this.notLiveMsg());const mgr=await(0,import_jetstream13.jetstreamManager)(this.nc);let info;try{info=await mgr.streams.info(chatStream(this.space),{subjects_filter:">"})}catch(e){if(!isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.StreamNotFound))throw e;return{perSender:null,maxAgeMs:null,oldestAt:null,senders:[],stream:false,lastSeq:0}}const senders=[];for(const[subject,messages]of Object.entries(info.state.subjects??{})){const p=parseSubject(subject);if(p?.kind==="chat"&&isPrincipalOwnerToken(p.owner))senders.push({channel:p.rest,sender:p.sender,messages})}const cap=info.config.max_msgs_per_subject;const age=info.config.max_age;return{perSender:typeof cap==="number"&&cap>0?cap:null,maxAgeMs:typeof age==="number"&&age>0?Math.round(age/1e6):null,oldestAt:info.state.messages>0?info.state.first_ts:null,senders:senders.sort((a,b)=>a.channel.localeCompare(b.channel)||a.sender.localeCompare(b.sender)),stream:true,lastSeq:info.state.last_seq}}async listChannels(){if(!this.nc)throw new Error(this.notLiveMsg());if(this.readsChannelsOnDemand)await this.readChannels();const mgr=await(0,import_jetstream13.jetstreamManager)(this.nc);const counts=new Map;try{const info=await mgr.streams.info(chatStream(this.space),{subjects_filter:">"});if(info.state.subjects){for(const[subject,count]of Object.entries(info.state.subjects)){const p=parseSubject(subject);if(p?.kind==="chat"&&isPrincipalOwnerToken(p.owner))counts.set(p.rest,(counts.get(p.rest)??0)+count)}}}catch(e){if(!isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.StreamNotFound))throw e}const channels=new Set([...counts.keys(),...this.channelConfigs.keys()]);return[...channels].map(channel=>({channel,messages:counts.get(channel)??0,config:this.channelConfigs.get(channel)})).sort((a,b)=>a.channel.localeCompare(b.channel))}async channelMembers(channel){const members=(await listMembers(await this.membersRegistry())).filter(r=>r.leaveCursor===void 0&&r.activated===true);const byId=new Map;for(const p of this.roster.values())byId.set(p.card.id,p);const memberForId=id2=>{const p=byId.get(id2);return p?{id:p.card.id,name:p.card.name,role:p.card.role,live:p.status!=="offline"}:{id:id2,name:id2,live:false}};const byName=(a,b)=>a.name.localeCompare(b.name);if(channel!==void 0){const stored=await this.deliveryClassFresh(channel)==="durable";const ids=new Set(members.filter(r=>r.channel===channel||stored&&isChannelFamily(r.channel)&&subjectMatches(r.channel,channel)).map(r=>r.owner));return[...ids].map(memberForId).sort(byName)}const map2=new Map;for(const r of members){const arr=map2.get(r.channel);const m=memberForId(r.owner);if(arr){if(!arr.some(x=>x.id===m.id))arr.push(m)}else{map2.set(r.channel,[m])}}for(const arr of map2.values())arr.sort(byName);return map2}async membershipFeedRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.membershipFeedKv??=await new import_kv7.Kvm(this.nc).open(membershipBucket(this.space));return this.membershipFeedKv}async readMembership(){const kv=await this.membershipFeedRegistry();const members=[];let asOf;let entries;try{entries=await lastKvEntries(kv)}catch(e){if(!isPublishPermissionDenied(e))throw e;throw new Error(`membership read refused for ${this.card.id}: this credential may not publish $JS.API.DIRECT.GET.KV_${membershipBucket(this.space)}, the membership feed read (SPEC Appendix B). A credential minted by an older issuer can lack this grant even when newly minted; upgrade the manager or auth service that issues credentials, then mint a new credential. Reusing credentials or reconnecting does not add the grant.`,{cause:e})}for(const e of entries){if(e.key===MEMBERSHIP_FEED_KEY){try{asOf=e.json().observedAt}catch{}continue}try{const rec=e.json();members.push({id:e.key,live:rec.live??[],durable:rec.durable??[],observedAt:rec.observedAt})}catch{}}return{asOf,members}}async watchMembership(onChange,onClosed){if(this.stopped)throw new Error("endpoint stopped - cannot watch membership");const watch={onChange,onClosed,stopped:false,arm:Promise.resolve()};this.membershipFeedWatches.add(watch);watch.arm=watch.arm.catch(()=>{}).then(()=>this.armMembershipWatch(watch));try{await watch.arm}catch(err3){watch.stopped=true;this.membershipFeedWatches.delete(watch);await this.disarmMembershipWatch(watch);throw err3}return{stop:async()=>{if(watch.stopPromise)return watch.stopPromise;watch.stopped=true;watch.stopPromise=new Promise((resolve,reject)=>{watch.resolveStop=resolve;watch.rejectStop=reject});watch.arm=watch.arm.catch(()=>{}).then(async()=>{await this.disarmMembershipWatch(watch);await this.deleteRetainedMembershipConsumer(watch);this.finishMembershipWatchStop(watch)}).catch(err3=>{watch.rejectStop?.(err3)});return watch.stopPromise}}}async armMembershipWatch(watch){if(watch.stopped)return;const kv=await this.membershipFeedRegistry();await this.deleteRetainedMembershipConsumer(watch);if(!(kv instanceof import_internal2.Bucket))throw new Error("membership watch needs the @nats-io/kv Bucket implementation");const cc=kv._buildCC(">",import_internal2.KvWatchInclude.LastValue,{headers_only:false});const consumer=await kv.js.consumers.getPushConsumer(kv.stream,cc);const info=await consumer.info(true);this.recordOwnWatchConsumer(info);watch.consumer=consumer;const permission2=this.nc&&this.watchDeletePermissions.get(this.nc);if(permission2)this.watchDeletePermissions.set(consumer,permission2);watch.consumerStream=info.stream_name;watch.consumerName=info.name;let replaying=info.num_pending>0;let iter;try{iter=await consumer.consume({callback:jm=>{if(watch.stopped||watch.consumer!==consumer)return;const entry=kv.jmToWatchEntry(jm,!replaying);watch.onChange(membershipChange(entry,!replaying));if(replaying&&jm.info.pending===0){replaying=false;watch.onChange({type:"replayed",revision:entry.revision})}}})}catch(err3){await this.disarmMembershipWatch(watch);throw err3}watch.iter=iter;if(watch.stopped){await this.disarmMembershipWatch(watch);return}if(!replaying)watch.onChange({type:"replayed",revision:0});iter.closed().then(()=>{if(watch.stopped||watch.consumer!==consumer)return;const err3=new Error("membership watch closed");watch.onClosed?.(err3);this.emit("error",err3)}).catch(()=>{})}async deleteRetainedMembershipConsumer(watch){if(!watch.consumerStream||!watch.consumerName)return;if(!this.nc||this.nc.isClosed())return;if(this.watchConsumerDeleteDenied(watch.consumerStream,watch.consumerName,this.nc)){watch.consumerStream=void 0;watch.consumerName=void 0;return}const jsm=await(0,import_jetstream13.jetstreamManager)(this.nc);if(await this.deleteMembershipConsumer(jsm,watch.consumerStream,watch.consumerName)){watch.consumerStream=void 0;watch.consumerName=void 0}}finishMembershipWatchStop(watch){if(!watch.stopped||watch.consumer||watch.iter||watch.consumerStream||watch.consumerName)return;this.membershipFeedWatches.delete(watch);watch.resolveStop?.();watch.resolveStop=void 0;watch.rejectStop=void 0}recordOwnWatchConsumer({stream_name,name}){const prefix=`$JS.API.CONSUMER.DELETE.${stream_name}.${name.slice(0,name.lastIndexOf("_")+1)}`;this.ownWatchDeletePrefixes.add(prefix);return prefix}isOwnWatchDelete(subject){const cut=subject.lastIndexOf("_")+1;return/^\d+$/.test(subject.slice(cut))&&this.ownWatchDeletePrefixes.has(subject.slice(0,cut))}watchConsumerDeleteDenied(stream,name,owner2){const permission2=owner2&&this.watchDeletePermissions.get(owner2)?.();return Boolean(permission2&&!issuedPermitsSubject(permission2,`$JS.API.CONSUMER.DELETE.${stream}.${name}`))}async deleteOwnConsumer(consumer){const{stream_name,name}=await consumer.info(true);if(this.watchConsumerDeleteDenied(stream_name,name,consumer))return;try{await consumer.delete()}catch(e){if(!isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.ConsumerNotFound)&&!isPublishPermissionDenied(e))throw e}}async deleteMembershipConsumer(jsm,stream,name){try{return await jsm.consumers.delete(stream,name)}catch(err3){if(membershipConsumerReleased(err3))return true;throw err3}}async disarmMembershipWatch(watch){const iter=watch.iter;const consumer=watch.consumer;watch.iter=void 0;watch.consumer=void 0;try{iter?.stop()}catch{}if(consumer){if(watch.consumerStream&&watch.consumerName&&this.watchConsumerDeleteDenied(watch.consumerStream,watch.consumerName,consumer)){watch.consumerStream=void 0;watch.consumerName=void 0;return}try{const deleted=await consumer.delete();if(deleted){watch.consumerStream=void 0;watch.consumerName=void 0}}catch(err3){if(membershipConsumerReleased(err3)){watch.consumerStream=void 0;watch.consumerName=void 0}else{const closedEpoch=err3 instanceof import_transport_node13.ClosedConnectionError;const timeout=err3 instanceof import_transport_node13.TimeoutError;if(timeout||closedEpoch){this.emit("error",err3)}else{throw err3}}}}}async rearmMembershipWatches(){await Promise.all([...this.membershipFeedWatches].map(async watch=>{watch.arm=watch.arm.catch(()=>{}).then(async()=>{await this.disarmMembershipWatch(watch);await this.deleteRetainedMembershipConsumer(watch);if(!watch.stopped)await this.armMembershipWatch(watch)});try{await watch.arm;this.finishMembershipWatchStop(watch)}catch(err3){this.emit("error",err3)}}))}async channelHistory(channel,opts){const from=opts?.publisher;const subject=from===void 0?chatSubject(this.space,"*","*",channel):chatSubject(this.space,assertValidOwnerToken(from.owner),assertValidOwnerToken(from.actor),channel);return(await this.streamHistory(chatStream(this.space),[subject],opts?.limit??100,void 0,opts?.signal)).map(r=>r.msg)}async channelHistoryPage(channel,opts){assertValidChannel(channel);if(!isConcreteChannel(channel))throw new Error("channelHistoryPage requires one concrete channel");const limit=opts?.limit??50;if(!Number.isSafeInteger(limit)||limit<1||limit>1e3)throw new Error("channelHistoryPage limit must be a whole number from 1 to 1000");if(!this.nc||!this.js)throw new Error(this.notLiveMsg());const jsm=this.jsm??=await(0,import_jetstream13.jetstreamManager)(this.nc);const signal=AbortSignal.any([AbortSignal.timeout(1e4),...opts?.signal?[opts.signal]:[]]);signal.throwIfAborted();const stream=chatStream(this.space);const name=chatHistDurable(this.owner,this.actor,this.requireLifecycleUid("channelHistoryPage"));const subject=chatSubject(this.space,"*","*",channel);const marker=(0,import_node_crypto10.randomUUID)();let created;for(;;){signal.throwIfAborted();try{created=await jsm.consumers.add(stream,{name,description:marker,filter_subject:subject,ack_policy:import_jetstream13.AckPolicy.None,deliver_policy:import_jetstream13.DeliverPolicy.All,mem_storage:true,inactive_threshold:(0,import_transport_node13.nanos)(250)});break}catch(e){if(!(e instanceof import_jetstream13.JetStreamApiError)||e.code!==10148)throw e;await(0,import_promises.setTimeout)(50,void 0,{signal})}}signal.throwIfAborted();const owns=info=>info.created===created.created&&info.config.description===marker&&info.config.filter_subject===subject;if(!owns(created))throw new Error("channelHistoryPage: consumer ownership was not established");const consumer=await this.js.consumers.get(stream,name);const pending=created.num_pending;const out=[];let delivered=0;if(pending>0){const iter=await consumer.consume({max_messages:Math.min(pending,32)});const stop=()=>iter.stop(abortReason(signal));signal.addEventListener("abort",stop,{once:true});try{signal.throwIfAborted();for await(const m of iter){signal.throwIfAborted();if(!subjectMatches(subject,m.subject))throw new Error("channelHistoryPage: consumer delivered another channel; ownership was lost");delivered++;const msg=historyMessageFromDelivery(m);if(msg){out.push(msg);if(out.length>limit+1)out.shift()}if(delivered>=pending)break}}finally{signal.removeEventListener("abort",stop);iter.stop()}signal.throwIfAborted();if(delivered!==pending)throw new Error(`channelHistoryPage: read ${delivered} of ${pending} messages before the window was cut short`)}signal.throwIfAborted();if(!owns(await consumer.info()))throw new Error("channelHistoryPage: consumer ownership was lost");signal.throwIfAborted();return{items:out.slice(-limit),complete:out.length<=limit}}async multiChannelHistory(channels,opts){const subjects=[...new Set(channels.map(channel=>{if(!isConcreteChannel(channel))throw new Error(`multiChannelHistory: "${channel}" is a wildcard channel - one consumer's filter subjects may not overlap, so name the concrete channels`);assertValidChannel(channel);return chatSubject(this.space,"*","*",channel)}))];if(subjects.length===0)return[];const limit=opts?.limit??100;const size=Math.max(1,Math.trunc(opts?.batch??MULTI_FILTER_BATCH));const batches=[];for(let i=0;i<subjects.length;i+=size)batches.push(subjects.slice(i,i+size));const pages2=new Array(batches.length);let next=0;const readBatch=async()=>{for(;;){const i=next++;if(i>=batches.length)return;pages2[i]=await this.streamHistory(chatStream(this.space),batches[i],limit,void 0,opts?.signal)}};await Promise.all(Array.from({length:Math.min(MULTI_FILTER_READ_CONCURRENCY,batches.length)},readBatch));const rows=pages2.flat().sort((a,b)=>a.seq-b.seq).slice(-limit);return rows.map(({seq,subject,msg})=>{const p=parseSubject(subject);if(p?.kind!=="chat")throw new Error(`multiChannelHistory: the broker delivered ${subject}, which is not a chat subject on this space`);return{channel:p.rest,seq,msg}})}async readHistory(channel,opts){const reply=await this.requestDelivery("readHistory",{channel,limit:opts?.limit});if(!reply.ok)throw new Error(reply.error??"readHistory failed");const data=reply.data;if(!Array.isArray(data?.items)||typeof data?.complete!=="boolean")throw new Error("readHistory: the delivery daemon returned a malformed page (expected { items, complete })");return{items:data.items,complete:data.complete}}async dmHistory(opts){try{return(await this.streamHistory(dmStream(this.space),[`${spacePrefix(this.space)}.inst.>`],opts?.limit??100,void 0,opts?.signal)).map(r=>r.msg)}catch(e){if(isPermissionDenied(e))return[];throw e}}async dmHistoryOf(principals,opts){const keys=[...new Set(principals)].map(p=>{const key=parsePrincipalKey(p);if(!key)throw new Error(`dmHistoryOf: "${p}" is not a principal <owner>.<actor>`);return key});if(!keys.length)return{state:"read",items:[]};const limit=opts?.limit??100;const read=subjects=>this.streamHistory(dmStream(this.space),subjects,limit,void 0,opts?.signal);let rows;try{rows=(await Promise.all([read(keys.map(k=>unicastRecvFilter(this.space,k.owner,k.actor))),read(keys.map(k=>unicastSubject(this.space,"*","*",k.owner,k.actor)))])).flat()}catch(e){if(isPermissionDenied(e))return{state:"denied",reason:e.message};throw e}const bySeq=new Map(rows.map(r=>[r.seq,r.msg]));return{state:"read",items:[...bySeq].sort(([a],[b])=>a-b).slice(-limit).map(([,msg])=>msg)}}async streamHistory(stream,subjects,limit,before,signal){if(!this.nc)throw new Error(this.notLiveMsg());signal?.throwIfAborted();if(!Number.isSafeInteger(limit))throw new Error(`history limit must be a whole number of messages this server can count exactly, received ${limit}`);if(limit<=0)return[];const nc=this.nc;let reader;try{reader=await this.acquireHistoryReader(nc,this.jsm??(this.jsm=await(0,import_jetstream13.jetstreamManager)(nc)),stream,signal);const ceiling=before!==void 0?before-1:await this.lastMatchingSeq(reader,subjects,signal);if(ceiling<1)return[];let span=Math.max(limit,64);let floor=1;let floorKnown=false;for(;;){signal?.throwIfAborted();const start=Math.max(floor,ceiling-span+1);const page=await this.drainWindow(reader,subjects,start,ceiling,limit,signal);if(page.length>=limit)return page.slice(-limit);if(!floorKnown){floor=Math.max(1,await this.firstMatchingSeq(reader,subjects,signal));floorKnown=true}if(start<=floor)return page.slice(-limit);span*=4}}catch(e){const msg=String(e?.message??"");if(/stream not found/i.test(msg)||e?.code===404)return[];throw e}finally{if(reader)this.releaseHistoryReader(reader)}}historyReaderId(nc){if(!this.userMode)return this.connId;const info=nc.info;if(!info)throw new Error("history: the server has not sent its INFO, so this connection has no history reader id yet");return calloutReaderId(info.server_id,info.client_id)}async acquireHistoryReader(nc,jsm,stream,signal){for(;;){signal?.throwIfAborted();const readerId=this.historyReaderId(nc);let pool=this.historyReaderSlots.get(stream);if(pool?.readerId!==readerId){pool={readerId,free:Array.from({length:HISTORY_READERS},(_,i)=>HISTORY_READERS-1-i),held:0,waiting:[],refusedUntil:0};this.historyReaderSlots.set(stream,pool)}if(pool.refusedUntil>Date.now())throw this.readerDeleteRefused(stream);const slot=pool.free.pop();if(slot!==void 0){pool.held++;return{nc,js:(0,import_jetstream13.jetstream)(nc),jsm,stream,pool,slot,name:historyReaderConsumer(readerId,slot),held:true,left:false}}if(pool.held===0)throw new Error(`history: every history reader name this connection has on ${stream} is set aside, held by a consumer it did not create (another process using the same credential, or one that stopped mid-read) or by a reader it could not confirm deleted; they expire ${HISTORY_READER_INACTIVE_MS/6e4} minutes after their last use`);const waitOn=pool;await new Promise((resolve,reject)=>{const wake=()=>{signal?.removeEventListener("abort",stop);resolve()};const stop=()=>{waitOn.waiting.splice(waitOn.waiting.indexOf(wake),1);reject(abortReason(signal))};waitOn.waiting.push(wake);signal?.addEventListener("abort",stop,{once:true})})}}releaseHistoryReader(reader){if(!reader.held)return;reader.held=false;const pool=reader.pool;pool.held--;if(!reader.left){pool.free.push(reader.slot);pool.waiting.shift()?.();return}this.setAsideHistoryReader(pool,reader.slot);if(pool.held===0)for(const wake of pool.waiting.splice(0))wake()}setAsideHistoryReader(pool,slot){setTimeout(()=>{pool.free.push(slot);pool.waiting.shift()?.()},HISTORY_READER_INACTIVE_MS).unref()}async openHistoryReader(reader,config2){const pool=reader.pool;for(;;){if(this.historyReaderId(reader.nc)!==pool.readerId)throw new Error(`history: the connection was re-established during the read on ${reader.stream}, so its history reader names changed; the read is not served`);const description=`cotal history read ${(0,import_node_crypto10.randomUUID)()}`;let info;try{info=await reader.jsm.consumers.add(reader.stream,{...config2,name:reader.name,description,ack_policy:import_jetstream13.AckPolicy.None,max_deliver:1,mem_storage:true,num_replicas:1,inactive_threshold:(0,import_transport_node13.nanos)(HISTORY_READER_INACTIVE_MS)})}catch(e){if(!isConsumerAlreadyExists(e))throw e}if(info?.config.description===description)return reader.js.consumers.getConsumerFromInfo(info);this.setAsideHistoryReader(pool,reader.slot);const next=pool.free.pop();if(next===void 0){reader.held=false;pool.held--;for(const wake of pool.waiting.splice(0))wake();throw new Error(`history: reader ${reader.name} on ${reader.stream} is held by a consumer this read did not create, and no other reader name is free`)}reader.slot=next;reader.name=historyReaderConsumer(pool.readerId,next)}}async closeHistoryReader(reader){try{await reader.jsm.consumers.delete(reader.stream,reader.name)}catch(e){if(isConsumerNotFound(e))return;reader.left=true;if(isPublishPermissionDenied(e)){if(this.historyReaderId(reader.nc)!==reader.pool.readerId)throw new Error(`history: the connection was re-established during the read on ${reader.stream}, so it may no longer delete its reader ${reader.name}, which expires on its own; the read is not served`);reader.pool.refusedUntil=Date.now()+HISTORY_READER_INACTIVE_MS;throw this.readerDeleteRefused(reader.stream)}throw e}}readerDeleteRefused(stream){return new Error(`history: this credential may not delete its own history readers on ${stream}; it predates the observer and admin reader-delete grant, so remint it`)}async firstMatchingSeq(reader,subjects,signal){signal?.throwIfAborted();const consumer=await this.openHistoryReader(reader,{filter_subjects:subjects,deliver_policy:import_jetstream13.DeliverPolicy.All});try{if((await consumer.info(true)).num_pending===0)return 0;signal?.throwIfAborted();const iter=await consumer.fetch({max_messages:1});const stop=()=>iter.stop(abortReason(signal));signal?.addEventListener("abort",stop,{once:true});try{signal?.throwIfAborted();for await(const m of iter)return m.seq}finally{signal?.removeEventListener("abort",stop);iter.stop()}throw new Error(`history: the broker reported messages on ${subjectLabel(subjects)} but delivered none - the read was cut short, not empty`)}finally{await this.closeHistoryReader(reader)}}async lastMatchingSeq(reader,subjects,signal){signal?.throwIfAborted();const consumer=await this.openHistoryReader(reader,{filter_subjects:subjects,deliver_policy:import_jetstream13.DeliverPolicy.Last});try{if((await consumer.info(true)).num_pending===0)return 0;signal?.throwIfAborted();const iter=await consumer.fetch({max_messages:1});const stop=()=>iter.stop(abortReason(signal));signal?.addEventListener("abort",stop,{once:true});try{signal?.throwIfAborted();for await(const m of iter)return m.seq}finally{signal?.removeEventListener("abort",stop);iter.stop()}throw new Error(`history: the broker reported messages on ${subjectLabel(subjects)} but delivered none - the read was cut short, not empty`)}finally{await this.closeHistoryReader(reader)}}async drainWindow(reader,subjects,start,ceiling,limit,signal){signal?.throwIfAborted();const out=[];const consumer=await this.openHistoryReader(reader,{filter_subjects:subjects,deliver_policy:import_jetstream13.DeliverPolicy.StartSequence,opt_start_seq:start});try{const pending=(await consumer.info(true)).num_pending;if(pending===0)return out;signal?.throwIfAborted();const iter=await consumer.consume({max_messages:Math.min(pending,32)});const stop=()=>iter.stop(abortReason(signal));signal?.addEventListener("abort",stop,{once:true});let delivered=0;let complete=false;try{signal?.throwIfAborted();for await(const m of iter){delivered++;if(m.info.deliverySequence!==delivered)throw new Error(`history: delivery ${m.info.deliverySequence} arrived where ${delivered} was due on ${subjectLabel(subjects)} - the window has a gap, so the page is not served`);if(m.seq>=ceiling){if(m.seq===ceiling){const msg2=historyMessageFromDelivery(m);if(msg2)out.push({seq:m.seq,subject:m.subject,msg:msg2})}complete=true;break}const msg=historyMessageFromDelivery(m);if(msg){out.push({seq:m.seq,subject:m.subject,msg});if(out.length>limit)out.shift()}if(delivered>=pending){complete=true;break}}}finally{signal?.removeEventListener("abort",stop);iter.stop()}if(!complete)throw new Error(`history: read ${delivered} of ${pending} messages on ${subjectLabel(subjects)} before the stream ended early - the window was cut short, not empty`);return out}finally{await this.closeHistoryReader(reader)}}watchStatus(){const nc=this.nc;if(!nc)return;const handedToRequest=this.trackRequestDenials(nc);void(async()=>{for await(const s of nc.status()){if(this.nc!==nc)continue;if(s.type==="disconnect"){this.emit("transport",{connected:false,server:s.server});continue}if(s.type==="reconnect"){this.armAuthExpiryReconnectFence(nc);this.emit("transport",{connected:true,server:s.server});for(const follower of this.activeGoalFollowers){follower.reconnected(nc)}continue}if(s.type==="close"){this.emit("transport",{connected:false});continue}if(s.type!=="error")continue;if(s.error instanceof import_transport_node13.PermissionViolationError&&this.chatSubRefusals.has(s.error))continue;if(s.error instanceof import_transport_node13.PermissionViolationError&&handedToRequest.has(s.error))continue;if(s.error instanceof import_transport_node13.PermissionViolationError&&s.error.operation==="publish"&&this.isOwnWatchDelete(s.error.subject))continue;if(!this.reportSubscriptionDenial(s.error))this.emit("error",describeStatusError(s.error))}})().catch(e=>{if(!this.stopped&&this.nc===nc)this.emit("error",e)});if(this.stopped)return;this.emit("transport",{connected:true,server:nc.getServer()})}reportSubscriptionDenial(error51){if(!(error51 instanceof import_transport_node13.PermissionViolationError)||error51.operation!=="subscription")return false;if(!this.reportedSubRefusals.has(error51)){this.reportedSubRefusals.add(error51);this.emit("error",describeStatusError(error51))}return true}trackRequestDenials(nc){const handed=new WeakSet;const request=nc.request.bind(nc);nc.request=(subject,payload,opts)=>{if(typeof subject==="string"&&this.ungrantedOwnWatchDelete(subject)){const violation=new import_transport_node13.PermissionViolationError(`Permissions Violation for Publish to "${subject}"`,"publish",subject);handed.add(violation);return Promise.reject(new import_transport_node13.RequestError("permissions violation",{cause:violation}))}const reply=request(subject,payload,opts);reply.catch(({cause})=>{if(cause instanceof import_transport_node13.PermissionViolationError&&cause.operation==="publish")handed.add(cause)});return reply};return handed}ungrantedOwnWatchDelete(subject){if(!this.isOwnWatchDelete(subject))return false;const permission2=this.watchDeletePermissions.get(this.nc)?.();return Boolean(permission2&&!issuedPermitsSubject(permission2,subject))}notLiveMsg(){return this.reconnecting||this.reestablishing?"reconnecting - try again shortly":"endpoint not started"}async publishMsg(subject,msg){if(!this.js)throw new Error(this.notLiveMsg());assertPartsSerializable(msg.parts);try{await this.js.publish(subject,JSON.stringify(msg),{msgID:msg.id})}catch(error51){if(error51 instanceof import_transport_node13.TimeoutError)throw new Error(`${error51.message} publishing to ${JSON.stringify(subject)}. The send outcome is unknown: the broker may have stored the message. Check before resending.`,{cause:error51});throw error51}}async ensureStreams(){if(!this.jsm)throw new Error(this.notLiveMsg());await createSpaceStreams(this.jsm,this.space)}async provisionDmInbox(owner2,actor2,lifecycleUid){await this.ensureDmDurable(owner2,actor2,lifecycleUid,{})}async ensureDmDurable(owner2,actor2,lifecycleUid,opts){const jsm=await this.manager();const stream=dmStream(this.space);const name=dmDurable(owner2,actor2,lifecycleUid);try{await jsm.consumers.info(stream,name);return}catch(e){if(!isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.ConsumerNotFound))throw e}const frontier=(await jsm.streams.info(stream)).state.last_seq;try{await jsm.consumers.add(stream,dmDurableConfig(this.space,owner2,actor2,lifecycleUid,{...opts,activationFrontier:frontier}))}catch(e){try{await jsm.consumers.info(stream,name);return}catch(probeError){if(isPermissionDenied(probeError))throw probeError}throw e}}async provisionDlvInbox(owner2,actor2,lifecycleUid){const jsm=await this.manager();await jsm.consumers.add(dlvStream(this.space),dlvDurableConfig(this.space,owner2,actor2,lifecycleUid))}async provisionTaskQueue(role){const jsm=await this.manager();await jsm.consumers.add(taskStream(this.space),taskDurableConfig(this.space,role))}async membersRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.membersKv??=await openMembersRegistry(this.nc,this.space);return this.membersKv}async aclRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.aclKv??=await openAclRegistry(this.nc,this.space);return this.aclKv}async commitAcl(targetId,lifecycleUid,allowSubscribe){await commitAcl(await this.aclRegistry(),targetId,lifecycleUid,allowSubscribe)}async reissueAcl(targetId,lifecycleUid,allowSubscribe){await reissueAcl(await this.aclRegistry(),targetId,lifecycleUid,allowSubscribe)}async aclForOwner(owner2,lifecycleUid){return(await readAcl(await this.aclRegistry(),owner2,lifecycleUid))?.record.allowSubscribe}async aclForAlias(principal){const row=await readAclForAlias(await this.aclRegistry(),principal);if(row===void 0)return void 0;const allow=row.record.allowSubscribe;const issued=row.record.issuedAllowSubscribe??allow;return{allowSubscribe:allow,issuedAllowSubscribe:issued,lifecycleUid:row.lifecycleUid}}async deliveryRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.deliveryKv??=await openDeliveryRegistry(this.nc,this.space);return this.deliveryKv}leaseIncarnation=(0,import_node_crypto10.randomUUID)();leaseAcquiredAt=new Map;encodeLease(shardIndex,ready,acquiredAt=this.leaseAcquiredAt.get(shardIndex)){return new TextEncoder().encode(JSON.stringify({holder:this.card.id,incarnation:this.leaseIncarnation,acquiredAt,since:Date.now(),ready}))}ownsDeliveryLease(info){return info.holder===this.card.id&&info.incarnation!==void 0&&info.incarnation===this.leaseIncarnation}async acquireDeliveryLease(shardIndex){const acquiredAt=Date.now();const revision=await(await this.deliveryRegistry()).create(leaseKey(shardIndex),this.encodeLease(shardIndex,false,acquiredAt));this.leaseAcquiredAt.set(shardIndex,acquiredAt);return revision}async markDeliveryLeaseReady(shardIndex,revision){return(await this.deliveryRegistry()).update(leaseKey(shardIndex),this.encodeLease(shardIndex,true),revision)}async markDeliveryLeaseNotReady(shardIndex,revision){return(await this.deliveryRegistry()).update(leaseKey(shardIndex),this.encodeLease(shardIndex,false),revision)}async renewDeliveryLease(shardIndex,revision){return(await this.deliveryRegistry()).update(leaseKey(shardIndex),this.encodeLease(shardIndex,true),revision)}async releaseDeliveryLease(shardIndex,revision){if(revision===void 0)return;await(await this.deliveryRegistry()).delete(leaseKey(shardIndex),{previousSeq:revision})}async readDeliveryLease(shardIndex){return(await this.readDeliveryLeaseEntry(shardIndex))?.info}async watchDeliveryLease(shardIndex,onEvent){this.leaseWatchIntent={shardIndex,onEvent};await this.bindDeliveryLeaseWatch();return()=>{if(this.leaseWatchIntent?.onEvent!==onEvent)return;this.leaseWatchIntent=void 0;this.stopDeliveryLeaseWatch()}}stopDeliveryLeaseWatch(){if(this.leaseWatchIter)this.retireDeliveryLeaseWatch(this.leaseWatchIter);this.leaseWatchIter=void 0}retireDeliveryLeaseWatch(iter){try{iter.stop()}catch{}if(!this.nc||this.nc.isClosed())return;const deleting=this.deleteOwnConsumer(kvWatchConsumer(iter)).catch(e=>this.emitRecoverable(new Error(`a retired delivery lease watch consumer was not deleted (${e.message}); the broker reaps it at its inactive threshold`)));this.leaseWatchDeletes.add(deleting);void deleting.then(()=>this.leaseWatchDeletes.delete(deleting))}async settleDeliveryLeaseWatches(){await Promise.allSettled(this.leaseWatchBinds);await Promise.all(this.leaseWatchDeletes)}retireKvWatch(iter){try{iter.stop()}catch{}if(!this.nc||this.nc.isClosed())return;const deleting=this.deleteOwnConsumer(kvWatchConsumer(iter)).catch(e=>this.emitRecoverable(new Error(`a retired KV watch consumer was not deleted (${e.message}); the broker reaps it at its inactive threshold`)));this.kvWatchDeletes.add(deleting);void deleting.then(()=>this.kvWatchDeletes.delete(deleting))}async settleKvWatches(){await Promise.allSettled(this.kvWatchBinds);await Promise.all(this.kvWatchDeletes)}bindKvWatch(kv){if(this.stopped)return Promise.resolve(void 0);const epoch=this.presenceEpoch;const binding=(async()=>{const permission2=this.nc&&this.watchDeletePermissions.get(this.nc);const iter=await kv.watch();const info=await kvWatchConsumer(iter).info(true);this.recordOwnWatchConsumer(info);if(permission2)this.watchDeletePermissions.set(kvWatchConsumer(iter),permission2);if(epoch===this.presenceEpoch&&!this.stopped)return{iter,info};this.retireKvWatch(iter);return void 0})();const settled=()=>{this.kvWatchBinds.delete(binding)};this.kvWatchBinds.add(binding);void binding.then(settled,settled);return binding}bindDeliveryLeaseWatch(){const binding=this.bindDeliveryLeaseWatchOnce();const settled=()=>{this.leaseWatchBinds.delete(binding)};this.leaseWatchBinds.add(binding);void binding.then(settled,settled);return binding}async bindDeliveryLeaseWatchOnce(){const intent=this.leaseWatchIntent;const epoch=this.presenceEpoch;const iter=await(await this.deliveryRegistry()).watch({key:leaseKey(intent.shardIndex)});if(this.leaseWatchIntent!==intent||epoch!==this.presenceEpoch){this.retireDeliveryLeaseWatch(iter);return}this.leaseWatchIter=iter;void(async()=>{for await(const e of iter){if(this.leaseWatchIter!==iter)break;if(e.operation==="DEL"||e.operation==="PURGE"){intent.onEvent(void 0);continue}try{intent.onEvent(e.json())}catch{intent.onEvent(void 0)}}})().catch(e=>this.emit("error",e))}async deliveryLeaseHolder(shardIndex){try{return(await this.readDeliveryLeaseEntry(shardIndex))?.info.holder}catch{return void 0}}async readDeliveryLeaseEntry(shardIndex){const e=await(await this.deliveryRegistry()).get(leaseKey(shardIndex));if(!e||e.operation==="DEL"||e.operation==="PURGE")return void 0;try{return{info:e.json(),revision:e.revision}}catch(err3){throw new Error(`delivery lease row "${leaseKey(shardIndex)}" exists but does not parse as a lease record (${err3.message}) - it is unreadable, not absent`)}}async managerLeaseRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());if(this.managerLeaseKv)return this.managerLeaseKv;const kvm=new import_kv7.Kvm((0,import_jetstream13.jetstream)(this.nc,{timeout:MANAGER_LEASE_ATTEMPT_MS}));if(this.authed){this.managerLeaseKv=await kvm.open(managerBucket(this.space))}else{try{this.managerLeaseKv=await kvm.create(managerBucket(this.space),{ttl:MANAGER_LEASE_TTL_MS})}catch{this.managerLeaseKv=await kvm.open(managerBucket(this.space))}}return this.managerLeaseKv}async holdDaemonRenewalLease(instanceId){const kv=await this.managerLeaseRegistry();const held2=this.daemonRenewalLeaseRevision;if(held2!==void 0){try{this.daemonRenewalLeaseRevision=await kv.update(MANAGER_RENEWAL_LEASE_KEY,this.encodeDaemonRenewalLease(instanceId),held2);return true}catch{this.daemonRenewalLeaseRevision=void 0}}try{this.daemonRenewalLeaseRevision=await kv.create(MANAGER_RENEWAL_LEASE_KEY,this.encodeDaemonRenewalLease(instanceId));return true}catch{return false}}async releaseDaemonRenewalLease(){const held2=this.daemonRenewalLeaseRevision;this.daemonRenewalLeaseRevision=void 0;if(held2===void 0)return;try{await(await this.managerLeaseRegistry()).delete(MANAGER_RENEWAL_LEASE_KEY,{previousSeq:held2})}catch{}}encodeDaemonRenewalLease(instanceId){return new TextEncoder().encode(JSON.stringify({instanceId,since:Date.now()}))}async readDaemonRenewalLease(){const e=await(await this.managerLeaseRegistry()).get(MANAGER_RENEWAL_LEASE_KEY);if(!e||e.operation!=="PUT")return void 0;return JSON.parse(new TextDecoder().decode(e.value))}encodeManagerLease(info){return new TextEncoder().encode(JSON.stringify(info))}async acquireManagerLease(info){return(await this.managerLeaseRegistry()).create(managerLeaseKey(info.instanceId),this.encodeManagerLease({...info,since:Date.now()}))}async renewManagerLease(info,revision){return(await this.managerLeaseRegistry()).update(managerLeaseKey(info.instanceId),this.encodeManagerLease({...info,since:Date.now()}),revision)}async readOwnManagerLease(instanceId){const e=await(await this.managerLeaseRegistry()).get(managerLeaseKey(instanceId));if(!e||e.operation!=="PUT")return void 0;return{info:JSON.parse(new TextDecoder().decode(e.value)),revision:e.revision,created:e.created.getTime()}}async releaseManagerLease(instanceId,revision){const kv=await this.managerLeaseRegistry();if(revision===void 0)await kv.delete(managerLeaseKey(instanceId));else await kv.delete(managerLeaseKey(instanceId),{previousSeq:revision})}async readManagerLease(){if(!this.nc)return void 0;try{const jsm=this.jsm??(this.jsm=await(0,import_jetstream13.jetstreamManager)(this.nc));const stream=`KV_${managerBucket(this.space)}`;const prefix=`$KV.${managerBucket(this.space)}.${MANAGER_LEASE_KEY}.`;const info=await jsm.streams.info(stream,{subjects_filter:`${prefix}*`});let newest;for(const subject of Object.keys(info.state.subjects??{})){let m;try{m=await jsm.streams.getMessage(stream,{last_by_subj:subject})}catch(e){if(e.code===import_jetstream13.JetStreamApiCodes.NoMessageFound)continue;throw e}if(m===null)continue;const op=m.header?.get("KV-Operation");if(op==="DEL"||op==="PURGE"||m.data.length===0)continue;if(newest===void 0||m.seq>newest.seq)newest={data:m.data,seq:m.seq}}if(newest===void 0)return void 0;return JSON.parse(new TextDecoder().decode(newest.data))}catch(e){const code=e.code;if(code===10037)return void 0;if(code===404||/stream not found/i.test(e?.message??""))return void 0;throw e}}async ownerMemberships(owner2,lifecycleUid){const recs=await listMembers(await this.membersRegistry(),{owner:owner2});return recs.filter(r=>r.lifecycleUid===lifecycleUid&&r.leaveCursor===void 0).map(r=>({channel:r.channel,generation:r.generation,activated:r.activated===true}))}async deliveryClassFresh(channel){if(!this.channelKv)return effectiveDeliveryClass(void 0,void 0);const[cfg,defaults]=await Promise.all([isConcreteChannel(channel)?readChannelConfig(this.channelKv,channel):Promise.resolve(void 0),readChannelDefaults(this.channelKv)]);return effectiveDeliveryClass(cfg,defaults)}resolveOwnerByName(name){const matches=[...this.roster.values()].filter(p=>p.card.name.toLowerCase()===name.toLowerCase());return matches.length===1?matches[0].card.id:void 0}plane3MsgId(entry,keySuffix){return entry.msg.id===""?{}:{msgID:`${entry.msg.id}:${keySuffix}`}}async publishDinbox(principal,lifecycleUid,entry){if(!this.js)return;const p=parsePrincipalKey(principal);if(!p)throw new Error(`publishDinbox: "${principal}" is not a valid member principal <owner>.<actor>`);await this.js.publish(dinboxSubject(this.space,p.owner,p.actor,lifecycleUid),JSON.stringify(entry),{...this.plane3MsgId(entry,`${principal}:${lifecycleUid}`)})}async fanoutDeliveredSeq(){const info=await this.consumerInfo(chatStream(this.space),FANOUT_DURABLE);return info?.delivered?.stream_seq??0}async durableJoinFor(owner2,channel,lifecycleUid,opts={}){if(!this.js)throw new Error(this.notLiveMsg());await this.manager();const kv=await this.membersRegistry();const existing=await readMember(kv,channel,owner2,lifecycleUid);const open5=existing?.record.state==="durable-active"&&existing.record.leaveCursor===void 0;if(open5&&existing.record.activated)return{durable:true,generation:existing.record.generation};const joinCursor=open5?existing.record.joinCursor:await this.chatFrontier();const generation=open5?existing.record.generation:(existing?.record.generation??0)+1;const base={channel,owner:owner2,lifecycleUid,state:"durable-active",joinCursor,generation,activated:false,writerIdentity:this.card.id,updatedAt:Date.now()};if(!open5){if(opts.aclFence&&!await this.aclAllows(owner2,lifecycleUid,channel))throw new Error(`durableJoin: "${channel}" is no longer within the read ACL of lifecycle ${lifecycleUid} (narrowed or retired); no membership row was written`);const written=await commitMemberRevision(kv,base);if(opts.aclFence)await this.keepRowIfAclAllows(kv,owner2,lifecycleUid,channel,written.revision)}const fence=Math.max(await this.chatFrontier(),await this.fanoutDeliveredSeq());await this.catchupCopy(owner2,lifecycleUid,channel,joinCursor,fence,generation);const activated=await activateMember(kv,channel,owner2,lifecycleUid,generation,joinCursor);if(!activated)return{durable:false,reason:"activation superseded by a concurrent leave or rejoin",generation};return{durable:true,generation}}async aclAllows(owner2,lifecycleUid,channel){const row=await readAcl(await this.aclRegistry(),owner2,lifecycleUid);return row!==void 0&&membershipInAllow(row.record.allowSubscribe,channel)}async keepRowIfAclAllows(kv,owner2,lifecycleUid,channel,revision){let disallowed=false;let why;try{if(await this.aclAllows(owner2,lifecycleUid,channel))return;disallowed=true;why="was narrowed or retired while the row was written"}catch(e){why=`could not be re-read after the row was written (${e.message})`}const fail3=(outcome,cause)=>new Error(`durableJoin: the read ACL of lifecycle ${lifecycleUid} ${why}; ${outcome}`,cause===void 0?void 0:{cause});try{if(disallowed)await deleteMember(kv,channel,owner2,lifecycleUid);else await kv.purge(memberKey(channel,owner2,lifecycleUid),{previousSeq:revision})}catch(e){if(!disallowed&&isCasLoss(e))throw fail3(`a later write replaced its "${channel}" row, which was left to that write`);throw fail3(`removing its "${channel}" row failed (${e.message})`,e)}throw fail3(`its "${channel}" row was removed`)}async durableLeaveFor(owner2,channel,lifecycleUid,expectedGeneration){if(!this.plane3)return;const kv=await this.membersRegistry();await tombstoneMember(kv,channel,owner2,lifecycleUid,await this.chatFrontier(),this.card.id,expectedGeneration)}async catchupCopy(owner2,lifecycleUid,channel,fromSeqExcl,toSeqIncl,generation){if(!this.js||!this.jsm||toSeqIncl<=fromSeqExcl)return 0;const subject=chatSubject(this.space,"*","*",channel);const family=isChannelFamily(channel);const durableClass=new Map;const stored=ch=>{if(!family)return Promise.resolve(true);let cls=durableClass.get(ch);if(cls===void 0)durableClass.set(ch,cls=this.deliveryClassFresh(ch).then(c=>c==="durable"));return cls};const cuP=parsePrincipalKey(owner2);const name=`cu_${cuP?lifecycleNameKey(cuP.owner,cuP.actor,lifecycleUid):`${token(owner2)}-${lifecycleUid}`}_${generation}`;await this.deleteConsumerIfPresent(chatStream(this.space),name);await this.jsm.consumers.add(chatStream(this.space),{name,filter_subject:subject,ack_policy:import_jetstream13.AckPolicy.None,mem_storage:true,inactive_threshold:(0,import_transport_node13.nanos)(3e4),deliver_policy:import_jetstream13.DeliverPolicy.StartSequence,opt_start_seq:fromSeqExcl+1});let copied=0;try{const consumer=await this.js.consumers.get(chatStream(this.space),name);let pending=(await consumer.info()).num_pending;while(pending>0){const want=Math.min(pending,256);const iter=await consumer.fetch({max_messages:want,expires:5e3});let got=0;for await(const m of iter){got++;if(m.seq>toSeqIncl)return copied;let msg;try{msg=m.json()}catch{continue}const parsed=parseSubject(m.subject);if(!parsed||!isFromSubjectSender(msg,parsed)||msg.from.id===owner2)continue;if(!await stored(parsed.rest))continue;await this.publishDinbox(owner2,lifecycleUid,{msg,channel:parsed.rest,seq:m.seq,reason:"durable-channel",generation,...family?{row:channel}:{}});copied++}if(got<want)break;pending-=got}}finally{await this.deleteConsumerIfPresent(chatStream(this.space),name)}return copied}async startPlane3(aclFor,opts={}){if(!this.js)throw new Error(this.notLiveMsg());this.plane3={aclFor,reloadMembershipCreds:opts.reloadMembershipCreds,evictPrincipal:opts.evictPrincipal,evictPrincipals:opts.evictPrincipals,planeConnLiveness:opts.planeConnLiveness,principalLiveness:opts.principalLiveness,reloadStoreIdentity:opts.reloadStoreIdentity,onDeliveryCredsAdopted:opts.onDeliveryCredsAdopted,startupComplete:opts.startupComplete};await this.armPlane3()}plane3MayAct(){return!this.plane3Quiesced}async handleDeliveryControl(req){if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon is not serving this shard (it is re-checking ownership); retry"};const caller=req.from.id;const args=req.args??{};if(req.op==="durableJoin")return this.deliveryJoin(caller,args);if(req.op==="durableLeave")return this.deliveryLeave(caller,args);if(req.op==="readHistory")return this.deliveryReadHistory(caller,args);if(req.op===ANYCAST_TAKES_OP)return this.anycastUnavailable?{ok:false,error:`delivery: ${this.anycastUnavailable}`}:{ok:true,data:{takes:true}};if(req.op===ANYCAST_STATUS_OP||req.op===ANYCAST_CANCEL_OP)return this.deliveryAnycast(req.op,caller,args);if(req.op==="listMemberships"){if(typeof args.lifecycleUid!=="string")return{ok:false,error:"listMemberships: the caller's lifecycleUid is required (membership rows are lifecycle-keyed, SPEC 13.1)"};let uid2;try{uid2=assertLifecycleToken(args.lifecycleUid)}catch(e){return{ok:false,error:e.message}}const memberships=await this.ownerMemberships(caller,uid2);if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon stopped serving this shard while the request was in flight; retry"};return{ok:true,data:{memberships}}}return{ok:false,error:`op "${req.op}" not supported on the delivery control service`}}checkDurableChannelArg(args,op,opts={}){const channel=typeof args.channel==="string"?args.channel.trim():"";if(!channel)return{ok:false,error:`${op}: channel must be a non-blank string`};try{assertValidChannel(channel)}catch(e){return{ok:false,error:e.message}}if(opts.family&&isChannelFamily(channel))return channel;if(!isConcreteChannel(channel))return{ok:false,error:opts.family?`${op}: "${channel}" stays live only: a durable membership takes a concrete channel or a family such as review.>, never the root > or a pattern with *`:`${op}: "${channel}" must be a concrete channel (durable membership is per-concrete-channel, not wildcard)`};return channel}async deliveryJoin(caller,args){const channel=this.checkDurableChannelArg(args,"durableJoin",{family:true});if(typeof channel!=="string")return channel;let acl;try{acl=await this.aclForAlias(caller)}catch(e){return{ok:false,error:e.message}}if(acl===void 0)return{ok:false,error:`durableJoin: no read ACL on record for ${caller} (not provisioned for durable delivery)`};if(!membershipInAllow(acl.allowSubscribe,channel))return{ok:false,error:`channel "${channel}" is not within your read ACL [${acl.allowSubscribe.join(", ")}]`};const uid2=acl.lifecycleUid;try{return{ok:true,data:await this.membershipWrite(caller,uid2,()=>this.durableJoinFor(caller,channel,uid2,{aclFence:true}))}}catch(e){return{ok:false,error:e.message}}}async lifecycleAclUnfenced(principal,lifecycleUid){try{const row=await readAcl(await this.aclRegistry(),principal,lifecycleUid);return row!==void 0&&row.record.allowSubscribe.length>0}catch{return true}}async membershipWrite(principal,lifecycleUid,write){if(this.retiringLifecycles.get(principal)?.has(lifecycleUid))throw new Error(`lifecycle ${lifecycleUid} of ${principal} is retiring: its membership inventory was requested, so its durable memberships no longer change`);const key=`${principal}/${lifecycleUid}`;const running=write();let writes=this.membershipWrites.get(key);if(writes===void 0)this.membershipWrites.set(key,writes=new Set);writes.add(running);try{return await running}finally{writes.delete(running);if(writes.size===0)this.membershipWrites.delete(key)}}async deliveryLeave(caller,args){const channel=this.checkDurableChannelArg(args,"durableLeave",{family:true});if(typeof channel!=="string")return channel;if(typeof args.generation!=="number"||!Number.isFinite(args.generation))return{ok:false,error:"durableLeave: a finite generation is required (fail-closed stale-leave guard)"};if(typeof args.lifecycleUid!=="string")return{ok:false,error:"durableLeave: the leaving incarnation's lifecycleUid is required (membership rows are lifecycle-keyed, SPEC 13.1)"};let uid2;try{uid2=assertLifecycleToken(args.lifecycleUid)}catch(e){return{ok:false,error:e.message}}const existing=await readMember(await this.membersRegistry(),channel,caller,uid2);if(!existing)return{ok:true,data:{channel,alreadyLeft:true}};const generation=args.generation;try{await this.membershipWrite(caller,uid2,()=>this.durableLeaveFor(caller,channel,uid2,generation))}catch(e){return{ok:false,error:e.message}}return{ok:true,data:{channel}}}async deliveryReadHistory(caller,args){const channel=this.checkDurableChannelArg(args,"readHistory");if(typeof channel!=="string")return channel;const asked=args.limit===void 0?READ_HISTORY_DEFAULT_LIMIT:args.limit;if(typeof asked!=="number"||!Number.isInteger(asked)||asked<1)return{ok:false,error:`readHistory: limit must be a positive integer (got ${JSON.stringify(args.limit)})`};const limit=Math.min(asked,READ_HISTORY_MAX_LIMIT);let acl;try{acl=await this.aclForAlias(caller)}catch(e){return{ok:false,error:e.message}}if(acl===void 0)return{ok:false,error:`readHistory: no read ACL on record for ${caller} - not permitted`};const inLive=channelInAllow(acl.allowSubscribe,channel);const inIssued=channelInAllow(acl.issuedAllowSubscribe,channel);if(!inLive||!inIssued){return{ok:false,error:`readHistory: channel "${channel}" is not within your read ACL [${acl.allowSubscribe.join(", ")}] - refused`}}let page;try{page=await this.channelHistory(channel,{limit:limit+1})}catch(e){return{ok:false,error:`readHistory: ${e.message}`}}const reachedStart=page.length<=limit;const wanted=reachedStart?page:page.slice(-limit);const fitted=fitHistoryPage(wanted,this.maxPayload);if(wanted.length>0&&fitted.length===0)return{ok:false,error:`readHistory: the newest message on "${channel}" alone exceeds the broker payload budget (${this.maxPayload} bytes) - refused loudly rather than served as an empty page`};return{ok:true,data:{items:fitted,complete:reachedStart&&fitted.length===wanted.length}}}async quiescePlane3(){this.plane3Quiesced=true;if(this.deliveryServeSub){try{this.deliveryServeSub.unsubscribe()}catch{}this.deliveryServeSub=void 0}if(this.deliveryAdminServeSub){try{this.deliveryAdminServeSub.unsubscribe()}catch{}this.deliveryAdminServeSub=void 0}this.dropAnycastRequests();for(const msgs of this.streamMsgs.splice(0)){try{msgs.stop()}catch{}}}plane3IsQuiesced(){return this.plane3Quiesced}async rearmPlane3(){if(!this.plane3Quiesced)return;this.plane3Quiesced=false;try{await this.armPlane3()}catch(e){this.plane3Quiesced=true;this.quiescePlane3();throw e}}async armPlane3(){if(!this.plane3||!this.js)return;if(this.plane3Quiesced)return;await this.manager();this.armDeliveryControl();await this.armAnycastRequests();await this.runFanout();await this.runReader()}armDeliveryControl(){if(this.deliveryServeSub){try{this.deliveryServeSub.unsubscribe()}catch{}const i=this.subs.indexOf(this.deliveryServeSub);if(i>=0)this.subs.splice(i,1)}this.deliveryServeSub=this.serveControl(CONTROL_DELIVERY,req=>this.handleDeliveryControl(req),{boundReply:true,concurrent:req=>ANYCAST_CONTROL_OPS.has(req.op)});if(this.deliveryAdminServeSub){try{this.deliveryAdminServeSub.unsubscribe()}catch{}const i=this.subs.indexOf(this.deliveryAdminServeSub);if(i>=0)this.subs.splice(i,1)}this.deliveryAdminServeSub=this.serveControl(CONTROL_DELIVERY_ADMIN,req=>this.handleDeliveryAdmin(req),{boundReply:true,concurrent:req=>req.op==="lifecycleMemberships"})}async armAnycastRequests(){if(!this.nc||!this.jsm)return;this.dropAnycastRequests();const definition=anycastStoreDefinition(this.space);let kv;try{kv=await new import_kv7.Kvm(this.nc).create(definition.bucket,definition.createOptions)}catch(e){if(!isPermissionDenied(e))throw e;this.anycastUnavailable=ANYCAST_RECORDS_CREDENTIAL_OUTDATED;this.emitRecoverable(new Error(`delivery: ${ANYCAST_RECORDS_CREDENTIAL_OUTDATED}`));return}this.anycastUnavailable=void 0;const authority=new AnycastRequestAuthority({jsm:this.jsm,kv,stream:taskStream(this.space),send:(to,event)=>this.sendAnycastNotice(to,event),mayAct:()=>this.plane3MayAct(),onError:e=>this.emitRecoverable(e)});this.anycastAuthority=authority;this.takeServeSub=this.serveTakes(authority);const sweep=()=>void authority.sweep().catch(e=>this.emitRecoverable(e));this.anycastSweep=setInterval(sweep,ANYCAST_SWEEP_MS);this.anycastSweep.unref?.();sweep()}dropAnycastRequests(){if(this.takeServeSub){try{this.takeServeSub.unsubscribe()}catch{}const i=this.subs.indexOf(this.takeServeSub);if(i>=0)this.subs.splice(i,1);this.takeServeSub=void 0}clearInterval(this.anycastSweep);this.anycastSweep=void 0;this.anycastAuthority=void 0}serveTakes(authority){const sub=this.nc.subscribe(takeServeFilter(this.space),{queue:TAKE_ROUTE});this.subs.push(sub);void(async()=>{for await(const m of sub){if(!m.reply||!m.reply.startsWith(`${m.subject}.reply.`)){this.emitRecoverable(new Error(`rejected take on ${m.subject}: reply target "${m.reply??"(none)"}" is not under the sender's own reply subtree`));continue}void this.answerTake(authority,m).catch(e=>this.emitRecoverable(e))}})().catch(e=>this.emitRecoverable(e));return sub}async answerTake(authority,m){let reply;if(this.takesInFlight>=MAX_TAKES_IN_FLIGHT)reply={ok:false,code:"busy",error:"the delivery daemon is answering too many takes; retry"};else{this.takesInFlight++;try{reply=await this.takeFor(authority,m)}catch(e){reply={ok:false,code:"busy",error:`the take could not be recorded: ${e.message}`}}finally{this.takesInFlight--}}m.respond(JSON.stringify(reply))}async takeFor(authority,m){if(!this.plane3MayAct())return{ok:false,code:"busy",error:"delivery: this daemon is not serving this shard (it is re-checking ownership); retry"};const parsed=parseTakeSubject(m.subject);let req;try{req=m.json()}catch{req=void 0}if(!parsed||!isPrincipalOwnerToken(parsed.owner)||req?.from?.id!==parsed.sender||typeof req.from.name!=="string")return{ok:false,code:"mismatch",error:"sender mismatch - take rejected"};if(!isAnycastSeq(req.seq)||!isAnycastSeq(req.count)||typeof req.id!=="string"||req.id.length>256||typeof req.epoch!=="string"||req.epoch.length>64)return{ok:false,code:"mismatch",error:"a take names a seq, the request id, a delivery count and the stream's creation time"};try{assertValidName(req.from.name)}catch(e){return{ok:false,code:"mismatch",error:`a take names its holder by a valid display name: ${e.message}`}}return authority.take(parsed.role,{from:{id:parsed.sender,name:req.from.name},seq:req.seq,id:req.id,count:req.count,epoch:req.epoch})}async sendAnycastNotice(to,event){if(!this.js)throw new Error(this.notLiveMsg());const recipient=parsePrincipalKey(to);if(!recipient)throw new Error(`anycast notice: "${to}" is not a principal`);const msg={id:event.key,ts:Date.now(),space:this.space,from:this.ref(),to,parts:[{kind:"text",text:event.text},{kind:"data",data:{[ANYCAST_NOTICE_KEY]:event.notice}}]};await this.js.publish(unicastSubject(this.space,recipient.owner,recipient.actor,this.owner,this.actor),JSON.stringify(msg),{msgID:msg.id})}async deliveryAnycast(op,caller,args){const authority=this.anycastAuthority;if(!authority)return{ok:false,error:`delivery: ${this.anycastUnavailable??"the anycast request records are not open on this daemon; retry"}`};if(!isAnycastSeq(args.seq))return{ok:false,error:`${op}: seq must be a whole number of at least 1`};if(args.id!==void 0&&(typeof args.id!=="string"||args.id.length>256))return{ok:false,error:`${op}: id must be a request id`};const q={seq:args.seq,...typeof args.id==="string"?{id:args.id}:{}};try{const status2=op===ANYCAST_CANCEL_OP?await authority.cancel(caller,q):await authority.status(caller,q);if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon stopped serving this shard while the request was in flight; retry"};return{ok:true,data:status2}}catch(e){return{ok:false,error:e.message}}}serveLiveness(plane,readState){if(!this.nc)throw new Error(this.notLiveMsg());const held2=this.livenessResponders.get(plane);if(held2)held2.readState=readState;else this.livenessResponders.set(plane,{readState});this.bindLiveness(plane)}bindLiveness(plane){const held2=this.livenessResponders.get(plane);if(!held2||!this.nc)return;if(held2.sub){try{held2.sub.unsubscribe()}catch{}const i=this.subs.indexOf(held2.sub);if(i>=0)this.subs.splice(i,1)}const{readState}=held2;const sub=this.nc.subscribe(livenessServeFilter(this.space,plane),{queue:`live.${plane}`});held2.sub=sub;this.subs.push(sub);const instance=(0,import_node_crypto10.randomUUID)();void(async()=>{for await(const m of sub){if(!m.reply||!m.reply.startsWith(`${m.subject}.reply.`)){this.emitRecoverable(new Error(`rejected liveness probe on ${m.subject}: reply target "${m.reply??"(none)"}" is not under the sender's own reply subtree`));continue}let responder;try{responder=await readState()}catch{responder="unknown"}const answer={plane,responder,instance};try{m.respond(JSON.stringify(answer))}catch{}}})().catch(e=>this.emit("error",e))}serveDeliveryLiveness(shardIndex=0){this.serveLiveness("delivery",async()=>responderFromLease(await this.readDeliveryLease(shardIndex),this.card.id))}async probeLiveness(plane,timeoutMs=2e3){if(!isLivenessPlane(plane))throw new Error(`liveness: "${plane}" is not a plane this surface answers for (${[...LIVENESS_PLANES].join(", ")})`);if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=livenessSubject(this.space,plane,this.owner,this.actor);const reply=`${reqSubject}.reply.${(0,import_node_crypto10.randomUUID)()}`;let outcome;let answered;let instance;try{const m=await this.requestBoundReply(this.nc,reqSubject,"",reply,timeoutMs);let body;try{body=m.json()}catch{body=void 0}const parsed=parseLivenessAnswer(body,plane);outcome=parsed?"replied":"malformed";answered=parsed?.responder;instance=parsed?.instance}catch(e){outcome=this.isNoResponders(e)?"noResponders":this.probeFailureOutcome(e)}const verdict={plane,responder:responderFromProbe(outcome,answered)};return instance===void 0?verdict:{...verdict,instance}}probeFailureOutcome(e){if(e instanceof import_transport_node13.AuthorizationError||e instanceof import_transport_node13.PermissionViolationError)return"refused";if(e instanceof import_transport_node13.TimeoutError)return"timeout";return"refused"}async handleDeliveryAdmin(req){await this.residentSwap;if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon is not serving this shard (it is re-checking ownership); retry"};if(req.op==="reloadCreds"){if(this.plane3?.startupComplete?.()===false)return{ok:false,error:"delivery: this daemon has not finished starting; nothing adopted - the next renewal pass or the daemon's 75% re-read adopts the re-signed creds"};const expected=req.args?.expected??{};const[delivery,membership]=await Promise.all([this.reloadCreds(expected.delivery).then(brokerAccepted=>({ok:true,brokerAccepted,residentSwap:"scheduled"}),e=>({ok:false,error:e.message})),this.plane3?.reloadMembershipCreds?this.plane3.reloadMembershipCreds(expected.membership).then(result=>({ok:true,...result}),e=>({ok:false,error:e.message})):Promise.resolve({ok:true,skipped:"no-membership-hook"})]);const failures=[delivery.ok?void 0:`delivery: ${delivery.error}`,membership.ok?void 0:`membership: ${membership.error}`].filter(m=>m!==void 0);if(delivery.ok){this.plane3?.onDeliveryCredsAdopted?.();this.scheduleResidentSwap()}return failures.length?{ok:false,error:failures.join("; "),data:{delivery,membership}}:{ok:true,data:{delivery,membership}}}if(req.op==="evictPrincipal"){if(!this.plane3?.evictPrincipal)return{ok:false,error:"evictPrincipal: no eviction executor wired on this daemon"};const principal=typeof req.args?.principal==="string"?req.args.principal.trim():"";if(!principal)return{ok:false,error:"evictPrincipal: a principal (owner.actor dot-form) is required"};try{return{ok:true,data:await this.plane3.evictPrincipal(principal)}}catch(e){return{ok:false,error:e.message}}}if(req.op==="evictPrincipals"){if(!this.plane3?.evictPrincipals)return{ok:false,error:"evictPrincipals: no batch eviction executor wired on this daemon"};const raw=req.args?.principals;const principals=Array.isArray(raw)?raw.map(p=>typeof p==="string"?p.trim():""):[];if(principals.length===0||principals.some(p=>!p))return{ok:false,error:"evictPrincipals: principals must be a non-empty array of owner.actor dot-form principals"};if(principals.length>EVICT_PRINCIPALS_MAX||new Set(principals).size!==principals.length)return{ok:false,error:`evictPrincipals: principals must be distinct and at most ${EVICT_PRINCIPALS_MAX}`};try{return{ok:true,data:await this.plane3.evictPrincipals(principals)}}catch(e){return{ok:false,error:e.message}}}if(req.op==="planeConnLiveness"){if(!this.plane3?.planeConnLiveness)return{ok:false,error:"planeConnLiveness: no plane-liveness oracle wired on this daemon"};try{return{ok:true,data:await this.plane3.planeConnLiveness(req.args?.query)}}catch(e){return{ok:false,error:e.message}}}if(req.op==="lifecycleMemberships"){const principal=typeof req.args?.principal==="string"?req.args.principal.trim():"";const uid2=typeof req.args?.lifecycleUid==="string"?req.args.lifecycleUid:"";if(!parsePrincipalKey(principal))return{ok:false,error:"lifecycleMemberships: a principal (owner.actor dot-form) is required"};try{assertLifecycleToken(uid2)}catch(e){return{ok:false,error:`lifecycleMemberships: ${e.message}`}}let marked=this.retiringLifecycles.get(principal);if(marked===void 0)this.retiringLifecycles.set(principal,marked=new Set);for(const earlier of[...marked])if(earlier!==uid2&&await aclRetired(await this.aclRegistry(),principal,earlier).catch(()=>false))marked.delete(earlier);if(await this.lifecycleAclUnfenced(principal,uid2))marked.add(uid2);else if(marked.size===0)this.retiringLifecycles.delete(principal);await Promise.allSettled(this.membershipWrites.get(`${principal}/${uid2}`)??[]);try{const channels=await listLifecycleMemberChannels(await this.membersRegistry(),principal,uid2);return{ok:true,data:{complete:true,channels}}}catch(e){return{ok:false,error:`lifecycleMemberships: the inventory read did not complete (${e.message})`}}}if(req.op==="principalLiveness"){if(!this.plane3?.principalLiveness)return{ok:false,error:"principalLiveness: no liveness oracle wired on this daemon"};const principal=typeof req.args?.principal==="string"?req.args.principal.trim():"";if(!principal)return{ok:false,error:"principalLiveness: a principal (owner.actor dot-form) is required"};try{return{ok:true,data:await this.plane3.principalLiveness(principal)}}catch(e){return{ok:false,error:e.message}}}if(req.op==="reloadStoreIdentity"){if(!this.plane3?.reloadStoreIdentity)return{ok:false,error:"reloadStoreIdentity: this daemon did not name the SecretStore it reloads from"};try{const identity=this.plane3.reloadStoreIdentity();let holdsDeliveryLease=false;try{const own=await this.readDeliveryLeaseEntry(0);holdsDeliveryLease=own!==void 0&&this.ownsDeliveryLease(own.info)}catch{holdsDeliveryLease=false}return{ok:true,data:{identity:parseSecretStoreIdentity(identity),responder:this.card.id,holdsDeliveryLease}}}catch(e){return{ok:false,error:e.message}}}return{ok:false,error:`op "${req.op}" not supported on the delivery admin service`}}async addPlane3Durable(stream,config2){try{await this.jsm.consumers.add(stream,config2)}catch(e){if(!isConsumerAlreadyExists(e)||!isRestoredConsumer(this.space,stream,await this.jsm.consumers.info(stream,config2.durable_name),config2))throw e}}async runFanout(){if(!this.js||!this.jsm)return;await this.addPlane3Durable(chatStream(this.space),fanoutDurableConfig(this.space,{ackWaitMs:this.ackWaitMs}));const consumer=await this.js.consumers.get(chatStream(this.space),FANOUT_DURABLE);const msgs=await consumer.consume();this.streamMsgs.push(msgs);void(async()=>{for await(const m of msgs){try{await this.fanOutMessage(m)}catch(e){if(!this.stopped)this.emit("error",e);try{m.nak()}catch{}}}})().catch(e=>{if(!this.stopped)this.emit("error",e)})}async fanOutMessage(m){if(!this.plane3MayAct())return;const parsed=parseSubject(m.subject);if(!parsed||parsed.kind!=="chat"){m.ack();return}const channel=parsed.rest;let msg;try{msg=m.json()}catch{m.ack();return}if(!isFromSubjectSender(msg,parsed)){m.ack();return}const seq=m.seq;const normalizedMsg=authenticatedChannelMessage(msg,channel);if(!this.plane3MayAct())return;if(await this.deliveryClassFresh(channel)==="durable"){for(const rec of await listMembers(await this.membersRegistry(),{covering:channel})){if(rec.owner===msg.from.id)continue;if(!durableEligible(rec,seq))continue;if(!this.plane3MayAct())return;await this.publishDinbox(rec.owner,rec.lifecycleUid,{msg:normalizedMsg,channel,seq,reason:"durable-channel",generation:rec.generation,...rec.channel!==channel?{row:rec.channel}:{}})}}else{for(const name of msg.mentions??[]){const owner2=this.resolveOwnerByName(name);if(!owner2||owner2===msg.from.id)continue;let row;try{row=await this.aclForAlias(owner2)}catch(e){this.emit("error",e);continue}if(!row||!channelInAllow(row.allowSubscribe,channel))continue;if(!this.plane3MayAct())return;await this.publishDinbox(owner2,row.lifecycleUid,{msg:normalizedMsg,channel,seq,reason:"live-mention",generation:0})}}if(!this.plane3MayAct())return;m.ack()}deliveryLimitRead;async deliveryLimitStamp(){const at=Date.now();if(this.deliveryLimitRead&&at-this.deliveryLimitRead.at<DELIVERY_LIMIT_READ_MS)return this.deliveryLimitRead.stamp;const count=(await this.jsm.streams.info(dlvStream(this.space))).config.max_msgs_per_subject;const stamp=count===HISTORY_NO_COUNT||count<1?"none":String(count);this.deliveryLimitRead={at,stamp};return stamp}async runReader(){if(!this.js||!this.jsm)return;await this.addPlane3Durable(inboxStream(this.space),inboxReaderConfig(this.space,{ackWaitMs:this.ackWaitMs}));const consumer=await this.js.consumers.get(inboxStream(this.space),INBOX_READER_DURABLE);const msgs=await consumer.consume();this.streamMsgs.push(msgs);void(async()=>{for await(const m of msgs){try{await this.readerHandle(m)}catch(e){if(!this.stopped)this.emit("error",e);try{m.nak()}catch{}}}})().catch(e=>{if(!this.stopped)this.emit("error",e)})}async lifecycleCoversPost(owner2,lifecycleUid,channel,seq){const kv=await this.membersRegistry();for(const row of[channel,...familiesCovering(channel).reverse()]){const rec=await readMember(kv,row,owner2,lifecycleUid);if(rec&&durableEligible(rec.record,seq))return true}return false}async removeRetiredMemberRow(channel,owner2,lifecycleUid){try{const kv=await this.membersRegistry();if(await readMember(kv,channel,owner2,lifecycleUid)===void 0)return;await deleteMember(kv,channel,owner2,lifecycleUid)}catch(e){this.emit("warning",new Error(`plane-3 reader: could not remove retired lifecycle ${owner2}.${lifecycleUid}'s "${channel}" member row: ${e.message}`))}}async readerHandle(m){if(!this.plane3MayAct())return;const pr=parseDinboxPrincipal(m.subject);if(!pr){m.ack();return}const owner2=`${pr.owner}.${pr.actor}`;let entry;try{entry=m.json()}catch{m.ack();return}if(!isRecord(entry)){m.ack();return}const redeliveries=m.info?.deliveryCount??1;const acl=await this.plane3?.aclFor(owner2,pr.lifecycleUid);if(acl===void 0){if(await aclRetired(await this.aclRegistry(),owner2,pr.lifecycleUid)){if(!this.plane3MayAct())return;let failure;try{await this.jsm.streams.deleteMessage(inboxStream(this.space),m.seq,false)}catch(e){if(!isJetStreamMissing(e,10043))failure=e instanceof Error?e:new Error(String(e))}if(!this.plane3MayAct())return;if(failure){if(redeliveries>=READER_MAX_REDELIVERIES){m.term();this.emit("error",new Error(`plane-3 reader: gave up removing entry ${m.seq} for retired lifecycle ${owner2}.${pr.lifecycleUid} after ${redeliveries} redeliveries: ${failure.message}`));return}m.nak(2e3);return}if(entry.reason==="durable-channel")await this.removeRetiredMemberRow(entry.row??entry.channel,owner2,pr.lifecycleUid);if(!this.plane3MayAct())return;m.ack();return}if(redeliveries>=READER_MAX_REDELIVERIES){m.term();this.emit("error",new Error(`plane-3 reader: gave up on entry for unknown owner ${owner2} after ${redeliveries} redeliveries`));return}m.nak(2e3);return}if(!channelInAllow(acl,entry.channel)){m.ack();return}if(entry.reason==="durable-channel"&&!await this.lifecycleCoversPost(owner2,pr.lifecycleUid,entry.channel,entry.seq)){m.ack();return}if(!this.plane3MayAct())return;try{const frame={version:1,channel:entry.channel,msg:authenticatedChannelMessage(entry.msg,entry.channel)};const frameHeaders=(0,import_transport_node13.headers)();frameHeaders.set(PLANE3_FRAME_HEADER,"1");frameHeaders.set(DELIVERY_LIMIT_HEADER,await this.deliveryLimitStamp());if(!this.plane3MayAct())return;await this.js.publish(dlvSubject(this.space,pr.owner,pr.actor,pr.lifecycleUid),JSON.stringify(frame),{...this.plane3MsgId(entry,`${owner2}:${pr.lifecycleUid}`),headers:frameHeaders})}catch{if(redeliveries>=READER_MAX_REDELIVERIES){m.term();this.emit("error",new Error(`plane-3 reader: gave up transferring ${entry.msg.id} for ${owner2} after ${redeliveries} redeliveries`));return}m.nak(2e3);return}if(!this.plane3MayAct())return;m.ack()}async pumpDlv(){if(!this.js)return;if(!this.ownLifecycleUid)return;const durable=dlvDurable(this.owner,this.actor,this.ownLifecycleUid);let consumer;try{consumer=await this.js.consumers.get(dlvStream(this.space),durable)}catch(e){if(isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.ConsumerNotFound))return;throw e}const lease=await this.readDeliveryLease(0);const liveDeliveryPlane=lease?.ready===true;if(!liveDeliveryPlane)this.emit("warning",new Error(`delivery durable "${durable}" for space "${this.space}" bound while the plane this connection reaches has no ready delivery lease, so the durable delivers nothing until a delivery daemon serves this plane. If a daemon serves this space on another plane, reconnect against it, which re-binds the durable there.`));const ackWaitMs=await ackWaitOf(consumer);const msgs=await consumer.consume();this.streamMsgs.push(msgs);void(async()=>{for await(const m of msgs){let limit;try{limit=deliveryLimitOf(m.headers?.get(DELIVERY_LIMIT_HEADER))}catch(e){this.emit("error",e);limit=null}if(limit!==null&&m.info.pending>=limit-1)this.emit("stored-copies-full",{limit});if(m.headers?.get(PLANE3_FRAME_HEADER)!=="1"){this.emit("error",new Error("plane-3 delivery: unauthenticated or unversioned DLV entry terminated"));try{m.term()}catch{}continue}let raw;try{raw=m.json()}catch(e){this.emit("error",e);try{m.term()}catch{}continue}if(!isPlane3DeliveryFrame(raw)){this.emit("error",new Error("plane-3 delivery: malformed versioned DLV entry terminated"));try{m.term()}catch{}continue}const msg=authenticatedChannelMessage(raw.msg,raw.channel);if(msg.from?.id===this.card.id){m.ack();continue}this.emit("message",msg,durableDelivery(m,ackWaitMs),{historical:false,kind:"channel"})}})().catch(e=>{if(!this.stopped)this.emit("error",e)})}async durableJoinChannel(channel){const reply=await this.requestDelivery("durableJoin",{channel},3e4);if(!reply.ok)throw new Error(reply.error??"durable join rejected");return reply.data??{durable:false}}async durableLeaveChannel(channel,generation){const lifecycleUid=this.requireLifecycleUid("leaving a durable channel");const reply=await this.requestDelivery("durableLeave",{channel,generation,lifecycleUid});if(!reply.ok)throw new Error(reply.error??"durable leave rejected")}async closeRefusedMembership(channel,generation){this.pendingDurableLeave.set(channel,generation);for(let attempt=0;;attempt++){if(this.stopped)return;try{await this.durableLeaveChannel(channel,generation);this.plane3Channels.delete(channel);this.pendingDurableLeave.delete(channel);return}catch(e){if(attempt===0)this.emitRecoverable(new Error(`channel "${channel}": Plane-3 durable membership (generation ${generation}) not yet tombstoned after a refused live sub - retrying; \xA77 boundary may be open until it succeeds (${e.message})`));await new Promise(r=>setTimeout(r,Math.min(3e4,1e3*2**attempt)))}}}pendingDurableLeaves(){return[...this.pendingDurableLeave.keys()]}isNoResponders(e){return e instanceof import_transport_node13.NoRespondersError||e instanceof import_transport_node13.RequestError&&e.isNoResponders()}async takeAnycast(role,seq,id2,count,epoch,nak){const nc=this.nc;if(!nc)return{taken:false,drop:false,reason:"daemon-down",detail:this.notLiveMsg()};const held2=(reason2,detail)=>({taken:false,drop:false,reason:reason2,detail});const subject=takeSubject(this.space,role,this.owner,this.actor);const body={from:{id:this.card.id,name:this.card.name},seq,id:id2,count,epoch};let reply;try{const m=await this.requestBoundReply(nc,subject,JSON.stringify(body),`${subject}.reply.${(0,import_node_crypto10.randomUUID)()}`,ANYCAST_TAKE_TIMEOUT_MS);reply=m.json()}catch(e){if(isPermissionDenied(e))return held2("credential-outdated","this seat's credential was minted before anycast takes existed, so it cannot take role requests; respawn the seat to get a current credential");if(this.isNoResponders(e))return this.takeResponderMissing();return held2("daemon-down",`the delivery daemon did not answer the take: ${e.message}`)}if(reply.ok)return{taken:true};if(reply.code==="mismatch"){const current=await this.readTaskEpoch().catch(()=>void 0);if(current!==void 0&¤t!==epoch)nak()}if(reply.code==="cancelled"||reply.code==="taken"||reply.code==="gone"||reply.code==="mismatch")return{taken:false,drop:true,reason:reply.code,detail:reply.error};return held2("daemon-busy",reply.error)}async takeResponderMissing(){const held2=(reason2,detail)=>({taken:false,drop:false,reason:reason2,detail});let reply;try{reply=await this.requestDelivery(ANYCAST_TAKES_OP,{},ANYCAST_TAKE_TIMEOUT_MS)}catch{return held2("daemon-down","no delivery daemon is answering on this mesh, so role requests wait on the queue until one does")}if(!reply.ok&&/not supported on the delivery control service/.test(reply.error??""))return held2("daemon-outdated","the delivery daemon predates anycast takes, so this seat holds role requests until the daemon is restarted at this version (`cotal up` runs it)");if(!reply.ok&&reply.error?.includes(ANYCAST_RECORDS_CREDENTIAL_OUTDATED))return held2("daemon-outdated",`this seat holds role requests until the delivery daemon can record takes: ${ANYCAST_RECORDS_CREDENTIAL_OUTDATED}`);return held2("daemon-down","the delivery daemon is not answering takes, so role requests wait on the queue until it does")}async anycastStatus(seq,id2){return this.anycastRequest(ANYCAST_STATUS_OP,seq,id2)}async cancelAnycast(seq,id2){return this.anycastRequest(ANYCAST_CANCEL_OP,seq,id2)}async anycastRequest(op,seq,id2){if(!this.authed)throw new Error("an open mesh runs no delivery daemon, so it keeps no record of anycast requests");if(!isAnycastSeq(seq))throw new Error(`seq must be a whole number of at least 1, got ${seq}`);let reply;try{reply=await this.requestDelivery(op,{seq,...id2!==void 0?{id:id2}:{}},1e4)}catch(e){if(this.isNoResponders(e))throw new Error("no delivery daemon is answering on this mesh, so the request's record cannot be read");throw e}if(!reply.ok){if(/not supported on the delivery control service/.test(reply.error??""))throw new Error("the delivery daemon predates anycast request status; restart it at this version (`cotal up` runs it)");throw new Error(reply.error??`${op} failed`)}return reply.data}async fetchMemberships(){let reply;try{reply=await this.requestDelivery("listMemberships",{lifecycleUid:this.requireLifecycleUid("listing durable memberships")},5e3)}catch(e){if(this.isNoResponders(e))return void 0;throw e}if(!reply.ok)throw new Error(reply.error??"listMemberships failed");return reply.data?.memberships??[]}async armBootDurableMemberships(){for(const channel of this.channels){if(this.plane3Channels.has(channel))continue;if(!isChannelFamily(channel)){if(!isConcreteChannel(channel))continue;const cls=await this.deliveryClassFresh(channel);if(cls!=="durable")continue}try{const r=await this.durableJoinChannel(channel);if(r.durable)this.plane3Channels.set(channel,r.generation??0);else void this.reconcileBootJoin(channel)}catch(e){if(!this.isNoResponders(e))this.emitRecoverable(e);void this.reconcileBootJoin(channel)}}}async reconcileBootJoin(channel){if(this.pendingBootJoins.has(channel))return;this.pendingBootJoins.add(channel);for(let attempt=0;;attempt++){await new Promise(r=>setTimeout(r,Math.min(3e4,1e3*2**attempt)));if(this.stopped||!this.channels.includes(channel)||this.plane3Channels.has(channel)){this.pendingBootJoins.delete(channel);return}try{const r=await this.durableJoinChannel(channel);if(r.durable){this.plane3Channels.set(channel,r.generation??0);this.pendingBootJoins.delete(channel);return}}catch(e){if(attempt===0&&!this.isNoResponders(e))this.emitRecoverable(new Error(`channel "${channel}": boot durable self-join not yet established - retrying until the delivery daemon is reachable (${e.message})`))}}}hasDurableMembership(channel){return this.plane3Channels.has(channel)}async manager(){if(!this.nc)throw new Error(this.notLiveMsg());this.jsm??=await(0,import_jetstream13.jetstreamManager)(this.nc);return this.jsm}async startConsumers(){if(!this.jsm)throw new Error(this.notLiveMsg());const ownUid=this.requireLifecycleUid("consuming the DM inbox");if(!this.authed){await this.ensureDmDurable(this.owner,this.actor,ownUid,{ackWaitMs:this.ackWaitMs,inactiveThresholdMs:this.inactiveThresholdMs})}await this.pump(dmStream(this.space),dmDurable(this.owner,this.actor,ownUid),{inbox:true});await this.pumpDlv();if(this.channels.length){const armed2=this.firstConnect?await this.armJoin(this.channels):void 0;for(const ch of this.channels)this.subscribeChat(ch);await this.confirmChatSub();if(armed2)await this.backfillArmed(armed2,this.backfillFloor)}if(this.firstConnect&&this.authed&&this.channels.length)await this.armBootDurableMemberships();this.firstConnect=false;if(this.card.role){if(!this.authed){await this.jsm.consumers.add(taskStream(this.space),taskDurableConfig(this.space,this.card.role,{ackWaitMs:this.ackWaitMs}))}await this.pump(taskStream(this.space),taskDurable(this.card.role),this.authed?{takeRole:this.card.role}:{})}}async pump(stream,durable,opts={}){if(!this.js)throw new Error(this.notLiveMsg());const consumer=opts.takeRole===void 0?await this.js.consumers.get(stream,durable):await this.bindTaskConsumer(stream,durable);const ackWaitMs=await ackWaitOf(consumer);const msgs=await consumer.consume();this.streamMsgs.push(msgs);if(opts.inbox)this.watchInbox(msgs,stream,durable);void(async()=>{for await(const m of msgs){const authed=this.authenticateStreamMsg(m);if(!authed)continue;const{msg,parsed}=authed;const delivery=durableDelivery(m,ackWaitMs);const role=opts.takeRole;if(role!==void 0){const epoch=this.taskEpoch;delivery.take=()=>this.takeAnycast(role,m.seq,msg.id,m.info.deliveryCount,epoch,()=>m.nak())}this.emit("message",authenticatedMessage(msg,parsed),delivery,{historical:false,kind:kindFromParsed(parsed.kind)})}})().catch(e=>{if(!this.stopped)this.emit("error",e)})}async bindTaskConsumer(stream,durable){for(let attempt=0;attempt<3;attempt++){const before=await this.readTaskEpoch();const consumer=await this.js.consumers.get(stream,durable);if(before===await this.readTaskEpoch())return consumer}throw new Error(`the ${stream} stream was recreated while its role consumer was binding; reconnect to bind it again`)}async readTaskEpoch(){const epoch=(await(await this.manager()).streams.info(taskStream(this.space))).created;this.taskEpoch=epoch;return epoch}watchInbox(msgs,stream,durable){const boundNc=this.nc;void(async()=>{let absences=0;let deleted=false;for await(const s of msgs.status()){if(this.stopped||this.nc!==boundNc)break;if(s.type==="next"){absences=0;deleted=false;continue}if(s.type==="consumer_deleted"){if(deleted)continue;deleted=true;absences=1}else if(s.type!=="consumer_not_found"&&s.type!=="stream_not_found")continue;if(++absences===2)this.emitRecoverable(new Error(`DM inbox missing: the broker reports consumer "${durable}" on stream "${stream}" missing, so direct messages to this endpoint are not delivered. The endpoint keeps checking; if the inbox does not come back, end this session and start a new one`))}})().catch(e=>{if(!this.stopped)this.emit("error",e)})}authenticateStreamMsg(m){let msg;try{msg=m.json()}catch(e){m.term();this.emit("error",e);return void 0}if(!isRecord(msg)||!isUsableMessageId(msg.id)){m.term();this.emit("error",new Error(`dropped message on ${m.subject}: absent or non-string id`));return void 0}const parsed=parseSubject(m.subject);if(!parsed||!isFromSubjectSender(msg,parsed)){m.term();this.emit("error",new Error(`dropped message on ${m.subject}: payload from ${msg.from?.id??"(none)"} does not match subject sender ${parsed?.sender??"(unparseable)"}`));return void 0}return{msg,parsed}}async bindDmOnly(mode){if(!this.js)throw new Error(this.notLiveMsg());const stream=dmStream(this.space);const durable=dmDurable(this.owner,this.actor,this.requireLifecycleUid("consuming the DM inbox"));let consumer;try{consumer=await this.js.consumers.get(stream,durable)}catch(e){if(isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.ConsumerNotFound))throw new DmDurableMissingError(stream,durable);throw new DmBindRefusedError(stream,durable,e)}const ackWaitMs=await ackWaitOf(consumer);if(this.dmOnlyInFlight){const settleMs=mode.settleTimeoutMs??3e4;await withDeadline(this.dmOnlyInFlight,settleMs,()=>new Error(`DM-only rebind waited ${settleMs}ms for the previous handler to settle; not reading the next DM yet`))}const msgs=await consumer.consume({max_messages:1});this.streamMsgs.push(msgs);const boundNc=this.nc;const retired=()=>this.stopped||this.nc!==boundNc||!boundNc||boundNc.isClosed();void(async()=>{for await(const m of msgs){if(retired())break;const authed=this.authenticateStreamMsg(m);if(!authed)continue;if(authed.parsed.kind!=="inst"){m.term();continue}const run=Promise.resolve().then(()=>mode.handler(authenticatedMessage(authed.msg,authed.parsed),dmOnlyDelivery(m,ackWaitMs,boundNc),{historical:false,kind:"dm"}));const flight=run.then(()=>{},()=>{});this.dmOnlyInFlight=flight;try{await run}catch(e){this.emit("error",e instanceof Error?e:new Error(String(e)))}finally{if(this.dmOnlyInFlight===flight)this.dmOnlyInFlight=void 0}}})().catch(e=>{if(!this.stopped)this.emit("error",e)})}subscribeChat(channel){if(!this.nc||this.chatSubs.has(channel))return;this.chatSubDenied.delete(channel);const subject=chatSubject(this.space,"*","*",channel);const sub=this.nc.subscribe(subject,{callback:(err3,m)=>{if(err3){if(err3 instanceof import_transport_node13.PermissionViolationError)this.chatSubRefusals.add(err3);this.chatSubDenied.add(channel);this.chatSubs.delete(channel);const i=this.channels.indexOf(channel);if(i>=0){this.channels.splice(i,1);const gen=this.plane3Channels.get(channel);if(gen!==void 0)void this.closeRefusedMembership(channel,gen);this.emit("error",new Error(`left channel "${channel}": its live subscription was refused by the broker`,{cause:err3}))}return}const parsed=parseSubject(m.subject);if(!parsed||parsed.kind!=="chat")return;let msg;try{msg=m.json()}catch(e){this.emit("error",e);return}if(!isRecord(msg)||!isUsableMessageId(msg.id))return;if(!isFromSubjectSender(msg,parsed))return;if(msg.from.id===this.card.id)return;const delivery={ack:()=>{},nak:()=>{},durable:false};this.emit("message",authenticatedMessage(msg,parsed),delivery,{historical:false,kind:kindFromParsed(parsed.kind)})}});this.chatSubs.set(channel,sub)}unsubscribeChat(channel){const sub=this.chatSubs.get(channel);if(sub){try{sub.unsubscribe()}catch{}this.chatSubs.delete(channel)}this.chatSubDenied.delete(channel)}async confirmChatSub(){if(!this.nc)throw new Error("connection not established");await this.nc.flush();await new Promise(r=>setTimeout(r,50))}async consumerInfo(stream,durable){if(!this.jsm)throw new Error(this.notLiveMsg());try{return await this.jsm.consumers.info(stream,durable)}catch(e){if(isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.ConsumerNotFound))return null;throw e}}async deleteConsumerIfPresent(stream,durable){if(!this.jsm)throw new Error(this.notLiveMsg());try{await this.jsm.consumers.delete(stream,durable)}catch(e){if(!isJetStreamMissing(e,import_jetstream13.JetStreamApiCodes.ConsumerNotFound,import_jetstream13.JetStreamApiCodes.StreamNotFound))throw e}}async chatFrontier(){const jsm=await this.manager();return(await jsm.streams.info(chatStream(this.space))).state.last_seq}async storedBytes(){return(await(await this.manager()).getAccountInfo()).storage}async armJoin(channels){const frontiers=new Map;for(const ch of channels){frontiers.set(ch,await this.chatFrontier())}return frontiers}async backfillArmed(frontiers,floorSeq){let total=0;for(const[ch,frontier]of frontiers){const policy=await this.joinPolicyFresh(ch);if(policy.replay)total+=await this.backfillChannel(ch,frontier,policy.windowMs,floorSeq)}return total}async joinPolicyFresh(channel){if(!this.channelKv)return{replay:effectiveReplay(void 0,void 0)};const[cfg,defaults]=await Promise.all([isConcreteChannel(channel)?readChannelConfig(this.channelKv,channel):Promise.resolve(void 0),readChannelDefaults(this.channelKv)]);return{replay:effectiveReplay(cfg,defaults),windowMs:effectiveReplayWindowMs(cfg,defaults)}}async collectHistory(subject,start,opts={}){const run=this.histLock.then(()=>this.collectHistoryInner(subject,start,opts));this.histLock=run.catch(()=>{});return run}async collectHistoryInner(subject,start,opts={}){if(!this.jsm||!this.js)throw new Error(this.notLiveMsg());const stream=chatStream(this.space);const name=chatHistDurable(this.owner,this.actor,this.requireLifecycleUid("chat history reads"));const out=[];await this.deleteConsumerIfPresent(stream,name);await this.jsm.consumers.add(stream,{name,filter_subject:subject,ack_policy:import_jetstream13.AckPolicy.None,mem_storage:true,inactive_threshold:(0,import_transport_node13.nanos)(3e4),..."time"in start?{deliver_policy:import_jetstream13.DeliverPolicy.StartTime,opt_start_time:start.time.toISOString()}:{deliver_policy:import_jetstream13.DeliverPolicy.StartSequence,opt_start_seq:start.seq}});try{const consumer=await this.js.consumers.get(stream,name);let pending=(await consumer.info()).num_pending;while(pending>0){const want=Math.min(pending,256);const iter=await consumer.fetch({max_messages:want,expires:5e3});let got=0;for await(const m of iter){got++;if(opts.untilSeq!==void 0&&m.seq>opts.untilSeq)return out;if(!subjectMatches(subject,m.subject))continue;out.push(m);if(opts.limit!==void 0&&out.length>=opts.limit)return out}if(got<want)break;pending-=got}}finally{await this.deleteConsumerIfPresent(stream,name)}return out}async backfillChannel(channel,upToSeq,sinceMs,floorSeq){if(floorSeq!==void 0&&floorSeq>=upToSeq)return 0;const subject=chatSubject(this.space,"*","*",channel);const start=floorSeq!==void 0?{seq:floorSeq+1}:sinceMs===void 0?{seq:1}:{time:new Date(Date.now()-sinceMs)};let msgs;try{msgs=await this.collectHistory(subject,start,{untilSeq:upToSeq})}catch(e){this.emit("error",e);if(isPermissionDenied(e))throw e;return 0}const noop={ack:()=>{},nak:()=>{},durable:false};let n=0;for(const sm of msgs){let msg;try{msg=sm.json()}catch{continue}if(!isRecord(msg)||!isUsableMessageId(msg.id))continue;const parsed=parseSubject(sm.subject);if(!parsed||!isFromSubjectSender(msg,parsed)||msg.from.id===this.card.id)continue;this.emit("message",authenticatedMessage(msg,parsed),noop,{historical:true,kind:"channel"});n++}return n}async recallChannel(channel,sinceSeq){if(!this.jsm)throw new Error(this.notLiveMsg());if(!isConcreteChannel(channel))return{messages:[],seqs:[],dropped:false,unanswered:true};const policy=await this.joinPolicyFresh(channel);if(!policy.replay)return{messages:[],seqs:[],dropped:true,unanswered:true};const subject=chatSubject(this.space,"*","*",channel);let raw;try{raw=await this.collectHistory(subject,{seq:sinceSeq+1})}catch(e){this.emit("error",e);if(isPermissionDenied(e))throw e;return{messages:[],seqs:[],dropped:true,unanswered:true}}const collected=[];const seqs=[];for(const sm of raw){let msg;try{msg=sm.json()}catch{continue}if(!isRecord(msg)||!isUsableMessageId(msg.id))continue;const parsed=parseSubject(sm.subject);if(!parsed||!isFromSubjectSender(msg,parsed)||msg.from.id===this.card.id)continue;collected.push(authenticatedMessage(msg,parsed));seqs.push(sm.seq)}let dropped;try{dropped=await this.chatMayHaveLost(subject,sinceSeq)}catch(e){this.emit("error",e);if(isPermissionDenied(e))throw e;return{messages:[],seqs:[],dropped:true,unanswered:true}}return{messages:collected,seqs,dropped,unanswered:false}}async chatMayHaveLost(subject,sinceSeq){if(!this.jsm)throw new Error(this.notLiveMsg());const info=await this.jsm.streams.info(chatStream(this.space),{subjects_filter:subject});if(info.state.first_seq>sinceSeq+1)return true;const cap=info.config.max_msgs_per_subject;let maxPerSubject=0;for(const count of Object.values(info.state.subjects??{}))maxPerSubject=Math.max(maxPerSubject,count);if(cap<1||maxPerSubject<cap)return false;const oldest=(await this.collectHistory(subject,{seq:1},{limit:1}))[0]?.seq;return oldest!==void 0&&oldest>sinceSeq+1}async publishPresence(){if(!this.doRegister||!this.kv)return;const p={card:this.card,...this.ownLifecycleUid!==void 0?{lifecycleUid:this.ownLifecycleUid}:{},runtime:processRuntime(this.ownLifecycleUid),status:this.status,condition:this.condition,environment:this.environment,activity:this.activity,statusSince:this.statusSince,activitySince:this.activitySince,activeAt:this.activeAt,attention:this.attentionMode,channelModes:this.channelModes,ts:Date.now()};const record3=this.status==="offline"?this.toOffline(p):p;assertPresenceRow(record3,this.card.id);const epoch=this.presenceEpoch;const conditionRevision=this.conditionRevision;const generation=++this.presencePutGeneration;try{await this.kv.put(this.card.id,JSON.stringify(record3))}catch(e){const superseded2=(this.presencePutSettled??0)>generation;this.presencePutSettled=Math.max(this.presencePutSettled??0,generation);if(epoch===this.presenceEpoch&&!this.stopped&&!superseded2){this.presenceWriteFailingSince??=Date.now();this.lastPresenceWriteError=e?.message??String(e);this.presenceWriteFailures++;this.escalatePresenceWriteFailureIfStuck()}if(e instanceof import_transport_node13.TimeoutError)throw new Error(`${e.message}. The presence write outcome is unknown: the broker may have stored the update. Read the roster before retrying.`,{cause:e});throw e}const superseded=(this.presencePutSettled??0)>generation;this.presencePutSettled=Math.max(this.presencePutSettled??0,generation);if(epoch!==this.presenceEpoch||this.stopped||superseded)return;if(conditionRevision!==this.conditionRevision){await this.publishPresence();return}this.clearPresenceWriteFailure()}clearPresenceWriteFailure(){this.presenceWriteFailingSince=void 0;this.lastPresenceWriteError=void 0;this.presenceWriteFailures=0;this.presenceWriteEscalated=false}escalatePresenceWriteFailureIfStuck(){if(this.presenceWriteEscalated||this.presenceWriteFailingSince===void 0||this.presenceWriteFailures<2||Date.now()-this.presenceWriteFailingSince<this.ttlMs)return;this.presenceWriteEscalated=true;this.emitRecoverable(new PresenceWriteStuckError(presenceBucket(this.space),this.presenceWriteFailingSince,this.presenceWriteFailures,this.ttlMs,this.lastPresenceWriteError))}presenceWriteFailure(){if(this.presenceWriteFailingSince===void 0)return void 0;return{since:this.presenceWriteFailingSince,forMs:Date.now()-this.presenceWriteFailingSince,error:this.lastPresenceWriteError,bucket:presenceBucket(this.space),consecutiveFailures:this.presenceWriteFailures,stuck:this.presenceWriteEscalated}}async startPresenceWatch(){if(!this.kv)return void 0;let hydrated;this.presenceSnapshot=new Promise(resolve=>{hydrated=resolve});const bound=await this.bindKvWatch(this.kv);if(!bound){hydrated();return void 0}const{iter,info}=bound;this.presenceWatchIter=iter;const empty=info.num_pending===0&&!this.doRegister;if(empty){this.presenceSnapshotPopulated=true;hydrated();this.markPresenceBucketEmpty()}void(async()=>{let ready=empty;for await(const e of iter){if(this.presenceWatchIter!==iter)break;this.handleKvEntry(e);if(!ready&&e.isUpdate){ready=true;this.presenceSnapshotPopulated=true;hydrated();this.emitPresenceViewIfChanged()}}hydrated()})().catch(e=>this.emit("error",e));return info}async readPresenceOnce(){if(!this.kv)return;for(const e of await lastKvEntries(this.kv))this.handleKvEntry(e);this.presenceSnapshotPopulated=true;if(this.lastPresenceWatchAt===0)this.markPresenceBucketEmpty();else this.emitPresenceViewIfChanged()}rebindStalePresenceWatch(now){if(this.stopped||this.reconnecting||!this.kv||!this.nc||this.nc.isClosed())return;if(this.presenceRebind||now-this.presenceRebindAt<this.ttlMs)return;this.presenceRebindAt=now;const old=this.presenceWatchIter;const epoch=this.presenceEpoch;this.presenceRebind=(async()=>{try{const silentMs=now-this.lastPresenceWatchAt;const info=await this.startPresenceWatch();if(!info)return;if(old&&old!==this.presenceWatchIter)this.retireKvWatch(old);if(info.num_pending===0)await this.onPresenceBucketEmpty();this.emit("warning",new Error(`presence watch silent for ${silentMs}ms with the connection up; rebound it from the bucket's current state`))}catch(e){if(epoch===this.presenceEpoch)this.emit("error",e)}finally{if(epoch===this.presenceEpoch)this.presenceRebind=void 0}})()}async startChannelWatch(){if(!this.channelKv)return;const bound=await this.bindKvWatch(this.channelKv);if(!bound)return;const{iter}=bound;this.channelWatchIter=iter;void(async()=>{for await(const e of iter)this.handleChannelEntry(e)})().catch(e=>this.emit("error",e))}async readChannelsOnce(){if(!this.channelKv)return;for(const e of await lastKvEntries(this.channelKv))this.handleChannelEntry(e)}handleChannelEntry(e){const isDefaults=e.key===CHANNEL_DEFAULTS_KEY;if(isDefaults)this.channelDefaults={};else this.channelConfigs.delete(e.key);if(e.operation==="DEL"||e.operation==="PURGE")return;try{if(isDefaults)this.channelDefaults=decodeChannelEntry(e);else this.channelConfigs.set(e.key,decodeChannelEntry(e))}catch(err3){this.emitRecoverable(new Error(`dropped channel registry entry for key ${JSON.stringify(e.key)}: ${err3.message}`))}}async onPresenceBucketEmpty(){if(this.doRegister){await this.publishPresence();return}this.markPresenceBucketEmpty()}markPresenceBucketEmpty(){this.presenceWatchEmpty=true;this.lastPresenceWatchAt=0;let changed=false;for(const[id2,p]of this.roster){if(p.status==="offline")continue;const offline=this.toOffline(p);this.roster.set(id2,offline);this.emit("presence",{type:"offline",presence:offline});changed=true}if(changed)this.emit("roster",this.getRoster());this.emitPresenceViewIfChanged()}handleKvEntry(e){if(e.key===TTL_RECONCILE_CANARY_KEY)return;this.lastPresenceWatchAt=Date.now();this.presenceWatchEmpty=false;if(e.operation==="DEL"||e.operation==="PURGE"){this.markOffline(e.key);return}const p=this.decodePresence(e);if(p)this.applyPresence(e.key,p)}decodePresence(e){let p;try{p=e.json()}catch{return void 0}if(!isPresenceRow(p,e.key)){this.presenceBindingDrops++;this.emitRecoverable(new Error(`dropped presence entry for key ${JSON.stringify(e.key)}: not a usable presence row (a record with card.id equal to its KV key, a string card.name, a known status, a finite ts, string display fields and a condition with a string code)`));return void 0}return p}applyPresence(id2,raw){const prev=this.roster.get(id2);const stale=Date.now()-raw.ts>this.ttlMs;if(stale&&raw.status!=="offline"){if(prev)return;this.roster.set(id2,this.toOffline(raw));this.emit("roster",this.getRoster());return}if(this.presenceSnapshotPopulated)this.emitPresenceViewIfChanged();const p=stale||raw.status==="offline"?this.toOffline(raw):raw;if(!prev&&p.status==="offline"){this.roster.set(id2,p);this.emit("roster",this.getRoster());return}if(prev&&prev.status!=="offline"&&p.status!=="offline"&&prev.lifecycleUid===p.lifecycleUid&&sameRuntime(prev.runtime,p.runtime)&&prev.status===p.status&&prev.activity===p.activity&&sameCondition(prev.condition,p.condition)&&prev.environment===p.environment&&prev.attention===p.attention&&sameChannelModes(prev.channelModes,p.channelModes)){this.roster.set(id2,p);return}this.roster.set(id2,p);const type=p.status==="offline"?"offline":!prev||prev.status==="offline"?"join":"update";this.emit("presence",{type,presence:p});this.emit("roster",this.getRoster())}toOffline(p){return{...p,status:"offline",statusSince:void 0,attention:void 0,channelModes:void 0}}markOffline(id2){const prev=this.roster.get(id2);if(!prev||prev.status==="offline")return;const offline=this.toOffline(prev);this.roster.set(id2,offline);this.emit("presence",{type:"offline",presence:offline});this.emit("roster",this.getRoster())}emitPresenceViewIfChanged(){const view=this.presenceView();if(view.state===this.presenceViewState)return;this.presenceViewState=view.state;this.emit("presence-view",view)}sweep(){const now=Date.now();if(this.lastPresenceWatchAt!==0&&now-this.lastPresenceWatchAt>this.ttlMs){this.emitPresenceViewIfChanged();this.rebindStalePresenceWatch(now);return}let changed=false;for(const[id2,p]of this.roster){if(p.status!=="offline"&&now-p.ts>this.ttlMs&&this.lastPresenceWatchAt-p.ts>this.ttlMs){const offline=this.toOffline(p);this.roster.set(id2,offline);this.emit("presence",{type:"offline",presence:offline});changed=true}}if(changed)this.emit("roster",this.getRoster())}};function subjectLabel(subjects){return subjects.length===1?subjects[0]:`${subjects.length} filtered subjects`}function isUsableMessageId(id2){return typeof id2==="string"}function kindFromParsed(kind){switch(kind){case"chat":return"channel";case"inst":return"dm";case"svc":return"anycast";default:throw new Error(`cannot derive a message kind from subject kind "${kind}"`)}}function isFromSubjectSender(msg,parsed){return isRecord(msg)&&isRecord(msg.from)&&msg.from.id===parsed.sender&&isPrincipalOwnerToken(parsed.owner)}function authenticatedMessage(msg,parsed){if(parsed.kind==="chat")return authenticatedChannelMessage(msg,parsed.rest);if(parsed.kind==="inst")return authenticatedDmMessage(msg,parsed.rest);if(parsed.kind==="svc")return authenticatedAnycastMessage(msg,parsed.rest);return msg}function authenticatedChannelMessage(msg,channel){if(msg.channel===channel&&msg.to===void 0&&msg.toService===void 0)return msg;const{to:_to,toService:_toService,...base}=msg;return{...base,channel}}function authenticatedDmMessage(msg,to){if(msg.to===to&&msg.channel===void 0&&msg.toService===void 0)return msg;const{channel:_channel,toService:_toService,...base}=msg;return{...base,to}}function authenticatedAnycastMessage(msg,toService){if(msg.toService===toService&&msg.to===void 0&&msg.channel===void 0)return msg;const{to:_to,channel:_channel,...base}=msg;return{...base,toService}}async function ackWaitOf(consumer){const{config:config2}=await consumer.info(true);if(config2.ack_wait===void 0)throw new Error(`consumer ${config2.durable_name} reports no ack wait`);return(0,import_transport_node13.millis)(config2.ack_wait)}function durableDelivery(m,ackWaitMs){return{ack:()=>m.ack(),nak:()=>m.nak(),durable:true,redelivery:{deliveryCount:m.info.deliveryCount,ackWaitMs,working:()=>m.working()}}}function dmOnlyDelivery(m,ackWaitMs,nc){const open5=what=>{if(!nc||nc.isClosed())throw new Error(`DM-only ${what} refused: the connection that delivered this copy is closed; the broker will redeliver it`)};return{ack:()=>{open5("ack");m.ack()},nak:()=>{open5("nak");m.nak()},durable:true,redelivery:{deliveryCount:m.info.deliveryCount,ackWaitMs,working:()=>{open5("in-progress signal");m.working()}}}}function historyMessageFromDelivery(m){let raw;try{raw=m.json()}catch{return void 0}if(!isHistoryDrainEnvelope(raw))return void 0;if(!isVerifiedHistoryRow(raw))return void 0;const parsed=parseSubject(m.subject);if(!parsed||!isFromSubjectSender(raw,parsed))return void 0;return authenticatedMessage(raw,parsed)}function isVerifiedHistoryRow(row){if(typeof row.from.name!=="string")return false;if(row.from.role!==void 0&&typeof row.from.role!=="string")return false;if(typeof row.ts!=="number"||!Number.isFinite(row.ts))return false;if(typeof row.space!=="string")return false;if(!Array.isArray(row.parts)||!row.parts.every(isReadableMessagePart))return false;if(row.mentions!==void 0&&(!Array.isArray(row.mentions)||!row.mentions.every(name=>typeof name==="string")))return false;if(row.replyTo!==void 0&&typeof row.replyTo!=="string")return false;if(row.contextId!==void 0&&typeof row.contextId!=="string")return false;return true}function isReadableMessagePart(value){return isRecord(value)&&typeof value.kind==="string"}function isHistoryDrainEnvelope(value){return isRecord(value)&&isUsableMessageId(value.id)&&isRecord(value.from)}function isPlane3DeliveryFrame(value){if(!isRecord(value))return false;const keys=Object.keys(value);if(keys.length!==3||!keys.includes("version")||!keys.includes("channel")||!keys.includes("msg"))return false;if(value.version!==1||typeof value.channel!=="string"||!isConcreteChannel(value.channel))return false;return isCotalMessage(value.msg)&&value.msg.channel===value.channel}function isCotalMessage(value){if(!isRecord(value))return false;const routes=["channel","to","toService"].filter(key=>key in value);if(routes.length!==1||typeof value[routes[0]]!=="string")return false;if(typeof value.id!=="string"||typeof value.ts!=="number"||!Number.isFinite(value.ts)||typeof value.space!=="string"||!isEndpointRef(value.from)||!Array.isArray(value.parts)||!value.parts.every(isMessagePart))return false;if(value.mentions!==void 0&&(!Array.isArray(value.mentions)||!value.mentions.every(name=>typeof name==="string")))return false;if(value.replyTo!==void 0&&typeof value.replyTo!=="string")return false;if(value.contextId!==void 0&&typeof value.contextId!=="string")return false;return true}function isEndpointRef(value){return isRecord(value)&&typeof value.id==="string"&&typeof value.name==="string"&&(value.role===void 0||typeof value.role==="string")}function isMessagePart(value){if(!isRecord(value)||typeof value.kind!=="string")return false;if(value.kind==="text")return typeof value.text==="string";if(value.kind==="data")return Object.prototype.hasOwnProperty.call(value,"data");if(value.kind===ARTIFACT_PART_KIND)return isArtifactPart(value);return/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/.test(value.kind)}function isRecord(value){return!!value&&typeof value==="object"&&!Array.isArray(value)}function jsonPathProblem(path,value,seen){if(value===null)return void 0;const t=typeof value;if(t==="boolean"||t==="string")return void 0;if(t==="number")return Number.isFinite(value)?void 0:`${path} is not a finite number`;if(t==="undefined"||t==="function"||t==="symbol"||t==="bigint")return`${path} is not a JSON value`;if(typeof value==="object"){if(seen.has(value))return`${path} is cyclic`;seen.add(value);let problem;if(Array.isArray(value)){for(let i=0;i<value.length;i++){problem=jsonPathProblem(`${path}[${i}]`,value[i],seen);if(problem)return problem}}else{const proto=Object.getPrototypeOf(value);if(proto!==null&&proto!==Object.prototype){seen.delete(value);return`${path} is not a plain object`}for(const key of Object.keys(value)){if(value[key]===void 0)continue;problem=jsonPathProblem(`${path}.${key}`,value[key],seen);if(problem)return problem}}seen.delete(value);return void 0}return`${path} is not a JSON value`}function assertPartsSerializable(parts){for(const p of parts){if(p.kind!=="data")continue;const problem=jsonPathProblem("data",p.data,new Set);if(problem!==void 0){throw new Error(`cannot publish a data part carrying a non-JSON value (SPEC \xA75) - ${problem}`)}}}function sameChannelModes(a,b){const ak=a?Object.keys(a):[];const bk=b?Object.keys(b):[];if(ak.length!==bk.length)return false;return ak.every(k=>a[k]===b?.[k])}function sameRuntime(a,b){return a?.id===b?.id&&a?.startedAt===b?.startedAt&&a?.source===b?.source}function sameCondition(a,b){return a?.code===b?.code&&a?.source===b?.source&&a?.message===b?.message&&a?.since===b?.since}function authOpts(a){const tls=a.tls?{}:void 0;if(a.bearer){if(a.creds||a.token||a.user||a.pass)throw new Error("bearer (user-mode auth) is mutually exclusive with creds/token/user/pass");if(!a.sentinelCreds)throw new Error("user-mode bearer requires sentinelCreds");return{authenticator:[nativeCredsAuthenticator(a.sentinelCreds),(0,import_transport_node13.tokenAuthenticator)(a.bearer)],tls}}if(a.creds){if(a.token||a.user||a.pass)throw new Error("creds are mutually exclusive with token/user/pass auth");const creds=a.creds;const authenticator=nonce3=>{const presented=typeof creds==="function"?creds():creds;const authenticated=nativeCredsAuthenticator(presented)(nonce3);a.onCreds?.(presented);return authenticated};return{authenticator,tls}}return{token:a.token,user:a.user,pass:a.pass,tls}}function bearerExpiryMs(bearer){return bearerLifetimeMs(bearer,0).expiresAtMs}function bearerLifetimeMs(bearer,adoptedAtMs){const payload=bearer.split(".")[1];if(!payload)throw new Error("user-mode bearer is not a JWT (no payload segment)");let claims2;try{claims2=JSON.parse(Buffer.from(payload,"base64url").toString("utf8"))}catch{throw new Error("user-mode bearer payload is not valid base64url JSON")}if(typeof claims2.exp!=="number")throw new Error("user-mode bearer is missing a numeric exp claim");const expiresAtMs=claims2.exp*1e3;return{issuedAtMs:Math.min(typeof claims2.iat==="number"?claims2.iat*1e3:adoptedAtMs,expiresAtMs),expiresAtMs}}function bearerRenewalDeadlineMs(bearer,adoptedAtMs){const{issuedAtMs,expiresAtMs}=bearerLifetimeMs(bearer,adoptedAtMs);return renewalDeadlineMs(issuedAtMs,expiresAtMs)}var RepeatedRefusal=class extends Error{};function decodeBearerPrincipal(bearer){const payload=bearer.split(".")[1];if(!payload)throw new Error("user-mode bearer is not a JWT (no payload segment)");let claims2;try{claims2=JSON.parse(Buffer.from(payload,"base64url").toString("utf8"))}catch{throw new Error("user-mode bearer payload is not valid base64url JSON")}const owner2=claims2.sub,actor2=claims2.act?.actor;if(typeof owner2!=="string"||typeof actor2!=="string")throw new Error("user-mode bearer is missing a string sub (owner) / act.actor claim");return{owner:owner2,actor:actor2}}function describeStatusError(err3){if(err3 instanceof import_transport_node13.PermissionViolationError){return new Error(`NATS permission denied: cannot ${err3.operation} "${err3.subject}" - check this endpoint's ACLs (a denied peer looks "absent" rather than blocked)`,{cause:err3})}return err3}function kvWatchConsumer(iter){const consumer=iter._data;if(!consumer)throw new Error("KV watch carries no consumer - the pinned nats.js changed shape");return consumer}function membershipConsumerReleased(err3){return isJetStreamMissing(err3,import_jetstream13.JetStreamApiCodes.ConsumerNotFound,import_jetstream13.JetStreamApiCodes.StreamNotFound)||isPublishPermissionDenied(err3)}function abortReason(signal){return signal?.reason instanceof Error?signal.reason:new DOMException("This operation was aborted","AbortError")}function isPublishPermissionDenied(e){const typed=e instanceof import_transport_node13.PermissionViolationError?e:e?.cause instanceof import_transport_node13.PermissionViolationError?e.cause:void 0;return typed?.operation==="publish"}function wsServers(servers){return/^wss?:\/\//i.test((servers.split(",")[0]??"").trim())}function defaultProbeTimeoutMs(servers){return wsServers(servers)?5e3:1e3}function dialerFor(servers){if(!wsServers(servers))return(opts=>(0,import_transport_node13.connect)(withDialedTlsHost(servers,opts)));return(opts=>{const{tls,...rest}=opts??{};const targets=Array.isArray(rest.servers)?rest.servers:String(rest.servers??servers).split(",");if(tls&&targets.some(target2=>!/^wss:\/\//i.test(String(target2).trim())))return Promise.reject(new Error("TLS-required WebSocket connections must use wss:// for every server"));return(0,import_nats_core6.wsconnect)(rest)})}function withDialedTlsHost(servers,opts){const urls=servers.split(",").map(url2=>url2.trim()).filter(Boolean);const tls=opts?.tls;if(urls.length!==1||tls===null||tls===void 0&&!/^tls:\/\//i.test(urls[0]))return opts;let host;try{({host}=hostPort(urls[0]))}catch{return opts}return(0,import_node_net.isIP)(host)?{...opts,tls:{host,...tls}}:opts}function hostPort(server){const raw=(server.split(",")[0]??"").trim();const scheme=raw.match(/^([a-z][a-z0-9+.-]*):\/\//i)?.[1]?.toLowerCase();const first=raw.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"");const u=new URL(`http://${first}`);const fallback=scheme==="wss"?443:scheme==="ws"?80:4222;return{host:u.hostname,port:u.port?Number(u.port):fallback}}function tcpInfoProbe(server,timeoutMs){return new Promise(resolve=>{let socket;let done=false;let connected=false;const finish=live=>{if(done)return;done=true;try{socket?.destroy()}catch{}resolve(live)};let host,port;try{({host,port}=hostPort(server))}catch{return resolve(false)}socket=(0,import_node_net.createConnection)({host,port});socket.setTimeout(timeoutMs);let buf="";socket.on("data",chunk=>{buf+=chunk.toString("utf8");const nl=buf.indexOf("\r\n");if(nl===-1){if(buf.length>4096)finish(false);return}const line=buf.slice(0,nl);const brace=line.indexOf("{");if(!/^INFO\b/.test(line)||brace===-1)return finish(false);try{finish({authRequired:JSON.parse(line.slice(brace))?.auth_required===true})}catch{finish(false)}});socket.on("connect",()=>{connected=true});socket.on("timeout",()=>finish(connected?"silent":false));socket.on("error",()=>finish(false));socket.on("close",()=>finish(false))})}function tcpDialable(server,timeoutMs){return new Promise(resolve=>{let socket;let done=false;const finish=dialable=>{if(done)return;done=true;try{socket?.destroy()}catch{}resolve(dialable)};let host,port;try{({host,port}=hostPort(server))}catch{return resolve(false)}socket=(0,import_node_net.createConnection)({host,port});socket.setTimeout(timeoutMs);socket.on("connect",()=>finish(true));socket.on("timeout",()=>finish(false));socket.on("error",()=>finish(false));socket.on("close",()=>finish(false))})}function isAuthRejection(e){return e instanceof import_transport_node13.AuthorizationError||e instanceof import_transport_node13.UserAuthenticationExpiredError}function retryAfterMs(e){const seconds=e?.retryAfterSeconds;return typeof seconds==="number"&&Number.isFinite(seconds)&&seconds>0?seconds*1e3:0}async function probeConnect(server=DEFAULT_SERVER,opts={}){const timeoutMs=opts.timeoutMs??defaultProbeTimeoutMs(server);const started=Date.now();const gate=opts.tls||wsServers(server)?tcpDialable:tcpInfoProbe;const greeting=await gate(server,timeoutMs);if(!greeting)return classifyProbeFailure(void 0,opts);if(greeting==="silent")return classifyProbeFailure(void 0,opts,false,"timeout");try{const nc=await dialerFor(server)({servers:server,timeout:Math.max(1,timeoutMs-(Date.now()-started)),reconnect:false,maxReconnectAttempts:0,...authOpts(opts)});await nc.close();return{ok:true}}catch(e){return classifyProbeFailure(e,opts,greeting!==true&&greeting.authRequired)}}function classifyProbeFailure(e,opts,authRequired=false,otherwise="unreachable"){if(typeof opts.creds==="string"){try{if(inspectCredHealth(opts.creds).state==="expired")return{ok:false,reason:"stale-auth"}}catch{}}if(e instanceof import_transport_node13.UserAuthenticationExpiredError)return{ok:false,reason:"stale-auth"};if(e instanceof import_transport_node13.AuthorizationError)return{ok:false,reason:"auth-required"};if(e instanceof import_transport_node13.TimeoutError)return{ok:false,reason:"timeout"};if(e instanceof import_transport_node13.ConnectionError&&e.message==="server does not support 'tls'")return{ok:false,reason:"tls-unsupported"};if(authRequired&&e?.code==="ECONNRESET")return{ok:false,reason:"auth-required",inferred:true};return{ok:false,reason:otherwise}}var EVICT_PRINCIPALS_MAX=256;var SOURCE_CHAIN_ID="[A-Za-z0-9_-]{1,64}";var SOURCE_CHAIN_ELEMENT=new RegExp(`^(root|handle\\.${SOURCE_CHAIN_ID}\\.${SOURCE_CHAIN_ID}|session\\.${SOURCE_CHAIN_ID})$`);async function fetchClusterDocument(store,closureDigest,walk){const{manifest,artifacts}=await fetchContractClosure(store,closureDigest,()=>[],walk);const rootBytes=artifacts.get(contractRefToHex(manifest.root));if(rootBytes===void 0)throw new EpEnvelopeError("failed-precondition",`the cluster manifest ${closureDigest} names root ${manifest.root} but the root artifact is absent from the fetched closure (SPEC 13.7)`);return parseClusterDocument(JSON.parse(dec3.decode(rootBytes)))}async function recompileClosure(store,closureDigest,walk){const{manifest,artifacts}=await fetchContractClosure(store,closureDigest,bytes=>extractSchemaRefs(bytes),walk);const members={};for(const[hex3,bytes]of artifacts)members[`sha256:${hex3}`]=JSON.parse(dec3.decode(bytes));const rootRef=manifest.root;const root=members[rootRef];if(root===void 0)throw new EpEnvelopeError("failed-precondition",`schema closure ${closureDigest} is missing its root ${rootRef} (SPEC 13.7)`);const bundleMembers={};for(const[ref,value]of Object.entries(members))if(ref!==rootRef)bundleMembers[ref]=value;const compiled=compileContract({root,members:bundleMembers});if(compiled.closureDigest!==closureDigest)throw new EpEnvelopeError("internal",`the recompiled schema closure hashes to ${compiled.closureDigest}, not the fetched ${closureDigest}; a store that served the wrong bytes never authorizes (SPEC 13.7)`);return compiled}function extractSchemaRefs(bytes){const refs=[];const walk=v=>{if(typeof v==="string"){const m=/^cotal:(sha256:[0-9a-f]{64})$/.exec(v);if(m)refs.push(m[1])}else if(Array.isArray(v)){for(const c of v)walk(c)}else if(v!==null&&typeof v==="object"){for(const c of Object.values(v))walk(c)}};walk(JSON.parse(dec3.decode(bytes)));return refs}var RESOLVE_MAX_INFLIGHT_READS=32;async function pooled(items,limit,work){const out=new Array(items.length);let next=0;const worker=async()=>{for(;;){const i=next++;if(i>=items.length)return;try{out[i]=await work(items[i])}catch(e){next=items.length;throw e}}};await Promise.all(Array.from({length:Math.min(limit,items.length)},worker));return out}async function resolveService(nc,space2,endpoint,caller,opts={}){if(opts.commands!==void 0){if(!Array.isArray(opts.commands)||opts.commands.length===0)throw new EpEnvelopeError("failed-precondition","commands must be a non-empty array when a resolve is narrowed");for(const command of opts.commands){try{assertCommandToken(command)}catch(e){throw new EpEnvelopeError("failed-precondition",`invalid requested command: ${e.message}`)}}}if(opts.optionalCommands!==void 0){if(!Array.isArray(opts.optionalCommands)||opts.optionalCommands.length===0)throw new EpEnvelopeError("failed-precondition","optionalCommands must be a non-empty array when supplied");for(const command of opts.optionalCommands){try{assertCommandToken(command)}catch(e){throw new EpEnvelopeError("failed-precondition",`invalid optional command: ${e.message}`)}}}const startedAt2=performance.now();const deadlineMs=opts.deadlineMs??1e4;const{answer,responder}=await describeEndpoint(nc,space2,endpoint,caller,{...opts,deadlineMs});const store=await contractStoreContext(nc,space2);const visible=new Set(answer.descriptor.clusters.flatMap(cl=>cl.commands));const requested=opts.commands===void 0?visible:new Set(opts.commands);const optional2=new Set(opts.optionalCommands);for(const command of requested){if(visible.has(command))continue;if(optional2.has(command)){requested.delete(command);continue}throw new EpEnvelopeError("not-found",`command "${command}" is not in ${endpoint}'s visible surface; describe lists ${[...visible].sort().join(", ")||"(none)"}`)}const artifactMemo=new Map;const walk=()=>{const walkBudgetMs=Math.floor(deadlineMs-(performance.now()-startedAt2));if(walkBudgetMs<=0)throw new EpEnvelopeError("deadline-exceeded",`resolving ${endpoint} exhausted its ${deadlineMs}ms deadline before a contract-store read`);return{artifactMemo,walkBudgetMs,...opts.signal?{signal:opts.signal}:{}}};const clusters=answer.descriptor.clusters.filter(cl=>cl.commands.some(command=>requested.has(command)));const docs=await pooled(clusters,RESOLVE_MAX_INFLIGHT_READS,cl=>{opts.signal?.throwIfAborted();return fetchClusterDocument(store,cl.digest,walk())});const declared=docs.flatMap(doc=>doc.commands).filter(cmd=>requested.has(cmd.name));const resolved=await pooled(declared,Math.max(1,RESOLVE_MAX_INFLIGHT_READS>>1),async cmd=>{opts.signal?.throwIfAborted();const[input,output]=await Promise.all([recompileClosure(store,cmd.inputDigest,walk()),recompileClosure(store,cmd.outputDigest,walk())]);return{command:cmd.name,contract:{input,output},class:cmd.class,targeted:cmd.targeted,modes:cmd.modes??[],capability:cmd.capability,...cmd.action?{action:true}:{}}});opts.signal?.throwIfAborted();const commands=new Map;for(const rc of resolved)commands.set(rc.command,rc);return{endpoint:answer.descriptor.endpoint,owner:answer.descriptor.owner,caller,responder,commands,...opts.instanceId!==void 0?{pinnedInstanceId:opts.instanceId}:{}}}function submitAndFollowGoal(nc,space2,endpoint,caller,deadlineMs,submit,opts){return submitAndFollowGoalWith(parseGoalResultFact,nc,space2,endpoint,caller,deadlineMs,submit,opts)}async function registryListingCaller(nc,space2,caller,credential){if(isIssuedCaller(caller))return caller;if(credential.exp===void 0)return void 0;try{return await issuedCallerOfToken(nc,space2,listingAcceptedToken(credential.connId,credential.exp),caller)}catch(e){if(isPermissionDenied(e))return void 0;throw e}}async function listRegistryEndpoints(space2,describe3,ask,input,opts={}){const deadline=Date.now()+(opts.deadlineMs??1e4);const ours=REGISTRY_CONTRACTS[REGISTRY_ENDPOINTS_COMMAND];let reply;for(let attempt=0;attempt<=BIND_SPLIT_REISSUES&&Date.now()<deadline;attempt++){const service=await describe3(deadline-Date.now(),opts.signal);const theirs=service.commands.get(REGISTRY_ENDPOINTS_COMMAND).contract;if(theirs.input.closureDigest!==ours.input.closureDigest||theirs.output.closureDigest!==ours.output.closureDigest)throw new EpEnvelopeError("contract-mismatch",`the registry serves a version of "${REGISTRY_ENDPOINTS_COMMAND}" this client does not implement; upgrade the client (SPEC 13.20)`);try{reply=await invokeCommand(ask.nc,space2,service,REGISTRY_ENDPOINTS_COMMAND,{...input},{deadlineMs:deadline-Date.now(),signal:opts.signal,...ask.caller?{caller:ask.caller}:{}})}catch(e){if(ask.caller!==void 0&&e instanceof EpEnvelopeError&&e.code==="permission-denied"&&e.outcome==="not-executed")return{unbound:true};throw e}if(reply.reply.ok!==false||!replyRefusedBeforeEffect(reply.reply.error))break}if(reply===void 0)throw new EpEnvelopeError("deadline-exceeded","the registry was not reached before the deadline");return{reply,...reply.reply.ok===true?{page:reply.reply.data}:{}}}var dec5=new TextDecoder;var enc5=new TextEncoder;var import_jetstream16=__toESM(require_mod4(),1);var import_kv8=__toESM(require_mod6(),1);var import_transport_node15=__toESM(require_transport_node(),1);var import_jetstream17=__toESM(require_mod4(),1);var import_transport_node16=__toESM(require_transport_node(),1);var import_kv9=__toESM(require_mod6(),1);var DEFAULT_FIELDS={replay:true,replayWindow:true,deliveryClass:true};var CHANNEL_FIELDS={...DEFAULT_FIELDS,description:true,instructions:true};var import_jetstream18=__toESM(require_mod4(),1);var enc6=new TextEncoder;var dec6=new TextDecoder;var mintGuardClearance=claimGuardClearanceMint();var TRAIT_SELECTORS=Object.freeze(["cluster","command","attribute","event"]);var import_jetstream19=__toESM(require_mod4(),1);var import_transport_node17=__toESM(require_transport_node(),1);var import_jetstream20=__toESM(require_mod4(),1);var import_transport_node18=__toESM(require_transport_node(),1);var COMMON_FIELDS=["v","executor","attemptId","ts","phase"];var PHASE_FIELDS={claimed:COMMON_FIELDS,launching:[...COMMON_FIELDS,"addr"],launched:[...COMMON_FIELDS,"addr"],settled:[...COMMON_FIELDS,"addr"]};var BASE=["v","ts","state","claimant"];var STATE_FIELDS={claimed:BASE,launching:[...BASE,"lifecycleUid","launchAttemptId","executor"],live:[...BASE,"lifecycleUid","runtimeOwner"],preserved:[...BASE,"lifecycleUid","runtimeOwner"],relaunching:[...BASE,"lifecycleUid","launchAttemptId","executor"],draining:[...BASE,"lifecycleUid","runtimeOwner","enteredAt"],released:BASE};var HANDLE_MAX_LIVE_TTL_MS=24*60*60*1e3;var HANDLE_MAX_STURDY_TTL_MS=30*24*60*60*1e3;var HANDLE_MAX_BYTES=64*1024;var SESSION_GRANT_MAX_TTL_MS=24*60*60*1e3;var SESSION_GRANT_MAX_BYTES=16*1024;var SESSION_TERMINAL_STATES=Object.freeze(["closed","expired","superseded","retired"]);var TERMINAL_STATE_SNAP=new Set(SESSION_TERMINAL_STATES);var MAX_B64_CHARS=4*1024*1024;var B64_ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var B64_INV=(()=>{const m=new Int16Array(128).fill(-1);for(let i=0;i<B64_ALPHABET.length;i++)m[B64_ALPHABET.charCodeAt(i)]=i;return m})();var import_jetstream21=__toESM(require_mod4(),1);var RENEW_AT_FRACTION=1/3;var OVERLAP_MS=10*60*1e3;function presenceAges(p,now){return{conditionSince:ageAt(now,p.condition?.since),statusSince:ageAt(now,p.statusSince),activitySince:p.activity?ageAt(now,p.activitySince):void 0,activeAt:ageAt(now,p.activeAt)}}function formatAge(ms){const s=Math.floor(ms/1e3);if(s<60)return`${s}s`;if(s<3600)return`${Math.floor(s/60)}m`;if(s<86400)return`${Math.floor(s/3600)}h`;return`${Math.floor(s/86400)}d`}function ageAt(now,at){if(typeof at!=="number"||!Number.isFinite(at))return void 0;return Math.max(0,now-at)}function oneLine(text2){return text2.replace(/[\p{Cc}\p{Cf}\p{Default_Ignorable_Code_Point}\p{Zl}\p{Zp}]/gu,c=>{let escaped="";for(let i=0;i<c.length;i++)escaped+=`\\u${c.charCodeAt(i).toString(16).padStart(4,"0")}`;return escaped})}var PRESENCE_TEXT_MAX=200;function presenceText(text2){const shown=Array.from(text2,oneLine);const width=s=>[...s].length;if(shown.reduce((n2,s)=>n2+width(s),0)<=PRESENCE_TEXT_MAX)return shown.join("");let kept="";let n=0;for(const s of shown){n+=width(s);if(n>PRESENCE_TEXT_MAX-1)break;kept+=s}return`${kept}\u2026`}function parseJoinLink(link){const tls=link.startsWith("cotals://");if(!tls&&!link.startsWith("cotal://"))throw new Error(`not a Cotal link (expected cotal:// or cotals://): ${link}`);const u=new URL(link.replace(/^cotals?:\/\//,tls?"https://":"http://"));if(!u.hostname)throw new Error(`Cotal link has no host: ${link}`);const space2=decodeURIComponent(u.pathname.replace(/^\/+/,"").split("/")[0]??"");if(!space2)throw new Error(`Cotal link has no space (cotal://host/<space>): ${link}`);const chParam=u.searchParams.get("channels")??u.searchParams.get("channel");const channels=chParam?chParam.split(",").map(s=>s.trim()).filter(Boolean):void 0;const user=u.username?decodeURIComponent(u.username):void 0;const pass=u.password?decodeURIComponent(u.password):void 0;return{servers:`nats://${u.hostname}:${u.port||"4222"}`,space:space2,channels,tls,token:user&&!pass?user:void 0,user:pass?user:void 0,pass:pass||void 0}}function brokerUrlHasUserinfo(servers){return servers.split(",").some(entry=>/^[^:/?#]+:\/\/[^/?#]*@/.test(entry.includes("://")?entry.trim():`nats://${entry.trim()}`))}var import_nkeys10=__toESM(require_mod(),1);var import_nkeys11=__toESM(require_mod(),1);var import_transport_node19=__toESM(require_transport_node(),1);var import_kv10=__toESM(require_mod6(),1);var import_node_fs5=require("node:fs");var import_node_path3=require("node:path");function ensureDirNoSymlink(parent,...segments){let dir=parent;for(const seg of segments){dir=(0,import_node_path3.join)(dir,seg);let st;try{st=(0,import_node_fs5.lstatSync)(dir)}catch(e){if(e.code==="ENOENT"){(0,import_node_fs5.mkdirSync)(dir,{mode:448});continue}throw e}if(st.isSymbolicLink())throw new Error(`refusing to write under "${dir}": it is a symlink`);if(!st.isDirectory())throw new Error(`refusing to write under "${dir}": not a directory`)}return dir}var import_node_fs6=require("node:fs");var LAUNCH_MATERIAL_ENV="COTAL_LAUNCH_MATERIAL";function readLaunchMaterial(path){let raw;try{if(process.platform!=="win32"){const mode=(0,import_node_fs6.statSync)(path).mode&511;if(mode&63)throw new Error(`is readable beyond its owner (mode ${mode.toString(8)}) - refusing to read connection material out of a file other local users can open`)}raw=(0,import_node_fs6.readFileSync)(path,"utf8")}catch(e){throw new Error(`launch material: cannot read ${path} (${e instanceof Error?e.message:String(e)})`)}let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error(`launch material: ${path} is not valid JSON`)}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))throw new Error(`launch material: ${path} must contain a JSON object`);return validate(parsed,path)}function validate(raw,path){const material={};const str2=key=>{const v=raw[key];if(v===void 0)return;if(typeof v!=="string"||!v.trim())throw new Error(`launch material: ${path} has a ${key} that is not a non-empty string`);material[key]=v};str2("servers");str2("creds");str2("token");str2("controlToken");if(raw.eventsRequired!==void 0){if(raw.eventsRequired!==true)throw new Error(`launch material: ${path} has eventsRequired that is not exactly true`);material.eventsRequired=true}if(raw.userAuth!==void 0){const u=raw.userAuth;if(typeof u!=="object"||u===null||Array.isArray(u))throw new Error(`launch material: ${path} has a userAuth that is not an object`);const{owner:owner2,actor:actor2,sentinelCredsPath,bearerCmd}=u;const named={owner:owner2,actor:actor2,sentinelCredsPath};for(const[k,v]of Object.entries(named))if(typeof v!=="string"||!v.trim())throw new Error(`launch material: ${path} has a userAuth.${k} that is not a non-empty string`);if(!Array.isArray(bearerCmd)||bearerCmd.length===0||!bearerCmd.every(a=>typeof a==="string"&&a))throw new Error(`launch material: ${path} has a userAuth.bearerCmd that is not a non-empty array of strings`);material.userAuth={owner:owner2,actor:actor2,sentinelCredsPath,bearerCmd}}if(Object.keys(material).length===0)throw new Error(`launch material: ${path} carries nothing this reader recognises. A launch that references material and supplies none is a broken launcher, not an open-mode launch, so it is refused rather than defaulted.`);return material}var import_transport_node20=__toESM(require_transport_node(),1);var import_jetstream22=__toESM(require_mod4(),1);var import_kv11=__toESM(require_mod6(),1);var import_node_net2=require("node:net");var LOOPBACK=new import_node_net2.BlockList;LOOPBACK.addSubnet("127.0.0.0",8,"ipv4");LOOPBACK.addAddress("::1","ipv6");var TARGET_FIELDS=["space","owner","actor","lifecycleUid"];var STRING_FIELDS=[...TARGET_FIELDS,"kind","server","authProvider","exchangeUrl","sentinelCreds","actorToken"];var LIST_FIELDS=["subscribe","allowSubscribe","allowPublish"];var FIELDS=new Set([...STRING_FIELDS,...LIST_FIELDS,"tlsRequired","idp","policy"]);var import_node_async_hooks=require("node:async_hooks");function claims(ext){return[ext.name,...ext.aliases??[]].map(word=>`${ext.kind}:${word}`)}var Registry=class{#byKey=new Map;#providers=new Map;#aliases=new Map;#stage=new import_node_async_hooks.AsyncLocalStorage;register(...exts){const stage=this.#stage.getStore();const taken=this.#claimed();for(const staged of stage?.values()??[])for(const key of claims(staged))taken.add(key);for(const ext of exts){for(const key of claims(ext)){if(taken.has(key))throw new Error(`extension already registered: ${key}`);taken.add(key)}}if(stage)for(const ext of exts)stage.set(`${ext.kind}:${ext.name}`,ext);else this.#publish(exts)}#claimed(){return new Set([...this.#byKey.keys(),...this.#aliases.keys()])}#publish(exts){for(const ext of exts){const key=`${ext.kind}:${ext.name}`;this.#byKey.set(key,ext);for(const alias of claims(ext).slice(1))this.#aliases.set(alias,key)}}unregister(kind,name){const key=`${kind}:${name}`;const ext=this.#byKey.get(key);if(!ext)return false;for(const alias of claims(ext).slice(1))this.#aliases.delete(alias);return this.#byKey.delete(key)}async runStaged(load){const stage=new Map;const value=await this.#stage.run(stage,load);return{value,staged:[...stage.values()]}}commitStaged(staged){const taken=this.#claimed();for(const ext of staged)for(const key of claims(ext))if(taken.has(key))throw new Error(`extension already registered: ${key}`);this.#publish(staged)}has(kind,name){return this.#byKey.has(this.#canonical(kind,name))}#canonical(kind,word){const key=`${kind}:${word}`;return this.#aliases.get(key)??key}resolve(kind,name){const ext=this.#byKey.get(this.#canonical(kind,name));if(!ext){if(this.#providers.has(`${kind}:${name}`))throw new Error(`${kind} "${name}" is declared by a provider this process has not loaded`);throw new Error(`no ${kind} registered for "${name}"`)}return ext}provide(provider){const keys=provider.provides.map(ref=>`${ref.kind}:${ref.name}`);for(const key of keys)if(this.#providers.has(key))throw new Error(`extension provider already declared: ${key}`);const entry={provider};for(const key of keys)this.#providers.set(key,entry)}provides(kind,name){return this.#providers.has(`${kind}:${name}`)}async load(kind,name){const entry=this.#providers.get(`${kind}:${name}`);if(entry){entry.loading??=entry.provider.load();await entry.loading;if(!this.#byKey.has(this.#canonical(kind,name)))throw new Error(`the provider declared for ${kind} "${name}" loaded without registering it`)}return this.resolve(kind,name)}all(kind){const values=[...this.#byKey.values()];return kind===void 0?values:values.filter(e=>e.kind===kind)}};var registry3=new Registry;var import_node_child_process2=require("node:child_process");function bearerCommandFailure(err3,stderr,timeoutMs,stdout=""){const said=stderr.trim();const retryAfter=/^retry-after (\d+)$/.exec(stdout.trim());if(said)return Object.assign(new Error(said),retryAfter?{retryAfterSeconds:Number(retryAfter[1])}:{});if(err3.killed)return new Error(`the bearer command timed out after ${timeoutMs}ms`);if(err3.signal)return new Error(`the bearer command was killed by ${err3.signal}`);if(typeof err3.code==="number")return new Error(`the bearer command exited with code ${err3.code} and printed nothing`);return new Error(err3.message)}function runAgentBearer(argv,opts={}){const timeoutMs=opts.timeoutMs??3e4;return new Promise((resolve,reject)=>{(0,import_node_child_process2.execFile)(argv[0],argv.slice(1),{timeout:timeoutMs,maxBuffer:64*1024,env:opts.env,signal:opts.signal},(err3,stdout,stderr)=>err3?reject(bearerCommandFailure(err3,stderr,timeoutMs,stdout)):resolve(stdout.trim()))})}var EVENT_CHANNEL_PREFIX="events.";function eventChannel(principal){return`${EVENT_CHANNEL_PREFIX}${principalKey(principal.owner,principal.actor).key}`}function eventChannelPrincipal(channel){if(typeof channel!=="string"||!channel.startsWith(EVENT_CHANNEL_PREFIX))return null;const principal=parsePrincipalKey(channel.slice(EVENT_CHANNEL_PREFIX.length));if(principal===null)return null;return eventChannel(principal)===channel?principal:null}var SELECTION_MAX_ITEMS=32;var order=(a,b)=>a<b?-1:a>b?1:0;function fail2(message){throw new Error(`conversation selection: ${message}`)}function record2(value,keys,what){if(!value||typeof value!=="object"||Array.isArray(value))fail2(`${what} must be an object`);const found=Object.keys(value);if(found.length!==keys.length||keys.some(k=>!found.includes(k)))fail2(`${what} must have exactly ${keys.join(", ")}`);return value}function list(value,what,max=Infinity){if(!Array.isArray(value))fail2(`${what} must be an array`);if(value.length>max)fail2(`${what} has ${value.length} entries; at most ${max} are allowed`);return value}function checkConversationSelection(value){const s=record2(value,["v","channels","role","capabilities","endpoints"],"selection");if(s.v!==1)fail2("v must be 1");const channels=list(s.channels,"channels",SELECTION_MAX_ITEMS).map(raw=>{const c=record2(raw,["channel","access"],"a channel entry");if(typeof c.channel!=="string")fail2("a channel must be a string");assertValidChannel(c.channel);if(c.access!=="read"&&c.access!=="read-post")fail2(`channel "${c.channel}" access must be "read" or "read-post"`);return{channel:c.channel,access:c.access}});if(s.role!==null&&typeof s.role!=="string")fail2("role must be a role token or null");const role=s.role===null?null:assertValidRole(s.role);const capabilities=list(s.capabilities,"capabilities").map(item=>{if(item!=="run"&&item!=="spawn"&&!(typeof item==="string"&&item.startsWith("role:")))fail2(`capability ${JSON.stringify(item)} is not run, spawn or role:<role>`);const capability=item;if(capability.startsWith("role:"))assertValidRole(capability.slice(5));return capability});const roles=capabilities.filter(c=>c.startsWith("role:"));if(role===null?roles.length!==0:roles.length!==1||roles[0]!==`role:${role}`)fail2("role must be set exactly when its role:<role> capability is selected, and no other role:<r> is allowed");if(list(s.endpoints,"endpoints").length)fail2("endpoint selection is not available in selection v1, so endpoints must be empty");const ascending=(keys,what)=>{for(let i=1;i<keys.length;i++)if(order(keys[i-1],keys[i])>=0)fail2(`${what} must be unique and in ascending order`)};ascending(channels.map(c=>c.channel),"channels");ascending(capabilities,"capabilities");if(!channels.length&&!capabilities.length)fail2("it selects nothing; leave it out to connect with only your own event channel");return{v:1,channels,role,capabilities,endpoints:[]}}function conversationSelection(input){const capabilities=[...input.capabilities??[],...input.role!==void 0?[`role:${input.role}`]:[]];return checkConversationSelection({v:1,channels:[...input.channels??[]].sort((a,b)=>order(a.channel,b.channel)),role:input.role??null,capabilities:capabilities.sort(order),endpoints:[]})}var EMPTY_CONVERSATION_SELECTION=Object.freeze({v:1,channels:Object.freeze([]),role:null,capabilities:Object.freeze([]),endpoints:Object.freeze([])});function managerCallerBinding(bearer,expected){let payload;try{const parts=bearer.split(".");if(parts.length!==3)throw new Error("invalid JWT");payload=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(fromBase64url(parts[1])))}catch{throw new Error("manager control exchange returned an invalid bearer")}const act=payload?.act;if(!act||act.view!=="manager-caller"||payload.sub!==expected.owner||act.owner!==expected.owner||act.actor!==expected.actor||act.lifecycleUid!==expected.lifecycleUid||!(payload.aud===expected.space||Array.isArray(payload.aud)&&payload.aud.length===1&&payload.aud[0]===expected.space))throw new Error("manager control exchange returned different space, principal, lifecycle or view coordinates");if(typeof act.managerInstanceId!=="string")throw new Error("manager control exchange returned no concrete manager instance");const instanceId=assertLifecycleToken(act.managerInstanceId,"managerInstanceId");if(expected.instanceId!==void 0&&instanceId!==expected.instanceId)throw new Error("manager control exchange selected a different manager instance");return{caller:{owner:expected.owner,actor:expected.actor,uid:expected.lifecycleUid},instanceId,...typeof act.credentialId==="string"?{credentialId:act.credentialId}:{}}}var DELEGATED_RECOVERY_REASONS=Object.freeze(["provider-unknown","store-unavailable","authority-unavailable","identity-unverified","descriptor-incomplete","retiring","authority-drift","identity-changed","scope-changed"]);function partText(p){if(p.kind==="text")return p.text;if(p.kind==="artifact")return`[artifact ${p.name} (${p.mediaType}, ${p.size} bytes) ${p.digest}]`;if(p.kind==="data"){const encoded=JSON.stringify(p.data);return encoded===void 0?`[empty data part]`:encoded}if(registry3.has("part-renderer",p.kind)){const renderer=registry3.resolve("part-renderer",p.kind);try{return renderer.render(p)}catch(e){return`[part renderer for ${JSON.stringify(p.kind)} failed: ${e.message}]`}}return`[unrenderable part kind ${JSON.stringify(p.kind)} \u2014 no renderer for it on this surface]`}function partsToText(parts){return parts.map(partText).join(" ")}var AGUI_FRAME_KIND="ag-ui.frame";var AGUI_EVENT_TYPE=Object.freeze({RUN_STARTED:"RUN_STARTED",RUN_FINISHED:"RUN_FINISHED",RUN_ERROR:"RUN_ERROR",TEXT_MESSAGE_START:"TEXT_MESSAGE_START",TEXT_MESSAGE_CONTENT:"TEXT_MESSAGE_CONTENT",TEXT_MESSAGE_END:"TEXT_MESSAGE_END",TOOL_CALL_START:"TOOL_CALL_START",TOOL_CALL_ARGS:"TOOL_CALL_ARGS",TOOL_CALL_END:"TOOL_CALL_END",TOOL_CALL_RESULT:"TOOL_CALL_RESULT",REASONING_MESSAGE_START:"REASONING_MESSAGE_START",REASONING_MESSAGE_CONTENT:"REASONING_MESSAGE_CONTENT",REASONING_MESSAGE_END:"REASONING_MESSAGE_END",CUSTOM:"CUSTOM"});function isAguiFramePart(part){if(typeof part!=="object"||part===null)return false;try{return part.kind===AGUI_FRAME_KIND}catch{return false}}var TURN_INPUT_SCHEMA=deepFreeze({type:"object",additionalProperties:false,required:["payload"],oneOf:[{required:["deadlineMs"]},{required:["deadlineAt"]}],properties:{payload:{type:"string",minLength:1,maxLength:65536},deadlineMs:{type:"integer",minimum:1},deadlineAt:{type:"integer",minimum:1},handoffFrom:{type:"string",minLength:1,maxLength:200}}});var TURN_OUTPUT_SCHEMA=deepFreeze({type:"object",additionalProperties:false,required:["name","owner","actor","uid","goalId","fingerprint","deadlineAt","executor"],properties:{name:{type:"string"},owner:{type:"string"},actor:{type:"string"},uid:{type:"string"},goalId:{type:"string"},fingerprint:{type:"string"},deadlineAt:{type:"integer",minimum:1},executor:{type:"object",additionalProperties:false,required:["lifecycleUid","epoch"],properties:{lifecycleUid:{type:"string"},epoch:{type:"integer",minimum:0}}}}});var TURN_YIELD_OUTPUT_SCHEMA=deepFreeze({type:"object",additionalProperties:false,required:["goalId","state"],properties:{goalId:{type:"string"},state:{enum:["succeeded","failed","cancelled","expired","uncertain"]}}});var CANCEL_INPUT_SCHEMA=deepFreeze({type:"object",additionalProperties:false,required:["goalId"],properties:{goalId:{type:"string",minLength:1},mode:{enum:["graceful","terminate"]}}});function deepFreeze(v){if(v!==null&&typeof v==="object"){for(const child of Object.values(v))deepFreeze(child);Object.freeze(v)}return v}var TURN_NOTICE_NONCE="turn-pending-notice-v1";function turnNoticeFilter(space2,instanceId,seat){return[spacePrefix(space2),...epPlaneTokens(seat),"reply",endpointToken("manager"),assertLifecycleToken(instanceId,"instanceId"),"*",...callerRailTokens(seat),TURN_NOTICE_NONCE].join(".")}function renderOnceTask(t){let context=t.payload;try{const p=JSON.parse(t.payload);if(typeof p.context==="string")context=p.context}catch{}const from=t.spawner??"your spawner";const deadline=t.deadlineAt!==void 0?`, or at ${new Date(t.deadlineAt).toISOString()} if you are still working then`:"";return`\u{1F3AF} Cotal \u2014 ${from} started this seat for one task (goal ${t.goalId}):
|
|
117
117
|
${context}
|
|
118
118
|
(This is the only task this seat takes. Do it with your own tools, and send your result to whoever needs it, for example with cotal_dm to ${from}, before you end your turn: this seat is stopped when your turn ends${deadline}, and a result you have not sent reaches no one. If you cannot finish, call cotal_yield with blocked or handoff and say why.)`}var nonBlank=()=>({type:"string",pattern:"^\\s*\\S"});var AGENT_ROW_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,required:["name","id","agent","space","mode","status","uptimeMs","mesh","lifecycleUid"],properties:{name:{type:"string"},id:{type:"string"},role:{type:"string"},agent:{type:"string"},space:{type:"string"},mode:{type:"string"},status:{type:"string"},uptimeMs:{type:"integer",minimum:0},mesh:{type:"string"},joinHealth:{type:"object",additionalProperties:false,required:["state","reason"],properties:{state:{type:"string",const:"degraded"},reason:{type:"string"}}},condition:{type:"object",additionalProperties:false,required:["code"],properties:{code:{type:"string"},source:{type:"string"},message:{type:"string"},since:{type:"number"}}},startupNotice:{type:"string",minLength:1,maxLength:1024},activeAt:{type:"number"},meshView:{type:"string",enum:["current","stale","unpopulated"]},presenceIdentityVerified:{type:"boolean"},presenceObservedAt:{type:"integer",minimum:0},offlineSince:{type:"integer",minimum:0},lifecycleUid:{type:"string"},authHealth:{type:"string"},authReason:{type:"string"},model:{type:"string"},variant:{type:"string"},provider:{type:"string"},cwd:{type:"string"},pid:{type:"integer",minimum:1},spawner:{type:"string"},instanceId:{type:"string"},host:{type:"string"},resume:{type:"object",additionalProperties:false,required:["source"],properties:{source:{type:"string"},title:{type:"string"},transcriptSha256:{type:"string"},host:{type:"string"},transferredAt:{type:"string"}}}}});var INSPECT_INPUT_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,required:["name"],properties:{name:{type:"string",minLength:1}}});var PERSONA_ENDPOINTS_SCHEMA=deepFreeze2({type:"array",items:{type:"object",additionalProperties:false,required:["endpoint","commands"],properties:{endpoint:{type:"string"},commands:{type:"array",items:{type:"string"}},instanceId:{type:"string"}}}});var SPAWN_INPUT_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,required:["name"],properties:{name:{type:"string",minLength:1},agent:nonBlank(),defaultAgent:nonBlank(),role:nonBlank(),config:nonBlank(),identity:nonBlank(),model:nonBlank(),variant:nonBlank(),launchOptions:{type:"object"},resume:nonBlank(),resumeClaim:nonBlank(),resumeAgent:nonBlank(),events:{type:"boolean"},cwd:nonBlank(),prompt:nonBlank(),persona:{type:"object",additionalProperties:false,required:["prompt"],properties:{prompt:nonBlank(),role:nonBlank(),model:nonBlank(),variant:nonBlank(),description:nonBlank(),subscribe:{type:"array",items:{type:"string"}},allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}},capabilities:{type:"array",items:{type:"string"}},endpoints:PERSONA_ENDPOINTS_SCHEMA,save:{type:"boolean"}}},runId:nonBlank(),subscribe:{type:"array",items:{type:"string"}},allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}},join:{type:"array",items:{type:"string"}},callerAcl:{type:"object",additionalProperties:false,required:["allowSubscribe","allowPublish"],properties:{allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}}}},shareTools:{type:"array",items:{type:"string"}},runtime:nonBlank(),supervise:{type:"object",additionalProperties:false,required:["restarts","windowMs"],properties:{restarts:{type:"integer",minimum:1},windowMs:{type:"integer",minimum:1}}},once:{type:"object",additionalProperties:false,properties:{deadlineMs:{anyOf:[{const:-1},{type:"integer",minimum:1,maximum:Number.MAX_SAFE_INTEGER}]}}}}});var SPAWN_OUTPUT_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,required:["name","owner","actor","uid","goalId","fingerprint","executor"],properties:{name:{type:"string"},owner:{type:"string"},actor:{type:"string"},uid:{type:"string"},goalId:{type:"string"},fingerprint:{type:"string"},readinessDeadlineMs:{type:"integer",minimum:1},executor:{type:"object",additionalProperties:false,required:["lifecycleUid","epoch"],properties:{lifecycleUid:{type:"string"},epoch:{type:"integer",minimum:0}}}}});var GRACEFUL_INPUT_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,properties:{graceful:{type:"boolean"}}});var STOP_OUTPUT_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,required:["name","stopped","graceful"],properties:{name:{type:"string"},stopped:{type:"boolean"},graceful:{type:"boolean"}}});function deepFreeze2(v){if(v!==null&&typeof v==="object"){for(const child of Object.values(v))deepFreeze2(child);Object.freeze(v)}return v}var import_nkeys12=__toESM(require_mod(),1);var TOOL_RESULTS_ENDPOINT="tool-results";var TOOL_RESULT_MAX_CONTENT_BYTES=64*1024;var TOOL_RESULT_MAX_RETENTION_MS=60*60*1e3;var TOOL_RESULT_CONSENT_MAX_TTL_MS=24*60*60*1e3;function deepFreeze3(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))deepFreeze3(child);Object.freeze(value)}return value}var text={type:"string",minLength:1};var id={type:"string",minLength:1,maxLength:200,pattern:"^[A-Za-z0-9_-]+$"};var actor={type:"string",minLength:1,pattern:"^[A-Za-z0-9_]+$"};var owner={type:"string",pattern:"^u_[a-z2-7]{26}$"};var uid={type:"string",pattern:"^[a-z0-9]{26,32}$"};var space={type:"string",minLength:1,pattern:"^[A-Za-z0-9_-]+$"};var uint={type:"integer",minimum:0,maximum:Number.MAX_SAFE_INTEGER};var bool={type:"boolean"};var closed2=properties=>({type:"object",additionalProperties:false,required:Object.keys(properties),properties});var target=closed2({owner,actor,lifecycleUid:uid});var pair={threadId:text,toolCallId:text};var status=(state,fields={})=>closed2({state:{const:state},...fields});var TOOL_RESULT_CONSENT_SCHEMA=deepFreeze3(closed2({v:{const:1},kind:{const:"tool-result-consent"},id,space,target,holder:closed2({owner,actor}),iat:uint,exp:uint,issuer:closed2({keyId:id}),sig:{type:"string",pattern:"^[A-Za-z0-9_-]{86}$"}}));var TOOL_RESULT_REVOCATION_SCHEMA=deepFreeze3(closed2({v:{const:1},kind:{const:"tool-result-revocation"},space,consentId:id,target,revokedAt:uint}));var TOOL_RESULT_SERVING_MATERIAL_SCHEMA=deepFreeze3(closed2({v:{const:1},kind:{const:"tool-result-serving-material"},space,accountPublicKey:{type:"string",pattern:"^A[A-Z2-7]{55}$"},target,grant:closed2({endpoint:{const:TOOL_RESULTS_ENDPOINT},instanceId:uid,epoch:uint,registrationRevision:{...uint,minimum:1}}),credential:{type:"string",minLength:1,maxLength:16384},snapshot:closed2({t0:uint,watermark:uint,watermarkTakenAt:uint,revokedConsentIds:{type:"array",uniqueItems:true,items:id}}),expiresAt:uint}));var TOOL_RESULT_INPUT_SCHEMA=deepFreeze3(closed2(pair));var TOOL_RESULT_ANSWER_SCHEMAS=deepFreeze3({available:status("available",{...pair,content:{type:"string",maxLength:TOOL_RESULT_MAX_CONTENT_BYTES},truncated:bool,byteCount:{...uint,maximum:TOOL_RESULT_MAX_CONTENT_BYTES},error:bool,capturedAt:uint}),pending:status("pending",pair),"not-shared":status("not-shared"),missing:status("missing"),expired:status("expired")});var TOOL_RESULT_OUTPUT_SCHEMA=deepFreeze3({oneOf:Object.values(TOOL_RESULT_ANSWER_SCHEMAS)});var TOOL_RESULT_CONSENT_INPUT_SCHEMA=deepFreeze3(closed2({consent:TOOL_RESULT_CONSENT_SCHEMA}));var TOOL_RESULT_CONSENT_OUTPUT_SCHEMA=deepFreeze3(status("active",{consentId:id}));var TOOL_RESULT_REVOKE_INPUT_SCHEMA=deepFreeze3(closed2({consentId:id}));var TOOL_RESULT_REVOKE_ANSWER_SCHEMAS=deepFreeze3({known:status("known",{consentId:id}),refused:status("refused",{consentId:id}),unknown:status("unknown",{consentId:id})});var TOOL_RESULT_REVOKE_OUTPUT_SCHEMA=deepFreeze3({oneOf:Object.values(TOOL_RESULT_REVOKE_ANSWER_SCHEMAS)});var TOOL_RESULTS_COMMANDS=deepFreeze3([{name:"tool-result",capability:"tool-results.read",input:TOOL_RESULT_INPUT_SCHEMA,output:TOOL_RESULT_OUTPUT_SCHEMA},{name:"tool-result-consent",capability:"tool-results.consent",input:TOOL_RESULT_CONSENT_INPUT_SCHEMA,output:TOOL_RESULT_CONSENT_OUTPUT_SCHEMA},{name:"tool-result-revoke",capability:"tool-results.revoke",input:TOOL_RESULT_REVOKE_INPUT_SCHEMA,output:TOOL_RESULT_REVOKE_OUTPUT_SCHEMA}]);var TOOL_RESULTS_CLUSTER=deepFreeze3({urn:"ai.cotal.tool-results",revision:1,attributes:[],events:[],commands:TOOL_RESULTS_COMMANDS.map(row=>({name:row.name,class:"ephemeral",targeted:true,modes:["handle"],capability:row.capability,inputDigest:singleDocumentClosure(row.input).closureDigest,outputDigest:singleDocumentClosure(row.output).closureDigest}))});var import_nkeys13=__toESM(require_mod(),1);var LANG_PROBLEM_DETAIL_KIND="ai.cotal.lang.problem";var RUN_ACTIVATION_WAIT_MS=15e3;var RUN_LAUNCH_DEADLINE_MS=RUN_ACTIVATION_WAIT_MS+1e4;var DELEGABLE_CAPABILITIES=Object.freeze(["spawn","run","admin"]);var import_jetstream23=__toESM(require_mod4(),1);var import_transport_node21=__toESM(require_transport_node(),1);var import_jetstream24=__toESM(require_mod4(),1);var import_kv12=__toESM(require_mod6(),1);var DIRECT_MATERIAL_VARS=["COTAL_CREDS","COTAL_SERVERS","COTAL_TOKEN","COTAL_OWNER","COTAL_ACTOR","COTAL_SENTINEL_CREDS","COTAL_BEARER_CMD","COTAL_EVENTS_REQUIRED","COTAL_CONTROL_TOKEN","COTAL_LINK"];function readMaterial(env){const path=env[LAUNCH_MATERIAL_ENV]?.trim();if(!path)return void 0;const direct=DIRECT_MATERIAL_VARS.filter(k=>env[k]?.trim());if(direct.length)throw new Error(`COTAL config: this launch carries connection material BOTH as ${LAUNCH_MATERIAL_ENV} and as ${direct.join(", ")}. One launch carries one identity plane - drop the direct variables, or drop the material file.`);return readLaunchMaterial(path)}function controlFromEnv(env=process.env){const path=env.COTAL_CONTROL_SOCKET?.trim();const token2=readMaterial(env)?.controlToken??env.COTAL_CONTROL_TOKEN?.trim();if(path&&token2)return{path,token:token2};if(!path&&!token2)return void 0;if(path)throw new Error("COTAL config: COTAL_CONTROL_SOCKET is set but no control token could be resolved - neither the launch material nor COTAL_CONTROL_TOKEN carries one. Half a pair is not a control endpoint, so this launch is refused rather than started without the control plane it was configured to have.");throw new Error("COTAL config: a control token was supplied but COTAL_CONTROL_SOCKET is unset, so there is no socket to authenticate against. Half a pair is not a control endpoint, so this launch is refused rather than started without the control plane it was configured to have.")}function hasIdentity(env=process.env){return Boolean(env.COTAL_NAME?.trim()||env.COTAL_LINK?.trim()||env.COTAL_AGENT_FILE?.trim())}var FEEDBACK_URL="https://broker.cotal.ai/v1/feedback";var PUBLIC_FEEDBACK_URL="https://cotal.ai/v1/feedback";function isAuthed(config2){return Boolean(config2.creds)||Boolean(config2.userAuth)}function splitList(v){if(!v)return[];return v.split(",").map(s=>s.trim()).filter(Boolean)}function endpointsEnv(v){let raw;try{raw=JSON.parse(v)}catch{raw=void 0}if(!Array.isArray(raw))throw new Error("COTAL_ENDPOINTS: expected the JSON list the launcher writes");return parsePersonaEndpoints(raw,"COTAL_ENDPOINTS")}function envList(v){return v===void 0?void 0:splitList(v)}var EnvFlagError=class extends Error{};function envFlag(env,name){const value=env[name]?.trim();if(!value)return void 0;if(/^(1|true|yes|on)$/i.test(value))return true;if(/^(0|false|no|off)$/i.test(value))return false;throw new EnvFlagError(`COTAL config: ${name} must be 1/true/yes/on or 0/false/no/off, got "${env[name]}"`)}function configFromEnv(env=process.env){const link=env.COTAL_LINK?.trim()?parseJoinLink(env.COTAL_LINK.trim()):void 0;const def=env.COTAL_AGENT_FILE?.trim()?loadAgentFile(env.COTAL_AGENT_FILE.trim()):void 0;const name=env.COTAL_NAME?.trim()||def?.name||(link?(0,import_node_os2.userInfo)().username:void 0);if(!name)throw new Error("COTAL_NAME, COTAL_AGENT_FILE or COTAL_LINK is required \u2014 a Cotal session needs an explicit identity from its launcher");const resolvedSubscribe=envList(env.COTAL_SUBSCRIBE)??def?.subscribe??link?.channels??[];let resolvedAllowSub;try{resolvedAllowSub=resolveReadAcl(resolvedSubscribe,envList(env.COTAL_ALLOW_SUBSCRIBE)??def?.allowSubscribe)}catch(e){throw new Error(`COTAL config: ${e.message}`)}const resolvedAllowPub=envList(env.COTAL_ALLOW_PUBLISH)??def?.allowPublish??[];for(const ch of[...resolvedSubscribe,...resolvedAllowSub,...resolvedAllowPub])assertValidChannel(ch);const qEnv=splitList(env.COTAL_QUIET),mEnv=splitList(env.COTAL_MUTED);const resolvedQuiet=qEnv.length?qEnv:def?.quiet??[];const resolvedMuted=mEnv.length?mEnv:def?.muted??[];const bothModes=resolvedQuiet.filter(c=>resolvedMuted.includes(c));if(bothModes.length)throw new Error(`COTAL config: channel(s) [${bothModes.join(", ")}] are in both quiet and muted`);for(const[field,chans]of[["quiet",resolvedQuiet],["muted",resolvedMuted]])for(const ch of chans){assertValidChannel(ch);if(!isConcreteChannel(ch))throw new Error(`COTAL config: ${field} channel "${ch}" must be concrete (no wildcard)`);if(!channelInAllow(resolvedAllowSub,ch))throw new Error(`COTAL config: ${field} channel "${ch}" is not within allowSubscribe [${resolvedAllowSub.join(", ")}]`)}const material=readMaterial(env);if(env.COTAL_SERVERS?.trim()&&brokerUrlHasUserinfo(env.COTAL_SERVERS))throw new Error("COTAL config: COTAL_SERVERS must not embed credentials; name the broker URL without user:password@, and pass the credential in COTAL_CREDS, COTAL_TOKEN or a COTAL_LINK");const credsPath=material?.creds??env.COTAL_CREDS?.trim();const initialCreds=credsPath?(0,import_node_fs7.readFileSync)(credsPath,"utf8"):void 0;const credsId=initialCreds?idFromCreds(initialCreds):void 0;const boundedCreds=initialCreds!==void 0&&typeof credsClaims(initialCreds).exp==="number";const declaredId=env.COTAL_ID?.trim()||void 0;if(declaredId&&credsId&&declaredId!==credsId)throw new Error(`COTAL config: COTAL_ID ${declaredId} != creds identity ${credsId} - they must be the same nkey`);const userVars=material?.userAuth?{owner:material.userAuth.owner,actor:material.userAuth.actor,sentinel:material.userAuth.sentinelCredsPath,bearerCmd:JSON.stringify(material.userAuth.bearerCmd)}:{owner:env.COTAL_OWNER?.trim(),actor:env.COTAL_ACTOR?.trim(),sentinel:env.COTAL_SENTINEL_CREDS?.trim(),bearerCmd:env.COTAL_BEARER_CMD?.trim()};const userSet=Object.values(userVars).filter(Boolean).length;if(userSet>0&&userSet<4)throw new Error("COTAL config: user-mode launch needs ALL of COTAL_OWNER, COTAL_ACTOR, COTAL_SENTINEL_CREDS, COTAL_BEARER_CMD \u2014 a partial set is a broken launcher, not a mode");if(userSet&&credsPath)throw new Error("COTAL config: COTAL_CREDS (static auth) and COTAL_OWNER/... (user-mode auth) are mutually exclusive");const lifecycleUid=env.COTAL_LIFECYCLE_UID?.trim()||void 0;const backfillFloorRaw=env.COTAL_BACKFILL_FLOOR?.trim()||void 0;let backfillFloor;if(backfillFloorRaw!==void 0){const n=Number(backfillFloorRaw);if(!Number.isInteger(n)||n<0)throw new Error(`COTAL config: COTAL_BACKFILL_FLOOR must be a non-negative integer stream sequence, got "${backfillFloorRaw}" (a broken launcher, not a mode)`);backfillFloor=n}const acceptedToken=env.COTAL_ACCEPTED_TOKEN?.trim()||void 0;const managerInstanceId=env.COTAL_MANAGER_INSTANCE?.trim()||void 0;if(managerInstanceId!==void 0)assertLifecycleToken(managerInstanceId,"COTAL_MANAGER_INSTANCE");if(acceptedToken&&!credsPath)throw new Error("COTAL config: COTAL_ACCEPTED_TOKEN names a static issuance and needs COTAL_CREDS beside it (a broken launcher, not a mode)");if((credsPath||userSet===4)&&!lifecycleUid)throw new Error("COTAL config: an authed launch (COTAL_CREDS or user-mode) requires COTAL_LIFECYCLE_UID - the launcher mints it at provision time (a broken launcher, not a mode)");let userAuth;if(userSet===4){let bearerCmd;try{bearerCmd=JSON.parse(userVars.bearerCmd)}catch{throw new Error("COTAL config: COTAL_BEARER_CMD must be a JSON argv array")}if(!Array.isArray(bearerCmd)||!bearerCmd.length||!bearerCmd.every(a=>typeof a==="string"))throw new Error("COTAL config: COTAL_BEARER_CMD must be a non-empty JSON array of strings");userAuth={owner:userVars.owner,actor:userVars.actor,sentinelCreds:(0,import_node_fs7.readFileSync)(userVars.sentinel,"utf8"),bearerCmd}}const eventsRequired=material?.eventsRequired===true||!material&&envFlag(env,"COTAL_EVENTS_REQUIRED")===true;if(eventsRequired&&!userAuth)throw new Error("COTAL config: COTAL_EVENTS_REQUIRED is valid only for a user-mode registration launch");if(eventsRequired){const principal=userSet===4?{owner:userVars.owner,actor:userVars.actor}:{owner:DEV_OWNER,actor:credsId??declaredId??""};if(!principal.actor)throw new Error("COTAL config: this space requires events, but the session has no stable principal to derive its event channel");const channel=eventChannel(principal);if(!channelInAllow(resolvedAllowPub,channel))throw new Error(`COTAL config: space "${env.COTAL_SPACE?.trim()||link?.space||"demo"}" requires events, but this session's grant does not cover its event channel "${channel}". Widen the whole user-auth actor row with \`cotal actor grant ${principal.actor} --owner ${principal.owner} --scope <current-scope> --allow-subscribe <current-read> --allow-publish '<current-post>,${channel}' --role <current-role> --label <current-label>\`; actor grant replaces the whole row, so preserve every current field.`)}return{space:env.COTAL_SPACE?.trim()||link?.space||"demo",id:credsId??declaredId,lifecycleUid,backfillFloor,acceptedToken,managerInstanceId,creds:boundedCreds?async()=>(0,import_node_fs7.readFileSync)(credsPath,"utf8"):initialCreds,userAuth,name,role:env.COTAL_ROLE||def?.role||void 0,description:def?.description,tags:def?.tags,meta:def?.meta,capabilities:splitList(env.COTAL_CAPABILITIES).length?splitList(env.COTAL_CAPABILITIES):def?.capabilities,endpoints:env.COTAL_ENDPOINTS!==void 0?endpointsEnv(env.COTAL_ENDPOINTS):def?.endpoints,model:env.COTAL_MODEL?.trim()||void 0,variant:env.COTAL_VARIANT?.trim()||void 0,servers:material?.servers||env.COTAL_SERVERS?.trim()||link?.servers||DEFAULT_SERVER,subscribe:resolvedSubscribe,allowSubscribe:resolvedAllowSub,allowPublish:resolvedAllowPub,eventsRequired,quiet:resolvedQuiet,muted:resolvedMuted,kind:assertValidKind(env.COTAL_KIND?.trim()||def?.kind||"agent"),token:material?.token||env.COTAL_TOKEN?.trim()||link?.token,user:link?.user,pass:link?.pass,tls:envFlag(env,"COTAL_TLS")||link?.tls||false,feedbackKey:env.COTAL_FEEDBACK_KEY?.trim()||void 0,feedbackUrl:env.COTAL_FEEDBACK_URL?.trim()||void 0}}function eventPlaneArmed(config2,env=process.env){return envFlag(env,"COTAL_EVENTS")===true||config2.eventsRequired===true}function feedbackLine(config2){const dest=config2.feedbackKey?"":`Without a feedback key it goes to the public cotal.ai intake and needs a contact email \u2014 the tool will tell you to ask the user for one if it can't find it. `;return`Use cotal_feedback with origin="human" when the user asks you to send feedback or gives you feedback to pass along. If you independently hit a major Cotal issue \u2014 for example repeated Cotal tool failures, inability to connect, lost/incorrect mesh messages, or a workflow-blocking bug \u2014 send cotal_feedback yourself with origin="agent". Do not send minor noise or secrets; include diagnostics only when they help debug the Cotal issue. `+dest}var import_node_async_hooks2=require("node:async_hooks");var import_node_events2=require("node:events");var import_node_os4=require("node:os");var import_node_path7=require("node:path");var import_node_crypto12=require("node:crypto");var import_promises3=require("node:fs/promises");var import_node_os3=require("node:os");var import_node_path5=require("node:path");var import_node_crypto11=require("node:crypto");var import_node_fs8=require("node:fs");var import_promises2=require("node:fs/promises");var import_node_path4=require("node:path");var EVENT_WAL_VERSION=3;var WalCorruptError=class extends Error{path;invariant;constructor(path,invariant,detail){super(`event WAL at ${path} is unusable (${invariant}): ${detail}`);this.path=path;this.invariant=invariant;this.name="WalCorruptError"}};var WalStaleWriterError=class extends Error{path;expectedGen;foundGen;constructor(path,expectedGen,foundGen){super(`event WAL at ${path} was written by another handle since this one read it (this handle expects generation ${expectedGen}, the file is at ${foundGen===void 0?"no file at all":`generation ${foundGen}`}) \u2014 refusing to overwrite it. A second emitter or a stale handle is writing this principal's log.`);this.path=path;this.expectedGen=expectedGen;this.foundGen=foundGen;this.name="WalStaleWriterError"}};var isSafeNonNegInt=n=>Number.isSafeInteger(n)&&n>=0;function docGeneration(path,doc){if(typeof doc.v==="number"&&doc.v<3)return 0;if(!isSafeNonNegInt(doc.gen))throw new WalCorruptError(path,"gen is a safe non-negative integer",`found gen=${String(doc.gen)} on a v${String(doc.v)} document`);return doc.gen}async function openExclusiveNoFollow(path){return(0,import_promises2.open)(path,import_node_fs8.constants.O_WRONLY|import_node_fs8.constants.O_CREAT|import_node_fs8.constants.O_EXCL|(import_node_fs8.constants.O_NOFOLLOW??0),384)}function assertPendingVintage(path,p,f){if(p.E!==f.lastSubjectSeq)throw new WalCorruptError(path,"pending.E === frontier.lastSubjectSeq",`pending.E=${p.E} frontier.lastSubjectSeq=${f.lastSubjectSeq} \u2014 the frozen expectation is not the tip this WAL believes, so retrying it can only CAS-halt or append at the wrong position`);if(p.seq!==f.seq+1)throw new WalCorruptError(path,"pending.seq === frontier.seq + 1",`pending.seq=${p.seq} frontier.seq=${f.seq} \u2014 a pending frame must be exactly the frontier's successor`);if(p.state==="sent_unacked"){if(p.ackSeq!==void 0)throw new WalCorruptError(path,"sent_unacked has no ackSeq",`state is "sent_unacked" but ackSeq=${String(p.ackSeq)} \u2014 the document contradicts its own tag`);return}if(!isSafeNonNegInt(p.ackSeq))throw new WalCorruptError(path,"acked.ackSeq present",`state is "acked" but ackSeq is ${String(p.ackSeq)}`);if(!(p.ackSeq>f.lastSubjectSeq))throw new WalCorruptError(path,"acked.ackSeq > frontier.lastSubjectSeq",`ackSeq=${p.ackSeq} frontier.lastSubjectSeq=${f.lastSubjectSeq} \u2014 the frontier is of a later vintage than the acked frame, so its sourceCursor may already have passed events that were never published; resuming would drop them with no gap for a consumer to see`)}function parseBrackets(path,field,v,nullable2){if(v===null&&nullable2)return null;if(typeof v!=="object"||v===null)throw new WalCorruptError(path,`${field} is an object${nullable2?" or null":""}`,JSON.stringify(v));const b=v;if(b.run!==void 0&&typeof b.run!=="string")throw new WalCorruptError(path,`${field}.run is a string or absent`,JSON.stringify(b.run));const lists={text:b.text,reasoning:b.reasoning,tools:b.tools};for(const[k,list2]of Object.entries(lists)){if(!Array.isArray(list2)||list2.some(x=>typeof x!=="string"))throw new WalCorruptError(path,`${field}.${k} is an array of strings`,JSON.stringify(list2))}if(b.run===void 0&&b.text.concat(b.reasoning,b.tools).length>0)throw new WalCorruptError(path,`${field} has no open run while messages or tool calls are open`,JSON.stringify(b));return{run:b.run,text:b.text,reasoning:b.reasoning,tools:b.tools}}function parseDoc(path,raw,space2,threadId,principal){let d;try{d=JSON.parse(raw)}catch(e){throw new WalCorruptError(path,"parseable JSON",e.message)}if(typeof d!=="object"||d===null)throw new WalCorruptError(path,"document is an object",typeof d);const doc=d;if(typeof doc.v!=="number"||!Number.isSafeInteger(doc.v)||doc.v<1)throw new WalCorruptError(path,"v is a positive integer",`found v=${String(doc.v)}`);if(doc.v>EVENT_WAL_VERSION)throw new WalCorruptError(path,`v <= ${EVENT_WAL_VERSION}`,`this WAL is v${doc.v} and this build understands v${EVENT_WAL_VERSION} \u2014 THE STATE IS NEWER THAN THE CODE, which is what a code rollback across the v2 migration (persisted bracket state) or the v3 one (the write generation) leaves behind. The migration is forward-only by design: there is no downgrade, because a lossy one would silently discard state this file exists to preserve. Run the newer build, or move this WAL aside and accept that the thread restarts from a new epoch.`);if(doc.space!==space2)throw new WalCorruptError(path,"space matches",`WAL space=${String(doc.space)} caller=${space2}`);if(doc.threadId!==threadId)throw new WalCorruptError(path,"threadId matches",`WAL threadId=${String(doc.threadId)} caller=${threadId}`);if(doc.principal!==principal)throw new WalCorruptError(path,"principal matches",`WAL principal=${String(doc.principal)} caller=${principal}`);if(typeof doc.epoch!=="string"||doc.epoch.length===0)throw new WalCorruptError(path,"epoch is a non-empty string",String(doc.epoch));const f=doc.frontier;if(!f||!isSafeNonNegInt(f.seq)||!isSafeNonNegInt(f.lastSubjectSeq))throw new WalCorruptError(path,"frontier is well-formed",JSON.stringify(doc.frontier));if(f.sourceCursor!==void 0&&typeof f.sourceCursor!=="string")throw new WalCorruptError(path,"frontier.sourceCursor is a string or absent",typeof f.sourceCursor);if(f.seq===0!==(f.lastSubjectSeq===0))throw new WalCorruptError(path,"frontier.seq and lastSubjectSeq are both zero or both nonzero",JSON.stringify(f));if((f.seq>0||f.lastSubjectSeq>0)&&typeof f.sourceCursor!=="string")throw new WalCorruptError(path,"a nonzero frontier carries its sourceCursor",JSON.stringify(f));if(doc.pending!==null&&typeof doc.pending!=="object")throw new WalCorruptError(path,"pending is present (null or an object)",doc.pending===void 0?"the key is absent, which is not the same as null":typeof doc.pending);let pending=null;if(doc.pending!==null){const p=doc.pending;if(p.state!=="sent_unacked"&&p.state!=="acked")throw new WalCorruptError(path,"pending.state is a known tag",String(p.state));if(typeof p.id!=="string"||p.id.length===0)throw new WalCorruptError(path,"pending.id is a non-empty string",String(p.id));try{assertIdToken(p.id,"event WAL pending.id")}catch(e){throw new WalCorruptError(path,"pending.id satisfies the wire id grammar",e.message)}if(!isSafeNonNegInt(p.E)||!isSafeNonNegInt(p.seq))throw new WalCorruptError(path,"pending E/seq are safe non-negative integers",JSON.stringify(p));if(typeof p.sourceCursor!=="string")throw new WalCorruptError(path,"pending.sourceCursor is a string",typeof p.sourceCursor);if(!Array.isArray(p.body)||p.body.length===0)throw new WalCorruptError(path,"pending.body is a non-empty array of parts",JSON.stringify(p.body));if(doc.v===1)throw new WalCorruptError(path,"a v1 WAL has no frame in flight",`this v1 document holds a ${String(p.state)} frame, and v2 requires the bracket state that belongs to it \u2014 which v1 never recorded and nothing here can reconstruct. Let the older build settle this frame first, then start the newer one.`);p.brackets=parseBrackets(path,"pending.brackets",p.brackets,false);pending=p;assertPendingVintage(path,pending,f)}const brackets=doc.v===1?null:parseBrackets(path,"brackets",doc.brackets,true);return{v:EVENT_WAL_VERSION,gen:docGeneration(path,doc),space:space2,epoch:doc.epoch,threadId,principal,frontier:f,pending,brackets}}var EventWal=class _EventWal{path;doc;chain=Promise.resolve();serialize(op){const next=this.chain.then(op,op);this.chain=next.catch(()=>void 0);return next}constructor(path,doc){this.path=path;this.doc=doc}get epoch(){return this.doc.epoch}get principal(){return this.doc.principal}get threadId(){return this.doc.threadId}get brackets(){return this.doc.brackets}get frontier(){return{...this.doc.frontier}}get pending(){return this.doc.pending?{...this.doc.pending}:null}subject;static async open(path,opts){let raw;let bytes;try{bytes=await(0,import_promises2.readFile)(path)}catch(e){if(e.code!=="ENOENT")throw e}if(bytes!==void 0){try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new WalCorruptError(path,"the file is valid UTF-8","invalid UTF-8 bytes; refusing rather than substituting U+FFFD")}}if(raw===void 0){if(opts.subjectMayExist)throw new WalCorruptError(path,"WAL exists when the subject may","no WAL file, but this thread may already have published");return new _EventWal(path,_EventWal.virgin(opts.space,opts.threadId,opts.principal))}if(raw.length===0)throw new WalCorruptError(path,"WAL is non-empty","the file is zero bytes \u2014 distinct from missing and never treated as a virgin thread");return new _EventWal(path,parseDoc(path,raw,opts.space,opts.threadId,opts.principal))}static virgin(space2,threadId,principal){return{v:EVENT_WAL_VERSION,gen:0,space:space2,epoch:(0,import_node_crypto11.randomUUID)(),threadId,principal,frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}}}async bindSubjectFrontier(frontier){if(this.subject===frontier)return;if(this.subject)throw new Error(`event WAL ${this.path}: a DIFFERENT subject frontier is already bound`);this.subject=frontier}get expectedTip(){if(!this.subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so there is no expectation to publish. The subject is shared by every thread of this principal, so this document's own last ack is not it; bind the principal's record with bindSubjectFrontier first.`);return this.subject.tip}async beginSend(frame){return this.serialize(async()=>{if(this.doc.pending)throw new Error(`event WAL ${this.path}: a frame is already pending; one emit unit is one pending frame`);assertIdToken(frame.id,"event WAL pending id");if(frame.E!==this.expectedTip)throw new Error(`event WAL ${this.path}: E=${frame.E} is not the subject's tip ${this.expectedTip}`);if(frame.seq!==this.doc.frontier.seq+1)throw new Error(`event WAL ${this.path}: seq=${frame.seq} is not the frontier's successor ${this.doc.frontier.seq+1}`);if(!Array.isArray(frame.body)||frame.body.length===0)throw new Error(`event WAL ${this.path}: a frame body must be a non-empty array of parts`);await this.write({...this.doc,pending:{state:"sent_unacked",...frame}})})}async recordAck(ackSeq){return this.serialize(async()=>{const p=this.doc.pending;if(!p||p.state!=="sent_unacked")throw new Error(`event WAL ${this.path}: no sent_unacked frame to ack`);if(!isSafeNonNegInt(ackSeq))throw new Error(`event WAL ${this.path}: ackSeq must be a safe non-negative integer, got ${String(ackSeq)}`);if(ackSeq<=this.expectedTip)throw new Error(`event WAL ${this.path}: ackSeq=${ackSeq} is not ahead of the subject's tip ${this.expectedTip}`);const subject=this.subject;if(!subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so this ack has no shared record to advance`);await this.assertNotClobbering();await subject.advance(ackSeq);await this.write({...this.doc,pending:{...p,state:"acked",ackSeq}})})}async fold(){return this.serialize(async()=>{const p=this.doc.pending;if(!p||p.state!=="acked"||p.ackSeq===void 0)throw new Error(`event WAL ${this.path}: no acked frame to fold`);await this.write({...this.doc,frontier:{seq:p.seq,lastSubjectSeq:p.ackSeq,sourceCursor:p.sourceCursor},pending:null,brackets:p.brackets})})}async advanceCursorOnly(rangeEnd){return this.serialize(async()=>{if(this.doc.pending)throw new Error(`event WAL ${this.path}: cannot advance the cursor while a frame is pending`);await this.write({...this.doc,frontier:{...this.doc.frontier,sourceCursor:rangeEnd}})})}async abandon(){return this.serialize(async()=>{await this.assertNotClobbering();if(!this.subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so an abandonment here would clear this log and leave the principal's shared tip standing, which is the partial abandonment this method refuses to produce; bind the principal's record with bindSubjectFrontier first.`);await this.subject.reset();await this.write({...this.doc,epoch:(0,import_node_crypto11.randomUUID)(),frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}})})}async write(next){await this.assertNotClobbering();const stamped={...next,gen:this.doc.gen+1};const tmp=(0,import_node_path4.join)((0,import_node_path4.dirname)(this.path),`.${(0,import_node_crypto11.createHash)("sha256").update(this.path).digest("hex").slice(0,12)}.${process.pid}.${(0,import_node_crypto11.randomUUID)().slice(0,8)}.wal.tmp`);const body=JSON.stringify(stamped);const fh=await openExclusiveNoFollow(tmp);try{await fh.writeFile(body,"utf8");await fh.sync()}finally{await fh.close()}try{await(0,import_promises2.rename)(tmp,this.path)}catch(e){await(0,import_promises2.unlink)(tmp).catch(()=>{});throw e}this.doc=stamped}async assertNotClobbering(){let bytes;try{bytes=await(0,import_promises2.readFile)(this.path)}catch(e){if(e.code!=="ENOENT")throw e}if(bytes===void 0){if(this.doc.gen!==0)throw new WalStaleWriterError(this.path,this.doc.gen,void 0);return}let raw;try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new WalCorruptError(this.path,"the file is valid UTF-8","invalid UTF-8 bytes on the file about to be replaced; refusing rather than substituting U+FFFD")}let d;try{d=JSON.parse(raw)}catch(e){throw new WalCorruptError(this.path,"parseable JSON",e.message)}if(typeof d!=="object"||d===null)throw new WalCorruptError(this.path,"document is an object",typeof d);const onDisk=docGeneration(this.path,d);if(onDisk!==this.doc.gen)throw new WalStaleWriterError(this.path,this.doc.gen,onDisk)}};var EventsStateRootMissing=class extends Error{constructor(message){super(message);this.name="EventsStateRootMissing"}};function resolveEventsStateRoot(env){const root=env.COTAL_WORKSPACE_ROOT;if(typeof root!=="string"||root.trim()==="")throw new EventsStateRootMissing("events are enabled for this session but COTAL_WORKSPACE_ROOT is not set, so there is nowhere to put the event write-ahead log. The launcher forwards it from LaunchOpts.workspaceRoot; a session started outside a manager has no workspace root and must not publish events. Refusing rather than defaulting to the working directory, which would put the WAL somewhere no later start looks.");return root}function h(value){return(0,import_node_crypto12.createHash)("sha256").update(value).digest("hex").slice(0,16)}function eventWalLocation(opts){const principal=eventPrincipalLocation(opts);const threadDir=(0,import_node_path5.join)(principal.principalDir,h(opts.threadId));return{...principal,threadDir,walPath:(0,import_node_path5.join)(threadDir,"wal.json")}}function eventPrincipalLocation(opts){const principalDir=(0,import_node_path5.join)(opts.workspaceRoot,".cotal","events",h(opts.space),h(opts.principal));return{principalDir,lockPath:(0,import_node_path5.join)(principalDir,".lock"),subjectPath:(0,import_node_path5.join)(principalDir,"subject.json")}}var PrincipalLockError=class extends Error{path;invariant;constructor(path,invariant,detail){super(`event WAL principal lock at ${path} (${invariant}): ${detail}`);this.path=path;this.invariant=invariant;this.name="PrincipalLockError"}};var held=new Map;function ownerIsAlive(pid){try{process.kill(pid,0);return true}catch(e){return e.code!=="ESRCH"}}async function createLockFile(path){try{return await openExclusiveNoFollow(path)}catch(e){if(e.code==="EEXIST")return void 0;throw e}}async function reclaimIfOwnerIsGone(path){let raw;try{raw=await(0,import_promises3.readFile)(path,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}let record3;try{record3=JSON.parse(raw)}catch{throw new PrincipalLockError(path,"the lock names its owner","the file is not readable JSON, so its owner cannot be checked; refusing rather than reclaiming a lock that may be held")}const r=record3;if(!Number.isSafeInteger(r.pid)||r.pid<=0||typeof r.host!=="string"||r.host.length===0)throw new PrincipalLockError(path,"the lock names its owner",`the record carries pid=${String(r.pid)} host=${String(r.host)}, which names nobody checkable`);const here=(0,import_node_os3.hostname)();if(r.host!==here)throw new PrincipalLockError(path,"the recorded owner is on THIS host",`held by pid ${r.pid} on ${r.host} while this process runs on ${here}; liveness on another machine is not observable from here`);if(ownerIsAlive(r.pid))throw new PrincipalLockError(path,"the recorded owner is gone",`pid ${r.pid} on ${here} is still running and holds this principal's emitter`);await(0,import_promises3.unlink)(path).catch(e=>{if(e.code!=="ENOENT")throw e})}async function acquirePrincipalLock(lockPath){const already=held.get(lockPath);if(already)return already;let fh=await createLockFile(lockPath);if(fh===void 0){await reclaimIfOwnerIsGone(lockPath);fh=await createLockFile(lockPath);if(fh===void 0)throw new PrincipalLockError(lockPath,"the reclaimed lock is free when this process takes it","another process created the lock between the reclaim and this open, and now holds this principal")}const record3=JSON.stringify({pid:process.pid,host:(0,import_node_os3.hostname)(),token:(0,import_node_crypto12.randomUUID)(),acquiredAt:new Date().toISOString()});try{await fh.writeFile(record3,"utf8");await fh.sync()}catch(e){await fh.close().catch(()=>{});await(0,import_promises3.unlink)(lockPath).catch(()=>{});throw e}const lock={path:lockPath,async release(){if(held.get(lockPath)!==lock)return;held.delete(lockPath);await fh.close().catch(()=>{});await(0,import_promises3.unlink)(lockPath).catch(e=>{if(e.code!=="ENOENT")throw e})}};held.set(lockPath,lock);return lock}async function fsyncDir(dir){let fh;try{fh=await(0,import_promises3.open)(dir,"r")}catch(e){const code=e.code;if(code==="EPERM"||code==="EACCES")return;throw e}try{await fh.sync()}catch(e){const code=e.code;if(code!=="EBADF"&&code!=="EINVAL"&&code!=="EPERM"&&code!=="EISDIR")throw e}finally{await fh.close()}}async function ensureEventWalDir(opts){const loc=eventWalLocation(opts);ensureDirNoSymlink(opts.workspaceRoot,".cotal","events",h(opts.space),h(opts.principal),h(opts.threadId));for(let dir=loc.threadDir;;dir=(0,import_node_path5.dirname)(dir)){await fsyncDir(dir);if(dir===opts.workspaceRoot||(0,import_node_path5.dirname)(dir)===dir)break}const lock=await acquirePrincipalLock(loc.lockPath);return{...loc,lock}}var import_node_crypto13=require("node:crypto");var import_node_fs9=require("node:fs");var import_promises4=require("node:fs/promises");var import_node_path6=require("node:path");var SUBJECT_FRONTIER_VERSION=1;var SubjectFrontierCorruptError=class extends Error{path;invariant;constructor(path,invariant,detail){super(`subject frontier ${path}: expected ${invariant} \u2014 ${detail}`);this.path=path;this.invariant=invariant;this.name="SubjectFrontierCorruptError"}};var SubjectFrontierMovedError=class extends Error{path;viewTip;diskTip;constructor(path,viewTip,diskTip){super(`subject frontier ${path}: the record moved under this writer (this view holds ${viewTip}, the file holds ${diskTip===void 0?"no record at all":diskTip}). The tip is shared by every thread of the principal, so writing this view's number would take the record backwards to a sequence the broker has already passed, and every later publish would expect a tip the subject no longer has.`);this.path=path;this.viewTip=viewTip;this.diskTip=diskTip;this.name="SubjectFrontierMovedError"}};var isSafeNonNegInt2=n=>typeof n==="number"&&Number.isSafeInteger(n)&&n>=0;var isFrontierTip=n=>isSafeNonNegInt2(n)&&n<Number.MAX_SAFE_INTEGER;var FileSubjectFrontier=class _FileSubjectFrontier{path;doc;constructor(path,doc){this.path=path;this.doc=doc}get tip(){return this.doc.tip}static async readRecord(path){let st;try{st=await(0,import_promises4.lstat)(path)}catch(e){if(e.code==="ENOENT")return void 0;throw e}if(st.isSymbolicLink())throw new SubjectFrontierCorruptError(path,"a real subject record, never a symlink","the writer never wrote a symlink");try{const fh=await(0,import_promises4.open)(path,import_node_fs9.constants.O_RDONLY|(import_node_fs9.constants.O_NOFOLLOW??0));try{return await fh.readFile()}finally{await fh.close()}}catch(e){const code=e.code;if(code==="ENOENT")return void 0;if(code==="ELOOP")throw new SubjectFrontierCorruptError(path,"a real subject record, never a symlink","the record became a symlink between the check and the open");throw e}}static async open(path,opts){const bytes=await _FileSubjectFrontier.readRecord(path);if(bytes===void 0){const recovered=await _FileSubjectFrontier.recoverTipFromThreadLogs((0,import_node_path6.dirname)(path),opts.principal);const fresh=new _FileSubjectFrontier(path,{v:SUBJECT_FRONTIER_VERSION,space:opts.space,principal:opts.principal,tip:0});if(recovered>0)await fresh.write({...fresh.doc,tip:recovered});return fresh}return new _FileSubjectFrontier(path,_FileSubjectFrontier.parse(path,bytes,opts))}static async recordedTip(path,opts){const bytes=await _FileSubjectFrontier.readRecord(path);return bytes===void 0?_FileSubjectFrontier.recoverTipFromThreadLogs((0,import_node_path6.dirname)(path),opts.principal):_FileSubjectFrontier.parse(path,bytes,opts).tip}static parse(path,bytes,opts){let raw;try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new SubjectFrontierCorruptError(path,"valid UTF-8","invalid UTF-8 bytes; refusing rather than substituting U+FFFD")}if(raw.length===0)throw new SubjectFrontierCorruptError(path,"a non-empty file","the file is zero bytes \u2014 distinct from missing, and never treated as virgin");let parsed;try{parsed=JSON.parse(raw)}catch(e){throw new SubjectFrontierCorruptError(path,"parseable JSON",e.message)}const d=parsed;if(d?.v!==SUBJECT_FRONTIER_VERSION)throw new SubjectFrontierCorruptError(path,`v === ${SUBJECT_FRONTIER_VERSION}`,String(d?.v));if(d.space!==opts.space)throw new SubjectFrontierCorruptError(path,"space matches",`file=${String(d.space)} caller=${opts.space}`);if(d.principal!==opts.principal)throw new SubjectFrontierCorruptError(path,"principal matches",`file=${String(d.principal)} caller=${opts.principal}`);if(!isFrontierTip(d.tip))throw new SubjectFrontierCorruptError(path,"tip is a safe non-negative integer below Number.MAX_SAFE_INTEGER",String(d.tip));return{v:d.v,space:d.space,principal:d.principal,tip:d.tip}}async advance(seq){return this.serialize(async()=>{if(!isFrontierTip(seq))throw new Error(`subject frontier ${this.path}: seq must be a safe non-negative integer below Number.MAX_SAFE_INTEGER, got ${String(seq)}`);if(seq<=this.doc.tip)throw new Error(`subject frontier ${this.path}: seq=${seq} does not advance the tip ${this.doc.tip}`);const disk=await this.readDiskTip();if(disk===void 0?this.doc.tip!==0:disk!==this.doc.tip)throw new SubjectFrontierMovedError(this.path,this.doc.tip,disk);await this.write({...this.doc,tip:seq})})}async readDiskTip(){const bytes=await _FileSubjectFrontier.readRecord(this.path);if(bytes===void 0)return void 0;return _FileSubjectFrontier.parse(this.path,bytes,{space:this.doc.space,principal:this.doc.principal}).tip}chain=Promise.resolve();serialize(op){const next=this.chain.then(op,op);this.chain=next.catch(()=>void 0);return next}static async recoverTipFromThreadLogs(principalDir,principal){let entries;try{entries=await(0,import_promises4.readdir)(principalDir,{withFileTypes:true})}catch(e){if(e.code==="ENOENT")return 0;throw e}let best=0;for(const ent of entries){if(ent.isSymbolicLink())throw new SubjectFrontierCorruptError((0,import_node_path6.join)(principalDir,ent.name),"a real directory beside the record, never a symlink","following it would carry this scan outside the principal directory, and the writer that creates these directories refuses a symlinked component for the same reason");if(!ent.isDirectory())continue;const walPath=(0,import_node_path6.join)(principalDir,ent.name,"wal.json");let st;try{st=await(0,import_promises4.lstat)(walPath)}catch(e){const code=e.code;if(code==="ENOENT"||code==="ENOTDIR")continue;throw e}if(st.isSymbolicLink())throw new SubjectFrontierCorruptError(walPath,"a real thread log, never a symlink","following it would read a log this principal's writer never wrote");if(st.nlink>1)throw new SubjectFrontierCorruptError(walPath,"a thread log with exactly one name",`it has ${st.nlink}, so the same file is reachable from outside this principal's directory and its tip is not this principal's to read`);let raw;try{const fh=await(0,import_promises4.open)(walPath,import_node_fs9.constants.O_RDONLY|(import_node_fs9.constants.O_NOFOLLOW??0));try{raw=await fh.readFile()}finally{await fh.close()}}catch(e){const code=e.code;if(code==="ENOENT"||code==="ENOTDIR")continue;if(code==="ELOOP")throw new SubjectFrontierCorruptError(walPath,"a real thread log, never a symlink","the file became a symlink between the check and the open");throw e}let doc;try{doc=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(raw))}catch(e){throw new SubjectFrontierCorruptError(walPath,"a readable thread log while recovering the subject tip",e.message)}if(doc.principal!==principal)throw new SubjectFrontierCorruptError(walPath,`a thread log for principal ${principal}`,`found ${String(doc.principal)}`);const seq=doc.frontier?.lastSubjectSeq;if(!isSafeNonNegInt2(seq))throw new SubjectFrontierCorruptError(walPath,"frontier.lastSubjectSeq is a safe non-negative integer",String(seq));if(seq>best)best=seq;const pending=doc.pending;if(pending&&pending.state==="acked"){const acked=pending.ackSeq;if(!isSafeNonNegInt2(acked))throw new SubjectFrontierCorruptError(walPath,"an acked pending carries a safe non-negative ackSeq",String(acked));if(!(acked>seq))throw new SubjectFrontierCorruptError(walPath,"an acked pending is ahead of the frontier it will fold into",`ackSeq=${acked} frontier.lastSubjectSeq=${seq}`);if(acked>best)best=acked}}return best}async reset(){return this.serialize(async()=>{await this.write({...this.doc,tip:0})})}async write(next){const tmp=`${this.path}.${(0,import_node_crypto13.randomUUID)()}.tmp`;const fh=await(0,import_promises4.open)(tmp,import_node_fs9.constants.O_WRONLY|import_node_fs9.constants.O_CREAT|import_node_fs9.constants.O_EXCL,384);try{await fh.writeFile(JSON.stringify(next));await fh.sync()}finally{await fh.close()}try{let st;try{st=await(0,import_promises4.lstat)(this.path)}catch(e){if(e.code!=="ENOENT")throw e}if(st?.isSymbolicLink())throw new SubjectFrontierCorruptError(this.path,"a real subject record, never a symlink","the writer never wrote a symlink");await(0,import_promises4.rename)(tmp,this.path)}catch(e){await(0,import_promises4.unlink)(tmp).catch(()=>{});throw e}await fsyncDir((0,import_node_path6.dirname)(this.path));this.doc=next}};var EventStateConflictError=class extends Error{constructor(message){super(message);this.name="EventStateConflictError"}};async function checkEventStartup(ep,env){const workspaceRoot=resolveEventsStateRoot(env);const principal=principalKey(ep.principal.owner,ep.principal.actor).key;const loc=eventPrincipalLocation({workspaceRoot,space:ep.space,principal});ensureDirNoSymlink(workspaceRoot,...(0,import_node_path7.relative)(workspaceRoot,loc.principalDir).split(import_node_path7.sep));const tip=await FileSubjectFrontier.recordedTip(loc.subjectPath,{space:ep.space,principal});if(tip!==0)return;const retention=await ep.chatRetention();if(retention.senders.some(row=>row.sender===principal&&row.channel===eventChannel(ep.principal)&&row.messages>0)){throw new EventStateConflictError(`Cannot start events for ${principal}: this state root has no acknowledged transcript frontier, but the broker retains events for this principal. Reuse the previous state root or launch with a new principal. Refusing before work; the existing transcript and local logs are unchanged.`)}}var TURN_PULL_RETRY_MS=15e3;var ONCE_HANDOFF_MS=6e4;var ONCE_EXIT_GRACE_MS=1e4;var KEY=Symbol.for("cotal.once-handoff");function proc(){const g=globalThis;return g[KEY]??={handoffs:new Map}}var keyOf=(uid2,goalId)=>`${uid2}:${goalId}`;function onceHandoffState(uid2,goalId){return proc().handoffs.get(keyOf(uid2,goalId))?.state??"pending"}function claimOnceHandoff(uid2,goalIds){const p=proc();if(goalIds.some(id2=>onceHandoffState(uid2,id2)!=="pending"))return false;for(const id2 of goalIds){const timer=setTimeout(()=>p.timedOut?.(uid2,id2),ONCE_HANDOFF_MS);timer.unref?.();p.handoffs.set(keyOf(uid2,id2),{state:"claimed",timer})}return true}function confirmOnceHandoff(uid2,goalId){const h2=proc().handoffs.get(keyOf(uid2,goalId));if(h2?.state==="sealed")return false;if(h2?.timer!==void 0)clearTimeout(h2.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"confirmed"});return true}function sealOnceHandoff(uid2,goalId){const h2=proc().handoffs.get(keyOf(uid2,goalId));if(h2?.state!=="claimed")return false;if(h2.timer!==void 0)clearTimeout(h2.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"sealed"});return true}function endOnceHandoff(uid2,goalId){const h2=proc().handoffs.get(keyOf(uid2,goalId));if(h2?.state==="confirmed"||h2?.state==="sealed")return;if(h2?.timer!==void 0)clearTimeout(h2.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"sealed"})}function stopOnceHandoffTimer(uid2,goalId){const h2=proc().handoffs.get(keyOf(uid2,goalId));if(h2?.state!=="claimed"||h2.timer===void 0)return;clearTimeout(h2.timer);h2.timer=void 0}function onOnceHandoffTimeout(fn){proc().timedOut=fn}function registerOnceExit(fn){proc().exit=fn}function exitOnceSeat(){const p=proc();if(p.exiting)return p.exiting;const exiting=askOnceExit(p.exit).then(ending=>{if(!ending){p.exiting=void 0;return false}setTimeout(()=>process.exit(1),ONCE_EXIT_GRACE_MS);return true});p.exiting=exiting;return exiting}async function askOnceExit(exit){let ending;try{ending=exit?.()}catch{return true}if(ending instanceof Promise)ending=await ending.catch(()=>false);return ending!==false}var PREVIEW_CONTROL=/(?!\n)[\p{Cc}\p{Cs}]/gu;function boundedRow(row,maxCodePoints){const points=Array.from(row);return points.length<=maxCodePoints?row:`${points.slice(0,maxCodePoints-1).join("")}\u2026`}function renderInboxPreview(snapshot,maxRowCodePoints=240){if(!Number.isInteger(maxRowCodePoints)||maxRowCodePoints<16||maxRowCodePoints>1e3)throw new Error(`inbox preview row bound must be a whole number from 16 to 1000, got ${maxRowCodePoints}`);return{unread:snapshot.unread,rows:snapshot.items.map(item=>boundedRow(fmtItem(item).replace(PREVIEW_CONTROL,"\uFFFD"),maxRowCodePoints))}}function attributionSafe(s){return peerLabel({name:s})}function fmtFrom(i){return peerLabel({name:i.fromName,role:i.fromRole})}function fmtBody(text2){return text2.split(LINE_BREAK).join("\n ")}function fmtItem(i){return formatItem(i)}function fmtDeliveryItem(i){const field=value=>Array.from(JSON.stringify(value),char=>[91,93,133,8232,8233].includes(char.charCodeAt(0))?`\\u${char.charCodeAt(0).toString(16).padStart(4,"0")}`:char).join("");const metadata2=[`sender_id=${field(i.fromId)}`,...i.id?[`message_id=${field(i.id)}`]:[],...i.contextId?[`context_id=${field(i.contextId)}`]:[],...i.replyTo?[`reply_to=${field(i.replyTo)}`]:[]];return formatItem(i,`[${metadata2.join(" ")}] `)}function formatItem(i,metadata2=""){const h2=i.historical?"(history) ":"";const r=i.deliveryCount!==void 0&&i.deliveryCount>1?`(broker redelivery, delivery ${i.deliveryCount}: prior model handoff unknown) `:"";const body=`${metadata2}${h2}${r}${fmtBody(i.text)}`;if(i.notice==="anycast")return`[anycast notice from the delivery daemon] ${body}`;if(i.kind==="dm")return`[DM from ${fmtFrom(i)}] ${body}`;if(i.kind==="anycast")return`[@${attributionSafe(i.service??"")} from ${fmtFrom(i)}] ${body}`;return`[#${attributionSafe(i.channel??"")}${i.mentionsMe?" @you":""} ${fmtFrom(i)}] ${body}`}function fmtChannel(channel){const safe=attributionSafe(channel??"").trim();return safe.length?safe:"?"}function fmtKind(kind){const safe=attributionSafe(kind??"").trim();return safe.length?safe:"message"}var legacyRail=new Map;var LEGACY_RAIL_RECHECK_MS=60*6e4;var LEGACY_RAIL_MAX=32;function onLegacyRail(key){const until=legacyRail.get(key);if(until===void 0)return false;if(Date.now()<until)return true;legacyRail.delete(key);return false}function rememberLegacyRail(key){legacyRail.set(key,Date.now()+LEGACY_RAIL_RECHECK_MS);if(legacyRail.size>LEGACY_RAIL_MAX)legacyRail.delete(legacyRail.keys().next().value)}async function withUserManagerListing(config2,token2,exp,ask){const user=config2.userAuth;const binding=managerCallerBinding(token2,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId});const railKey=binding.credentialId??token2;const connectOpts=standaloneConnectOpts({bearer:token2,sentinelCreds:user.sentinelCreds,tls:config2.tls});const connId=String(connectOpts.name);const nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:1e4});const issued=async()=>{try{const caller=await issuedUserCaller(nc,config2.space,connId,binding.caller);legacyRail.delete(railKey);return caller}catch(e){if(!isPermissionDenied(e))throw e;rememberLegacyRail(railKey);return void 0}};try{const skipped=onLegacyRail(railKey);const caller=skipped?void 0:await issued();const listing=caller??await registryListingCaller(nc,config2.space,binding.caller,{connId,...exp!==void 0?{exp}:{}});return await ask(nc,listing??(skipped?await issued():void 0))}finally{await drainAndClose(nc)}}async function invokeUserManager(config2,bearer,command,args,opts={}){opts.signal?.throwIfAborted();const user=config2.userAuth;const endpoint=BASELINE_LIFECYCLE_ENDPOINT;let nc;let caller;let instanceId;let service;let skippedAcceptedRead;const onAbort=()=>{void nc?.close()};const resolve=(signal=opts.signal,deadlineMs=opts.deadlineMs??1e4)=>resolveService(nc,config2.space,endpoint,caller,{instanceId,deadlineMs,signal,commands:opts.follow?[command,"goal-result"]:[command],...opts.follow&&command!=="goal-result"?{optionalCommands:["goal-result"]}:{}});const resolvePrepared=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const remaining=()=>{signal?.throwIfAborted();const left=deadline-Date.now();if(left<=0)throw new EpEnvelopeError("deadline-exceeded","the deadline passed before the manager was resolved; the manager request WAS NOT RUN",void 0,"not-executed");return left};try{return await resolve(signal,remaining())}catch(error51){if(!skippedAcceptedRead||!isPermissionDenied(error51))throw error51;const{key,connId}=skippedAcceptedRead;skippedAcceptedRead=void 0;remaining();caller=await issuedUserCaller(nc,config2.space,connId,caller);legacyRail.delete(key);return resolve(signal,remaining())}};const connect3=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const token2=await bearer(signal);let credentialId;({caller,instanceId,credentialId}=managerCallerBinding(token2,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId}));const connectOpts=standaloneConnectOpts({bearer:token2,sentinelCreds:user.sentinelCreds,tls:config2.tls});signal?.throwIfAborted();const left=deadline-Date.now();if(left<=0)throw new EpEnvelopeError("deadline-exceeded","the deadline passed before the manager was connected; the manager request WAS NOT RUN",void 0,"not-executed");nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:left});if(signal?.aborted)onAbort();signal?.throwIfAborted();const railKey=credentialId??token2;if(onLegacyRail(railKey)){skippedAcceptedRead={key:railKey,connId:String(connectOpts.name)}}else{try{caller=await issuedUserCaller(nc,config2.space,String(connectOpts.name),caller)}catch(e){if(!isPermissionDenied(e))throw e;rememberLegacyRail(railKey)}}};const prepare=async(signal,deadline)=>{await connect3(signal,deadline);service=await resolvePrepared(signal,deadline)};const invoke=async(signal=opts.signal)=>{const unfollowable=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable)return unfollowable;const invokeOpts={target:opts.target,deadlineMs:opts.deadlineMs,signal};const result=await invokeCommand(nc,config2.space,service,command,args,invokeOpts);if(result.reply.ok===false&&replyRefusedBeforeEffect(result.reply.error)){try{service=await resolve(signal);const unfollowable2=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable2)throw new Error(unfollowable2.reply.error.message)}catch(error51){return{...result,reply:{...result.reply,error:{...result.reply.error,message:`${command} WAS NOT RUN; manager instance ${instanceId} refused before effects, and re-resolution failed: ${error51 instanceof Error?error51.message:String(error51)}`}}}}return invokeCommand(nc,config2.space,service,command,args,invokeOpts)}return result};opts.signal?.addEventListener("abort",onAbort,{once:true});try{if(opts.follow)return await opts.follow(invoke,prepare);await connect3();service=await resolvePrepared();return await invoke()}finally{opts.signal?.removeEventListener("abort",onAbort);const control=nc;if(control)await drainAndClose(control,2e3)}}var import_node_crypto14=require("node:crypto");var SPAWN_TIMEOUT_MS=4e4;var MANAGER_BEARER_MARGIN_MS=12e4;var CONNECT_GRACE_MS=1e4;function isLocalServer(servers){return servers.split(",").every(s=>/^(?:[a-z]+:\/\/)?(?:[^@/]*@)?(?:localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(?::\d+)?(?:\/|$)/i.test(s.trim()))}var EVENTS_META_KEY="ai.cotal.events";function buildMeta(config2,processCwd){const meta3={...config2.meta??{}};if(config2.model)meta3.model=config2.model;if(config2.variant)meta3.variant=config2.variant;if(config2.connector)meta3.connector=config2.connector;meta3.host=(0,import_node_os4.hostname)();delete meta3["ai.cotal.manager.instance"];if(config2.managerInstanceId)meta3["ai.cotal.manager.instance"]=config2.managerInstanceId;meta3[EVENTS_META_KEY]=eventPlaneArmed(config2)?"on":"off";if(processCwd)meta3.cwd=process.cwd();else delete meta3.cwd;return Object.keys(meta3).length?meta3:void 0}function afterRecallMark(a,b){return a.ts!==b.ts?a.ts>b.ts:a.id>b.id}var MAX_INBOX=200;var TAKE_WAIT_MS=2e3;var TAKE_RETRY_MS=1e4;var MAX_IN_FLIGHT=MAX_INBOX*2;var MAX_AHEAD=256;var CLASSIFICATION_CAP=4096;var FOCUS_EXCLUSION_CAP=4096;var IDLESS_READS=3;var PROTECTED_DISPOSITION_CAP=4096;var MAX_CORRELATIONS=1024;var ENDPOINT_ERROR_LOG_WINDOW_MS=3e4;var MAX_ENDPOINT_NOTICES=16;var NAMED_SIMILAR=5;var MAX_SETTLED_TURNS=32;function settledTurnError(goalId,t){const deadline=t.deadlineAt!==void 0?` (deadline ${new Date(t.deadlineAt).toISOString()})`:"";return`turn "${goalId}" was already settled ${t.once!==void 0?"by its manager":"by the run"}${deadline}, so this yield was not recorded`}var MAX_DATE_MS=864e13;function isPendingTurn(t){const r=t;if(typeof r!=="object"||r===null||typeof r.goalId!=="string"||typeof r.payload!=="string")return false;if(!Number.isSafeInteger(r.acceptedAt)||r.acceptedAt<0)return false;if(r.once!==void 0&&r.once!==true)return false;if(r.deadlineAt===void 0)return r.once===true;return Number.isSafeInteger(r.deadlineAt)&&r.deadlineAt>=1&&r.deadlineAt<=MAX_DATE_MS}function onceSpawner(payload){try{const spawner=JSON.parse(payload).once?.spawner;return typeof spawner==="string"&&spawner.length>0?spawner:void 0}catch{return void 0}}function carriesAnycastNotice(m){return m.parts.some(p=>p.kind==="data"&&typeof p.data==="object"&&p.data!==null&&!Array.isArray(p.data)&&ANYCAST_NOTICE_KEY in p.data)}function idlessDigest(m){return(0,import_node_crypto14.createHash)("sha256").update(JSON.stringify(m)).digest("base64url")}function sleep(ms){return new Promise(r=>setTimeout(r,ms))}function ingestDedupKey(id2){return id2===""?void 0:id2}var AUTOMATIC_QUEUE_STALL_MS=6e5;function renderAskRequest(p){const escalation=renderEscalation(p);if(escalation!=="")return escalation;const ask=p.ask;if(ask===null||typeof ask!=="object")return"";const a=ask;const entries=a.schema!==null&&typeof a.schema==="object"?Object.entries(a.schema):[];const fields=entries.length===0?"any record":entries.map(([k,v])=>`${k}: ${String(v)}`).join(", ");const by=typeof a.deadlineAt==="number"?`, by ${new Date(a.deadlineAt).toISOString()}`:"";const refused=typeof a.refused==="string"?`
|
|
119
119
|
Your last answer was refused: ${a.refused}`:"";return`
|
|
@@ -135,7 +135,7 @@ ${history.map(format).join("\n")}
|
|
|
135
135
|
(This is replayed history, not new work. Do not act on or reply to these old requests unless the person explicitly asks.)`)}return blocks.join("\n\n")}function writeReply(sock,reply,awaitHandoff){return new Promise(resolve=>{let settled=false;const done=ok3=>{if(settled)return;settled=true;resolve(ok3)};sock.once("error",()=>done(false));sock.once("close",()=>done(false));if(!awaitHandoff){const stall=setTimeout(()=>done(false),LEGACY_WRITE_DEADLINE_MS);stall.unref?.();try{sock.end(JSON.stringify(reply)+"\n",(err3=>{clearTimeout(stall);done(!err3)}))}catch{clearTimeout(stall);done(false)}return}const deadline=setTimeout(()=>{sock.destroy();done(false)},HANDOFF_DEADLINE_MS);deadline.unref?.();let receipt2="";sock.on("data",d=>{receipt2+=d;if(!receipt2.includes("\n"))return;clearTimeout(deadline);try{sock.end()}catch{}done(true)});try{sock.write(JSON.stringify(reply)+"\n",err3=>{if(!err3)return;clearTimeout(deadline);done(false)})}catch{clearTimeout(deadline);done(false)}})}function startControlServer(agent,endpoint,handle,opts={}){const{path}=endpoint;const digest=(0,import_node_crypto17.createHash)("sha256").update(endpoint.token).digest();const server=(0,import_node_net3.createServer)(sock=>{let buf="";let handled=false;sock.setEncoding("utf8");const deadline=setTimeout(()=>sock.destroy(),AUTH_DEADLINE_MS);deadline.unref?.();sock.on("close",()=>clearTimeout(deadline));sock.on("data",async d=>{if(handled)return;buf+=d;if(buf.length>MAX_FRAME_BYTES){sock.destroy();return}const nl=buf.indexOf("\n");if(nl<0)return;handled=true;clearTimeout(deadline);let frame={};try{frame=JSON.parse(buf.slice(0,nl)||"{}")}catch{}if(!tokenMatches(frame.token,digest)){sock.destroy();return}const op=frame.op;if(op==="shutdown"){try{sock.end(JSON.stringify({ok:true})+"\n")}catch{}opts.onShutdown?.();return}if(op==="session"){const sessionId=opts.onSession?.();try{sock.end(JSON.stringify(sessionId?{ok:true,sessionId}:{ok:false,error:"session not ready"})+"\n")}catch{}return}const ev=frame.event??{};const awaitHandoff=frame.handoff===true;const reply=await handle(agent,ev);const delivered=await writeReply(sock,reply,awaitHandoff);opts.onReply?.(ev,delivered,awaitHandoff)});sock.on("error",()=>{})});let bound=false;let retried=false;const emit=server.emit.bind(server);server.emit=(event,...args)=>{const error51=args[0];if(event!=="error"||bound||retried||process.platform==="win32"||path.startsWith("\0")||error51?.code!=="EADDRINUSE")return emit(event,...args);retried=true;let original;try{original=(0,import_node_fs11.lstatSync)(path);if(!original.isSocket())return emit(event,...args)}catch(e){if(e.code!=="ENOENT")return emit(event,...args)}const probe=(0,import_node_net3.connect)(path);let settled=false;const finish=stale=>{if(settled)return;settled=true;clearTimeout(deadline);probe.destroy();server.off("close",cancel);if(!stale){emit(event,...args);return}try{const current=(0,import_node_fs11.lstatSync)(path);if(!original||!current.isSocket()||current.dev!==original.dev||current.ino!==original.ino){emit(event,...args);return}(0,import_node_fs11.unlinkSync)(path)}catch(e){if(e.code!=="ENOENT"){emit("error",e);return}}server.listen(path)};const cancel=()=>{settled=true;clearTimeout(deadline);probe.destroy()};const deadline=setTimeout(()=>finish(false),250);server.once("close",cancel);probe.once("connect",()=>finish(false));probe.once("error",e=>finish(e.code==="ECONNREFUSED"||e.code==="ENOENT"));return true};server.on("error",e=>{process.stderr.write(`[cotal-connector] control server error: ${e.message}
|
|
136
136
|
`);if(opts.fatalBind&&!bound)process.exit(1)});server.listen(path,()=>{bound=true;process.stderr.write(`[cotal-connector] control socket: ${path}
|
|
137
137
|
`)});return server}function prepareInlineDelivery(agent,options){if(!/^[A-Za-z0-9_-]{1,128}$/.test(options.connectionId))throw new Error("invalid inline connection identity");const maxItem=options.maxItemCodePoints??1024;const maxItems=options.maxItems??8;if(!Number.isInteger(maxItem)||maxItem<1||!Number.isInteger(maxItems)||maxItems<1)throw new Error("inline delivery limits must be positive whole numbers");const pending=agent.peekInbox("automatic");const queued=agent.inboxCount("automatic");const selected=[];const render=items=>{const remaining=queued-items.length;return{text:`Cotal: inline messages for connection_id ${options.connectionId}.
|
|
138
|
-
`+formatInjection(items,{metadata:true})+"\nThese complete messages were delivered inline; do not fetch them again with cotal_inbox. Native delivery can repeat after an unconfirmed handoff; use message_id to avoid repeating work."+(remaining?` ${remaining} other message${remaining===1?" remains":"s remain"} pending; use cotal_inbox to read those.`:""),count:items.length,remaining}};for(const item of pending){if(selected.length>=maxItems)break;if(agent.isInFlight(item.recvKey)||Array.from(fmtDeliveryItem(item)).length>maxItem)continue;const candidate2=[...selected,{...item}];if(options.fits(render(candidate2)))selected.push(candidate2[candidate2.length-1])}if(!selected.length)return void 0;const keys=selected.map(item=>item.recvKey);if(!agent.holdInFlight(keys))return void 0;let settled=false;return{payload:render(selected),current(){const live=new Set(agent.peekInbox("automatic").map(item=>item.recvKey));return!settled&&!agent.stopping&&keys.every(key=>live.has(key))},settle(delivered){if(settled)return;settled=true;agent.releaseInFlight(keys);if(delivered)agent.drainInboxDeliveries(keys)}}}var ok=text2=>({text:text2});var err=text2=>({text:text2,isError:true});function receipt(status2,value){if(status2!==202||typeof value!=="object"||value===null||Array.isArray(value))return void 0;const body=value;if(body.ok!==true||typeof body.id!=="string"||body.id.length===0||body.id.length>200)return void 0;if(/[\u0000-\u001f\u007f]/.test(body.id)||body.id.trim()!==body.id)return void 0;if(typeof body.published!=="boolean")return void 0;return{id:body.id,published:body.published}}async function submitFeedback(input,options={}){const url2=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const headers3={"content-type":"application/json"};const body={...input};if(options.key){headers3.authorization=`Bearer ${options.key}`}else{if(!options.email)return err("Keyless feedback goes to the public cotal.ai intake, which requires a traceable contact email \u2014 ask the user for one and retry with the email argument (or set COTAL_FEEDBACK_EMAIL).");body.email=options.email}let res;let raw;try{res=await fetch(url2,{method:"POST",headers:headers3,body:JSON.stringify(body),redirect:"error"});raw=await res.text()}catch(e){return err(`Couldn't reach the feedback intake at ${url2}: ${e.message} The submission was not retried.`)}let reply=void 0;if(raw)try{reply=JSON.parse(raw)}catch{reply=void 0}const stored=receipt(res.status,reply);if(stored){const note=stored.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent (id ${stored.id})${note}. Thanks!`)}const errorText2=typeof reply==="object"&&reply!==null&&typeof reply.error==="string"?reply.error:void 0;if(!res.ok)return err(`Feedback rejected (${res.status}${errorText2?`: ${errorText2}`:""}).`);return err(`Feedback acceptance is unconfirmed (${res.status}). The request may have reached the intake and was not retried.`)}var import_node_child_process3=require("node:child_process");var import_node_crypto18=require("node:crypto");var import_node_fs12=require("node:fs");var import_node_path9=require("node:path");var import_node_zlib=require("node:zlib");var DOCS_VERSION="0.163.2";function loadDocsMetadata(){return{"version":"0.163.2","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here (informative)","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here (informative)","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept (informative)","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference: the `cotal_*` tool surface every connected agent gets.","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference (informative task card)","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept (informative)","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference (the persisted form of an agent's identity + persona, read by every launcher)","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference (informative)","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide: describes the TypeScript reference implementation, not the wire contract.","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide (informative)","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI), not the wire contract.","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI and connectors), not the wire contract.","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide (informative)","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide (informative)","category":"Guide","summary":"Launch Codex on a Cotal mesh, connect your own Codex conversations, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide (informative)","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-opencode","title":"Connect OpenCode","kind":"Guide (informative)","category":"Guide","summary":"Launch OpenCode on a Cotal mesh and choose the model and options for your installed version."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Launch pi on a Cotal mesh or load the Cotal extension into your own pi host."},{"slug":"connector-runtime-reference","title":"Connector runtime reference","kind":"Reference","category":"Reference","summary":"Shared connection recovery, presence display, send receipts, delivery acknowledgement, reply correlation, and resume records."},{"slug":"connectors","title":"Connectors","kind":"Guide (informative)","category":"Guide","summary":"Choose an agent application and connect its sessions to a Cotal mesh."},{"slug":"console","title":"Use the console","kind":"Guide","category":"Guide","summary":"Inspect a mesh from the terminal and use authorized operator controls."},{"slug":"control-discovery","title":"Endpoint discovery","kind":"Reference","category":"Reference","summary":"Command contracts, manager instance selection, request outcomes, and service registration."},{"slug":"control-lifecycle","title":"Manager lifecycle contracts","kind":"Reference","category":"Reference","summary":"Managed identities, static slots, spawn goals, chat sessions, terminal access, and grants."},{"slug":"control-surface","title":"The control surface","kind":"Concept (informative)","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide (informative)","category":"Guide","summary":"Describe agents and channels in a manifest, then boot or deploy that team."},{"slug":"delivery-daemon","title":"The delivery daemon","kind":"Concept (informative)","category":"Concept","summary":"Why durable channel delivery needs a trusted service, and what happens without it."},{"slug":"delivery-service-reference","title":"Delivery service contracts","kind":"Reference","category":"Reference","summary":"Fan-out, trusted reads, leases, membership retirement, credential adoption, and daemon lifetime."},{"slug":"deploy","title":"Deploy agent teams","kind":"Guide (informative)","category":"Guide","summary":"Review the container example, its current build limitation, and the credentials it needs."},{"slug":"embedding-daemons","title":"Embedded daemon lifecycle","kind":"Reference","category":"Reference","summary":"Process runners, account-scoped hosted services, and delivery credential renewal."},{"slug":"embedding-delegated-seats","title":"Delegated seat contracts","kind":"Reference","category":"Reference","summary":"Managed lifecycle handoff, provider closure guarantees, and the limits of delegated recovery contracts."},{"slug":"embedding-endpoints","title":"CotalEndpoint reference","kind":"Reference","category":"Reference","summary":"Presence metadata, observer freshness, write diagnosis, liveness probes, and DM-only endpoint readers."},{"slug":"embedding-exports","title":"Embedding package exports","kind":"Reference","category":"Reference","summary":"Public package entry points, endpoint credentials, and Manager execution contracts."},{"slug":"embedding-manager","title":"Manager embedding authority","kind":"Reference","category":"Reference","summary":"Manager startup, signer custody, remote authority callbacks, and delegated user intent contracts."},{"slug":"embedding-provisioning","title":"Embedded space provisioning","kind":"Reference","category":"Reference","summary":"Broker trust, space credentials, durable host state, and current hosting limitations."},{"slug":"embedding-remote-clients","title":"Embedded remote clients","kind":"Reference","category":"Reference","summary":"MCP conversation routing, browser callers, remote Manager clients, and private-result prerequisites."},{"slug":"embedding-schema-inspection","title":"Space schema inspection","kind":"Reference","category":"Reference","summary":"Resource definitions, bounded read-only observations, and the limits of schema and initialization comparisons."},{"slug":"embedding-service-access","title":"Service endpoint access","kind":"Reference","category":"Reference","summary":"Authority proofs, serving credentials, verified grants, and renewal."},{"slug":"embedding-service-authority","title":"Service authority contracts","kind":"Reference","category":"Reference","summary":"Service authority contracts, platform supervisors, revocation prerequisites, and native custody limits."},{"slug":"embedding-service-callers","title":"Service endpoint callers","kind":"Reference","category":"Reference","summary":"Caller policy grants, broker payload prerequisites, revocation, and recovery limits."},{"slug":"embedding-service-custody","title":"Native service custody","kind":"Reference","category":"Reference","summary":"Immutable service reservations, bootstrap, cancellation, and bounded writer guarantees."},{"slug":"embedding-service-host","title":"Service endpoint hosting","kind":"Reference","category":"Reference","summary":"Owner approvals, native host operations, registration, and lifecycle custody."},{"slug":"embedding","title":"Embedding Cotal","kind":"Concept (informative)","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here (informative)","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference (informative)","category":"Reference","summary":"Definitions of Cotal's identity, messaging, delivery, and operator terms."},{"slug":"hermes-connector-reference","title":"Hermes connector reference","kind":"Reference","category":"Reference","summary":"Hermes gateway ownership, profile state, delivery rules, presence hooks, and session forks."},{"slug":"identity-authority","title":"Credential authority","kind":"Reference","category":"Reference","summary":"Credential minting, profile grants, endpoint generations, and capability limits."},{"slug":"identity-service-auth","title":"Auth service integration","kind":"Reference","category":"Reference","summary":"Auth-service listeners, pinned IdP proofs, bridge hooks, and owner derivation."},{"slug":"identity-user-auth","title":"User-auth lifecycle","kind":"Reference","category":"Reference","summary":"Actor grants, delegation, catalogs, enrollment, sessions, views, and remote managers."},{"slug":"installation","title":"Install Cotal","kind":"Start here","category":"Start here","summary":"Install the cotal command with the shell installer or npm."},{"slug":"jcode-connector-reference","title":"Jcode connector reference","kind":"Reference","category":"Reference","summary":"Private Jcode process ownership, session forks, readiness checks, model selection, and event delivery."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference (informative)","category":"Reference","summary":"Effect signatures, result shapes, concurrency rules, and common refusals for cotal-lang programs."},{"slug":"launch-agents","title":"Launch agents","kind":"Guide","category":"Guide","summary":"Launch an agent through a manager, attach to its terminal, and choose its persona and runtime."},{"slug":"manager-console-api","title":"Manager console HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference: every field of the mesh manifest.","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-commands","title":"Mesh command catalog","kind":"Reference (informative)","category":"Reference","summary":"Built-in endpoint command declarations, capabilities, targeting modes and JSON schemas."},{"slug":"mesh-view","title":"MeshView","kind":"Reference: TypeScript observer surfaces (`MeshView`)","category":"Reference","summary":"The TypeScript observer model used by the terminal console and line stream, with dashboard feature coverage."},{"slug":"opencode-connector-reference","title":"OpenCode connector reference","kind":"Reference","category":"Reference","summary":"OpenCode version support, injected configuration, session delivery, and structured event limits."},{"slug":"overview","title":"API reference","kind":"Reference","category":"Reference","summary":"Find Cotal CLI commands, agent tools, configuration fields, and data models."},{"slug":"pi-connector-reference","title":"pi connector reference","kind":"Reference","category":"Reference","summary":"pi host lifecycle, delivery confirmation, continuation attempts, managed recovery, and event persistence."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept (informative)","category":"Concept","summary":"How presence, routing, durable delivery, and attention determine what peers can observe and receive."},{"slug":"recover-a-mesh","title":"Recover a mesh","kind":"Guide","category":"Guide","summary":"Use status and logs to diagnose service failures, stuck presence, or a frozen registration gate."},{"slug":"register-a-mesh","title":"Register a mesh","kind":"Guide","category":"Guide","summary":"Choose the mesh a command targets and register remote brokers with verified trust."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal releases with pnpm, Changesets, and one GitHub Actions workflow, changesets.yml."},{"slug":"remote-supervision","title":"Supervise a remote mesh","kind":"Guide","category":"Guide","summary":"Separate broker and manager hosts, publish an exchange, and enroll remote agents."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0, and the v0.x wire contract can still change under the change process."},{"slug":"run-a-mesh","title":"Run a mesh","kind":"Guide (informative)","category":"Guide","summary":"Start, inspect, and stop the local stack in a prepared project."},{"slug":"security-boundaries","title":"Host boundaries","kind":"Reference","category":"Reference","summary":"Credential lifetimes, metadata exposure, launch authority, and local process risks."},{"slug":"security","title":"Security model","kind":"Concept (informative threat model)","category":"Concept","summary":"Threats, guarantees, and limits for peers sharing a trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"How cotal setup works, and the cross-repo couplings it depends on."},{"slug":"setup","title":"Configure a space","kind":"Guide","category":"Guide","summary":"Prepare a project, choose its agent application, and save its space settings."},{"slug":"spaces","title":"Spaces","kind":"Concept (informative)","category":"Concept","summary":"How spaces isolate collaboration, and how channels, permissions, membership, and conversation ids organize work within them."},{"slug":"stability","title":"Interface stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"supervise-processes","title":"Supervise the stack","kind":"Guide","category":"Guide","summary":"Choose process ownership under systemd and monitor actual component health."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"CLI usage telemetry fields, levels, storage, delivery, and opt-outs."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept (informative)","category":"Concept","summary":"How Cotal's wire contract uses NATS and JetStream, and what another transport binding would have to preserve."},{"slug":"upgrade-cotal","title":"Upgrade Cotal","kind":"Guide","category":"Guide","summary":"Choose an exact release, prepare the deployment, and verify the upgraded installation."},{"slug":"upgrading","title":"Upgrading a running deployment","kind":"Guide (informative)","category":"Guide","summary":"Interface stability says what the version numbers promise."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Start here (informative)","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide (informative)","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept (informative)","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=(0,import_node_fs12.readFileSync)((0,import_node_path9.join)(__dirname,"docs-bundle.bin"));if(packed.length!==1236087||(0,import_node_crypto18.createHash)("sha256").update(packed).digest("hex")!=="ea31640c4025c61e02fb58c6cb23626c85f6de8386ca337f62a20711bf3c2365")throw new Error("docs data file docs-bundle.bin beside this module is not the one built with it");return corpusPacked=packed}var sourceBounds=[[0,2205],[2205,4e3],[4e3,9323],[9323,31350],[31350,35747],[35747,40128],[40128,43688],[43688,50491],[50491,54595],[54595,64392],[64392,68544],[68544,73062],[73062,75346],[75346,79357],[79357,111137],[111137,126885],[126885,142638],[142638,160409],[160409,176789],[176789,191840],[191840,207780],[207780,231224],[231224,236954],[236954,247632],[247632,267906],[267906,272395],[272395,311141],[311141,320861],[320861,352030],[352030,369531],[369531,393862],[393862,424781],[424781,439282],[439282,441229],[441229,450105],[450105,466710],[466710,474794],[474794,478615],[478615,481996],[481996,485299],[485299,487430],[487430,490203],[490203,495384],[495384,497281],[497281,500840],[500840,512984],[512984,521775],[521775,525300],[525300,532573],[532573,537617],[537617,540524],[540524,551044],[551044,554021],[554021,562573],[562573,565563],[565563,570508],[570508,582995],[582995,595799],[595799,602340],[602340,609921],[609921,613270],[613270,616219],[616219,623776],[623776,627492],[627492,629702],[629702,633164],[633164,636581],[636581,637695],[637695,639444],[639444,643107],[643107,647748],[647748,654384],[654384,664894],[664894,678210],[678210,680047],[680047,693032],[693032,698419],[698419,702375],[702375,704884],[704884,709926],[709926,724113],[724113,730888],[730888,738065],[738065,738882],[738882,743258],[743258,749178],[749178,752556],[752556,756764],[756764,761854],[761854,767435],[767435,770857],[770857,774448],[774448,779613],[779613,783256],[783256,796482],[796482,799300],[799300,801983],[801983,804650],[804650,807141],[807141,811161],[811161,815906],[815906,818915],[818915,888261],[888261,891332],[891332,892525],[892525,899026],[899026,907765],[907765,918543],[918543,927354],[927354,932537],[932537,1191566],[1191566,1230875],[1230875,1236087]];var sourceLengths=[4844,4048,13310,87378,12190,10741,36165,17849,9941,85121,37758,11019,5079,9872,86645,42336,44337,50452,45279,43514,43587,66199,14399,28302,58259,10129,114966,26839,94086,49557,73031,95384,39939,8216,22172,44626,21923,9348,8035,7790,4874,6360,13164,4537,8347,32337,21939,8745,47165,12743,7133,27685,7140,22325,6860,12405,32472,33984,16669,18466,8355,7031,19589,8312,5100,8160,9930,2248,5412,9845,11102,16082,26828,34218,4227,35397,12378,9651,8201,13306,98055,16844,17746,1638,10013,15381,7818,10170,12738,14071,7511,9014,12695,8527,35301,6519,6405,6095,6007,9711,11859,7205,204463,6927,2473,15538,22385,27911,21160,12616,751268,111139,21676];var decodedBodies=[];function loadDocsSourceLengths(){corpusData();return sourceLengths.slice()}function decodeDocsSource(source){const bounds=sourceBounds[source];if(!Number.isInteger(source)||!bounds)throw new Error("docs source index is out of bounds");const body=JSON.parse((0,import_node_zlib.gunzipSync)(corpusData().subarray(bounds[0],bounds[1])).toString("utf8"));if(typeof body!=="string"||body.length!==sourceLengths[source])throw new Error("docs source body does not match its generated bounds");return body}function loadDocsSource(source){return decodedBodies[source]??=decodeDocsSource(source)}function loadDocsIndex(){const packed=(0,import_node_fs12.readFileSync)((0,import_node_path9.join)(__dirname,"docs-index.bin"));if(packed.length!==634052||(0,import_node_crypto18.createHash)("sha256").update(packed).digest("hex")!=="9f7a81321181ee90129460cd8316871472ad93152d44b159c2f207aab790eff9")throw new Error("docs data file docs-index.bin beside this module is not the one built with it");return(0,import_node_zlib.gunzipSync)(packed)}var TOKEN2=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s){const raw=s.toLowerCase().match(TOKEN2);if(!raw)return[];const out=[];for(const r of raw){if(r.length>=2)out.push(r);const t=r.replace(EDGE,"");if(t.length>=2&&t!==r)out.push(t);if(t.includes(".")){for(const seg of t.split("."))if(seg.length>=2)out.push(seg)}}return out}var STOP=new Set("a an and are as at be by do for from has how in is it of on or that the this to use using was what when where which who with you your".split(" "));function decodeIndex(bytes,bodyLengths,version2){if(bytes.length<4)throw new Error("docs index is truncated or malformed");const headerLength=bytes.readUInt32LE(0);if(4+headerLength>bytes.length)throw new Error("docs index is truncated or malformed");const header=JSON.parse(bytes.toString("utf8",4,4+headerLength));if(header.version!==version2||header.bodyLengths.length!==bodyLengths.length||header.bodyLengths.some((length2,i)=>length2!==bodyLengths[i]))throw new Error("docs index does not match the docs bundle it is searching");const n=header.sections;const length=4*n+header.terms.length+1+2*header.postings;if(bytes.length-4-headerLength!==4*length)throw new Error("docs index is truncated or malformed");const columns=new Uint32Array(length);for(let i=0;i<length;i++)columns[i]=bytes.readUInt32LE(4+headerLength+4*i);const offsets=4*n;const sectionColumn=offsets+header.terms.length+1;let total=0;for(let i=0;i<n;i++)total+=columns[3*n+i];return{sections:n,terms:header.terms,headings:header.headings,source:columns.subarray(0,n),start:columns.subarray(n,2*n),end:columns.subarray(2*n,3*n),length:columns.subarray(3*n,4*n),offsets:columns.subarray(offsets,sectionColumn),postSection:columns.subarray(sectionColumn,sectionColumn+header.postings),postWeight:columns.subarray(sectionColumn+header.postings),avgdl:total/Math.max(1,n)}}var indexed;function metadata(){return indexed??=loadDocsMetadata()}var pages=new Map;function localPage(source){let page=pages.get(source);if(!page){page={...metadata().pages[source],body:loadDocsSource(source)};pages.set(source,page)}return page}function sourceBody(source){return source<metadata().pages.length?localPage(source).body:loadDocsSource(source)}var REMOTE_BASE="https://docs.cotal.ai";function resolvePage(page){const meta3=metadata();loadDocsSourceLengths();const reference=page.trim().toLowerCase().split(/[?#]/)[0].replace(/^\.\//,"");let key;if(/^(?:\.\.\/)?spec\/cotal-lang\.md$/.test(reference))key="lang";else if(/^(?:\.\.\/)?spec\/cotal\.schema\.json$/.test(reference))key="schema";else if(reference==="../spec.md")key="spec";else{const match=/^(?:(?:\.\.\/)?docs\/)?([a-z0-9-]+)(?:\.mdx?)?$/.exec(reference);if(!match)return void 0;key=match[1]}const count=meta3.pages.length;if(key==="spec")return{slug:"spec",title:meta3.spec.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count)};if(key==="lang"||key==="cotal-lang")return{slug:"lang",title:meta3.lang.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count+1)};if(key==="schema")return{slug:"schema",title:meta3.schema.title,kind:"reference",category:"reference",summary:"",body:loadDocsSource(count+2)};const source=meta3.pages.findIndex((p,source2)=>(pages.get(source2)??p).slug===key);return source<0?void 0:localPage(source)}function remoteUrl(slug){const base=`${REMOTE_BASE}/v/${DOCS_VERSION}`;if(slug==="schema")return`${base}/cotal.schema.json`;if(slug==="lang")return`${base}/cotal-lang.md`;return`${base}/${slug}.md`}function renderDocsIndex(){const b=metadata();const rows=b.pages.map(p=>{const kind=p.kind?`: ${p.kind}`:"";return`- \`${p.slug}\`${kind}
|
|
138
|
+
`+formatInjection(items,{metadata:true})+"\nThese complete messages were delivered inline; do not fetch them again with cotal_inbox. Native delivery can repeat after an unconfirmed handoff; use message_id to avoid repeating work."+(remaining?` ${remaining} other message${remaining===1?" remains":"s remain"} pending; use cotal_inbox to read those.`:""),count:items.length,remaining}};for(const item of pending){if(selected.length>=maxItems)break;if(agent.isInFlight(item.recvKey)||Array.from(fmtDeliveryItem(item)).length>maxItem)continue;const candidate2=[...selected,{...item}];if(options.fits(render(candidate2)))selected.push(candidate2[candidate2.length-1])}if(!selected.length)return void 0;const keys=selected.map(item=>item.recvKey);if(!agent.holdInFlight(keys))return void 0;let settled=false;return{payload:render(selected),current(){const live=new Set(agent.peekInbox("automatic").map(item=>item.recvKey));return!settled&&!agent.stopping&&keys.every(key=>live.has(key))},settle(delivered){if(settled)return;settled=true;agent.releaseInFlight(keys);if(delivered)agent.drainInboxDeliveries(keys)}}}var ok=text2=>({text:text2});var err=text2=>({text:text2,isError:true});function receipt(status2,value){if(status2!==202||typeof value!=="object"||value===null||Array.isArray(value))return void 0;const body=value;if(body.ok!==true||typeof body.id!=="string"||body.id.length===0||body.id.length>200)return void 0;if(/[\u0000-\u001f\u007f]/.test(body.id)||body.id.trim()!==body.id)return void 0;if(typeof body.published!=="boolean")return void 0;return{id:body.id,published:body.published}}async function submitFeedback(input,options={}){const url2=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const headers3={"content-type":"application/json"};const body={...input};if(options.key){headers3.authorization=`Bearer ${options.key}`}else{if(!options.email)return err("Keyless feedback goes to the public cotal.ai intake, which requires a traceable contact email \u2014 ask the user for one and retry with the email argument (or set COTAL_FEEDBACK_EMAIL).");body.email=options.email}let res;let raw;try{res=await fetch(url2,{method:"POST",headers:headers3,body:JSON.stringify(body),redirect:"error"});raw=await res.text()}catch(e){return err(`Couldn't reach the feedback intake at ${url2}: ${e.message} The submission was not retried.`)}let reply=void 0;if(raw)try{reply=JSON.parse(raw)}catch{reply=void 0}const stored=receipt(res.status,reply);if(stored){const note=stored.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent (id ${stored.id})${note}. Thanks!`)}const errorText2=typeof reply==="object"&&reply!==null&&typeof reply.error==="string"?reply.error:void 0;if(!res.ok)return err(`Feedback rejected (${res.status}${errorText2?`: ${errorText2}`:""}).`);return err(`Feedback acceptance is unconfirmed (${res.status}). The request may have reached the intake and was not retried.`)}var import_node_child_process3=require("node:child_process");var import_node_crypto18=require("node:crypto");var import_node_fs12=require("node:fs");var import_node_path9=require("node:path");var import_node_zlib=require("node:zlib");var DOCS_VERSION="0.163.3";function loadDocsMetadata(){return{"version":"0.163.3","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here (informative)","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here (informative)","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept (informative)","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference: the `cotal_*` tool surface every connected agent gets.","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference (informative task card)","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept (informative)","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference (the persisted form of an agent's identity + persona, read by every launcher)","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference (informative)","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide: describes the TypeScript reference implementation, not the wire contract.","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide (informative)","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI), not the wire contract.","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI and connectors), not the wire contract.","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide (informative)","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide (informative)","category":"Guide","summary":"Launch Codex on a Cotal mesh, connect your own Codex conversations, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide (informative)","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-opencode","title":"Connect OpenCode","kind":"Guide (informative)","category":"Guide","summary":"Launch OpenCode on a Cotal mesh and choose the model and options for your installed version."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Launch pi on a Cotal mesh or load the Cotal extension into your own pi host."},{"slug":"connector-runtime-reference","title":"Connector runtime reference","kind":"Reference","category":"Reference","summary":"Shared connection recovery, presence display, send receipts, delivery acknowledgement, reply correlation, and resume records."},{"slug":"connectors","title":"Connectors","kind":"Guide (informative)","category":"Guide","summary":"Choose an agent application and connect its sessions to a Cotal mesh."},{"slug":"console","title":"Use the console","kind":"Guide","category":"Guide","summary":"Inspect a mesh from the terminal and use authorized operator controls."},{"slug":"control-discovery","title":"Endpoint discovery","kind":"Reference","category":"Reference","summary":"Command contracts, manager instance selection, request outcomes, and service registration."},{"slug":"control-lifecycle","title":"Manager lifecycle contracts","kind":"Reference","category":"Reference","summary":"Managed identities, static slots, spawn goals, chat sessions, terminal access, and grants."},{"slug":"control-surface","title":"The control surface","kind":"Concept (informative)","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide (informative)","category":"Guide","summary":"Describe agents and channels in a manifest, then boot or deploy that team."},{"slug":"delivery-daemon","title":"The delivery daemon","kind":"Concept (informative)","category":"Concept","summary":"Why durable channel delivery needs a trusted service, and what happens without it."},{"slug":"delivery-service-reference","title":"Delivery service contracts","kind":"Reference","category":"Reference","summary":"Fan-out, trusted reads, leases, membership retirement, credential adoption, and daemon lifetime."},{"slug":"deploy","title":"Deploy agent teams","kind":"Guide (informative)","category":"Guide","summary":"Review the container example, its current build limitation, and the credentials it needs."},{"slug":"embedding-daemons","title":"Embedded daemon lifecycle","kind":"Reference","category":"Reference","summary":"Process runners, account-scoped hosted services, and delivery credential renewal."},{"slug":"embedding-delegated-seats","title":"Delegated seat contracts","kind":"Reference","category":"Reference","summary":"Managed lifecycle handoff, provider closure guarantees, and the limits of delegated recovery contracts."},{"slug":"embedding-endpoints","title":"CotalEndpoint reference","kind":"Reference","category":"Reference","summary":"Presence metadata, observer freshness, write diagnosis, liveness probes, and DM-only endpoint readers."},{"slug":"embedding-exports","title":"Embedding package exports","kind":"Reference","category":"Reference","summary":"Public package entry points, endpoint credentials, and Manager execution contracts."},{"slug":"embedding-manager","title":"Manager embedding authority","kind":"Reference","category":"Reference","summary":"Manager startup, signer custody, remote authority callbacks, and delegated user intent contracts."},{"slug":"embedding-provisioning","title":"Embedded space provisioning","kind":"Reference","category":"Reference","summary":"Broker trust, space credentials, durable host state, and current hosting limitations."},{"slug":"embedding-remote-clients","title":"Embedded remote clients","kind":"Reference","category":"Reference","summary":"MCP conversation routing, browser callers, remote Manager clients, and private-result prerequisites."},{"slug":"embedding-schema-inspection","title":"Space schema inspection","kind":"Reference","category":"Reference","summary":"Resource definitions, bounded read-only observations, and the limits of schema and initialization comparisons."},{"slug":"embedding-service-access","title":"Service endpoint access","kind":"Reference","category":"Reference","summary":"Authority proofs, serving credentials, verified grants, and renewal."},{"slug":"embedding-service-authority","title":"Service authority contracts","kind":"Reference","category":"Reference","summary":"Service authority contracts, platform supervisors, revocation prerequisites, and native custody limits."},{"slug":"embedding-service-callers","title":"Service endpoint callers","kind":"Reference","category":"Reference","summary":"Caller policy grants, broker payload prerequisites, revocation, and recovery limits."},{"slug":"embedding-service-custody","title":"Native service custody","kind":"Reference","category":"Reference","summary":"Immutable service reservations, bootstrap, cancellation, and bounded writer guarantees."},{"slug":"embedding-service-host","title":"Service endpoint hosting","kind":"Reference","category":"Reference","summary":"Owner approvals, native host operations, registration, and lifecycle custody."},{"slug":"embedding","title":"Embedding Cotal","kind":"Concept (informative)","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here (informative)","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference (informative)","category":"Reference","summary":"Definitions of Cotal's identity, messaging, delivery, and operator terms."},{"slug":"hermes-connector-reference","title":"Hermes connector reference","kind":"Reference","category":"Reference","summary":"Hermes gateway ownership, profile state, delivery rules, presence hooks, and session forks."},{"slug":"identity-authority","title":"Credential authority","kind":"Reference","category":"Reference","summary":"Credential minting, profile grants, endpoint generations, and capability limits."},{"slug":"identity-service-auth","title":"Auth service integration","kind":"Reference","category":"Reference","summary":"Auth-service listeners, pinned IdP proofs, bridge hooks, and owner derivation."},{"slug":"identity-user-auth","title":"User-auth lifecycle","kind":"Reference","category":"Reference","summary":"Actor grants, delegation, catalogs, enrollment, sessions, views, and remote managers."},{"slug":"installation","title":"Install Cotal","kind":"Start here","category":"Start here","summary":"Install the cotal command with the shell installer or npm."},{"slug":"jcode-connector-reference","title":"Jcode connector reference","kind":"Reference","category":"Reference","summary":"Private Jcode process ownership, session forks, readiness checks, model selection, and event delivery."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference (informative)","category":"Reference","summary":"Effect signatures, result shapes, concurrency rules, and common refusals for cotal-lang programs."},{"slug":"launch-agents","title":"Launch agents","kind":"Guide","category":"Guide","summary":"Launch an agent through a manager, attach to its terminal, and choose its persona and runtime."},{"slug":"manager-console-api","title":"Manager console HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference: every field of the mesh manifest.","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-commands","title":"Mesh command catalog","kind":"Reference (informative)","category":"Reference","summary":"Built-in endpoint command declarations, capabilities, targeting modes and JSON schemas."},{"slug":"mesh-view","title":"MeshView","kind":"Reference: TypeScript observer surfaces (`MeshView`)","category":"Reference","summary":"The TypeScript observer model used by the terminal console and line stream, with dashboard feature coverage."},{"slug":"opencode-connector-reference","title":"OpenCode connector reference","kind":"Reference","category":"Reference","summary":"OpenCode version support, injected configuration, session delivery, and structured event limits."},{"slug":"overview","title":"API reference","kind":"Reference","category":"Reference","summary":"Find Cotal CLI commands, agent tools, configuration fields, and data models."},{"slug":"pi-connector-reference","title":"pi connector reference","kind":"Reference","category":"Reference","summary":"pi host lifecycle, delivery confirmation, continuation attempts, managed recovery, and event persistence."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept (informative)","category":"Concept","summary":"How presence, routing, durable delivery, and attention determine what peers can observe and receive."},{"slug":"recover-a-mesh","title":"Recover a mesh","kind":"Guide","category":"Guide","summary":"Use status and logs to diagnose service failures, stuck presence, or a frozen registration gate."},{"slug":"register-a-mesh","title":"Register a mesh","kind":"Guide","category":"Guide","summary":"Choose the mesh a command targets and register remote brokers with verified trust."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal releases with pnpm, Changesets, and one GitHub Actions workflow, changesets.yml."},{"slug":"remote-supervision","title":"Supervise a remote mesh","kind":"Guide","category":"Guide","summary":"Separate broker and manager hosts, publish an exchange, and enroll remote agents."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0, and the v0.x wire contract can still change under the change process."},{"slug":"run-a-mesh","title":"Run a mesh","kind":"Guide (informative)","category":"Guide","summary":"Start, inspect, and stop the local stack in a prepared project."},{"slug":"security-boundaries","title":"Host boundaries","kind":"Reference","category":"Reference","summary":"Credential lifetimes, metadata exposure, launch authority, and local process risks."},{"slug":"security","title":"Security model","kind":"Concept (informative threat model)","category":"Concept","summary":"Threats, guarantees, and limits for peers sharing a trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"How cotal setup works, and the cross-repo couplings it depends on."},{"slug":"setup","title":"Configure a space","kind":"Guide","category":"Guide","summary":"Prepare a project, choose its agent application, and save its space settings."},{"slug":"spaces","title":"Spaces","kind":"Concept (informative)","category":"Concept","summary":"How spaces isolate collaboration, and how channels, permissions, membership, and conversation ids organize work within them."},{"slug":"stability","title":"Interface stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"supervise-processes","title":"Supervise the stack","kind":"Guide","category":"Guide","summary":"Choose process ownership under systemd and monitor actual component health."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"CLI usage telemetry fields, levels, storage, delivery, and opt-outs."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept (informative)","category":"Concept","summary":"How Cotal's wire contract uses NATS and JetStream, and what another transport binding would have to preserve."},{"slug":"upgrade-cotal","title":"Upgrade Cotal","kind":"Guide","category":"Guide","summary":"Choose an exact release, prepare the deployment, and verify the upgraded installation."},{"slug":"upgrading","title":"Upgrading a running deployment","kind":"Guide (informative)","category":"Guide","summary":"Interface stability says what the version numbers promise."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Start here (informative)","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide (informative)","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept (informative)","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=(0,import_node_fs12.readFileSync)((0,import_node_path9.join)(__dirname,"docs-bundle.bin"));if(packed.length!==1236957||(0,import_node_crypto18.createHash)("sha256").update(packed).digest("hex")!=="5c4887dd50bdbbe2c176f7599b37f3975386ce37dcd7542fe0afe6e53cb9cabf")throw new Error("docs data file docs-bundle.bin beside this module is not the one built with it");return corpusPacked=packed}var sourceBounds=[[0,2205],[2205,4e3],[4e3,9323],[9323,31350],[31350,35747],[35747,40128],[40128,43688],[43688,50491],[50491,54595],[54595,64392],[64392,68544],[68544,73062],[73062,75346],[75346,79357],[79357,111137],[111137,126885],[126885,142638],[142638,160409],[160409,176789],[176789,191840],[191840,207780],[207780,231224],[231224,236954],[236954,247938],[247938,268212],[268212,272701],[272701,311447],[311447,321242],[321242,352411],[352411,369912],[369912,394304],[394304,425302],[425302,439803],[439803,441750],[441750,450626],[450626,467317],[467317,475401],[475401,479222],[479222,482603],[482603,485906],[485906,488037],[488037,490810],[490810,495991],[495991,497888],[497888,501447],[501447,513591],[513591,522382],[522382,525907],[525907,533180],[533180,538224],[538224,541131],[541131,551651],[551651,554628],[554628,563348],[563348,566338],[566338,571283],[571283,583770],[583770,596574],[596574,603115],[603115,610696],[610696,614045],[614045,616994],[616994,624551],[624551,628267],[628267,630477],[630477,633939],[633939,637356],[637356,638470],[638470,640219],[640219,643882],[643882,648523],[648523,655159],[655159,665669],[665669,678985],[678985,680822],[680822,693807],[693807,699194],[699194,703150],[703150,705659],[705659,710701],[710701,724888],[724888,731663],[731663,738840],[738840,739657],[739657,744033],[744033,749953],[749953,753331],[753331,757539],[757539,762629],[762629,768210],[768210,771632],[771632,775223],[775223,780388],[780388,784031],[784031,797326],[797326,800144],[800144,802827],[802827,805494],[805494,807985],[807985,812005],[812005,816750],[816750,819759],[819759,889105],[889105,892176],[892176,893369],[893369,899870],[899870,908609],[908609,919387],[919387,928198],[928198,933381],[933381,1192410],[1192410,1231745],[1231745,1236957]];var sourceLengths=[4844,4048,13310,87378,12190,10741,36165,17849,9941,85121,37758,11019,5079,9872,86645,42336,44337,50452,45279,43514,43587,66199,14399,29244,58259,10129,114966,27044,94086,49557,73240,95605,39939,8216,22172,44897,21923,9348,8035,7790,4874,6360,13164,4537,8347,32337,21939,8745,47165,12743,7133,27685,7140,22854,6860,12405,32472,33984,16669,18466,8355,7031,19589,8312,5100,8160,9930,2248,5412,9845,11102,16082,26828,34218,4227,35397,12378,9651,8201,13306,98055,16844,17746,1638,10013,15381,7818,10170,12738,14071,7511,9014,12695,8527,35472,6519,6405,6095,6007,9711,11859,7205,204463,6927,2473,15538,22385,27911,21160,12616,751268,111238,21676];var decodedBodies=[];function loadDocsSourceLengths(){corpusData();return sourceLengths.slice()}function decodeDocsSource(source){const bounds=sourceBounds[source];if(!Number.isInteger(source)||!bounds)throw new Error("docs source index is out of bounds");const body=JSON.parse((0,import_node_zlib.gunzipSync)(corpusData().subarray(bounds[0],bounds[1])).toString("utf8"));if(typeof body!=="string"||body.length!==sourceLengths[source])throw new Error("docs source body does not match its generated bounds");return body}function loadDocsSource(source){return decodedBodies[source]??=decodeDocsSource(source)}function loadDocsIndex(){const packed=(0,import_node_fs12.readFileSync)((0,import_node_path9.join)(__dirname,"docs-index.bin"));if(packed.length!==634384||(0,import_node_crypto18.createHash)("sha256").update(packed).digest("hex")!=="e803374dadb5a664381d2742bccba9cbeba70d8cd30240d99eb9a7b1059248fb")throw new Error("docs data file docs-index.bin beside this module is not the one built with it");return(0,import_node_zlib.gunzipSync)(packed)}var TOKEN2=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s){const raw=s.toLowerCase().match(TOKEN2);if(!raw)return[];const out=[];for(const r of raw){if(r.length>=2)out.push(r);const t=r.replace(EDGE,"");if(t.length>=2&&t!==r)out.push(t);if(t.includes(".")){for(const seg of t.split("."))if(seg.length>=2)out.push(seg)}}return out}var STOP=new Set("a an and are as at be by do for from has how in is it of on or that the this to use using was what when where which who with you your".split(" "));function decodeIndex(bytes,bodyLengths,version2){if(bytes.length<4)throw new Error("docs index is truncated or malformed");const headerLength=bytes.readUInt32LE(0);if(4+headerLength>bytes.length)throw new Error("docs index is truncated or malformed");const header=JSON.parse(bytes.toString("utf8",4,4+headerLength));if(header.version!==version2||header.bodyLengths.length!==bodyLengths.length||header.bodyLengths.some((length2,i)=>length2!==bodyLengths[i]))throw new Error("docs index does not match the docs bundle it is searching");const n=header.sections;const length=4*n+header.terms.length+1+2*header.postings;if(bytes.length-4-headerLength!==4*length)throw new Error("docs index is truncated or malformed");const columns=new Uint32Array(length);for(let i=0;i<length;i++)columns[i]=bytes.readUInt32LE(4+headerLength+4*i);const offsets=4*n;const sectionColumn=offsets+header.terms.length+1;let total=0;for(let i=0;i<n;i++)total+=columns[3*n+i];return{sections:n,terms:header.terms,headings:header.headings,source:columns.subarray(0,n),start:columns.subarray(n,2*n),end:columns.subarray(2*n,3*n),length:columns.subarray(3*n,4*n),offsets:columns.subarray(offsets,sectionColumn),postSection:columns.subarray(sectionColumn,sectionColumn+header.postings),postWeight:columns.subarray(sectionColumn+header.postings),avgdl:total/Math.max(1,n)}}var indexed;function metadata(){return indexed??=loadDocsMetadata()}var pages=new Map;function localPage(source){let page=pages.get(source);if(!page){page={...metadata().pages[source],body:loadDocsSource(source)};pages.set(source,page)}return page}function sourceBody(source){return source<metadata().pages.length?localPage(source).body:loadDocsSource(source)}var REMOTE_BASE="https://docs.cotal.ai";function resolvePage(page){const meta3=metadata();loadDocsSourceLengths();const reference=page.trim().toLowerCase().split(/[?#]/)[0].replace(/^\.\//,"");let key;if(/^(?:\.\.\/)?spec\/cotal-lang\.md$/.test(reference))key="lang";else if(/^(?:\.\.\/)?spec\/cotal\.schema\.json$/.test(reference))key="schema";else if(reference==="../spec.md")key="spec";else{const match=/^(?:(?:\.\.\/)?docs\/)?([a-z0-9-]+)(?:\.mdx?)?$/.exec(reference);if(!match)return void 0;key=match[1]}const count=meta3.pages.length;if(key==="spec")return{slug:"spec",title:meta3.spec.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count)};if(key==="lang"||key==="cotal-lang")return{slug:"lang",title:meta3.lang.title,kind:"normative",category:"normative",summary:"",body:loadDocsSource(count+1)};if(key==="schema")return{slug:"schema",title:meta3.schema.title,kind:"reference",category:"reference",summary:"",body:loadDocsSource(count+2)};const source=meta3.pages.findIndex((p,source2)=>(pages.get(source2)??p).slug===key);return source<0?void 0:localPage(source)}function remoteUrl(slug){const base=`${REMOTE_BASE}/v/${DOCS_VERSION}`;if(slug==="schema")return`${base}/cotal.schema.json`;if(slug==="lang")return`${base}/cotal-lang.md`;return`${base}/${slug}.md`}function renderDocsIndex(){const b=metadata();const rows=b.pages.map(p=>{const kind=p.kind?`: ${p.kind}`:"";return`- \`${p.slug}\`${kind}
|
|
139
139
|
${p.summary}`});return[`# Cotal v${b.version} documentation`,"","The authoritative docs bundled with this installed version. This index lists what","exists; it holds no answers itself. Your next call:",'- Know the page? Read it in full: `cotal_docs(page: "<slug>")` (e.g. "spec", "architecture").','- Not sure which page? Search: `cotal_docs(query: "\u2026")` returns the most relevant sections.',"Prefer these docs over training memory, and read the full page before writing code or wire","frames. Docs are bundled and version-exact; add `refresh: true` to also pull any patches","published to docs.cotal.ai for this same version.","","## The normative sources",`- \`spec\`: ${b.spec.title} (the wire contract; where a page disagrees, the spec wins)`,`- \`lang\`: ${b.lang.title} (the workflow language a durable run executes; spec \xA714)`,`- \`schema\`: ${b.schema.title} (authoritative for message shapes)`,"","## Pages",...rows].join("\n")}function renderPage(p,note){return`${note}
|
|
140
140
|
|
|
141
141
|
${p.body}`.trimStart()}var K1=1.2;var B=.75;function sources(){const b=metadata();return[...b.pages.map((page,source)=>pages.get(source)??page),{slug:"spec",...b.spec},{slug:"lang",...b.lang},{slug:"schema",...b.schema}]}var index;function searchIndex(){if(index)return index;const lengths=loadDocsSourceLengths();for(const[source,page]of pages)lengths[source]=page.body.length;return index=decodeIndex(loadDocsIndex(),lengths,DOCS_VERSION)}function termId(terms,term){let low=0;let high=terms.length-1;while(low<=high){const mid=low+high>>>1;const candidate2=terms[mid];if(candidate2===term)return mid;if(candidate2<term)low=mid+1;else high=mid-1}return-1}function searchDocs(query,limit=5){if(limit<=0)return[];let terms=tokenize(query).filter(t=>!STOP.has(t));if(!terms.length)terms=tokenize(query);const termSet=new Set(terms);if(!termSet.size)return[];const idx=searchIndex();const N=idx.sections;const scores=new Float64Array(N);for(const t of termSet){const id2=termId(idx.terms,t);if(id2<0)continue;const from=idx.offsets[id2];const to=idx.offsets[id2+1];const n=to-from;const idf=Math.log(1+(N-n+.5)/(n+.5));for(let p=from;p<to;p++){const s=idx.postSection[p];const f=idx.postWeight[p];scores[s]+=idf*(f*(K1+1)/(f+K1*(1-B+B*idx.length[s]/idx.avgdl)))}}const scored=[];for(let s=0;s<N;s++)if(scores[s]>0)scored.push({s,score:scores[s]});scored.sort((a,b)=>b.score-a.score);const all=sources();const perPage=new Map;const hits=[];for(const{s,score}of scored){const source=all[idx.source[s]];const seen=perPage.get(source.slug)??0;if(seen>=2)continue;perPage.set(source.slug,seen+1);hits.push({slug:source.slug,pageTitle:source.title,heading:idx.headings[s],text:sourceBody(idx.source[s]).slice(idx.start[s],idx.end[s]),score});if(hits.length>=limit)break}return hits}function capSection(text2,maxLines=48){const lines=text2.split("\n");if(lines.length<=maxLines)return text2.trim();return lines.slice(0,maxLines).join("\n").trimEnd()+"\n\n\u2026 (section continues; read the full page)"}function renderSearch(query,hits){loadDocsSourceLengths();if(!hits.length){return`No matches for "${query}" in the Cotal v${DOCS_VERSION} docs. Call cotal_docs() for the page index, or search an exact identifier (a subject, a cotal_* tool, a field name).`}const blocks=hits.map(h2=>`## ${h2.heading}
|