@cotal-ai/connector-jcode 0.140.7 → 0.141.0
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/host.js +7 -7
- package/dist/mcp.js +3 -3
- package/package.json +3 -3
package/dist/mcp.js
CHANGED
|
@@ -113,7 +113,7 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
|
|
|
113
113
|
]))`;continue}else if(source[i]==="$"){pattern+=`($|(?=[\r
|
|
114
114
|
]))`;continue}}if(flags.s&&source[i]==="."){pattern+=inCharGroup?`${source[i]}\r
|
|
115
115
|
`:`[${source[i]}\r
|
|
116
|
-
]`;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 main=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){main.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?{...main,[refs.definitionPath]:definitions}:main:{$ref:[...refs.$refStrategy==="relative"?[]:refs.basePath,refs.definitionPath,name].join("/"),[refs.definitionPath]:{...definitions,[name]:main}};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=reason=>{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(reason)}},{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error52=>this._onerror(new Error(`Failed to send cancellation: ${error52}`)));const error51=reason instanceof McpError?reason:new McpError(ErrorCode.RequestTimeout,String(reason));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 resources=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:[...resources,...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}};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 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");var import_nkeys2=__toESM(require_mod(),1);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 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}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 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 channelInAllow(allow,channel){return allow.some(a=>subjectMatches(a,channel))}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))}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 ID=/^[A-Za-z0-9_-]{1,64}$/;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 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}var EP_AUTHZ_MODES=Object.freeze(["self","owner","any","child","ledger","handle","exact"]);var AUTHZ_SET=new Set(EP_AUTHZ_MODES);import{createHash}from"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 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+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_UNANSWERED="ai.cotal.ep.unanswered";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_ERROR_SET=new Set(EP_ERROR_CODES);var UTF8=new TextEncoder;var LABEL="[a-z0-9]([a-z0-9-]*[a-z0-9])?";var EXTENSION_CODE=new RegExp(`^${LABEL}(\\.${LABEL}){2,}$`);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 list=registry2.get(def.kind)??[];list.push(def);registry2.set(def.kind,list)}Object.freeze(AUTHORITY_KIND_DEFS);Object.freeze(RECORD_KINDS);var AUTHORITY_DEF_SET=new Set(AUTHORITY_KIND_DEFS);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_jetstream=__toESM(require_mod4(),1);var dec=new TextDecoder("utf-8",{fatal:true});var STATIC_GENERATION_HORIZON_SEC=30*24*60*60;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;var enc2=new TextEncoder;var dec2=new TextDecoder("utf-8",{fatal:true});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;var AUTHORITY_HEAD_ARITY=new Map(AUTHORITY_KIND_DEFS.map(d=>[d.kind,1+d.qualifiers.length]));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_SNAP=new Map(Object.entries(REPEAT_SAFE_COMMANDS).map(([endpoint,commands])=>[endpoint,new Set(commands)]));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 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=reason=>{throw new PatternRefused(reason)};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(validate,closureDigest){const compiled=Object.freeze({validate,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 validate;try{for(const[digest,member]of Object.entries(bundle.members??{}))ajv.addSchema(member,`cotal:${digest}`);validate=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 validate}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 TRAIT_GUARDED="ai.cotal.guarded";var TRAIT_PRICED="ai.cotal.priced";var GOVERNED_TRAIT_URNS=Object.freeze([TRAIT_GUARDED,TRAIT_PRICED]);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"]);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"]);var import_nats_core2=__toESM(require_mod3(),1);var import_nats_core=__toESM(require_mod3(),1);var dec3=new TextDecoder;var enc3=new TextEncoder;var import_jetstream6=__toESM(require_mod4(),1);var import_transport_node6=__toESM(require_transport_node(),1);var CONTRACT_ARTIFACT_MAX_BYTES=256*1024;var CONTRACT_CLOSURE_MAX_BYTES=1024*1024;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 import_nkeys4=__toESM(require_mod(),1);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(h,l){this.hi=h|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 h=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(h,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,h){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(h){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(h,c){var j,u=0;for(j=0;j<17;j++){u=u+(h[j]+c[j]|0)|0;h[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),h=new Uint32Array(17),c=new Uint32Array(17),g=new Uint32Array(17);for(j=0;j<17;j++)r[j]=h[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(h,c);for(i=0;i<17;i++){x[i]=0;for(j=0;j<17;j++)x[i]=x[i]+h[j]*(j<=i?r[i-j]:320*r[i+17-j]|0)|0|0}for(i=0;i<17;i++)h[i]=x[i];u=0;for(j=0;j<16;j++){u=u+h[j]|0;h[j]=u&255;u>>>=8}u=u+h[16]|0;h[16]=u&3;u=5*(u>>>2)|0;for(j=0;j<16;j++){u=u+h[j]|0;h[j]=u&255;u>>>=8}u=u+h[16]|0;h[16]=u}for(j=0;j<17;j++)g[j]=h[j];add1305(h,minusp);s=-(h[16]>>>7)|0;for(j=0;j<17;j++)h[j]^=s&(g[j]^h[j]);for(j=0;j<16;j++)c[j]=k[j+16];c[16]=0;add1305(h,c);for(j=0;j<16;j++)out[outpos+j]=h[j];return 0}function crypto_onetimeauth_verify(h,hpos,m,mpos,n,k){var x=new Uint8Array(16);crypto_onetimeauth(x,0,m,mpos,n,k);return crypto_verify_16(h,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,h,i;for(i=0;i<arguments.length;i++){l=arguments[i].lo;h=arguments[i].hi;a+=l&m16;b+=l>>>16;c+=h&m16;d+=h>>>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,h=0,i;for(i=0;i<arguments.length;i++){l^=arguments[i].lo;h^=arguments[i].hi}return new u64(h,l)}function R(x,c){var h,l,c1=32-c;if(c<32){h=x.hi>>>c|x.lo<<c1;l=x.lo>>>c|x.hi<<c1}else if(c<64){h=x.lo>>>c|x.hi<<c1;l=x.hi>>>c|x.lo<<c1}return new u64(h,l)}function Ch(x,y,z2){var h=x.hi&y.hi^~x.hi&z2.hi,l=x.lo&y.lo^~x.lo&z2.lo;return new u64(h,l)}function Maj(x,y,z2){var h=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(h,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 h=new Uint8Array(64),x=new Uint8Array(256);var i,b=n;for(i=0;i<64;i++)h[i]=iv[i];crypto_hashblocks(h,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(h,x,n);for(i=0;i<64;i++)out[i]=h[i];return 0}function add(p,q){var a=gf(),b=gf(),c=gf(),d=gf(),e=gf(),f=gf(),g=gf(),h=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(h,b,a);M(p[0],e,f);M(p[1],h,g);M(p[2],g,f);M(p[3],e,h)}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),h=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(h,sm,n+64);reduce(h);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]+=h[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),h=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(h,m,n);reduce(h);scalarmult(p,q,h);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,nonce,key){checkArrayTypes(msg,nonce,key);checkLengths(key,nonce);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,nonce,key);return c.subarray(crypto_secretbox_BOXZEROBYTES)};nacl2.secretbox.open=function(box,nonce,key){checkArrayTypes(box,nonce,key);checkLengths(key,nonce);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,nonce,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,nonce,publicKey,secretKey){var k=nacl2.box.before(publicKey,secretKey);return nacl2.secretbox(msg,nonce,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,nonce,publicKey,secretKey){var k=nacl2.box.before(publicKey,secretKey);return nacl2.secretbox.open(msg,nonce,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 h=new Uint8Array(crypto_hash_BYTES);crypto_hash(h,msg,msg.length);return h};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);var ED25519_P=(1n<<255n)-19n;var import_nkeys9=__toESM(require_mod(),1);var import_transport_node14=__toESM(require_transport_node(),1);var import_transport_node13=__toESM(require_transport_node(),1);var import_nats_core6=__toESM(require_mod3(),1);var LIVENESS_PLANES=Object.freeze(["manager","delivery"]);var startedAt=Math.floor(performance.timeOrigin);var import_nkeys6=__toESM(require_mod(),1);var RENEWAL_WINDOW=Object.freeze({from:.5,to:.8});var BROKER_FLOOR=Object.freeze({major:2,minor:12});var import_jetstream10=__toESM(require_mod4(),1);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);var import_kv2=__toESM(require_mod6(),1);var import_internal=__toESM(require_internal_mod3(),1);var import_jetstream8=__toESM(require_mod4(),1);var import_kv3=__toESM(require_mod6(),1);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 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;var PRESENCE_STORAGE=import_jetstream10.StorageType.Memory;var MANAGER_LEASE_TTL_MS=1e4;var MANAGER_LEASE_RENEW_MS=MANAGER_LEASE_TTL_MS/4;var LEGACY_MEMBERSHIP_MAX_BYTES=64*1024*1024;var MEMBERSHIP_MAX_VALUE_SIZE=256*1024;var LEGACY_ARTIFACT_STORE_MAX_BYTES=4*1024*1024*1024;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 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;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]));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 LAUNCH_READ_COMMANDS=Object.freeze(["status","models","resolve-cwd"]);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"}};var isWin=process.platform==="win32";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);var import_kv6=__toESM(require_mod6(),1);var import_transport_node12=__toESM(require_transport_node(),1);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}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 HISTORY_READER_INACTIVE_MS=5*6e4;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})$`);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 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 enc6=new TextEncoder;var dec6=new TextDecoder;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{Zl}\p{Zp}\p{Bidi_Control}]/gu,c=>`\\u${c.charCodeAt(0).toString(16).padStart(4,"0")}`)}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`}var import_nkeys10=__toESM(require_mod(),1);var import_transport_node19=__toESM(require_transport_node(),1);var import_kv10=__toESM(require_mod6(),1);var import_transport_node20=__toESM(require_transport_node(),1);var import_jetstream22=__toESM(require_mod4(),1);var import_kv11=__toESM(require_mod6(),1);import{BlockList,isIPv4,isIPv6}from"node:net";var LOOPBACK=new 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"]);import{AsyncLocalStorage}from"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 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 SELECTION_MAX_ITEMS=32;var EMPTY_CONVERSATION_SELECTION=Object.freeze({v:1,channels:Object.freeze([]),role:null,capabilities:Object.freeze([]),endpoints:Object.freeze([])});var DELEGATED_RECOVERY_REASONS=Object.freeze(["provider-unknown","store-unavailable","authority-unavailable","identity-unverified","descriptor-incomplete","retiring","authority-drift","identity-changed","scope-changed"]);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}}}}});function deepFreeze(v){if(v!==null&&typeof v==="object"){for(const child of Object.values(v))deepFreeze(child);Object.freeze(v)}return v}var import_nkeys11=__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 deepFreeze2(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))deepFreeze2(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=deepFreeze2(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=deepFreeze2(closed2({v:{const:1},kind:{const:"tool-result-revocation"},space,consentId:id,target,revokedAt:uint}));var TOOL_RESULT_SERVING_MATERIAL_SCHEMA=deepFreeze2(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=deepFreeze2(closed2(pair));var TOOL_RESULT_ANSWER_SCHEMAS=deepFreeze2({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=deepFreeze2({oneOf:Object.values(TOOL_RESULT_ANSWER_SCHEMAS)});var TOOL_RESULT_CONSENT_INPUT_SCHEMA=deepFreeze2(closed2({consent:TOOL_RESULT_CONSENT_SCHEMA}));var TOOL_RESULT_CONSENT_OUTPUT_SCHEMA=deepFreeze2(status("active",{consentId:id}));var TOOL_RESULT_REVOKE_INPUT_SCHEMA=deepFreeze2(closed2({consentId:id}));var TOOL_RESULT_REVOKE_ANSWER_SCHEMAS=deepFreeze2({known:status("known",{consentId:id}),refused:status("refused",{consentId:id}),unknown:status("unknown",{consentId:id})});var TOOL_RESULT_REVOKE_OUTPUT_SCHEMA=deepFreeze2({oneOf:Object.values(TOOL_RESULT_REVOKE_ANSWER_SCHEMAS)});var TOOL_RESULTS_COMMANDS=deepFreeze2([{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=deepFreeze2({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_nkeys12=__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 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 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 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 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 h=i.historical?"(history) ":"";const r=i.deliveryCount!==void 0&&i.deliveryCount>1?`(broker redelivery, delivery ${i.deliveryCount}: prior model handoff unknown) `:"";const body=`${metadata2}${h}${r}${fmtBody(i.text)}`;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}`}var LEGACY_RAIL_RECHECK_MS=60*6e4;function afterRecallMark(a,b){return a.ts!==b.ts?a.ts>b.ts:a.id>b.id}var MAX_INBOX=200;var MAX_IN_FLIGHT=MAX_INBOX*2;function presenceReadCondition(failure){return`the presence read failed (${failure.message})`}var SUN_PATH_MAX_BYTES=process.platform==="darwin"?104:108;var TOOL_RESULT_EVENT="cotal.toolResult";var TRUNCATABLE_FIELDS=[{type:AGUI_EVENT_TYPE.TOOL_CALL_ARGS,field:"delta"},{type:AGUI_EVENT_TYPE.TOOL_CALL_RESULT,field:"content"},{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,field:"delta"}];var EGRESS_FORBIDDEN_TYPES=new Set([AGUI_EVENT_TYPE.TOOL_CALL_ARGS,AGUI_EVENT_TYPE.TOOL_CALL_RESULT]);var KNOWN_EVENT_KEYS_BY_TYPE=new Map([[AGUI_EVENT_TYPE.RUN_STARTED,new Set(["type","timestamp","rawEvent","threadId","runId","parentRunId","input","cotal"])],[AGUI_EVENT_TYPE.RUN_FINISHED,new Set(["type","timestamp","rawEvent","threadId","runId","result","outcome","cotal"])],[AGUI_EVENT_TYPE.RUN_ERROR,new Set(["type","timestamp","rawEvent","message","code","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","name","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_START,new Set(["type","timestamp","rawEvent","toolCallId","toolCallName","parentMessageId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_ARGS,new Set(["type","timestamp","rawEvent","toolCallId","delta","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_END,new Set(["type","timestamp","rawEvent","toolCallId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_RESULT,new Set(["type","timestamp","rawEvent","messageId","toolCallId","content","role","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE.CUSTOM,new Set(["type","timestamp","rawEvent","name","value","cotal"])]]);var TOOL_RESULT_VALUE_KEYS=new Set(["toolCallId","isError"]);function toolResultValueDefect(value){if(typeof value!=="object"||value===null||Array.isArray(value))return"value";const keys=Object.keys(value);for(const key of keys){if(!TOOL_RESULT_VALUE_KEYS.has(key))return`value.${key}`}if(keys.length!==TOOL_RESULT_VALUE_KEYS.size)return"value";const v=value;if(typeof v.toolCallId!=="string")return"value";if(typeof v.isError!=="boolean")return"value";return void 0}function toolResultValue(value){if(toolResultValueDefect(value)!==void 0)return void 0;const v=value;return{toolCallId:v.toolCallId,isError:v.isError}}var SIZING_ID="S".repeat(64);var SIZING_EXPECTATION=Number.MAX_SAFE_INTEGER;var str=v=>typeof v==="string"?v:void 0;var CONT=" \xB7 ";var TEXT_PREFIX="\xBB ";var THINK_PREFIX="(thinking) ";var TOOL_PREFIX="\u2699 ";var RESULT_PREFIX=" \u21B3 ";var BLOCK_START_CHARS=new Set([..."#>|`~=_*+-[<0123456789"," "]);function renderEvents(events){const lines=[];const text2=new Map;const reasoning=new Map;const toolName=new Map;const toolArgs=new Map;const emit=(first,cont,body)=>{const[head,...rest]=body.split("\n");lines.push(first+head);for(const l of rest)lines.push(cont+l)};const flush=(map2,id2,first,cont,suffix="")=>{const acc=map2.get(id2);if(acc!==void 0&&acc.length>0)emit(first,cont,acc+suffix);map2.delete(id2)};for(const e of events){const type=typeof e==="object"&&e!==null?str(e.type):void 0;switch(type){case AGUI_EVENT_TYPE.RUN_STARTED:emit("\u25B8 ",CONT,`run ${str(e.runId)??"?"} started`);break;case AGUI_EVENT_TYPE.RUN_FINISHED:{const outcome=str(e.outcome?.type);emit("\u25C2 ",CONT,`run ${str(e.runId)??"?"} finished${outcome?` (${outcome})`:""}`);break}case AGUI_EVENT_TYPE.RUN_ERROR:{const code=str(e.code);emit("\u2717 ",CONT,`run error${code?` [${code}]`:""}: ${str(e.message)??"(no message)"}`);break}case AGUI_EVENT_TYPE.TEXT_MESSAGE_START:text2.set(str(e.messageId)??"","");break;case AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT:{const id2=str(e.messageId)??"";text2.set(id2,(text2.get(id2)??"")+(str(e.delta)??""));break}case AGUI_EVENT_TYPE.TEXT_MESSAGE_END:flush(text2,str(e.messageId)??"",TEXT_PREFIX,TEXT_PREFIX);break;case AGUI_EVENT_TYPE.REASONING_MESSAGE_START:reasoning.set(str(e.messageId)??"","");break;case AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT:{const id2=str(e.messageId)??"";reasoning.set(id2,(reasoning.get(id2)??"")+(str(e.delta)??""));break}case AGUI_EVENT_TYPE.REASONING_MESSAGE_END:flush(reasoning,str(e.messageId)??"",THINK_PREFIX,CONT);break;case AGUI_EVENT_TYPE.TOOL_CALL_START:{const id2=str(e.toolCallId)??"";toolName.set(id2,str(e.toolCallName)??"?");toolArgs.set(id2,"");break}case AGUI_EVENT_TYPE.TOOL_CALL_ARGS:{const id2=str(e.toolCallId)??"";toolArgs.set(id2,(toolArgs.get(id2)??"")+(str(e.delta)??""));break}case AGUI_EVENT_TYPE.TOOL_CALL_END:{const id2=str(e.toolCallId)??"";emit(TOOL_PREFIX,CONT,`${toolName.get(id2)??"?"}(${toolArgs.get(id2)??""})`);toolName.delete(id2);toolArgs.delete(id2);break}case AGUI_EVENT_TYPE.TOOL_CALL_RESULT:emit(RESULT_PREFIX,CONT,str(e.content)??"(no content)");break;case AGUI_EVENT_TYPE.CUSTOM:{const failed=e.name===TOOL_RESULT_EVENT?toolResultValue(e.value)?.isError:void 0;if(failed!==void 0)emit(RESULT_PREFIX,CONT,failed?"failed":"done");else emit("\u2022 ",CONT,`custom ${str(e.name)??"(unnamed)"}`);break}default:emit("\u2022 ",CONT,`unrecognised event ${JSON.stringify(type??null)}`)}}for(const id2 of[...text2.keys()])flush(text2,id2,TEXT_PREFIX,TEXT_PREFIX," \u2026");for(const id2 of[...reasoning.keys()])flush(reasoning,id2,THINK_PREFIX,CONT," \u2026");for(const id2 of[...toolName.keys()])emit(TOOL_PREFIX,CONT,`${toolName.get(id2)??"?"}(${toolArgs.get(id2)??""}) \u2026`);return lines}var aguiFramePartRenderer=Object.freeze({kind:"part-renderer",name:AGUI_FRAME_KIND,render(part){if(!isAguiFramePart(part))return`[not an AG-UI frame]`;const events=part.events;if(!Array.isArray(events)||events.length===0)return`[AG-UI frame carrying no events]`;const lines=renderEvents(events);return lines.length>0?lines.join("\n"):`[AG-UI frame with ${events.length} event(s) and nothing to show]`}});function registerAguiFramePartRenderer(){if(registry3.has("part-renderer",AGUI_FRAME_KIND))return;registry3.register(aguiFramePartRenderer)}registerAguiFramePartRenderer();var MAX_FRAME_BYTES=1<<20;var ok=text2=>({text:text2});var err=text2=>({text:text2,isError:true});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}try{const res=await fetch(url2,{method:"POST",headers:headers3,body:JSON.stringify(body)});const raw=await res.text();let reply={};if(raw)try{reply=JSON.parse(raw)}catch{reply={error:raw}}if(!res.ok)return err(`Feedback rejected (${res.status}${reply.error?`: ${reply.error}`:""}).`);const note=reply.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent${reply.id?` (id ${reply.id})`:""}${note}. Thanks!`)}catch(e){return err(`Couldn't reach the feedback intake at ${url2}: ${e.message}`)}}import{execFileSync}from"node:child_process";import{createHash as createHash2}from"node:crypto";import{readFileSync}from"node:fs";import{join}from"node:path";import{gunzipSync}from"node:zlib";var DOCS_VERSION="0.140.7";function loadDocsMetadata(){return{"version":"0.140.7","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here","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","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept","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","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference","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","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","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","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","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","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","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","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","category":"Guide","summary":"Launch Codex on a Cotal mesh, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide","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","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","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","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","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","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide","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","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","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","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference","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","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","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-view","title":"MeshView","kind":"Reference","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","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","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","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","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","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","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","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","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=readFileSync(join(import.meta.dirname,"docs-bundle.bin"));if(packed.length!==1132950||createHash2("sha256").update(packed).digest("hex")!=="b13e2f7ed990f8ac608ec86cfdfab5427823db79dfb69de33d3a8490b816e0ea")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,29199],[29199,33561],[33561,37932],[37932,41364],[41364,46597],[46597,50111],[50111,59099],[59099,63251],[63251,67699],[67699,69721],[69721,73732],[73732,104132],[104132,119620],[119620,134750],[134750,152349],[152349,167213],[167213,181938],[181938,197291],[197291,216893],[216893,222609],[222609,232167],[232167,250678],[250678,255082],[255082,277640],[277640,286746],[286746,315265],[315265,331170],[331170,353952],[353952,383643],[383643,396737],[396737,398684],[398684,407513],[407513,423519],[423519,431010],[431010,433694],[433694,437075],[437075,440378],[440378,442423],[442423,445028],[445028,449702],[449702,451506],[451506,455057],[455057,466502],[466502,474463],[474463,477988],[477988,485261],[485261,490305],[490305,493212],[493212,501171],[501171,504148],[504148,511418],[511418,514408],[514408,519215],[519215,530334],[530334,541942],[541942,546834],[546834,554365],[554365,557714],[557714,560285],[560285,567543],[567543,570928],[570928,573138],[573138,576600],[576600,580017],[580017,581131],[581131,582880],[582880,586543],[586543,591096],[591096,597529],[597529,607843],[607843,620732],[620732,622569],[622569,635554],[635554,640670],[640670,644535],[644535,647044],[647044,652090],[652090,658865],[658865,665075],[665075,665822],[665822,669894],[669894,675156],[675156,678534],[678534,682420],[682420,686612],[686612,691414],[691414,694836],[694836,698235],[698235,702282],[702282,705925],[705925,719115],[719115,721933],[721933,724616],[724616,727283],[727283,729774],[729774,733794],[733794,738494],[738494,740713],[740713,803251],[803251,806322],[806322,807302],[807302,813638],[813638,821394],[821394,831424],[831424,840122],[840122,845179],[845179,1089751],[1089751,1127738],[1127738,1132950]];var sourceLengths=[4844,4048,13310,78408,12092,10644,34303,13195,8549,78405,37758,10864,4557,9872,82530,41661,42535,50018,41170,42638,41811,54299,14375,25041,52926,9889,64826,24959,86388,44853,68054,91273,36249,8216,22028,42818,20304,6278,8035,7790,4835,5961,11801,4292,8347,30465,19623,8745,47165,12743,7133,20461,7140,18798,6860,11996,28607,30497,12022,18311,8355,6090,18823,7449,5100,8160,9930,2248,5412,9845,10853,15565,26241,33068,4227,35397,11735,9420,8201,13307,16844,15126,1464,9180,13455,7818,9320,10514,11921,7511,8528,9633,8527,35171,6519,6405,6095,6007,9711,11730,5283,184354,6927,2023,15129,20040,25734,20809,12299,708317,107513,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(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=readFileSync(join(import.meta.dirname,"docs-index.bin"));if(packed.length!==588714||createHash2("sha256").update(packed).digest("hex")!=="a459ad5e009f1801fbc22d6c30ac6722517fc2154751f072f8175269c30131df")throw new Error("docs data file docs-index.bin beside this module is not the one built with it");return 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}
|
|
116
|
+
]`;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 main=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){main.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?{...main,[refs.definitionPath]:definitions}:main:{$ref:[...refs.$refStrategy==="relative"?[]:refs.basePath,refs.definitionPath,name].join("/"),[refs.definitionPath]:{...definitions,[name]:main}};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=reason=>{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(reason)}},{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error52=>this._onerror(new Error(`Failed to send cancellation: ${error52}`)));const error51=reason instanceof McpError?reason:new McpError(ErrorCode.RequestTimeout,String(reason));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 resources=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:[...resources,...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}};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 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");var import_nkeys2=__toESM(require_mod(),1);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 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}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 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 channelInAllow(allow,channel){return allow.some(a=>subjectMatches(a,channel))}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))}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 ID=/^[A-Za-z0-9_-]{1,64}$/;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 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}var EP_AUTHZ_MODES=Object.freeze(["self","owner","any","child","ledger","handle","exact"]);var AUTHZ_SET=new Set(EP_AUTHZ_MODES);import{createHash}from"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 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+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_UNANSWERED="ai.cotal.ep.unanswered";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_ERROR_SET=new Set(EP_ERROR_CODES);var UTF8=new TextEncoder;var LABEL="[a-z0-9]([a-z0-9-]*[a-z0-9])?";var EXTENSION_CODE=new RegExp(`^${LABEL}(\\.${LABEL}){2,}$`);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 list=registry2.get(def.kind)??[];list.push(def);registry2.set(def.kind,list)}Object.freeze(AUTHORITY_KIND_DEFS);Object.freeze(RECORD_KINDS);var AUTHORITY_DEF_SET=new Set(AUTHORITY_KIND_DEFS);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_jetstream=__toESM(require_mod4(),1);var dec=new TextDecoder("utf-8",{fatal:true});var STATIC_GENERATION_HORIZON_SEC=30*24*60*60;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;var enc2=new TextEncoder;var dec2=new TextDecoder("utf-8",{fatal:true});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;var AUTHORITY_HEAD_ARITY=new Map(AUTHORITY_KIND_DEFS.map(d=>[d.kind,1+d.qualifiers.length]));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_SNAP=new Map(Object.entries(REPEAT_SAFE_COMMANDS).map(([endpoint,commands])=>[endpoint,new Set(commands)]));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 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=reason=>{throw new PatternRefused(reason)};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(validate,closureDigest){const compiled=Object.freeze({validate,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 validate;try{for(const[digest,member]of Object.entries(bundle.members??{}))ajv.addSchema(member,`cotal:${digest}`);validate=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 validate}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 TRAIT_GUARDED="ai.cotal.guarded";var TRAIT_PRICED="ai.cotal.priced";var GOVERNED_TRAIT_URNS=Object.freeze([TRAIT_GUARDED,TRAIT_PRICED]);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"]);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"]);var import_nats_core2=__toESM(require_mod3(),1);var import_nats_core=__toESM(require_mod3(),1);var dec3=new TextDecoder;var enc3=new TextEncoder;var import_jetstream6=__toESM(require_mod4(),1);var import_transport_node6=__toESM(require_transport_node(),1);var CONTRACT_ARTIFACT_MAX_BYTES=256*1024;var CONTRACT_CLOSURE_MAX_BYTES=1024*1024;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 import_nkeys4=__toESM(require_mod(),1);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(h,l){this.hi=h|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 h=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(h,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,h){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(h){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(h,c){var j,u=0;for(j=0;j<17;j++){u=u+(h[j]+c[j]|0)|0;h[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),h=new Uint32Array(17),c=new Uint32Array(17),g=new Uint32Array(17);for(j=0;j<17;j++)r[j]=h[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(h,c);for(i=0;i<17;i++){x[i]=0;for(j=0;j<17;j++)x[i]=x[i]+h[j]*(j<=i?r[i-j]:320*r[i+17-j]|0)|0|0}for(i=0;i<17;i++)h[i]=x[i];u=0;for(j=0;j<16;j++){u=u+h[j]|0;h[j]=u&255;u>>>=8}u=u+h[16]|0;h[16]=u&3;u=5*(u>>>2)|0;for(j=0;j<16;j++){u=u+h[j]|0;h[j]=u&255;u>>>=8}u=u+h[16]|0;h[16]=u}for(j=0;j<17;j++)g[j]=h[j];add1305(h,minusp);s=-(h[16]>>>7)|0;for(j=0;j<17;j++)h[j]^=s&(g[j]^h[j]);for(j=0;j<16;j++)c[j]=k[j+16];c[16]=0;add1305(h,c);for(j=0;j<16;j++)out[outpos+j]=h[j];return 0}function crypto_onetimeauth_verify(h,hpos,m,mpos,n,k){var x=new Uint8Array(16);crypto_onetimeauth(x,0,m,mpos,n,k);return crypto_verify_16(h,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,h,i;for(i=0;i<arguments.length;i++){l=arguments[i].lo;h=arguments[i].hi;a+=l&m16;b+=l>>>16;c+=h&m16;d+=h>>>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,h=0,i;for(i=0;i<arguments.length;i++){l^=arguments[i].lo;h^=arguments[i].hi}return new u64(h,l)}function R(x,c){var h,l,c1=32-c;if(c<32){h=x.hi>>>c|x.lo<<c1;l=x.lo>>>c|x.hi<<c1}else if(c<64){h=x.lo>>>c|x.hi<<c1;l=x.hi>>>c|x.lo<<c1}return new u64(h,l)}function Ch(x,y,z2){var h=x.hi&y.hi^~x.hi&z2.hi,l=x.lo&y.lo^~x.lo&z2.lo;return new u64(h,l)}function Maj(x,y,z2){var h=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(h,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 h=new Uint8Array(64),x=new Uint8Array(256);var i,b=n;for(i=0;i<64;i++)h[i]=iv[i];crypto_hashblocks(h,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(h,x,n);for(i=0;i<64;i++)out[i]=h[i];return 0}function add(p,q){var a=gf(),b=gf(),c=gf(),d=gf(),e=gf(),f=gf(),g=gf(),h=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(h,b,a);M(p[0],e,f);M(p[1],h,g);M(p[2],g,f);M(p[3],e,h)}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),h=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(h,sm,n+64);reduce(h);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]+=h[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),h=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(h,m,n);reduce(h);scalarmult(p,q,h);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,nonce,key){checkArrayTypes(msg,nonce,key);checkLengths(key,nonce);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,nonce,key);return c.subarray(crypto_secretbox_BOXZEROBYTES)};nacl2.secretbox.open=function(box,nonce,key){checkArrayTypes(box,nonce,key);checkLengths(key,nonce);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,nonce,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,nonce,publicKey,secretKey){var k=nacl2.box.before(publicKey,secretKey);return nacl2.secretbox(msg,nonce,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,nonce,publicKey,secretKey){var k=nacl2.box.before(publicKey,secretKey);return nacl2.secretbox.open(msg,nonce,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 h=new Uint8Array(crypto_hash_BYTES);crypto_hash(h,msg,msg.length);return h};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);var ED25519_P=(1n<<255n)-19n;var import_nkeys9=__toESM(require_mod(),1);var import_transport_node14=__toESM(require_transport_node(),1);var import_transport_node13=__toESM(require_transport_node(),1);var import_nats_core6=__toESM(require_mod3(),1);var LIVENESS_PLANES=Object.freeze(["manager","delivery"]);var startedAt=Math.floor(performance.timeOrigin);var import_nkeys6=__toESM(require_mod(),1);var RENEWAL_WINDOW=Object.freeze({from:.5,to:.8});var BROKER_FLOOR=Object.freeze({major:2,minor:12});var import_jetstream10=__toESM(require_mod4(),1);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);var import_kv2=__toESM(require_mod6(),1);var import_internal=__toESM(require_internal_mod3(),1);var import_jetstream8=__toESM(require_mod4(),1);var import_kv3=__toESM(require_mod6(),1);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 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;var PRESENCE_STORAGE=import_jetstream10.StorageType.Memory;var MANAGER_LEASE_TTL_MS=1e4;var MANAGER_LEASE_RENEW_MS=MANAGER_LEASE_TTL_MS/4;var LEGACY_MEMBERSHIP_MAX_BYTES=64*1024*1024;var MEMBERSHIP_MAX_VALUE_SIZE=256*1024;var LEGACY_ARTIFACT_STORE_MAX_BYTES=4*1024*1024*1024;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 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;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]));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 LAUNCH_READ_COMMANDS=Object.freeze(["status","models","resolve-cwd"]);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"}};var isWin=process.platform==="win32";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);var import_kv6=__toESM(require_mod6(),1);var import_transport_node12=__toESM(require_transport_node(),1);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}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 HISTORY_READER_INACTIVE_MS=5*6e4;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})$`);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 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 enc6=new TextEncoder;var dec6=new TextDecoder;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{Zl}\p{Zp}\p{Bidi_Control}]/gu,c=>`\\u${c.charCodeAt(0).toString(16).padStart(4,"0")}`)}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`}var import_nkeys10=__toESM(require_mod(),1);var import_transport_node19=__toESM(require_transport_node(),1);var import_kv10=__toESM(require_mod6(),1);var import_transport_node20=__toESM(require_transport_node(),1);var import_jetstream22=__toESM(require_mod4(),1);var import_kv11=__toESM(require_mod6(),1);import{BlockList,isIPv4,isIPv6}from"node:net";var LOOPBACK=new 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"]);import{AsyncLocalStorage}from"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 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 SELECTION_MAX_ITEMS=32;var EMPTY_CONVERSATION_SELECTION=Object.freeze({v:1,channels:Object.freeze([]),role:null,capabilities:Object.freeze([]),endpoints:Object.freeze([])});var DELEGATED_RECOVERY_REASONS=Object.freeze(["provider-unknown","store-unavailable","authority-unavailable","identity-unverified","descriptor-incomplete","retiring","authority-drift","identity-changed","scope-changed"]);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}}}}});function deepFreeze(v){if(v!==null&&typeof v==="object"){for(const child of Object.values(v))deepFreeze(child);Object.freeze(v)}return v}var import_nkeys11=__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 deepFreeze2(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))deepFreeze2(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=deepFreeze2(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=deepFreeze2(closed2({v:{const:1},kind:{const:"tool-result-revocation"},space,consentId:id,target,revokedAt:uint}));var TOOL_RESULT_SERVING_MATERIAL_SCHEMA=deepFreeze2(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=deepFreeze2(closed2(pair));var TOOL_RESULT_ANSWER_SCHEMAS=deepFreeze2({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=deepFreeze2({oneOf:Object.values(TOOL_RESULT_ANSWER_SCHEMAS)});var TOOL_RESULT_CONSENT_INPUT_SCHEMA=deepFreeze2(closed2({consent:TOOL_RESULT_CONSENT_SCHEMA}));var TOOL_RESULT_CONSENT_OUTPUT_SCHEMA=deepFreeze2(status("active",{consentId:id}));var TOOL_RESULT_REVOKE_INPUT_SCHEMA=deepFreeze2(closed2({consentId:id}));var TOOL_RESULT_REVOKE_ANSWER_SCHEMAS=deepFreeze2({known:status("known",{consentId:id}),refused:status("refused",{consentId:id}),unknown:status("unknown",{consentId:id})});var TOOL_RESULT_REVOKE_OUTPUT_SCHEMA=deepFreeze2({oneOf:Object.values(TOOL_RESULT_REVOKE_ANSWER_SCHEMAS)});var TOOL_RESULTS_COMMANDS=deepFreeze2([{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=deepFreeze2({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_nkeys12=__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 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 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 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 h=i.historical?"(history) ":"";const r=i.deliveryCount!==void 0&&i.deliveryCount>1?`(broker redelivery, delivery ${i.deliveryCount}: prior model handoff unknown) `:"";const body=`${metadata2}${h}${r}${fmtBody(i.text)}`;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}`}var LEGACY_RAIL_RECHECK_MS=60*6e4;function afterRecallMark(a,b){return a.ts!==b.ts?a.ts>b.ts:a.id>b.id}var MAX_INBOX=200;var MAX_IN_FLIGHT=MAX_INBOX*2;function presenceReadCondition(failure){return`the presence read failed (${failure.message})`}var SUN_PATH_MAX_BYTES=process.platform==="darwin"?104:108;var TOOL_RESULT_EVENT="cotal.toolResult";var TRUNCATABLE_FIELDS=[{type:AGUI_EVENT_TYPE.TOOL_CALL_ARGS,field:"delta"},{type:AGUI_EVENT_TYPE.TOOL_CALL_RESULT,field:"content"},{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,field:"delta"}];var EGRESS_FORBIDDEN_TYPES=new Set([AGUI_EVENT_TYPE.TOOL_CALL_ARGS,AGUI_EVENT_TYPE.TOOL_CALL_RESULT]);var KNOWN_EVENT_KEYS_BY_TYPE=new Map([[AGUI_EVENT_TYPE.RUN_STARTED,new Set(["type","timestamp","rawEvent","threadId","runId","parentRunId","input","cotal"])],[AGUI_EVENT_TYPE.RUN_FINISHED,new Set(["type","timestamp","rawEvent","threadId","runId","result","outcome","cotal"])],[AGUI_EVENT_TYPE.RUN_ERROR,new Set(["type","timestamp","rawEvent","message","code","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","name","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_START,new Set(["type","timestamp","rawEvent","toolCallId","toolCallName","parentMessageId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_ARGS,new Set(["type","timestamp","rawEvent","toolCallId","delta","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_END,new Set(["type","timestamp","rawEvent","toolCallId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_RESULT,new Set(["type","timestamp","rawEvent","messageId","toolCallId","content","role","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE.CUSTOM,new Set(["type","timestamp","rawEvent","name","value","cotal"])]]);var TOOL_RESULT_VALUE_KEYS=new Set(["toolCallId","isError"]);function toolResultValueDefect(value){if(typeof value!=="object"||value===null||Array.isArray(value))return"value";const keys=Object.keys(value);for(const key of keys){if(!TOOL_RESULT_VALUE_KEYS.has(key))return`value.${key}`}if(keys.length!==TOOL_RESULT_VALUE_KEYS.size)return"value";const v=value;if(typeof v.toolCallId!=="string")return"value";if(typeof v.isError!=="boolean")return"value";return void 0}function toolResultValue(value){if(toolResultValueDefect(value)!==void 0)return void 0;const v=value;return{toolCallId:v.toolCallId,isError:v.isError}}var SIZING_ID="S".repeat(64);var SIZING_EXPECTATION=Number.MAX_SAFE_INTEGER;var str=v=>typeof v==="string"?v:void 0;var CONT=" \xB7 ";var TEXT_PREFIX="\xBB ";var THINK_PREFIX="(thinking) ";var TOOL_PREFIX="\u2699 ";var RESULT_PREFIX=" \u21B3 ";var BLOCK_START_CHARS=new Set([..."#>|`~=_*+-[<0123456789"," "]);function renderEvents(events){const lines=[];const text2=new Map;const reasoning=new Map;const toolName=new Map;const toolArgs=new Map;const emit=(first,cont,body)=>{const[head,...rest]=body.split("\n");lines.push(first+head);for(const l of rest)lines.push(cont+l)};const flush=(map2,id2,first,cont,suffix="")=>{const acc=map2.get(id2);if(acc!==void 0&&acc.length>0)emit(first,cont,acc+suffix);map2.delete(id2)};for(const e of events){const type=typeof e==="object"&&e!==null?str(e.type):void 0;switch(type){case AGUI_EVENT_TYPE.RUN_STARTED:emit("\u25B8 ",CONT,`run ${str(e.runId)??"?"} started`);break;case AGUI_EVENT_TYPE.RUN_FINISHED:{const outcome=str(e.outcome?.type);emit("\u25C2 ",CONT,`run ${str(e.runId)??"?"} finished${outcome?` (${outcome})`:""}`);break}case AGUI_EVENT_TYPE.RUN_ERROR:{const code=str(e.code);emit("\u2717 ",CONT,`run error${code?` [${code}]`:""}: ${str(e.message)??"(no message)"}`);break}case AGUI_EVENT_TYPE.TEXT_MESSAGE_START:text2.set(str(e.messageId)??"","");break;case AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT:{const id2=str(e.messageId)??"";text2.set(id2,(text2.get(id2)??"")+(str(e.delta)??""));break}case AGUI_EVENT_TYPE.TEXT_MESSAGE_END:flush(text2,str(e.messageId)??"",TEXT_PREFIX,TEXT_PREFIX);break;case AGUI_EVENT_TYPE.REASONING_MESSAGE_START:reasoning.set(str(e.messageId)??"","");break;case AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT:{const id2=str(e.messageId)??"";reasoning.set(id2,(reasoning.get(id2)??"")+(str(e.delta)??""));break}case AGUI_EVENT_TYPE.REASONING_MESSAGE_END:flush(reasoning,str(e.messageId)??"",THINK_PREFIX,CONT);break;case AGUI_EVENT_TYPE.TOOL_CALL_START:{const id2=str(e.toolCallId)??"";toolName.set(id2,str(e.toolCallName)??"?");toolArgs.set(id2,"");break}case AGUI_EVENT_TYPE.TOOL_CALL_ARGS:{const id2=str(e.toolCallId)??"";toolArgs.set(id2,(toolArgs.get(id2)??"")+(str(e.delta)??""));break}case AGUI_EVENT_TYPE.TOOL_CALL_END:{const id2=str(e.toolCallId)??"";emit(TOOL_PREFIX,CONT,`${toolName.get(id2)??"?"}(${toolArgs.get(id2)??""})`);toolName.delete(id2);toolArgs.delete(id2);break}case AGUI_EVENT_TYPE.TOOL_CALL_RESULT:emit(RESULT_PREFIX,CONT,str(e.content)??"(no content)");break;case AGUI_EVENT_TYPE.CUSTOM:{const failed=e.name===TOOL_RESULT_EVENT?toolResultValue(e.value)?.isError:void 0;if(failed!==void 0)emit(RESULT_PREFIX,CONT,failed?"failed":"done");else emit("\u2022 ",CONT,`custom ${str(e.name)??"(unnamed)"}`);break}default:emit("\u2022 ",CONT,`unrecognised event ${JSON.stringify(type??null)}`)}}for(const id2 of[...text2.keys()])flush(text2,id2,TEXT_PREFIX,TEXT_PREFIX," \u2026");for(const id2 of[...reasoning.keys()])flush(reasoning,id2,THINK_PREFIX,CONT," \u2026");for(const id2 of[...toolName.keys()])emit(TOOL_PREFIX,CONT,`${toolName.get(id2)??"?"}(${toolArgs.get(id2)??""}) \u2026`);return lines}var aguiFramePartRenderer=Object.freeze({kind:"part-renderer",name:AGUI_FRAME_KIND,render(part){if(!isAguiFramePart(part))return`[not an AG-UI frame]`;const events=part.events;if(!Array.isArray(events)||events.length===0)return`[AG-UI frame carrying no events]`;const lines=renderEvents(events);return lines.length>0?lines.join("\n"):`[AG-UI frame with ${events.length} event(s) and nothing to show]`}});function registerAguiFramePartRenderer(){if(registry3.has("part-renderer",AGUI_FRAME_KIND))return;registry3.register(aguiFramePartRenderer)}registerAguiFramePartRenderer();var MAX_FRAME_BYTES=1<<20;var ok=text2=>({text:text2});var err=text2=>({text:text2,isError:true});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}try{const res=await fetch(url2,{method:"POST",headers:headers3,body:JSON.stringify(body)});const raw=await res.text();let reply={};if(raw)try{reply=JSON.parse(raw)}catch{reply={error:raw}}if(!res.ok)return err(`Feedback rejected (${res.status}${reply.error?`: ${reply.error}`:""}).`);const note=reply.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent${reply.id?` (id ${reply.id})`:""}${note}. Thanks!`)}catch(e){return err(`Couldn't reach the feedback intake at ${url2}: ${e.message}`)}}import{execFileSync}from"node:child_process";import{createHash as createHash2}from"node:crypto";import{readFileSync}from"node:fs";import{join}from"node:path";import{gunzipSync}from"node:zlib";var DOCS_VERSION="0.141.0";function loadDocsMetadata(){return{"version":"0.141.0","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here","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","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept","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","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference","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","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","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","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","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","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","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","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","category":"Guide","summary":"Launch Codex on a Cotal mesh, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide","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","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","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","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","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","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide","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","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","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","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference","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","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","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-view","title":"MeshView","kind":"Reference","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","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","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","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","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","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","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","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","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=readFileSync(join(import.meta.dirname,"docs-bundle.bin"));if(packed.length!==1144136||createHash2("sha256").update(packed).digest("hex")!=="4b5bd7eb828f97e8320c8fe02b43c96bbafd4001bd2e82ecde96e8183e5596f8")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,29705],[29705,34102],[34102,38480],[38480,41912],[41912,48264],[48264,51778],[51778,60766],[60766,64918],[64918,69366],[69366,71388],[71388,75399],[75399,105803],[105803,121291],[121291,136421],[136421,154147],[154147,169011],[169011,183736],[183736,199089],[199089,218799],[218799,224515],[224515,234073],[234073,252584],[252584,256988],[256988,279546],[279546,288652],[288652,317171],[317171,333076],[333076,355858],[355858,385549],[385549,398643],[398643,400590],[400590,409419],[409419,425425],[425425,432916],[432916,435600],[435600,438981],[438981,442284],[442284,444329],[444329,446934],[446934,451608],[451608,453412],[453412,456963],[456963,468432],[468432,476393],[476393,479918],[479918,487191],[487191,492235],[492235,495142],[495142,503101],[503101,506078],[506078,513348],[513348,516338],[516338,521145],[521145,532264],[532264,544097],[544097,548989],[548989,556520],[556520,559869],[559869,562440],[562440,569698],[569698,573083],[573083,575293],[575293,578755],[578755,582172],[582172,583286],[583286,585035],[585035,588698],[588698,593251],[593251,599684],[599684,610194],[610194,623246],[623246,625083],[625083,638068],[638068,643347],[643347,647212],[647212,649721],[649721,654763],[654763,661538],[661538,667748],[667748,668495],[668495,672567],[672567,677829],[677829,681207],[681207,685093],[685093,689285],[689285,694087],[694087,697509],[697509,700908],[700908,705445],[705445,709088],[709088,722278],[722278,725096],[725096,727779],[727779,730446],[730446,732937],[732937,736957],[736957,741657],[741657,743876],[743876,807947],[807947,811018],[811018,811998],[811998,818334],[818334,826191],[826191,836578],[836578,845296],[845296,850353],[850353,1100164],[1100164,1138924],[1138924,1144136]];var sourceLengths=[4844,4048,13310,80109,12190,10700,34303,16450,8549,78405,37758,10864,4557,9872,82529,41661,42535,50397,41170,42638,41811,54615,14375,25041,52926,9889,64826,24959,86388,44853,68054,91273,36249,8216,22028,42818,20304,6278,8035,7790,4835,5961,11801,4292,8347,30545,19623,8745,47165,12743,7133,20461,7140,18798,6860,11996,28607,31175,12022,18311,8355,6090,18823,7449,5100,8160,9930,2248,5412,9845,10853,15565,26828,33529,4227,35397,12139,9420,8201,13306,16844,15126,1464,9180,13455,7818,9320,10514,11921,7511,8528,10902,8527,35171,6519,6405,6095,6007,9711,11730,5283,189088,6927,2023,15129,20328,26806,20876,12299,724257,109503,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(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=readFileSync(join(import.meta.dirname,"docs-index.bin"));if(packed.length!==592178||createHash2("sha256").update(packed).digest("hex")!=="78cfd64a72e5508d6bf44e2979dcc6fb3ec03b798497f86620ee824549ad2179")throw new Error("docs data file docs-index.bin beside this module is not the one built with it");return 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}
|
|
117
117
|
${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}
|
|
118
118
|
|
|
119
119
|
${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 candidate=terms[mid];if(candidate===term)return mid;if(candidate<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(h=>`## ${h.heading}
|
|
@@ -143,8 +143,8 @@ ${who}`)}return err2(`Couldn't DM: ${e.message}`)}}},{name:"cotal_anycast",title
|
|
|
143
143
|
${lines.join("\n")}`:`No channels in "${config2.space}" to list${want?` matching ${JSON.stringify(filter)}`:""}${after===void 0?"":` after #${after}`}.`;return ok2(notes.length?`${head}
|
|
144
144
|
${notes.join("\n")}`:head)}},{name:"cotal_channel_mode",title:"Cotal: silence or mute a channel",description:"Set how a single channel interrupts you: your per-channel attention, more specific than cotal_status. quiet = ambient stays buffered and pull-only (read it with cotal_inbox); it never enters another turn, while an @mention still wakes and injects. muted = you stop receiving this channel entirely, including @mentions (DMs still reach you). normal = clear the override; the channel follows your global attention. Runtime + per-instance: resets when your session restarts. An operator can set a lasting default in your agent file. See your current settings with cotal_channels.",schema:{channel:external_exports.string().describe("The channel to set (a concrete channel you can read, e.g. random)."),mode:external_exports.enum(["normal","quiet","muted"]).describe("quiet = receive silently, @mentions still wake; muted = stop receiving it (incl. @mentions); normal = follow global attention.")},async run(agent,_config,{channel,mode}){if(!agent.connected)return ok2(`Not connected to the mesh yet (${config2.servers}).`);try{await agent.setChannelMode(channel,mode);const desc=mode==="quiet"?"delivered but won't wake you; @mentions still wake you":mode==="muted"?"no longer received (incl. @mentions); DMs still reach you":"back to following your global attention";return ok2(`#${channel} is now ${mode} \u2014 ${desc}.`)}catch(e){return err2(`Couldn't set #${channel} to ${mode}: ${e.message}`)}}},{name:"cotal_join",title:"Cotal: join a channel",description:"Join a channel to see its posts. If the channel replays history, you also get its recent posts as catch-up. Join the channel of every task you are part of. You can join only channels your read permission covers. A pattern follows a whole family of channels: review.> covers every channel under review, including ones opened later, but not review itself, and review.* covers one level. Follow a family only if that is your job, because every post in it reaches you. Under a family such as review.>, posts on its durable channels are kept for you while you are offline, from the join on, and its live channels reach you only while you are connected. A pattern with * or the root > is followed live only: posts sent while you are offline are not kept for you. Join a channel by its full name when you must not miss a post.",schema:{channel:external_exports.string().describe("The channel to join (e.g. incident), or a family such as team.>.")},async run(agent,_config,{channel}){const notName=notAChannelName(channel,"Nothing was joined.");if(notName!==void 0)return err2(`Couldn't join: ${notName}`);if(!(isConcreteChannel(channel)?channelInAllow:patternInAllow)(config2.allowSubscribe,channel))return err2(`Can't join #${channel}: it's outside your read ACL (allowSubscribe: ${config2.allowSubscribe.map(c=>`#${c}`).join(", ")}).`);try{const r=await agent.joinChannel(channel);if(!r.joined)return ok2(`Already on #${channel}.`);const info=renderChannelInfo(channel,agent.channelInfo(channel));const caught=r.backfilled>0?`
|
|
145
145
|
Backfilled ${r.backfilled} earlier message${r.backfilled===1?"":"s"} into your inbox (marked "history" \u2014 they pre-date your join; read with cotal_inbox).`:"";const headline=r.durable?isChannelFamily(channel)?`Joined #${channel} (stored copies on: posts on its durable channels are kept for you while you're offline, from now on; its live channels reach you only while you're connected).`:`Joined #${channel} (durable backstop active \u2014 messages sent while you're offline replay on your next turn).`:r.reason?isConcreteChannel(channel)||isChannelFamily(channel)?`Joined #${channel} (LIVE only \u2014 ${r.reason}; messages sent while you're offline won't be replayed).`:`Joined #${channel} (live only: ${r.reason}).`:`Joined #${channel} (live).`;return ok2(`${headline}
|
|
146
|
-
${info}${caught}`)}catch(e){return err2(`Couldn't join #${channel}: ${e.message}`)}}},{name:"cotal_leave",title:"Cotal: leave a channel",description:"Leave a channel when you are done with its task. You stay reachable by DM and anycast.",schema:{channel:external_exports.string().describe("The channel or family to leave.")},async run(agent,_config,{channel}){try{const r=await agent.leaveChannel(channel);return ok2(r.left?`Left #${channel}.`:`You weren't on #${channel}.`)}catch(e){return err2(`Couldn't leave #${channel}: ${e.message}`)}}},{name:"cotal_spawn",title:"Cotal: spawn a new teammate",description:`Start another agent on the mesh to do a job. It runs as its own process: it shows up on the roster, the user can watch it work, and any agent can message it. A subagent that your own harness starts, such as Claude Code's Task tool, runs inside your session, where nobody else can see or reach it. Prefer cotal_spawn. Use a subagent only for a self-contained job nobody else needs to follow, where it keeps the work contained and can be more efficient, depending on the harness. name picks a saved persona, which sets the new agent's role and what it may do. cotal_personas lists them, and cotal_persona saves a new one. Give it a prompt that says what to do. If others could use its work, put it on the task's channel with join and say in the prompt where the brief is. Example: \`{name: "reviewer", join: ["review.login-page"], prompt: "Read the brief on #review.login-page, post your findings there, then despawn yourself."}\` The new agent can read and post wherever its persona allows. An operator's persona that names no channels gets your permissions and no more; one you save with cotal_persona gets only the channels it lists. Give a helper only what its job needs. To limit its channels, write a persona with cotal_persona that lists just the ones it needs, then spawn that persona. Only an operator can let a helper spawn agents or run workflows, and endpoint access also comes from the operator, so ask the user if the job needs them. cotal_orientation shows what you hold. For a single job on a Claude Code, jcode, OpenCode or pi helper, pass once: true with the prompt, and the helper is stopped when it ends that turn; or tell it in the prompt to despawn itself when done, as in the example. A standing teammate keeps running until it despawns itself or you call cotal_despawn. For work with several steps, a wait on a person, or a need to survive restarts, use cotal_run.`,schema:{name:external_exports.string().describe("Which persona to spawn: the persona FILENAME in .cotal/agents (e.g. `review-critic`), without the .md. The new peer joins under the persona's own `name:` (auto-numbered with an underscore, e.g. socrates_2, if that's taken). Fails if no such persona file exists; spawn an existing persona, don't invent a name."),join:external_exports.array(external_exports.string()).optional().describe("Channels the new peer joins at start, on top of what its persona file lists (e.g. ['general']). Concrete names only, each within YOUR read ACL (a spawn hands on only what you may read yourself; anything else is refused before launch). Omitted, a persona that lists no channel starts on none and its cotal_send with no channel is refused."),instance:external_exports.string().refine(value=>{try{assertLifecycleToken(value,"instance");return true}catch{return false}},"instance must be a lifecycle token ([a-z0-9]{26,32})").optional().describe("Optional manager instance id for a multi-manager space. An open managed seat defaults to its launching manager; an unbound open or static caller uses class anycast. User-auth selection remains issuer-bound. A pin that cannot be resolved is refused without falling back to another manager."),role:external_exports.string().optional().describe("Optional role for the new peer (e.g. worker, reviewer); overrides the persona file's role. A role of `manager` requires the persona to carry capabilities: [spawn]: a seat that presents as a manager but cannot spawn is refused at spawn time. Ask an operator to add the grant to the persona file (a persona you defined with cotal_persona cannot declare it itself)."),agent:external_exports.string().optional().describe("Optional harness the new peer runs on: the agent/connector type (claude, jcode, opencode, hermes), NOT the persona to spawn (that's `name`). Resolution order: this explicit agent > the persona's agent: pin > the caller's COTAL_DEFAULT_AGENT > the manager's COTAL_DEFAULT_AGENT > the product default (Claude)."),model:external_exports.string().min(1).optional().describe("Optional model override (e.g. opus, sonnet); it wins over the persona file's model:. The spawn fails if the manager does not record this pin. The result names the recorded model; do not treat a spawn as cross-vendor unless that name matches what you requested. If the pin cannot be read back, the result is partial and the seat still runs."),variant:external_exports.string().optional().describe("Optional model variant override (connector-defined; for OpenCode, a model variant such as high/max/low)."),launchOptions:external_exports.record(external_exports.string(),external_exports.unknown()).optional().describe("Optional connector-specific launch options: an opaque key\u2192value map the chosen connector forwards raw to its own host form (claude CLI flags, OpenCode agent config); a connector with no option surface (Hermes) rejects any, and malformed keys are refused."),cwd:external_exports.string().optional().describe("Optional working directory to root the new peer at (e.g. a different repo). A relative path resolves against the manager's workspace; omitted \u2192 it shares the manager's workspace. A directory that does not exist on the serving manager's host is refused before launch, with the host named; in a multi-manager space pin the manager with instance."),prompt:external_exports.string().min(1).optional().describe("Optional kickoff message auto-submitted as the new peer's first turn. Pass it when the peer should begin work immediately; omitted means no first model turn is submitted."),events:external_exports.boolean().optional().describe("Event planes are on by default for connectors that publish one. Pass false to opt out; true only restates the default."),once:external_exports.boolean().optional().describe("Run `prompt` as the new peer's one task, then stop the peer. The task reaches the peer as a relayed turn rather than a kickoff, and the peer is stopped when it ends that turn or when the deadline passes. Needs `prompt`. A Claude Code peer takes the task only when its startup shows channels on; otherwise the spawn fails at startup and says why."),deadline:external_exports.string().optional().describe("With once: how long the task may run, as a duration such as 30m, 2h or 1d, counted from when the manager accepts the spawn. Omitted, it is 1h. Pass -1 for no deadline: the peer then keeps its name and its seat slot until it ends its turn or is despawned."),runtime:external_exports.string().trim().min(1).optional().describe("Optional terminal runtime for this one seat (pty, or an installed extension such as tmux). Omitted, the serving manager uses its own. An unknown or unreachable runtime, and auto, refuse the launch and start nothing.")},async run(agent,_config,{name,instance,role,agent:agentType,model,variant,launchOptions,cwd,prompt,events,once,deadline,runtime,join:join2}){let onceArg;if(deadline!==void 0&&once!==true)return err2("`deadline` applies only to a once spawn; pass once: true with it.");if(once===true){if(deadline===void 0)onceArg={};else if(deadline.trim()==="-1")onceArg={deadlineMs:-1};else{let ms;try{ms=parseDuration(deadline)}catch(e){return err2(`deadline: ${e.message}, or -1 for no deadline`)}if(!Number.isSafeInteger(ms)||ms<1)return err2(`deadline: "${deadline}" is not a positive duration; pass one such as 30m, or -1 for no deadline`);onceArg={deadlineMs:ms}}}try{const reply=await agent.spawn(name,role,{agent:agentType,model,variant,launchOptions,cwd,prompt,events,runtime,instance,join:join2,...onceArg!==void 0?{once:onceArg}:{}});const pending=reply.code==="uncertain";const submission=reply.data;if(!reply.ok&&submission?.submissionUnknown&&submission.goalId){const goalId=submission.goalId;const next=`cotal_invoke(endpoint="manager", command="goal-result", args={"goalId":${JSON.stringify(goalId)}})`;const message=`Spawn submission for ${name} has an unknown outcome for goal "${goalId}". Acceptance has not been confirmed; the seat may appear later. Do NOT retry: another submission could create a second lifecycle. ${reply.error??"The submission wait ended."} Next: ${next} as this same caller, or inspect 'ps'/'inspect'. A missing result does not prove the submission failed.`;return{text:message,structured:{status:"unknown",name,goalId,next,message}}}if(!reply.ok&&!pending)return err2(`Couldn't spawn ${name}: ${renderLifecycleBlocked(reply.error??"manager refused",reply)}`);const d=reply.data;const actual=d?.name??name;const mode=d?.mode;const who=peerLabel({name:actual,role});const lead=actual!==name?`"${name}" was taken \u2014 spawning ${who} instead`:`Spawning ${who}`;const pin=d?.model?` recorded model ${JSON.stringify(d.model)}`:"";if(d?.pinAudit){const{requested,error:error51,unreported}=d.pinAudit;const id2=d.id??d.actor;const manager=d.executor?.lifecycleUid??reply.instanceId;const next=`cotal ps --on ${manager}`;const state=pending?"it has not joined the mesh within its readiness window and may still be booting":"it joined the mesh";const audit=unreported?"was not reported by this manager":"could not be audited";const message=`${lead} (id ${id2}, manager ${manager}${mode?`, runtime ${mode}`:""}): ${state}, but its model pin ${JSON.stringify(requested)} ${audit} (${error51}). Do not spawn it again: a retry starts a second agent. Next: \`${next}\` shows the seat and the model its manager recorded.`;return{text:message,structured:{status:"partial",name:actual,id:id2,manager,...mode?{runtime:mode}:{},joined:!pending,model:{requested,audited:false,reported:!unreported,error:error51},next,message}}}if(pending)return ok2(`${lead}${pin} (id ${d?.actor}, manager ${d?.executor?.lifecycleUid}), but it did not join the mesh within its readiness window. It may still be booting, so do not spawn it again: a retry starts a second agent. Watch cotal_roster for ${actual}, and cotal_despawn it if it never joins.`);const task=d?.once?` Its task is goal ${JSON.stringify(d.once.goalId)}, ${d.once.deadlineAt!==void 0?`with a deadline of ${new Date(d.once.deadlineAt).toISOString()}`:"with no deadline"}; it is stopped when the task ends. Read the outcome with cotal_invoke(endpoint="manager", command="goal-result", args={"goalId":${JSON.stringify(d.once.goalId)}}).`:"";return ok2(spawnResult({requested:name,started:who,renamed:actual!==name,mode,model:d?.model,join:join2,waitingFor:d?.waitingFor,once:d?.once!==void 0})+task)}catch(e){return controlFailure(`Couldn't spawn ${name}`,e)}}},{name:"cotal_feedback",title:"Cotal: send beta feedback",description:"Send feedback about Cotal to its developers. With a configured feedback key it goes to the keyed beta intake; without one it goes to the public cotal.ai intake, which requires a contact email.",schema:{origin:external_exports.enum(["human","agent"]).describe(`"human" when relaying the user's feedback, "agent" when reporting an issue you hit yourself.`),type:external_exports.enum(["bug","idea","friction","praise","other"]).describe("What kind of feedback this is."),summary:external_exports.string().max(300).describe("Required one-line summary, max 300 characters."),details:external_exports.string().max(1e4).optional().describe("Longer free-form details. Do not include secrets."),severity:external_exports.enum(["low","medium","high"]).optional().describe("How badly this hurts (bugs/friction)."),area:external_exports.string().max(120).optional().describe("The part of Cotal this concerns (e.g. presence, channels, CLI)."),repro:external_exports.string().max(1e4).optional().describe("Steps to reproduce."),expected:external_exports.string().max(5e3).optional().describe("What you expected to happen."),actual:external_exports.string().max(5e3).optional().describe("What actually happened."),diagnostics:external_exports.string().max(1e4).optional().describe("Relevant diagnostics as text (logs, errors). Never include secrets."),email:external_exports.string().optional().describe("Contact email, required on the keyless public path when none is configured in the environment.")},async run(_agent,_config,args){const{email:email3,...payload}=args;const contact=config2.feedbackKey?void 0:resolveFeedbackEmail(email3,env);return submitFeedback({...payload,source},{key:config2.feedbackKey,url:config2.feedbackUrl,email:contact})}},{name:"cotal_despawn",title:"Cotal: stop a teammate",description:"Stop a helper when its job is done, or stop yourself by leaving out name. The manager that started you then ends your process. This works only for an agent a manager started; a session someone connected by hand is refused. Graceful by default; pass graceful: false only for a hung agent.",schema:{name:external_exports.string().optional().describe("Name of the peer to stop. Omit to stop yourself (self-despawn)."),instance:external_exports.string().refine(value=>{try{assertLifecycleToken(value,"instance");return true}catch{return false}},"instance must be a lifecycle token ([a-z0-9]{26,32})").optional().describe("Optional manager instance id for the named peer. Requires `name`. Omitted keeps this session's existing manager selection. A managed user-auth seat must use its own manager. An unresolved pin is refused without fallback."),graceful:external_exports.boolean().optional().describe("Default true: let the session exit cleanly. false = hard kill.")},async run(agent,_config,{name,instance,graceful}){try{const reply=await agent.despawn(name,{graceful,instance});if(!reply.ok){return err2(`Couldn't despawn ${name??"self"}: ${reply.error??"manager refused"}`)}const who=name??"self";return ok2(`Stopping ${who}${graceful===false?" (hard)":""} \u2014 it will leave the roster shortly.`)}catch(e){return controlFailure(`Couldn't despawn ${name??"self"}`,e)}}},{name:"cotal_yield",title:"Cotal: yield a run turn",description:'Report the outcome of a workflow turn assigned to you. Use this only when your context contains a pending run turn; it does not start a workflow or resolve a checkpoint/ask.\n\nUsually finish your session turn normally: that yields `done` automatically. If you cannot progress, call `{"status":"blocked","note":"<what prevents progress>"}`. To hand the assigned turn to another agent, call `{"status":"handoff","to":"<agent-name>","note":"<handoff context>"}`.\n\nWhen you hold several assigned turns, pass `turn` with the exact goal id from the relevant run-turn context block. Without `turn`, the oldest turn already shown to your session is selected. A turn that has not been shown cannot be yielded, and neither can one the run already settled, such as a turn whose deadline elapsed: that refusal names the turn and its deadline. A successful reply confirms the turn was yielded, not that the whole workflow completed; the run\'s coordinator can inspect progress with `cotal_run` status.',schema:{status:external_exports.enum(["done","blocked","handoff"]).describe("done = finished (usually implicit: just end your turn instead); blocked = can't proceed; handoff = another agent should take it."),to:external_exports.string().optional().describe("Required for handoff: the agent name the assigned turn should pass to."),note:external_exports.string().max(4096).optional().describe("Short free-text for the run: what blocked you, or what the next agent should know."),turn:external_exports.string().optional().describe("The turn's goal id, from the \u{1F3AF} block. Omit when you hold only one.")},async run(agent,_config,{status:status2,to,note,turn}){try{const reply=await agent.yieldTurn(status2,{to,note,turn});if(!reply.ok)return err2(`Couldn't yield: ${reply.error??"manager refused"}`);return ok2(`Turn yielded (${status2}${to?` \u2192 ${to}`:""}) \u2014 the run continues.`)}catch(e){return err2(`Couldn't yield: ${e.message}`)}}},{name:"cotal_run",title:"Cotal: run a workflow program",description:'Use for coordination with several steps, waits on a person, or work that must survive restarts. For one job done by one helper, use cotal_spawn. Use Cotal Lang to program multi-step coordination between agents: sequence work, run tasks in parallel, branch on results, wait for events, and request human decisions. Agents own their reasoning and conversations; the workflow specifies when they act and which outcomes determine the next step.\n\nBefore writing a program, read cotal_docs pages `workflows` and `lang-card`. Hosted execution requires a running execution-capable manager, the `run` capability, and issued caller authority. A managed agent on a user-auth mesh uses its own bearer command and selected participant manager; both its current grant and its direct parent\'s current grant must allow `run`. Open meshes, unsupported local user-mode hosts and execution-free control managers refuse hosted runs. `@cotal-ai/lang` provides validation and simulation separately; those are not verbs of this tool.\n\nSTART: pass `verb: "start"` and the program text in `source`. Example: `{"verb":"start","source":"await sleep(\\"1s\\", { name: \\"first-run\\" });"}`. Optional `file` labels diagnostics only; it reads nothing from disk. The manager validates before recording the run and returns a runId. Acceptance is not completion.\n\nINSPECT: use `verb: "status"` with that `runId` for state and step journal, or `verb: "ps"` to list runs. Both are read-only. Report completion only after observing state `completed`; surface failures or unresolved steps.\n\nANSWER: first inspect status, then pass `verb: "answer"`, `runId`, the exact open `stepKey`, and, when requested, `value` matching the answer shape. An ask requires its requested record; a checkpoint can resolve without a value. `artifact` may name the evidence reviewed. Answer only with authority to make that decision; never invent an approval.\n\nRESUME: pass `verb: "resume"` and `runId` to continue a run from its recorded source. A held run appears as `released` in status. Do not start a duplicate run to continue it or resume one the manager is already driving.\n\nRuns continue independently of your session and can recover after a manager restart. Their channel effects are bounded by the starting credential\'s issued channel scope. To report that your assigned agent turn is blocked or handed off, use `cotal_yield` instead. Pass `instance` for the exact manager when an unbound user-auth caller has several managers; a failed pin does not fall back.',schema:{verb:external_exports.enum(["start","status","ps","answer","resume"]).describe("start = validate and drive a new program; status = one run's record + journal; ps = list runs; answer = resolve an open checkpoint/ask; resume = take a released or held run over."),source:external_exports.string().min(1).optional().describe("start only: the cotal-lang program source, inline. Required for start."),file:external_exports.string().min(1).optional().describe("start only: a file name to attribute the source to in error messages. Diagnostic only; nothing is read from disk."),timeout:external_exports.string().min(1).optional().describe("start/resume: the default checkpoint timeout for the drive, as a duration (e.g. `1h`, `30m`). Default 1h."),runId:external_exports.string().min(1).optional().describe("Required for status, answer and resume: the run id (`run-<32 hex>`) returned by start or ps."),stepKey:external_exports.string().min(1).optional().describe("Required for answer: copy the exact open step key from status, e.g. `/checkpoint:approve#0`."),value:external_exports.unknown().optional().describe("answer only: supply the value requested by the open checkpoint or ask and match its answer shape. A checkpoint may resolve without a value; an ask must receive its requested record. Use null only when that is the intended answer."),artifact:external_exports.string().min(1).optional().describe("answer only: a reference to what you reviewed before answering, recorded beside the answer."),endpoint:external_exports.string().min(1).optional().describe("status/ps/answer: the endpoint the run record lives under. Omit for runs the manager hosts."),page:external_exports.strictObject({limit:external_exports.number().int().min(1).max(16).optional(),cursor:external_exports.string().min(1).max(3072).regex(/^[A-Za-z0-9_-]+$/).optional()}).optional().describe("ps only: one bounded diagnostic JSON page, default 8 rows. Pin the manager with instance unless this session is already bound. Continuation is not snapshot, absence or ownership proof. A manager from release 0.88.0 or earlier refuses `page`."),instance:managerInstanceArg},async run(agent,config3,a){const need=(field,verb)=>a[field]===void 0?err2(`cotal_run ${verb}: \`${String(field)}\` is required`):void 0;try{if(a.page!==void 0&&a.verb!=="ps")return err2("cotal_run: page is supported only for ps");if(a.page!==void 0&&a.instance===void 0&&config3.managerInstanceId===void 0)return err2("cotal_run ps: diagnostic pages require an explicit instance or a bound manager");if(a.verb==="start"){const missing2=need("source","start");if(missing2)return missing2;const reply2=await agent.run("start",{source:a.source,file:a.file,timeout:a.timeout},a.instance);if(!reply2.ok)return err2(renderRunRefusal("start",reply2));const{runId}=reply2.data;return ok2(`Started run ${runId} on the manager. It runs there until it completes or is held; cotal_run(verb="status", runId="${runId}"${a.instance?`, instance="${a.instance}"`:""}) follows its steps, and an open checkpoint is answered with verb="answer"${a.instance?` on instance="${a.instance}"`:""}.`)}if(a.verb==="resume"){const missing2=need("runId","resume");if(missing2)return missing2;const reply2=await agent.run("resume",{runId:a.runId,timeout:a.timeout},a.instance);if(!reply2.ok)return err2(renderRunRefusal("resume",reply2));return ok2(`Resumed run ${a.runId} on the manager from its recorded program.${a.instance?` Use instance="${a.instance}" for subsequent status and answer calls to this manager.`:""}`)}if(a.verb==="ps"){const reply2=await agent.run("ps",{endpoint:a.endpoint,...a.page!==void 0?{page:a.page}:{}},a.instance);if(!reply2.ok)return err2(renderRunRefusal("ps",reply2));if(a.page!==void 0){const page=reply2.data;if(page===null||typeof page!=="object"||Array.isArray(page)||page.semantics!=="diagnostic")return err2("the manager did not return a diagnostic inventory page");const text2=JSON.stringify(page);if(a.page.cursor!==void 0&&page.nextCursor===a.page.cursor)return err2(`Diagnostic inventory made no progress; retain this incomplete observation, do not retry in a loop: ${text2}`);return ok2(text2)}const rows=reply2.data;if(rows.length===0)return ok2("No workflow runs are recorded in this space.");return ok2(rows.map(r=>`${r.runId} ${r.endpoint} ${r.state??"(no status)"} holder=${r.holder??"-"} journal=${r.journalHigh??"-"}${r.forkedFrom?` forked-from=${r.forkedFrom.run}@${r.forkedFrom.step}`:""}`).join("\n"))}if(a.verb==="status"){const missing2=need("runId","status");if(missing2)return missing2;const reply2=await agent.run("status",{runId:a.runId,endpoint:a.endpoint},a.instance);if(!reply2.ok)return err2(renderRunRefusal("status",reply2));const v=reply2.data;const head=`run ${v.runId} on ${v.endpoint}: ${v.status?`${v.status.state}, holder ${v.status.holder}, epoch ${v.status.epoch}`:"(no status)"}`;const lines=v.journal.map(r=>r.kind==="activation"?`#${r.n} activation holder=${r.holder} epoch=${r.epoch} replayedTo=${r.replayedTo}`:`#${r.n} step ${r.step} ${r.outcome}${r.asks!==void 0?`
|
|
147
|
-
asks: ${r.asks}${r.addressee!==void 0?` (escalates to ${r.addressee})`:""}`:""}`);return ok2([head,...lines.length?lines:["(no journal records: never started, or retired)"]].join("\n"))}const missing=need("runId","answer")??need("stepKey","answer");if(missing)return missing;const reply=await agent.run("answer",{runId:a.runId,stepKey:a.stepKey,value:a.value,artifact:a.artifact,endpoint:a.endpoint},a.instance);if(!reply.ok)return err2(renderRunRefusal("answer",reply));return ok2(`Answered ${a.stepKey} on run ${a.runId} as ${config3.name}: ${JSON.stringify(reply.data)}`)}catch(e){return runFailure(`cotal_run ${a.verb}`,e)}}},{name:"cotal_persona",title:"Cotal: define a persona",description:'Save a persona that cotal_spawn can start. Most jobs need a persona written for them. Reuse one from cotal_personas only when it really fits, such as a general reviewer. Every persona you save stays in the user\'s workspace after the helper stops. Name it after what it does, such as review-login-page. Write the prompt about the job: what to do, where the brief is, how to report, and when to stop. Point to sources for facts rather than stating them. Set role when others should reach it through a role. List its channels and give it only what the job needs: subscribe for where it starts, allowSubscribe for what it may read, and allowPublish for what it may post to. If you list subscribe alone, it may read just those channels and can\'t post anywhere. Leave all three out and it can read and post nowhere, so list the channels it needs. A persona you
|
|
146
|
+
${info}${caught}`)}catch(e){return err2(`Couldn't join #${channel}: ${e.message}`)}}},{name:"cotal_leave",title:"Cotal: leave a channel",description:"Leave a channel when you are done with its task. You stay reachable by DM and anycast.",schema:{channel:external_exports.string().describe("The channel or family to leave.")},async run(agent,_config,{channel}){try{const r=await agent.leaveChannel(channel);return ok2(r.left?`Left #${channel}.`:`You weren't on #${channel}.`)}catch(e){return err2(`Couldn't leave #${channel}: ${e.message}`)}}},{name:"cotal_spawn",title:"Cotal: spawn a new teammate",description:`Start another agent on the mesh to do a job. It runs as its own process: it shows up on the roster, the user can watch it work, and any agent can message it. A subagent that your own harness starts, such as Claude Code's Task tool, runs inside your session, where nobody else can see or reach it. Prefer cotal_spawn. Use a subagent only for a self-contained job nobody else needs to follow, where it keeps the work contained and can be more efficient, depending on the harness. Usually you write the new agent's persona here: pass persona, whose prompt says who it is, and a name. The top-level prompt is the first message it works on, so say there what to do. If others could use its work, put it on the task's channel with join and say in the prompt where the brief is. To start a saved persona instead, pass its name and no persona; cotal_personas lists them. Pass persona.save: true, or use cotal_persona, only for a persona worth reusing. Example: \`{name: "reviewer", join: ["review.login-page"], persona: {prompt: "You review the login page change and report each finding with its file and line.", allowSubscribe: ["review.login-page"], allowPublish: ["review.login-page"]}, prompt: "Read the brief on #review.login-page, post your findings there, then despawn yourself."}\` The new agent can read and post wherever its persona allows. A persona you pass here, or an operator's persona, that names no channels gets your read and post grants and no more; one you save with cotal_persona gets only the channels it lists. Give a helper only what its job needs, so list just the channels it needs. You can give it only channels and capabilities you hold. On a mesh that checks grants, a spawn that asks for more is refused, and the refusal names each part you do not hold. It can spawn agents or run workflows only if its persona lists spawn or run. Endpoint access comes from the operator, so ask the user if the job needs it. cotal_orientation shows what you hold. For a single job on a Claude Code, jcode, OpenCode or pi helper, pass once: true with the prompt, and the helper is stopped when it ends that turn; or tell it in the prompt to despawn itself when done, as in the example. A standing teammate keeps running until it despawns itself or you call cotal_despawn. For work with several steps, a wait on a person, or a need to survive restarts, use cotal_run.`,schema:{name:external_exports.string().describe("With `persona`, the new helper's name (auto-numbered with an underscore, e.g. reviewer_2, if that's taken). Without it, which catalog persona to spawn: the persona FILENAME in .cotal/agents (e.g. `review-critic`), without the .md; the peer joins under the persona's own `name:`, and an unknown name fails."),persona:external_exports.object({prompt:external_exports.string().min(1).describe("Who the helper is: its persona body, as a persona file's body would be. Its first message is the top-level `prompt`."),role:external_exports.string().min(1).optional().describe("The helper's role (e.g. reviewer). The top-level `role` wins."),model:external_exports.string().min(1).optional().describe("The helper's model. The top-level `model` wins. The spawn fails if the manager does not record this pin."),variant:external_exports.string().min(1).optional().describe("The helper's model variant. The top-level `variant` wins."),description:external_exports.string().min(1).optional().describe("A one-line description, shown in the catalog when the persona is saved."),subscribe:external_exports.array(external_exports.string()).optional().describe("Channels the helper reads at start. Omit every channel field to take your own read and post grants; pass [] for none."),allowSubscribe:external_exports.array(external_exports.string()).optional().describe("Channels the helper may read. Each must be one you may read."),allowPublish:external_exports.array(external_exports.string()).optional().describe("Channels the helper may post to. Each must be one you may post to."),capabilities:external_exports.array(external_exports.string()).optional().describe("Capabilities to hand on, such as spawn or run. Each must be one you hold."),save:external_exports.boolean().optional().describe("Also save this persona to the catalog under `name`, for a broad persona worth reusing. A name already in the catalog is refused before anything starts.")}).strict().optional().describe("Define the helper on this spawn instead of from a catalog file: `prompt` (who it is), with optional `role`, `model`, `variant`, `description`, `subscribe`, `allowSubscribe`, `allowPublish`, `capabilities` and `save`. Not saved unless `save` is true."),join:external_exports.array(external_exports.string()).optional().describe("Channels the new peer joins at start, on top of what its persona file lists (e.g. ['general']). Concrete names only, each within YOUR read ACL (a spawn hands on only what you may read yourself; anything else is refused before launch). Omitted, a persona that lists no channel starts on none and its cotal_send with no channel is refused."),instance:external_exports.string().refine(value=>{try{assertLifecycleToken(value,"instance");return true}catch{return false}},"instance must be a lifecycle token ([a-z0-9]{26,32})").optional().describe("Optional manager instance id for a multi-manager space. An open managed seat defaults to its launching manager; an unbound open or static caller uses class anycast. User-auth selection remains issuer-bound. A pin that cannot be resolved is refused without falling back to another manager."),role:external_exports.string().optional().describe("Optional role for the new peer (e.g. worker, reviewer); overrides the persona's role. A role of `manager` requires the helper to hold `spawn`, from `persona.capabilities` or its catalog file: a seat that presents as a manager but cannot spawn is refused at spawn time. You can hand on `spawn` only if you hold it."),agent:external_exports.string().optional().describe("Optional harness the new peer runs on: the agent/connector type (claude, jcode, opencode, hermes), NOT the persona to spawn (that's `name`). Resolution order: this explicit agent > the persona's agent: pin > the caller's COTAL_DEFAULT_AGENT > the manager's COTAL_DEFAULT_AGENT > the product default (Claude)."),model:external_exports.string().min(1).optional().describe("Optional model override (e.g. opus, sonnet); it wins over the persona file's model:. The spawn fails if the manager does not record this pin. The result names the recorded model; do not treat a spawn as cross-vendor unless that name matches what you requested. If the pin cannot be read back, the result is partial and the seat still runs."),variant:external_exports.string().optional().describe("Optional model variant override (connector-defined; for OpenCode, a model variant such as high/max/low)."),launchOptions:external_exports.record(external_exports.string(),external_exports.unknown()).optional().describe("Optional connector-specific launch options: an opaque key\u2192value map the chosen connector forwards raw to its own host form (claude CLI flags, OpenCode agent config); a connector with no option surface (Hermes) rejects any, and malformed keys are refused."),cwd:external_exports.string().optional().describe("Optional working directory to root the new peer at (e.g. a different repo). A relative path resolves against the manager's workspace; omitted \u2192 it shares the manager's workspace. A directory that does not exist on the serving manager's host is refused before launch, with the host named; in a multi-manager space pin the manager with instance."),prompt:external_exports.string().min(1).optional().describe("Optional kickoff message auto-submitted as the new peer's first turn. Pass it when the peer should begin work immediately; omitted means no first model turn is submitted."),events:external_exports.boolean().optional().describe("Event planes are on by default for connectors that publish one. Pass false to opt out; true only restates the default."),once:external_exports.boolean().optional().describe("Run `prompt` as the new peer's one task, then stop the peer. The task reaches the peer as a relayed turn rather than a kickoff, and the peer is stopped when it ends that turn or when the deadline passes. Needs `prompt`. A Claude Code peer takes the task only when its startup shows channels on; otherwise the spawn fails at startup and says why."),deadline:external_exports.string().optional().describe("With once: how long the task may run, as a duration such as 30m, 2h or 1d, counted from when the manager accepts the spawn. Omitted, it is 1h. Pass -1 for no deadline: the peer then keeps its name and its seat slot until it ends its turn or is despawned."),runtime:external_exports.string().trim().min(1).optional().describe("Optional terminal runtime for this one seat (pty, or an installed extension such as tmux). Omitted, the serving manager uses its own. An unknown or unreachable runtime, and auto, refuse the launch and start nothing.")},async run(agent,_config,{name,persona,instance,role,agent:agentType,model,variant,launchOptions,cwd,prompt,events,once,deadline,runtime,join:join2}){let onceArg;if(deadline!==void 0&&once!==true)return err2("`deadline` applies only to a once spawn; pass once: true with it.");if(once===true){if(deadline===void 0)onceArg={};else if(deadline.trim()==="-1")onceArg={deadlineMs:-1};else{let ms;try{ms=parseDuration(deadline)}catch(e){return err2(`deadline: ${e.message}, or -1 for no deadline`)}if(!Number.isSafeInteger(ms)||ms<1)return err2(`deadline: "${deadline}" is not a positive duration; pass one such as 30m, or -1 for no deadline`);onceArg={deadlineMs:ms}}}try{const reply=await agent.spawn(name,role,{agent:agentType,model,variant,launchOptions,cwd,prompt,events,runtime,instance,join:join2,persona,...onceArg!==void 0?{once:onceArg}:{}});const pending=reply.code==="uncertain";const submission=reply.data;if(!reply.ok&&submission?.submissionUnknown&&submission.goalId){const goalId=submission.goalId;const next=`cotal_invoke(endpoint="manager", command="goal-result", args={"goalId":${JSON.stringify(goalId)}})`;const message=`Spawn submission for ${name} has an unknown outcome for goal "${goalId}". Acceptance has not been confirmed; the seat may appear later. Do NOT retry: another submission could create a second lifecycle. ${reply.error??"The submission wait ended."} Next: ${next} as this same caller, or inspect 'ps'/'inspect'. A missing result does not prove the submission failed.`;return{text:message,structured:{status:"unknown",name,goalId,next,message}}}if(!reply.ok&&!pending)return err2(`Couldn't spawn ${name}: ${renderLifecycleBlocked(reply.error??"manager refused",reply)}`);const d=reply.data;const actual=d?.name??name;const mode=d?.mode;const who=peerLabel({name:actual,role});const lead=actual!==name?`"${name}" was taken \u2014 spawning ${who} instead`:`Spawning ${who}`;const pin=d?.model?` recorded model ${JSON.stringify(d.model)}`:"";if(d?.pinAudit){const{requested,error:error51,unreported}=d.pinAudit;const id2=d.id??d.actor;const manager=d.executor?.lifecycleUid??reply.instanceId;const next=`cotal ps --on ${manager}`;const state=pending?"it has not joined the mesh within its readiness window and may still be booting":"it joined the mesh";const audit=unreported?"was not reported by this manager":"could not be audited";const message=`${lead} (id ${id2}, manager ${manager}${mode?`, runtime ${mode}`:""}): ${state}, but its model pin ${JSON.stringify(requested)} ${audit} (${error51}). Do not spawn it again: a retry starts a second agent. Next: \`${next}\` shows the seat and the model its manager recorded.`;return{text:message,structured:{status:"partial",name:actual,id:id2,manager,...mode?{runtime:mode}:{},joined:!pending,model:{requested,audited:false,reported:!unreported,error:error51},next,message}}}if(pending)return ok2(`${lead}${pin} (id ${d?.actor}, manager ${d?.executor?.lifecycleUid}), but it did not join the mesh within its readiness window. It may still be booting, so do not spawn it again: a retry starts a second agent. Watch cotal_roster for ${actual}, and cotal_despawn it if it never joins.`);const task=d?.once?` Its task is goal ${JSON.stringify(d.once.goalId)}, ${d.once.deadlineAt!==void 0?`with a deadline of ${new Date(d.once.deadlineAt).toISOString()}`:"with no deadline"}; it is stopped when the task ends. Read the outcome with cotal_invoke(endpoint="manager", command="goal-result", args={"goalId":${JSON.stringify(d.once.goalId)}}).`:"";return ok2(spawnResult({requested:name,started:who,renamed:actual!==name,mode,model:d?.model,join:join2,waitingFor:d?.waitingFor,once:d?.once!==void 0})+task)}catch(e){return controlFailure(`Couldn't spawn ${name}`,e)}}},{name:"cotal_feedback",title:"Cotal: send beta feedback",description:"Send feedback about Cotal to its developers. With a configured feedback key it goes to the keyed beta intake; without one it goes to the public cotal.ai intake, which requires a contact email.",schema:{origin:external_exports.enum(["human","agent"]).describe(`"human" when relaying the user's feedback, "agent" when reporting an issue you hit yourself.`),type:external_exports.enum(["bug","idea","friction","praise","other"]).describe("What kind of feedback this is."),summary:external_exports.string().max(300).describe("Required one-line summary, max 300 characters."),details:external_exports.string().max(1e4).optional().describe("Longer free-form details. Do not include secrets."),severity:external_exports.enum(["low","medium","high"]).optional().describe("How badly this hurts (bugs/friction)."),area:external_exports.string().max(120).optional().describe("The part of Cotal this concerns (e.g. presence, channels, CLI)."),repro:external_exports.string().max(1e4).optional().describe("Steps to reproduce."),expected:external_exports.string().max(5e3).optional().describe("What you expected to happen."),actual:external_exports.string().max(5e3).optional().describe("What actually happened."),diagnostics:external_exports.string().max(1e4).optional().describe("Relevant diagnostics as text (logs, errors). Never include secrets."),email:external_exports.string().optional().describe("Contact email, required on the keyless public path when none is configured in the environment.")},async run(_agent,_config,args){const{email:email3,...payload}=args;const contact=config2.feedbackKey?void 0:resolveFeedbackEmail(email3,env);return submitFeedback({...payload,source},{key:config2.feedbackKey,url:config2.feedbackUrl,email:contact})}},{name:"cotal_despawn",title:"Cotal: stop a teammate",description:"Stop a helper when its job is done, or stop yourself by leaving out name. The manager that started you then ends your process. This works only for an agent a manager started; a session someone connected by hand is refused. Graceful by default; pass graceful: false only for a hung agent.",schema:{name:external_exports.string().optional().describe("Name of the peer to stop. Omit to stop yourself (self-despawn)."),instance:external_exports.string().refine(value=>{try{assertLifecycleToken(value,"instance");return true}catch{return false}},"instance must be a lifecycle token ([a-z0-9]{26,32})").optional().describe("Optional manager instance id for the named peer. Requires `name`. Omitted keeps this session's existing manager selection. A managed user-auth seat must use its own manager. An unresolved pin is refused without fallback."),graceful:external_exports.boolean().optional().describe("Default true: let the session exit cleanly. false = hard kill.")},async run(agent,_config,{name,instance,graceful}){try{const reply=await agent.despawn(name,{graceful,instance});if(!reply.ok){return err2(`Couldn't despawn ${name??"self"}: ${reply.error??"manager refused"}`)}const who=name??"self";return ok2(`Stopping ${who}${graceful===false?" (hard)":""} \u2014 it will leave the roster shortly.`)}catch(e){return controlFailure(`Couldn't despawn ${name??"self"}`,e)}}},{name:"cotal_yield",title:"Cotal: yield a run turn",description:'Report the outcome of a workflow turn assigned to you. Use this only when your context contains a pending run turn; it does not start a workflow or resolve a checkpoint/ask.\n\nUsually finish your session turn normally: that yields `done` automatically. If you cannot progress, call `{"status":"blocked","note":"<what prevents progress>"}`. To hand the assigned turn to another agent, call `{"status":"handoff","to":"<agent-name>","note":"<handoff context>"}`.\n\nWhen you hold several assigned turns, pass `turn` with the exact goal id from the relevant run-turn context block. Without `turn`, the oldest turn already shown to your session is selected. A turn that has not been shown cannot be yielded, and neither can one the run already settled, such as a turn whose deadline elapsed: that refusal names the turn and its deadline. A successful reply confirms the turn was yielded, not that the whole workflow completed; the run\'s coordinator can inspect progress with `cotal_run` status.',schema:{status:external_exports.enum(["done","blocked","handoff"]).describe("done = finished (usually implicit: just end your turn instead); blocked = can't proceed; handoff = another agent should take it."),to:external_exports.string().optional().describe("Required for handoff: the agent name the assigned turn should pass to."),note:external_exports.string().max(4096).optional().describe("Short free-text for the run: what blocked you, or what the next agent should know."),turn:external_exports.string().optional().describe("The turn's goal id, from the \u{1F3AF} block. Omit when you hold only one.")},async run(agent,_config,{status:status2,to,note,turn}){try{const reply=await agent.yieldTurn(status2,{to,note,turn});if(!reply.ok)return err2(`Couldn't yield: ${reply.error??"manager refused"}`);return ok2(`Turn yielded (${status2}${to?` \u2192 ${to}`:""}) \u2014 the run continues.`)}catch(e){return err2(`Couldn't yield: ${e.message}`)}}},{name:"cotal_run",title:"Cotal: run a workflow program",description:'Use for coordination with several steps, waits on a person, or work that must survive restarts. For one job done by one helper, use cotal_spawn. Use Cotal Lang to program multi-step coordination between agents: sequence work, run tasks in parallel, branch on results, wait for events, and request human decisions. Agents own their reasoning and conversations; the workflow specifies when they act and which outcomes determine the next step.\n\nBefore writing a program, read cotal_docs pages `workflows` and `lang-card`. Hosted execution requires a running execution-capable manager, the `run` capability, and issued caller authority. A managed agent on a user-auth mesh uses its own bearer command and selected participant manager; both its current grant and its direct parent\'s current grant must allow `run`. Open meshes, unsupported local user-mode hosts and execution-free control managers refuse hosted runs. `@cotal-ai/lang` provides validation and simulation separately; those are not verbs of this tool.\n\nSTART: pass `verb: "start"` and the program text in `source`. Example: `{"verb":"start","source":"await sleep(\\"1s\\", { name: \\"first-run\\" });"}`. Optional `file` labels diagnostics only; it reads nothing from disk. The manager validates before recording the run and returns a runId. Acceptance is not completion.\n\nINSPECT: use `verb: "status"` with that `runId` for state and step journal, or `verb: "ps"` to list runs. Both are read-only. Report completion only after observing state `completed`; surface failures or unresolved steps.\n\nANSWER: first inspect status, then pass `verb: "answer"`, `runId`, the exact open `stepKey`, and, when requested, `value` matching the answer shape. An ask requires its requested record; a checkpoint can resolve without a value. `artifact` may name the evidence reviewed. Answer only with authority to make that decision; never invent an approval.\n\nRESUME: pass `verb: "resume"` and `runId` to continue a run from its recorded source. A held run appears as `released` in status. Do not start a duplicate run to continue it or resume one the manager is already driving.\n\nRuns continue independently of your session and can recover after a manager restart. Their channel effects are bounded by the starting credential\'s issued channel scope. To report that your assigned agent turn is blocked or handed off, use `cotal_yield` instead. Pass `instance` for the exact manager when an unbound user-auth caller has several managers; a failed pin does not fall back.',schema:{verb:external_exports.enum(["start","status","ps","answer","resume"]).describe("start = validate and drive a new program; status = one run's record + journal; ps = list runs; answer = resolve an open checkpoint/ask; resume = take a released or held run over."),source:external_exports.string().min(1).optional().describe("start only: the cotal-lang program source, inline. Required for start."),file:external_exports.string().min(1).optional().describe("start only: a file name to attribute the source to in error messages. Diagnostic only; nothing is read from disk."),timeout:external_exports.string().min(1).optional().describe("start/resume: the default checkpoint timeout for the drive, as a duration (e.g. `1h`, `30m`). Default 1h."),runId:external_exports.string().min(1).optional().describe("Required for status, answer and resume: the run id (`run-<32 hex>`) returned by start or ps."),stepKey:external_exports.string().min(1).optional().describe("Required for answer: copy the exact open step key from status, e.g. `/checkpoint:approve#0`."),value:external_exports.unknown().optional().describe("answer only: supply the value requested by the open checkpoint or ask and match its answer shape. A checkpoint may resolve without a value; an ask must receive its requested record. Use null only when that is the intended answer."),artifact:external_exports.string().min(1).optional().describe("answer only: a reference to what you reviewed before answering, recorded beside the answer."),endpoint:external_exports.string().min(1).optional().describe("status/ps/answer: the endpoint the run record lives under. Omit for runs the manager hosts."),page:external_exports.strictObject({limit:external_exports.number().int().min(1).max(16).optional(),cursor:external_exports.string().min(1).max(3072).regex(/^[A-Za-z0-9_-]+$/).optional()}).optional().describe("ps only: one bounded diagnostic JSON page, default 8 rows. Pin the manager with instance unless this session is already bound. Continuation is not snapshot, absence or ownership proof. A manager from release 0.88.0 or earlier refuses `page`."),instance:managerInstanceArg},async run(agent,config3,a){const need=(field,verb)=>a[field]===void 0?err2(`cotal_run ${verb}: \`${String(field)}\` is required`):void 0;try{if(a.page!==void 0&&a.verb!=="ps")return err2("cotal_run: page is supported only for ps");if(a.page!==void 0&&a.instance===void 0&&config3.managerInstanceId===void 0)return err2("cotal_run ps: diagnostic pages require an explicit instance or a bound manager");if(a.verb==="start"){const missing2=need("source","start");if(missing2)return missing2;const reply2=await agent.run("start",{source:a.source,file:a.file,timeout:a.timeout},a.instance);if(!reply2.ok)return err2(renderRunRefusal("start",reply2));const{runId}=reply2.data;return ok2(`Started run ${runId} on the manager. It runs there until it completes or is held; cotal_run(verb="status", runId="${runId}"${a.instance?`, instance="${a.instance}"`:""}) follows its steps, and an open checkpoint is answered with verb="answer"${a.instance?` on instance="${a.instance}"`:""}.`)}if(a.verb==="resume"){const missing2=need("runId","resume");if(missing2)return missing2;const reply2=await agent.run("resume",{runId:a.runId,timeout:a.timeout},a.instance);if(!reply2.ok)return err2(renderRunRefusal("resume",reply2));return ok2(`Resumed run ${a.runId} on the manager from its recorded program.${a.instance?` Use instance="${a.instance}" for subsequent status and answer calls to this manager.`:""}`)}if(a.verb==="ps"){const reply2=await agent.run("ps",{endpoint:a.endpoint,...a.page!==void 0?{page:a.page}:{}},a.instance);if(!reply2.ok)return err2(renderRunRefusal("ps",reply2));if(a.page!==void 0){const page=reply2.data;if(page===null||typeof page!=="object"||Array.isArray(page)||page.semantics!=="diagnostic")return err2("the manager did not return a diagnostic inventory page");const text2=JSON.stringify(page);if(a.page.cursor!==void 0&&page.nextCursor===a.page.cursor)return err2(`Diagnostic inventory made no progress; retain this incomplete observation, do not retry in a loop: ${text2}`);return ok2(text2)}const rows=reply2.data;if(rows.length===0)return ok2("No workflow runs are recorded in this space.");return ok2(rows.map(r=>`${r.runId} ${r.endpoint} ${r.state??"(no status)"} holder=${r.holder??"-"} journal=${r.journalHigh??"-"}${r.forkedFrom?` forked-from=${r.forkedFrom.run}@${r.forkedFrom.step}`:""}`).join("\n"))}if(a.verb==="status"){const missing2=need("runId","status");if(missing2)return missing2;const reply2=await agent.run("status",{runId:a.runId,endpoint:a.endpoint},a.instance);if(!reply2.ok)return err2(renderRunRefusal("status",reply2));const v=reply2.data;const head=`run ${v.runId} on ${v.endpoint}: ${v.status?`${v.status.state}, holder ${v.status.holder}, epoch ${v.status.epoch}`:"(no status)"}`;const lines=v.journal.map(r=>r.kind==="activation"?`#${r.n} activation holder=${r.holder} epoch=${r.epoch} replayedTo=${r.replayedTo}`:`#${r.n} step ${r.step} ${r.outcome}${r.asks!==void 0?`
|
|
147
|
+
asks: ${r.asks}${r.addressee!==void 0?` (escalates to ${r.addressee})`:""}`:""}`);return ok2([head,...lines.length?lines:["(no journal records: never started, or retired)"]].join("\n"))}const missing=need("runId","answer")??need("stepKey","answer");if(missing)return missing;const reply=await agent.run("answer",{runId:a.runId,stepKey:a.stepKey,value:a.value,artifact:a.artifact,endpoint:a.endpoint},a.instance);if(!reply.ok)return err2(renderRunRefusal("answer",reply));return ok2(`Answered ${a.stepKey} on run ${a.runId} as ${config3.name}: ${JSON.stringify(reply.data)}`)}catch(e){return runFailure(`cotal_run ${a.verb}`,e)}}},{name:"cotal_persona",title:"Cotal: define a persona",description:'Save a persona that cotal_spawn can start by name. Most jobs need a persona written for them. For one job, pass persona to cotal_spawn instead, and save one here only when it is worth reusing. Reuse one from cotal_personas only when it really fits, such as a general reviewer. Every persona you save stays in the user\'s workspace after the helper stops. No cotal_* tool removes one: remove one you own with cotal_invoke, endpoint `manager`, command `remove-persona`, args `{ name }`; the operator removes any with `cotal persona remove <name>`. Name it after what it does, such as review-login-page. Write the prompt about the job: what to do, where the brief is, how to report, and when to stop. Point to sources for facts rather than stating them. Set role when others should reach it through a role. List its channels and give it only what the job needs: subscribe for where it starts, allowSubscribe for what it may read, and allowPublish for what it may post to. If you list subscribe alone, it may read just those channels and can\'t post anywhere. Leave all three out and it can read and post nowhere, so list the channels it needs. A persona you pass to cotal_spawn differs here: with no channel field it takes your own read and post grants. To let its agent spawn others or run workflows, list spawn or run in capabilities. You can give only capabilities you hold, and each later spawn of the persona is checked again against its spawner. Only you or an operator can change a persona you saved.\n\nBefore you write one, check what you can give. cotal_orientation shows your own channels and capabilities, and cotal_channels lists the channels in the space. cotal_endpoints lists the endpoints you can call, and cotal_describe shows what one lets a caller do. The agent-files page in cotal_docs lists every persona field.\n\nExample:\n\n```\n{\n name: "review-login-page",\n role: "reviewer",\n subscribe: ["review.login-page"],\n allowPublish: ["review.login-page"],\n prompt: "You review the login page change in PR 812. The brief is on #review.login-page. Check the session timeout and the error messages against docs/auth.md. Post each finding there with its file and line. When you are done, post a one-line verdict and despawn yourself."\n}\n```',schema:{name:external_exports.string().regex(/^[A-Za-z0-9_-]+$/,"letters, digits, _ or - only").describe("Unique name for the persona (also the spawn name): letters, digits, _ or -."),instance:managerInstanceArg,prompt:external_exports.string().max(1e4).describe("The persona: an appended system prompt describing who this agent is. A complete agent file (leading --- frontmatter with subscribe / allowSubscribe / allowPublish) is merged, not wrapped."),model:external_exports.string().max(120).optional().describe("Optional model override (e.g. opus, sonnet). Wins over a model: in the prompt's frontmatter."),role:external_exports.string().max(120).optional().describe("Optional role written into the persona file (e.g. reviewer). Wins over a role: in the prompt's frontmatter."),agent:external_exports.string().max(120).optional().describe("Optional harness pin written into the persona file (e.g. jcode). Wins over an agent: in the prompt's frontmatter."),subscribe:external_exports.array(external_exports.string()).optional().describe("Optional active read set written into the persona file. Wins over subscribe: in the prompt's frontmatter."),allowSubscribe:external_exports.array(external_exports.string()).optional().describe("Optional read ACL written into the persona file. Wins over allowSubscribe: in the prompt's frontmatter."),allowPublish:external_exports.array(external_exports.string()).optional().describe("Optional post ACL written into the persona file. Wins over allowPublish: in the prompt's frontmatter."),capabilities:external_exports.array(external_exports.string()).optional().describe("Optional capabilities written into the persona file, such as spawn or run. Each must be one you hold; the manager refuses anything more and writes nothing. A redefine that omits it keeps the saved list, which is checked the same way; pass [] to clear it. Capabilities in the prompt's frontmatter are dropped."),announce:external_exports.string().optional().describe("Optional channel to post a one-line note on once the persona is saved. Omit it to keep the definition private to the manager's persona catalog. Name the channel your team is actually working on, not `general`: a peer that did not ask for this persona has no way to judge whether spawning it is wanted, and a broadcast soliciting spawns from an unfamiliar principal gives peers no reason to trust the request. Your post ACL applies as it does to any other message.")},async run(agent,_config,{name,prompt,instance,model,role,agent:agentType,subscribe,allowSubscribe,allowPublish,capabilities,announce}){try{const reply=await agent.definePersona({name,prompt,instance,model,role,agent:agentType,subscribe,allowSubscribe,allowPublish,capabilities,announce});if(reply.definitionOutcome==="unknown"){const readback=`cotal_personas(name="${name}"${instance===void 0?"":`, instance="${instance}"`})`;const message=`The definition outcome for persona \`${name}\` is unknown: ${reply.error??"the manager reply was not observed"}. The file may already have been written or may still be written. Do not re-run this definition or spawn it on this result. Read back with ${readback} on the same manager before acting. A missing readback alone does not prove the write will not land.`;return{text:message,structured:{status:"unknown",name,...instance===void 0?{}:{instance},next:readback,message}}}if(!reply.ok)return err2(`Couldn't define ${name}: ${reply.error??"manager refused"}`);const spawnHint=`spawn it with cotal_spawn(name="${name}"${instance===void 0?"":`, instance="${instance}"`}) to bring it online`;if(reply.announceError&&reply.announceOutcome==="denied")return ok2(`Persona \`${name}\` saved \u2014 but the announcement to #${announce} was REFUSED and did not go out: ${reply.announceError}. The persona is on disk; do not re-run this call. Check your \`allowPublish\` for #${announce}, then post it yourself if you still want to. You can ${spawnHint}.`);if(reply.announceError)return ok2(`Persona \`${name}\` saved \u2014 but I could NOT CONFIRM the announcement to #${announce}: ${reply.announceError}. It may or may not have been delivered. The persona is on disk; do not re-run this call, and READ #${announce} before posting anything yourself \u2014 posting blind is how the channel gets it twice. You can ${spawnHint}.`);return ok2(`Persona \`${name}\` saved${announce?` and announced on #${announce}`:""} \u2014 ${spawnHint}.`)}catch(e){const detail=e?.message??String(e);if(detail.startsWith("announce:"))return err2(`Couldn't define ${name}: ${detail}. Nothing was written.`);return controlFailure(`Couldn't define ${name}`,e)}}},{name:"cotal_personas",title:"Cotal: list or show personas",description:"Read the workspace persona catalog the manager owns (.cotal/agents). Omit `name` to list spawnable persona names (role, model, and a one-line description when you own the file). Pass `name` to show one card you own, including the persona body. Same ownership as cotal_persona: a file you do not own lists as a name only, while unauthorized, unknown, and unparseable shows are all not-found. Use this to see whether a name is taken before cotal_persona, or what a teammate's persona says, without shelling out. Pass `instance` to read one manager's catalog when the owner has several managers.",schema:{name:external_exports.string().regex(/^[A-Za-z0-9_-]+$/,"letters, digits, _ or - only").optional().describe("Persona to show. Omit to list the catalog."),instance:managerInstanceArg},async run(agent,_config,{name,instance}){try{if(name){const reply2=await agent.showPersona(name,instance);if(!reply2.ok)return err2(`Couldn't show ${name}: ${reply2.error??"manager refused"}`);const row=reply2.data??{};if(row.error)return err2(`Persona \`${name}\` is unparseable: ${row.error}`);const meta3=[row.role&&`role=${row.role}`,row.model&&`model=${row.model}`,row.owner&&`owner=${row.owner}`].filter(Boolean).join(" ");const lines2=[`Persona \`${row.name??name}\`${meta3?` ${meta3}`:""}`];if(row.description)lines2.push(row.description);if(row.persona)lines2.push("",row.persona);return ok2(lines2.join("\n"))}const reply=await agent.listPersonas(instance);if(!reply.ok)return err2(`Couldn't list personas: ${reply.error??"manager refused"}`);const personas=reply.data?.personas??[];if(!personas.length)return ok2("No personas in the manager catalog.");const lines=personas.map(p=>{if(p.error)return`${p.name} \u2A2F unparseable`;const meta3=[p.role,p.model&&`model=${p.model}`,p.owner&&`owner=${p.owner}`].filter(Boolean).join(" ");const head=meta3?`${p.name} ${meta3}`:p.name;return p.description?`${head}
|
|
148
148
|
${p.description}`:head});return ok2(`Personas in the manager catalog (${personas.length}):
|
|
149
149
|
${lines.join("\n")}`)}catch(e){return controlFailure(name?`Couldn't show ${name}`:"Couldn't list personas",e)}}},{name:"cotal_endpoints",title:"Cotal: list the endpoints you can call",description:"List the endpoints registered in this space that this session can call, and for each one the commands its grants cover and the request forms they allow. The space's registry answers from the grants recorded when this session's credential was issued, so the broker or the endpoint can still refuse a listed command. Endpoints where this session holds no command are left out, and so are endpoints whose command declarations cannot be read. A command whose grants are too many to list form by form is named under `unprojected`. On a user-auth mesh manager commands ride a separate manager-call credential; pass view=\"manager\" to list what that credential can call. Call cotal_describe for a command's input schema. A page holds up to 100 endpoints; pass the previous page's `next` as `after` for the next one.",schema:{after:external_exports.string().min(1).max(128).optional().describe("The `next` value from the previous page."),limit:external_exports.number().int().min(1).max(REGISTRY_PAGE_LIMIT).optional().describe(`Endpoints per page (default ${REGISTRY_PAGE_LIMIT}).`),view:external_exports.enum(["session","manager"]).optional().describe("`session` (default): this session's own credential. `manager`: its manager-call credential."),instance:external_exports.string().min(1).max(64).optional().describe("Manager view only: the manager instance whose call credential to use.")},async run(agent,_config,{after,limit,view,instance}){if(instance!==void 0&&view!=="manager")return err2('`instance` selects the manager for view="manager" only.');const label=view==="manager"?"the manager-call credential":"this session";try{const input={...after!==void 0?{after}:{},...limit!==void 0?{limit}:{}};const r=view==="manager"?await agent.listManagerEndpoints(input,instance):await agent.ep.listEndpoints(input);if("none"in r)return err2(`There is no manager view: ${r.none}.`);if(r.unbound)return err2(`The credential of ${label} has no listing binding, so the registry cannot list what it may call. A credential issued before the listing existed, or one with no expiry, has none; a new credential does.`);if(r.reply.reply.ok!==true){const e=r.reply.reply.error;return err2(`The registry refused the listing: ${e?.code??"error"}: ${e?.message??"no message"}`)}const page=r.page;const more=page.next!==void 0?` More endpoints follow; pass after="${page.next}".`:"";return endpointData(`${page.rows.length} endpoints ${label} can call (source: ${page.source}).${more}`,page)}catch(e){if(e instanceof EpEnvelopeError&&e.details?.some(d=>d.kind===EP_UNANSWERED))return err2("The registry did not answer, so nothing is listed. The space may run no registry, or it is down; other tools are unaffected.");return endpointFailure("Couldn't list endpoints",e)}}},{name:"cotal_describe",title:"Cotal: describe an endpoint",description:"List the commands a registered endpoint serves, as this session's credential sees them: each command's capability, whether it is targeted, and its input schema. The surface comes from the endpoint's describe reply and the content-addressed contract store, digest-verified, never from the endpoint's own claims. Read it before cotal_invoke.",schema:{endpoint:external_exports.string().min(1).max(200).describe("The endpoint name, e.g. com.example.orders."),refresh:external_exports.boolean().optional().describe("Resolve again instead of using this session's cached surface.")},async run(agent,config3,{endpoint,refresh}){try{const instanceId=endpoint==="manager"&&!isAuthed(config3)?config3.managerInstanceId:void 0;const svc=await agent.ep.describeService(endpoint,{refresh,...instanceId!==void 0?{instanceId}:{}});const commands=[...svc.commands.values()].sort((a,b)=>a.command.localeCompare(b.command)).map(c=>({command:c.command,capability:c.capability,class:c.class,targeted:c.targeted,...c.targeted?{modes:c.modes}:{},input:c.contract.input.validate.schema,inputDigest:c.contract.input.closureDigest}));return endpointData(`${svc.endpoint}: owner ${svc.owner}, instance ${svc.responder.instanceId}, epoch ${svc.responder.epoch}, ${commands.length} commands.`,commands)}catch(e){return endpointFailure(`Couldn't describe ${endpoint}`,e)}}},{name:"cotal_invoke",title:"Cotal: invoke an endpoint command",description:"Call one command on a registered endpoint with JSON arguments, over this session's own connection and grants. The arguments are checked against the command's digest-verified input schema before anything is sent, and the reply against its output schema. A failure reports its code and outcome: `not-executed` means the command did not run; `unknown` means it may have. Do not repeat a call whose outcome is unknown without checking first.",schema:{endpoint:external_exports.string().min(1).max(200).describe("The endpoint name, e.g. com.example.orders."),command:external_exports.string().min(1).max(128).describe("The command name from cotal_describe."),args:external_exports.record(external_exports.string(),external_exports.unknown()).optional().describe("The command's arguments as a JSON object."),self:external_exports.boolean().optional().describe("Targeted commands only: act on this session itself."),timeoutMs:external_exports.number().int().min(1).max(12e4).optional().describe("Reply deadline in milliseconds (default 30000).")},async run(agent,config3,{endpoint,command,args,self:self2,timeoutMs}){try{const instanceId=endpoint==="manager"&&self2&&!isAuthed(config3)?config3.managerInstanceId:void 0;const r=await agent.ep.invokeService(endpoint,command,args,{deadlineMs:timeoutMs??3e4,...self2?{target:{mode:"self"}}:{},...instanceId!==void 0?{instanceId}:{}});if(r.reply.ok!==true){const e=r.reply.error;const details=e?.details?.length?JSON.stringify(e.details):"";const message=e?.message??"no message";const head=`${endpoint}.${command} failed: ${e?.code??"error"}${e?.outcome?` (outcome ${e.outcome})`:""}: `;if(head.length+message.length>ENDPOINT_RESULT_MAX_CHARS)return err2(`${head}the error message is ${message.length} characters, over this tool's ${ENDPOINT_RESULT_MAX_CHARS}-character limit, and was withheld.`);if(head.length+message.length+details.length+40>ENDPOINT_RESULT_MAX_CHARS)return err2(`${head}${message}
|
|
150
150
|
details withheld: ${details.length} characters, over this tool's ${ENDPOINT_RESULT_MAX_CHARS}-character limit.`);return err2(`${head}${message}${details?`
|