@cotal-ai/pi 0.164.15 → 0.164.17

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.
@@ -112,7 +112,7 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
112
112
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}}}for(const entry of ctx.seen.entries()){const seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){const ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}const id2=ctx.metadataRegistry.get(entry[0])?.id;if(id2){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry);continue}}}}function finalize(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");const flattenRef=zodSchema=>{const seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;const schema2=seen.def??seen.schema;const _cached={...schema2};const ref=seen.ref;seen.ref=null;if(ref){flattenRef(ref);const refSeen=ctx.seen.get(ref);const refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")){schema2.allOf=schema2.allOf??[];schema2.allOf.push(refSchema)}else{Object.assign(schema2,refSchema)}Object.assign(schema2,_cached);const isParentRef=zodSchema._zod.parent===ref;if(isParentRef){for(const key in schema2){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached)){delete schema2[key]}}}if(refSchema.$ref&&refSeen.def){for(const key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key])){delete schema2[key]}}}}const parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);const parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){schema2.$ref=parentSeen.schema.$ref;if(parentSeen.def){for(const key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key])){delete schema2[key]}}}}}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};for(const entry of[...ctx.seen.entries()].reverse()){flattenRef(entry[0])}const result={};if(ctx.target==="draft-2020-12"){result.$schema="https://json-schema.org/draft/2020-12/schema"}else if(ctx.target==="draft-07"){result.$schema="http://json-schema.org/draft-07/schema#"}else if(ctx.target==="draft-04"){result.$schema="http://json-schema.org/draft-04/schema#"}else if(ctx.target==="openapi-3.0"){}else{}if(ctx.external?.uri){const id2=ctx.external.registry.get(schema)?.id;if(!id2)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id2)}Object.assign(result,root.def??root.schema);const rootMetaId=ctx.metadataRegistry.get(schema)?.id;if(rootMetaId!==void 0&&result.id===rootMetaId)delete result.id;const defs=ctx.external?.defs??{};for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.def&&seen.defId){if(seen.def.id===seen.defId)delete seen.def.id;defs[seen.defId]=seen.def}}if(ctx.external){}else{if(Object.keys(defs).length>0){if(ctx.target==="draft-2020-12"){result.$defs=defs}else{result.definitions=defs}}}try{const finalized=JSON.parse(JSON.stringify(result));Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:false,writable:false});return finalized}catch(_err){throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){const ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return false;ctx.seen.add(_schema);const def=_schema._zod.def;if(def.type==="transform")return true;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"){return isTransforming(def.innerType,ctx)}if(def.type==="intersection"){return isTransforming(def.left,ctx)||isTransforming(def.right,ctx)}if(def.type==="record"||def.type==="map"){return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx)}if(def.type==="pipe"){if(_schema._zod.traits.has("$ZodCodec"))return true;return isTransforming(def.in,ctx)||isTransforming(def.out,ctx)}if(def.type==="object"){for(const key in def.shape){if(isTransforming(def.shape[key],ctx))return true}return false}if(def.type==="union"){for(const option of def.options){if(isTransforming(option,ctx))return true}return false}if(def.type==="tuple"){for(const item of def.items){if(isTransforming(item,ctx))return true}if(def.rest&&isTransforming(def.rest,ctx))return true;return false}return false}var createToJSONSchemaMethod,createStandardJSONSchemaMethod;var init_to_json_schema=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js"(){init_registries();createToJSONSchemaMethod=(schema,processors={})=>params=>{const ctx=initializeContext({...params,processors});process2(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};createStandardJSONSchemaMethod=(schema,io,processors={})=>params=>{const{libraryOptions,target:target2}=params??{};const ctx=initializeContext({...libraryOptions??{},target:target2,io,processors});process2(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)}}});function toJSONSchema(input,params){if("_idmap"in input){const registry4=input;const ctx2=initializeContext({...params,processors:allProcessors});const defs={};for(const entry of registry4._idmap.entries()){const[_,schema]=entry;process2(schema,ctx2)}const schemas={};const external={registry:registry4,uri:params?.uri,defs};ctx2.external=external;for(const entry of registry4._idmap.entries()){const[key,schema]=entry;extractDefs(ctx2,schema);schemas[key]=finalize(ctx2,schema)}if(Object.keys(defs).length>0){const defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}const ctx=initializeContext({...params,processors:allProcessors});process2(input,ctx);extractDefs(ctx,input);return finalize(ctx,input)}var formatMap,stringProcessor,numberProcessor,booleanProcessor,bigintProcessor,symbolProcessor,nullProcessor,undefinedProcessor,voidProcessor,neverProcessor,anyProcessor,unknownProcessor,dateProcessor,enumProcessor,literalProcessor,nanProcessor,templateLiteralProcessor,fileProcessor,successProcessor,customProcessor,functionProcessor,transformProcessor,mapProcessor,setProcessor,arrayProcessor,objectProcessor,unionProcessor,intersectionProcessor,tupleProcessor,recordProcessor,nullableProcessor,nonoptionalProcessor,defaultProcessor,prefaultProcessor,catchProcessor,pipeProcessor,readonlyProcessor,promiseProcessor,optionalProcessor,lazyProcessor,allProcessors;var init_json_schema_processors=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js"(){init_to_json_schema();init_util();formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""};stringProcessor=(schema,ctx,_json,_params)=>{const json2=_json;json2.type="string";const{minimum,maximum,format,patterns:patterns2,contentEncoding}=schema._zod.bag;if(typeof minimum==="number")json2.minLength=minimum;if(typeof maximum==="number")json2.maxLength=maximum;if(format){json2.format=formatMap[format]??format;if(json2.format==="")delete json2.format;if(format==="time"){delete json2.format}}if(contentEncoding)json2.contentEncoding=contentEncoding;if(patterns2&&patterns2.size>0){const regexes=[...patterns2];if(regexes.length===1)json2.pattern=regexes[0].source;else if(regexes.length>1){json2.allOf=[...regexes.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}}};numberProcessor=(schema,ctx,_json,_params)=>{const json2=_json;const{minimum,maximum,format,multipleOf,exclusiveMaximum,exclusiveMinimum}=schema._zod.bag;if(typeof format==="string"&&format.includes("int"))json2.type="integer";else json2.type="number";const exMin=typeof exclusiveMinimum==="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY);const exMax=typeof exclusiveMaximum==="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY);const legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin){if(legacy){json2.minimum=exclusiveMinimum;json2.exclusiveMinimum=true}else{json2.exclusiveMinimum=exclusiveMinimum}}else if(typeof minimum==="number"){json2.minimum=minimum}if(exMax){if(legacy){json2.maximum=exclusiveMaximum;json2.exclusiveMaximum=true}else{json2.exclusiveMaximum=exclusiveMaximum}}else if(typeof maximum==="number"){json2.maximum=maximum}if(typeof multipleOf==="number")json2.multipleOf=multipleOf};booleanProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"};bigintProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("BigInt cannot be represented in JSON Schema")}};symbolProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Symbols cannot be represented in JSON Schema")}};nullProcessor=(_schema,ctx,json2,_params)=>{if(ctx.target==="openapi-3.0"){json2.type="string";json2.nullable=true;json2.enum=[null]}else{json2.type="null"}};undefinedProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Undefined cannot be represented in JSON Schema")}};voidProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Void cannot be represented in JSON Schema")}};neverProcessor=(_schema,_ctx,json2,_params)=>{json2.not={}};anyProcessor=(_schema,_ctx,_json,_params)=>{};unknownProcessor=(_schema,_ctx,_json,_params)=>{};dateProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Date cannot be represented in JSON Schema")}};enumProcessor=(schema,_ctx,json2,_params)=>{const def=schema._zod.def;const values=getEnumValues(def.entries);if(values.every(v=>typeof v==="number"))json2.type="number";if(values.every(v=>typeof v==="string"))json2.type="string";json2.enum=values};literalProcessor=(schema,ctx,json2,_params)=>{const def=schema._zod.def;const vals=[];for(const val of def.values){if(val===void 0){if(ctx.unrepresentable==="throw"){throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else{}}else if(typeof val==="bigint"){if(ctx.unrepresentable==="throw"){throw new Error("BigInt literals cannot be represented in JSON Schema")}else{vals.push(Number(val))}}else{vals.push(val)}}if(vals.length===0){}else if(vals.length===1){const val=vals[0];json2.type=val===null?"null":typeof val;if(ctx.target==="draft-04"||ctx.target==="openapi-3.0"){json2.enum=[val]}else{json2.const=val}}else{if(vals.every(v=>typeof v==="number"))json2.type="number";if(vals.every(v=>typeof v==="string"))json2.type="string";if(vals.every(v=>typeof v==="boolean"))json2.type="boolean";if(vals.every(v=>v===null))json2.type="null";json2.enum=vals}};nanProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("NaN cannot be represented in JSON Schema")}};templateLiteralProcessor=(schema,_ctx,json2,_params)=>{const _json=json2;const pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string";_json.pattern=pattern.source};fileProcessor=(schema,_ctx,json2,_params)=>{const _json=json2;const file2={type:"string",format:"binary",contentEncoding:"binary"};const{minimum,maximum,mime}=schema._zod.bag;if(minimum!==void 0)file2.minLength=minimum;if(maximum!==void 0)file2.maxLength=maximum;if(mime){if(mime.length===1){file2.contentMediaType=mime[0];Object.assign(_json,file2)}else{Object.assign(_json,file2);_json.anyOf=mime.map(m=>({contentMediaType:m}))}}else{Object.assign(_json,file2)}};successProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"};customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Custom types cannot be represented in JSON Schema")}};functionProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Function types cannot be represented in JSON Schema")}};transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Transforms cannot be represented in JSON Schema")}};mapProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Map cannot be represented in JSON Schema")}};setProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Set cannot be represented in JSON Schema")}};arrayProcessor=(schema,ctx,_json,params)=>{const json2=_json;const def=schema._zod.def;const{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json2.minItems=minimum;if(typeof maximum==="number")json2.maxItems=maximum;json2.type="array";json2.items=process2(def.element,ctx,{...params,path:[...params.path,"items"]})};objectProcessor=(schema,ctx,_json,params)=>{const json2=_json;const def=schema._zod.def;json2.type="object";json2.properties={};const shape=def.shape;for(const key in shape){json2.properties[key]=process2(shape[key],ctx,{...params,path:[...params.path,"properties",key]})}const allKeys=new Set(Object.keys(shape));const requiredKeys=new Set([...allKeys].filter(key=>{const v=def.shape[key]._zod;if(ctx.io==="input"){return v.optin===void 0}else{return v.optout===void 0}}));if(requiredKeys.size>0){json2.required=Array.from(requiredKeys)}if(def.catchall?._zod.def.type==="never"){json2.additionalProperties=false}else if(!def.catchall){if(ctx.io==="output")json2.additionalProperties=false}else if(def.catchall){json2.additionalProperties=process2(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})}};unionProcessor=(schema,ctx,json2,params)=>{const def=schema._zod.def;const isExclusive=def.inclusive===false;const options=def.options.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive){json2.oneOf=options}else{json2.anyOf=options}};intersectionProcessor=(schema,ctx,json2,params)=>{const def=schema._zod.def;const a=process2(def.left,ctx,{...params,path:[...params.path,"allOf",0]});const b=process2(def.right,ctx,{...params,path:[...params.path,"allOf",1]});const isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1;const allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json2.allOf=allOf};tupleProcessor=(schema,ctx,_json,params)=>{const json2=_json;const def=schema._zod.def;json2.type="array";const prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items";const restPath=ctx.target==="draft-2020-12"?"items":ctx.target==="openapi-3.0"?"items":"additionalItems";const prefixItems=def.items.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,prefixPath,i]}));const rest=def.rest?process2(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;if(ctx.target==="draft-2020-12"){json2.prefixItems=prefixItems;if(rest){json2.items=rest}}else if(ctx.target==="openapi-3.0"){json2.items={anyOf:prefixItems};if(rest){json2.items.anyOf.push(rest)}json2.minItems=prefixItems.length;if(!rest){json2.maxItems=prefixItems.length}}else{json2.items=prefixItems;if(rest){json2.additionalItems=rest}}const{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json2.minItems=minimum;if(typeof maximum==="number")json2.maxItems=maximum};recordProcessor=(schema,ctx,_json,params)=>{const json2=_json;const def=schema._zod.def;json2.type="object";const keyType=def.keyType;const keyBag=keyType._zod.bag;const patterns2=keyBag?.patterns;if(def.mode==="loose"&&patterns2&&patterns2.size>0){const valueSchema=process2(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json2.patternProperties={};for(const pattern of patterns2){json2.patternProperties[pattern.source]=valueSchema}}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json2.propertyNames=process2(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]})}json2.additionalProperties=process2(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}const keyValues=keyType._zod.values;if(keyValues){const validKeyValues=[...keyValues].filter(v=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0){json2.required=validKeyValues}}};nullableProcessor=(schema,ctx,json2,params)=>{const def=schema._zod.def;const inner=process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0"){seen.ref=def.innerType;json2.nullable=true}else{json2.anyOf=[inner,{type:"null"}]}};nonoptionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};defaultProcessor=(schema,ctx,json2,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;json2.default=JSON.parse(JSON.stringify(def.defaultValue))};prefaultProcessor=(schema,ctx,json2,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;if(ctx.io==="input")json2._prefault=JSON.parse(JSON.stringify(def.defaultValue))};catchProcessor=(schema,ctx,json2,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}json2.default=catchValue};pipeProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;const inIsTransform=def.in._zod.traits.has("$ZodTransform");const innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;process2(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};readonlyProcessor=(schema,ctx,json2,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;json2.readOnly=true};promiseProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};optionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};lazyProcessor=(schema,ctx,_json,params)=>{const innerType=schema._zod.innerType;process2(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor}}});var JSONSchemaGenerator;var init_json_schema_generator=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-generator.js"(){init_json_schema_processors();init_to_json_schema();JSONSchemaGenerator=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";if(normalizedTarget==="draft-4")normalizedTarget="draft-04";if(normalizedTarget==="draft-7")normalizedTarget="draft-07";this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return process2(schema,this.ctx,_params)}emit(schema,_params){if(_params){if(_params.cycles)this.ctx.cycles=_params.cycles;if(_params.reused)this.ctx.reused=_params.reused;if(_params.external)this.ctx.external=_params.external}extractDefs(this.ctx,schema);const result=finalize(this.ctx,schema);const{"~standard":_,...plainResult}=result;return plainResult}}}});var json_schema_exports={};var init_json_schema=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js"(){}});var core_exports2={};__export(core_exports2,{$ZodAny:()=>$ZodAny,$ZodArray:()=>$ZodArray,$ZodAsyncError:()=>$ZodAsyncError,$ZodBase64:()=>$ZodBase64,$ZodBase64URL:()=>$ZodBase64URL,$ZodBigInt:()=>$ZodBigInt,$ZodBigIntFormat:()=>$ZodBigIntFormat,$ZodBoolean:()=>$ZodBoolean,$ZodCIDRv4:()=>$ZodCIDRv4,$ZodCIDRv6:()=>$ZodCIDRv6,$ZodCUID:()=>$ZodCUID,$ZodCUID2:()=>$ZodCUID2,$ZodCatch:()=>$ZodCatch,$ZodCheck:()=>$ZodCheck,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat,$ZodCheckEndsWith:()=>$ZodCheckEndsWith,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan,$ZodCheckIncludes:()=>$ZodCheckIncludes,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals,$ZodCheckLessThan:()=>$ZodCheckLessThan,$ZodCheckLowerCase:()=>$ZodCheckLowerCase,$ZodCheckMaxLength:()=>$ZodCheckMaxLength,$ZodCheckMaxSize:()=>$ZodCheckMaxSize,$ZodCheckMimeType:()=>$ZodCheckMimeType,$ZodCheckMinLength:()=>$ZodCheckMinLength,$ZodCheckMinSize:()=>$ZodCheckMinSize,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat,$ZodCheckOverwrite:()=>$ZodCheckOverwrite,$ZodCheckProperty:()=>$ZodCheckProperty,$ZodCheckRegex:()=>$ZodCheckRegex,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals,$ZodCheckStartsWith:()=>$ZodCheckStartsWith,$ZodCheckStringFormat:()=>$ZodCheckStringFormat,$ZodCheckUpperCase:()=>$ZodCheckUpperCase,$ZodCodec:()=>$ZodCodec,$ZodCustom:()=>$ZodCustom,$ZodCustomStringFormat:()=>$ZodCustomStringFormat,$ZodDate:()=>$ZodDate,$ZodDefault:()=>$ZodDefault,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion,$ZodE164:()=>$ZodE164,$ZodEmail:()=>$ZodEmail,$ZodEmoji:()=>$ZodEmoji,$ZodEncodeError:()=>$ZodEncodeError,$ZodEnum:()=>$ZodEnum,$ZodError:()=>$ZodError,$ZodExactOptional:()=>$ZodExactOptional,$ZodFile:()=>$ZodFile,$ZodFunction:()=>$ZodFunction,$ZodGUID:()=>$ZodGUID,$ZodIPv4:()=>$ZodIPv4,$ZodIPv6:()=>$ZodIPv6,$ZodISODate:()=>$ZodISODate,$ZodISODateTime:()=>$ZodISODateTime,$ZodISODuration:()=>$ZodISODuration,$ZodISOTime:()=>$ZodISOTime,$ZodIntersection:()=>$ZodIntersection,$ZodJWT:()=>$ZodJWT,$ZodKSUID:()=>$ZodKSUID,$ZodLazy:()=>$ZodLazy,$ZodLiteral:()=>$ZodLiteral,$ZodMAC:()=>$ZodMAC,$ZodMap:()=>$ZodMap,$ZodNaN:()=>$ZodNaN,$ZodNanoID:()=>$ZodNanoID,$ZodNever:()=>$ZodNever,$ZodNonOptional:()=>$ZodNonOptional,$ZodNull:()=>$ZodNull,$ZodNullable:()=>$ZodNullable,$ZodNumber:()=>$ZodNumber,$ZodNumberFormat:()=>$ZodNumberFormat,$ZodObject:()=>$ZodObject,$ZodObjectJIT:()=>$ZodObjectJIT,$ZodOptional:()=>$ZodOptional,$ZodPipe:()=>$ZodPipe,$ZodPrefault:()=>$ZodPrefault,$ZodPreprocess:()=>$ZodPreprocess,$ZodPromise:()=>$ZodPromise,$ZodReadonly:()=>$ZodReadonly,$ZodRealError:()=>$ZodRealError,$ZodRecord:()=>$ZodRecord,$ZodRegistry:()=>$ZodRegistry,$ZodSet:()=>$ZodSet,$ZodString:()=>$ZodString,$ZodStringFormat:()=>$ZodStringFormat,$ZodSuccess:()=>$ZodSuccess,$ZodSymbol:()=>$ZodSymbol,$ZodTemplateLiteral:()=>$ZodTemplateLiteral,$ZodTransform:()=>$ZodTransform,$ZodTuple:()=>$ZodTuple,$ZodType:()=>$ZodType,$ZodULID:()=>$ZodULID,$ZodURL:()=>$ZodURL,$ZodUUID:()=>$ZodUUID,$ZodUndefined:()=>$ZodUndefined,$ZodUnion:()=>$ZodUnion,$ZodUnknown:()=>$ZodUnknown,$ZodVoid:()=>$ZodVoid,$ZodXID:()=>$ZodXID,$ZodXor:()=>$ZodXor,$brand:()=>$brand,$constructor:()=>$constructor,$input:()=>$input,$output:()=>$output,Doc:()=>Doc,JSONSchema:()=>json_schema_exports,JSONSchemaGenerator:()=>JSONSchemaGenerator,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,_any:()=>_any,_array:()=>_array,_base64:()=>_base64,_base64url:()=>_base64url,_bigint:()=>_bigint,_boolean:()=>_boolean,_catch:()=>_catch,_check:()=>_check,_cidrv4:()=>_cidrv4,_cidrv6:()=>_cidrv6,_coercedBigint:()=>_coercedBigint,_coercedBoolean:()=>_coercedBoolean,_coercedDate:()=>_coercedDate,_coercedNumber:()=>_coercedNumber,_coercedString:()=>_coercedString,_cuid:()=>_cuid,_cuid2:()=>_cuid2,_custom:()=>_custom,_date:()=>_date,_decode:()=>_decode,_decodeAsync:()=>_decodeAsync,_default:()=>_default,_discriminatedUnion:()=>_discriminatedUnion,_e164:()=>_e164,_email:()=>_email,_emoji:()=>_emoji2,_encode:()=>_encode,_encodeAsync:()=>_encodeAsync,_endsWith:()=>_endsWith,_enum:()=>_enum,_file:()=>_file,_float32:()=>_float32,_float64:()=>_float64,_gt:()=>_gt,_gte:()=>_gte,_guid:()=>_guid,_includes:()=>_includes,_int:()=>_int,_int32:()=>_int32,_int64:()=>_int64,_intersection:()=>_intersection,_ipv4:()=>_ipv4,_ipv6:()=>_ipv6,_isoDate:()=>_isoDate,_isoDateTime:()=>_isoDateTime,_isoDuration:()=>_isoDuration,_isoTime:()=>_isoTime,_jwt:()=>_jwt,_ksuid:()=>_ksuid,_lazy:()=>_lazy,_length:()=>_length,_literal:()=>_literal,_lowercase:()=>_lowercase,_lt:()=>_lt,_lte:()=>_lte,_mac:()=>_mac,_map:()=>_map,_max:()=>_lte,_maxLength:()=>_maxLength,_maxSize:()=>_maxSize,_mime:()=>_mime,_min:()=>_gte,_minLength:()=>_minLength,_minSize:()=>_minSize,_multipleOf:()=>_multipleOf,_nan:()=>_nan,_nanoid:()=>_nanoid,_nativeEnum:()=>_nativeEnum,_negative:()=>_negative,_never:()=>_never,_nonnegative:()=>_nonnegative,_nonoptional:()=>_nonoptional,_nonpositive:()=>_nonpositive,_normalize:()=>_normalize,_null:()=>_null2,_nullable:()=>_nullable,_number:()=>_number,_optional:()=>_optional,_overwrite:()=>_overwrite,_parse:()=>_parse,_parseAsync:()=>_parseAsync,_pipe:()=>_pipe,_positive:()=>_positive,_promise:()=>_promise,_property:()=>_property,_readonly:()=>_readonly,_record:()=>_record,_refine:()=>_refine,_regex:()=>_regex,_safeDecode:()=>_safeDecode,_safeDecodeAsync:()=>_safeDecodeAsync,_safeEncode:()=>_safeEncode,_safeEncodeAsync:()=>_safeEncodeAsync,_safeParse:()=>_safeParse,_safeParseAsync:()=>_safeParseAsync,_set:()=>_set,_size:()=>_size,_slugify:()=>_slugify,_startsWith:()=>_startsWith,_string:()=>_string,_stringFormat:()=>_stringFormat,_stringbool:()=>_stringbool,_success:()=>_success,_superRefine:()=>_superRefine,_symbol:()=>_symbol,_templateLiteral:()=>_templateLiteral,_toLowerCase:()=>_toLowerCase,_toUpperCase:()=>_toUpperCase,_transform:()=>_transform,_trim:()=>_trim,_tuple:()=>_tuple,_uint32:()=>_uint32,_uint64:()=>_uint64,_ulid:()=>_ulid,_undefined:()=>_undefined2,_union:()=>_union,_unknown:()=>_unknown,_uppercase:()=>_uppercase,_url:()=>_url,_uuid:()=>_uuid,_uuidv4:()=>_uuidv4,_uuidv6:()=>_uuidv6,_uuidv7:()=>_uuidv7,_void:()=>_void,_xid:()=>_xid,_xor:()=>_xor,clone:()=>clone,config:()=>config,createStandardJSONSchemaMethod:()=>createStandardJSONSchemaMethod,createToJSONSchemaMethod:()=>createToJSONSchemaMethod,decode:()=>decode3,decodeAsync:()=>decodeAsync,describe:()=>describe,encode:()=>encode2,encodeAsync:()=>encodeAsync,extractDefs:()=>extractDefs,finalize:()=>finalize,flattenError:()=>flattenError,formatError:()=>formatError,globalConfig:()=>globalConfig,globalRegistry:()=>globalRegistry,initializeContext:()=>initializeContext,isValidBase64:()=>isValidBase64,isValidBase64URL:()=>isValidBase64URL,isValidJWT:()=>isValidJWT,locales:()=>locales_exports,meta:()=>meta,parse:()=>parse,parseAsync:()=>parseAsync,prettifyError:()=>prettifyError,process:()=>process2,regexes:()=>regexes_exports,registry:()=>registry3,safeDecode:()=>safeDecode,safeDecodeAsync:()=>safeDecodeAsync,safeEncode:()=>safeEncode,safeEncodeAsync:()=>safeEncodeAsync,safeParse:()=>safeParse,safeParseAsync:()=>safeParseAsync,toDotPath:()=>toDotPath,toJSONSchema:()=>toJSONSchema,treeifyError:()=>treeifyError,util:()=>util_exports,version:()=>version});var init_core2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js"(){init_core();init_parse();init_errors();init_schemas();init_checks();init_versions();init_util();init_regexes();init_locales();init_registries();init_doc();init_api();init_to_json_schema();init_json_schema_processors();init_json_schema_generator();init_json_schema()}});var checks_exports2={};__export(checks_exports2,{endsWith:()=>_endsWith,gt:()=>_gt,gte:()=>_gte,includes:()=>_includes,length:()=>_length,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,maxLength:()=>_maxLength,maxSize:()=>_maxSize,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,negative:()=>_negative,nonnegative:()=>_nonnegative,nonpositive:()=>_nonpositive,normalize:()=>_normalize,overwrite:()=>_overwrite,positive:()=>_positive,property:()=>_property,regex:()=>_regex,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,trim:()=>_trim,uppercase:()=>_uppercase});var init_checks2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js"(){init_core2()}});var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date2,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date2(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var ZodISODateTime,ZodISODate,ZodISOTime,ZodISODuration;var init_iso=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js"(){init_core2();init_schemas2();ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def);ZodStringFormat.init(inst,def)});ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def);ZodStringFormat.init(inst,def)});ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def);ZodStringFormat.init(inst,def)});ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def);ZodStringFormat.init(inst,def)})}});var initializer2,ZodError,ZodRealError;var init_errors2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js"(){init_core2();init_core2();init_util();initializer2=(inst,issues)=>{$ZodError.init(inst,issues);inst.name="ZodError";Object.defineProperties(inst,{format:{value:mapper=>formatError(inst,mapper)},flatten:{value:mapper=>flattenError(inst,mapper)},addIssue:{value:issue2=>{inst.issues.push(issue2);inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},addIssues:{value:issues2=>{inst.issues.push(...issues2);inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return inst.issues.length===0}}})};ZodError=$constructor("ZodError",initializer2);ZodRealError=$constructor("ZodError",initializer2,{Parent:Error})}});var parse2,parseAsync2,safeParse2,safeParseAsync2,encode3,decode4,encodeAsync2,decodeAsync2,safeEncode2,safeDecode2,safeEncodeAsync2,safeDecodeAsync2;var init_parse2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js"(){init_core2();init_errors2();parse2=_parse(ZodRealError);parseAsync2=_parseAsync(ZodRealError);safeParse2=_safeParse(ZodRealError);safeParseAsync2=_safeParseAsync(ZodRealError);encode3=_encode(ZodRealError);decode4=_decode(ZodRealError);encodeAsync2=_encodeAsync(ZodRealError);decodeAsync2=_decodeAsync(ZodRealError);safeEncode2=_safeEncode(ZodRealError);safeDecode2=_safeDecode(ZodRealError);safeEncodeAsync2=_safeEncodeAsync(ZodRealError);safeDecodeAsync2=_safeDecodeAsync(ZodRealError)}});var schemas_exports2={};__export(schemas_exports2,{ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodIntersection:()=>ZodIntersection,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url3,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,codec:()=>codec,cuid:()=>cuid3,cuid2:()=>cuid22,custom:()=>custom,date:()=>date3,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,float32:()=>float32,float64:()=>float64,function:()=>_function,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname4,httpUrl:()=>httpUrl,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,literal:()=>literal,looseObject:()=>looseObject,looseRecord:()=>looseRecord,mac:()=>mac2,map:()=>map,meta:()=>meta2,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,never:()=>never,nonoptional:()=>nonoptional,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,partialRecord:()=>partialRecord,pipe:()=>pipe,prefault:()=>prefault,preprocess:()=>preprocess,promise:()=>promise,readonly:()=>readonly,record:()=>record,refine:()=>refine,set:()=>set2,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,transform:()=>transform,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union2,unknown:()=>unknown,url:()=>url,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor});function _installLazyMethods(inst,group,methods){const proto=Object.getPrototypeOf(inst);let installed=_installedGroups.get(proto);if(!installed){installed=new Set;_installedGroups.set(proto,installed)}if(installed.has(group))return;installed.add(group);for(const key in methods){const fn=methods[key];Object.defineProperty(proto,key,{configurable:true,enumerable:false,get(){const bound=fn.bind(this);Object.defineProperty(this,key,{configurable:true,writable:true,enumerable:true,value:bound});return bound},set(v){Object.defineProperty(this,key,{configurable:true,writable:true,enumerable:true,value:v})}})}}function string2(params){return _string(ZodString,params)}function email2(params){return _email(ZodEmail,params)}function guid2(params){return _guid(ZodGUID,params)}function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:regexes_exports.httpProtocol,hostname:regexes_exports.domain,...util_exports.normalizeParams(params)})}function emoji2(params){return _emoji2(ZodEmoji,params)}function nanoid2(params){return _nanoid(ZodNanoID,params)}function cuid3(params){return _cuid(ZodCUID,params)}function cuid22(params){return _cuid2(ZodCUID2,params)}function ulid2(params){return _ulid(ZodULID,params)}function xid2(params){return _xid(ZodXID,params)}function ksuid2(params){return _ksuid(ZodKSUID,params)}function ipv42(params){return _ipv4(ZodIPv4,params)}function mac2(params){return _mac(ZodMAC,params)}function ipv62(params){return _ipv6(ZodIPv6,params)}function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}function base642(params){return _base64(ZodBase64,params)}function base64url3(params){return _base64url(ZodBase64URL,params)}function e1642(params){return _e164(ZodE164,params)}function jwt(params){return _jwt(ZodJWT,params)}function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname4(_params){return _stringFormat(ZodCustomStringFormat,"hostname",regexes_exports.hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",regexes_exports.hex,_params)}function hash(alg,params){const enc7=params?.enc??"hex";const format=`${alg}_${enc7}`;const regex=regexes_exports[format];if(!regex)throw new Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}function number2(params){return _number(ZodNumber,params)}function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}function boolean2(params){return _boolean(ZodBoolean,params)}function bigint2(params){return _bigint(ZodBigInt,params)}function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}function symbol(params){return _symbol(ZodSymbol,params)}function _undefined3(params){return _undefined2(ZodUndefined,params)}function _null3(params){return _null2(ZodNull,params)}function any(){return _any(ZodAny)}function unknown(){return _unknown(ZodUnknown)}function never(params){return _never(ZodNever,params)}function _void2(params){return _void(ZodVoid,params)}function date3(params){return _date(ZodDate,params)}function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){const shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}function object(shape,params){const def={type:"object",shape:shape??{},...util_exports.normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...util_exports.normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...util_exports.normalizeParams(params)})}function union2(options,params){return new ZodUnion({type:"union",options,...util_exports.normalizeParams(params)})}function xor(options,params){return new ZodXor({type:"union",options,inclusive:false,...util_exports.normalizeParams(params)})}function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...util_exports.normalizeParams(params)})}function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}function tuple(items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new ZodTuple({type:"tuple",items,rest,...util_exports.normalizeParams(params)})}function record(keyType,valueType,params){if(!valueType||!valueType._zod){return new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...util_exports.normalizeParams(valueType)})}return new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params)})}function partialRecord(keyType,valueType,params){const k=clone(keyType);k._zod.values=void 0;return new ZodRecord({type:"record",keyType:k,valueType,...util_exports.normalizeParams(params)})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...util_exports.normalizeParams(params)})}function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...util_exports.normalizeParams(params)})}function set2(valueType,params){return new ZodSet({type:"set",valueType,...util_exports.normalizeParams(params)})}function _enum2(values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map(v=>[v,v])):values;return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...util_exports.normalizeParams(params)})}function file(params){return _file(ZodFile,params)}function transform(fn){return new ZodTransform({type:"transform",transform:fn})}function optional(innerType){return new ZodOptional({type:"optional",innerType})}function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...util_exports.normalizeParams(params)})}function success(innerType){return new ZodSuccess({type:"success",innerType})}function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function nan(params){return _nan(ZodNaN,params)}function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){const def=codec2._zod.def;return new ZodCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...util_exports.normalizeParams(params)})}function lazy(getter){return new ZodLazy({type:"lazy",getter})}function promise(innerType){return new ZodPromise({type:"promise",innerType})}function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}function check(fn){const ch=new $ZodCheck({check:"custom"});ch._zod.check=fn;return ch}function custom(fn,_params){return _custom(ZodCustom,fn??(()=>true),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}function _instanceof(cls,params={}){const inst=new ZodCustom({type:"custom",check:"custom",fn:data=>data instanceof cls,abort:true,...util_exports.normalizeParams(params)});inst._zod.bag.Class=cls;inst._zod.check=payload=>{if(!(payload.value instanceof cls)){payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})}};return inst}function json(params){const jsonSchema=lazy(()=>{return union2([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)])});return jsonSchema}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var _installedGroups,ZodType,_ZodString,ZodString,ZodStringFormat,ZodEmail,ZodGUID,ZodUUID,ZodURL,ZodEmoji,ZodNanoID,ZodCUID,ZodCUID2,ZodULID,ZodXID,ZodKSUID,ZodIPv4,ZodMAC,ZodIPv6,ZodCIDRv4,ZodCIDRv6,ZodBase64,ZodBase64URL,ZodE164,ZodJWT,ZodCustomStringFormat,ZodNumber,ZodNumberFormat,ZodBoolean,ZodBigInt,ZodBigIntFormat,ZodSymbol,ZodUndefined,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodVoid,ZodDate,ZodArray,ZodObject,ZodUnion,ZodXor,ZodDiscriminatedUnion,ZodIntersection,ZodTuple,ZodRecord,ZodMap,ZodSet,ZodEnum,ZodLiteral,ZodFile,ZodTransform,ZodOptional,ZodExactOptional,ZodNullable,ZodDefault,ZodPrefault,ZodNonOptional,ZodSuccess,ZodCatch,ZodNaN,ZodPipe,ZodCodec,ZodPreprocess,ZodReadonly,ZodTemplateLiteral,ZodLazy,ZodPromise,ZodFunction,ZodCustom,describe2,meta2,stringbool;var init_schemas2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js"(){init_core2();init_core2();init_json_schema_processors();init_to_json_schema();init_checks2();init_iso();init_parse2();_installedGroups=new WeakMap;ZodType=$constructor("ZodType",(inst,def)=>{$ZodType.init(inst,def);Object.assign(inst["~standard"],{jsonSchema:{input:createStandardJSONSchemaMethod(inst,"input"),output:createStandardJSONSchemaMethod(inst,"output")}});inst.toJSONSchema=createToJSONSchemaMethod(inst,{});inst.def=def;inst.type=def.type;Object.defineProperty(inst,"_def",{value:def});inst.parse=(data,params)=>parse2(inst,data,params,{callee:inst.parse});inst.safeParse=(data,params)=>safeParse2(inst,data,params);inst.parseAsync=async(data,params)=>parseAsync2(inst,data,params,{callee:inst.parseAsync});inst.safeParseAsync=async(data,params)=>safeParseAsync2(inst,data,params);inst.spa=inst.safeParseAsync;inst.encode=(data,params)=>encode3(inst,data,params);inst.decode=(data,params)=>decode4(inst,data,params);inst.encodeAsync=async(data,params)=>encodeAsync2(inst,data,params);inst.decodeAsync=async(data,params)=>decodeAsync2(inst,data,params);inst.safeEncode=(data,params)=>safeEncode2(inst,data,params);inst.safeDecode=(data,params)=>safeDecode2(inst,data,params);inst.safeEncodeAsync=async(data,params)=>safeEncodeAsync2(inst,data,params);inst.safeDecodeAsync=async(data,params)=>safeDecodeAsync2(inst,data,params);_installLazyMethods(inst,"ZodType",{check(...chks){const def2=this.def;return this.clone(util_exports.mergeDefs(def2,{checks:[...def2.checks??[],...chks.map(ch=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:true})},with(...chks){return this.check(...chks)},clone(def2,params){return clone(this,def2,params)},brand(){return this},register(reg,meta3){reg.add(this,meta3);return this},refine(check2,params){return this.check(refine(check2,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union2([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default2(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch2(this,params)},pipe(target2){return pipe(this,target2)},readonly(){return readonly(this)},describe(description){const cl=this.clone();globalRegistry.add(cl,{description});return cl},meta(...args){if(args.length===0)return globalRegistry.get(this);const cl=this.clone();globalRegistry.add(cl,args[0]);return cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn){return fn(this)}});Object.defineProperty(inst,"description",{get(){return globalRegistry.get(inst)?.description},configurable:true});return inst});_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>stringProcessor(inst,ctx,json2,params);const bag=inst._zod.bag;inst.format=bag.format??null;inst.minLength=bag.minimum??null;inst.maxLength=bag.maximum??null;_installLazyMethods(inst,"_ZodString",{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})});ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def);_ZodString.init(inst,def);inst.email=params=>inst.check(_email(ZodEmail,params));inst.url=params=>inst.check(_url(ZodURL,params));inst.jwt=params=>inst.check(_jwt(ZodJWT,params));inst.emoji=params=>inst.check(_emoji2(ZodEmoji,params));inst.guid=params=>inst.check(_guid(ZodGUID,params));inst.uuid=params=>inst.check(_uuid(ZodUUID,params));inst.uuidv4=params=>inst.check(_uuidv4(ZodUUID,params));inst.uuidv6=params=>inst.check(_uuidv6(ZodUUID,params));inst.uuidv7=params=>inst.check(_uuidv7(ZodUUID,params));inst.nanoid=params=>inst.check(_nanoid(ZodNanoID,params));inst.guid=params=>inst.check(_guid(ZodGUID,params));inst.cuid=params=>inst.check(_cuid(ZodCUID,params));inst.cuid2=params=>inst.check(_cuid2(ZodCUID2,params));inst.ulid=params=>inst.check(_ulid(ZodULID,params));inst.base64=params=>inst.check(_base64(ZodBase64,params));inst.base64url=params=>inst.check(_base64url(ZodBase64URL,params));inst.xid=params=>inst.check(_xid(ZodXID,params));inst.ksuid=params=>inst.check(_ksuid(ZodKSUID,params));inst.ipv4=params=>inst.check(_ipv4(ZodIPv4,params));inst.ipv6=params=>inst.check(_ipv6(ZodIPv6,params));inst.cidrv4=params=>inst.check(_cidrv4(ZodCIDRv4,params));inst.cidrv6=params=>inst.check(_cidrv6(ZodCIDRv6,params));inst.e164=params=>inst.check(_e164(ZodE164,params));inst.datetime=params=>inst.check(datetime2(params));inst.date=params=>inst.check(date2(params));inst.time=params=>inst.check(time2(params));inst.duration=params=>inst.check(duration2(params))});ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def);_ZodString.init(inst,def)});ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def);ZodStringFormat.init(inst,def)});ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def);ZodStringFormat.init(inst,def)});ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def);ZodStringFormat.init(inst,def)});ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def);ZodStringFormat.init(inst,def)});ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def);ZodStringFormat.init(inst,def)});ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def);ZodStringFormat.init(inst,def)});ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def);ZodStringFormat.init(inst,def)});ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def);ZodStringFormat.init(inst,def)});ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def);ZodStringFormat.init(inst,def)});ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def);ZodStringFormat.init(inst,def)});ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def);ZodStringFormat.init(inst,def)});ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def);ZodStringFormat.init(inst,def)});ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def);ZodStringFormat.init(inst,def)});ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def);ZodStringFormat.init(inst,def)});ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def);ZodStringFormat.init(inst,def)});ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def);ZodStringFormat.init(inst,def)});ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def);ZodStringFormat.init(inst,def)});ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def);ZodStringFormat.init(inst,def)});ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def);ZodStringFormat.init(inst,def)});ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def);ZodStringFormat.init(inst,def)});ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def);ZodStringFormat.init(inst,def)});ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>numberProcessor(inst,ctx,json2,params);_installLazyMethods(inst,"ZodNumber",{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}});const bag=inst._zod.bag;inst.minValue=Math.max(bag.minimum??Number.NEGATIVE_INFINITY,bag.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null;inst.maxValue=Math.min(bag.maximum??Number.POSITIVE_INFINITY,bag.exclusiveMaximum??Number.POSITIVE_INFINITY)??null;inst.isInt=(bag.format??"").includes("int")||Number.isSafeInteger(bag.multipleOf??.5);inst.isFinite=true;inst.format=bag.format??null});ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def);ZodNumber.init(inst,def)});ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>booleanProcessor(inst,ctx,json2,params)});ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>bigintProcessor(inst,ctx,json2,params);inst.gte=(value,params)=>inst.check(_gte(value,params));inst.min=(value,params)=>inst.check(_gte(value,params));inst.gt=(value,params)=>inst.check(_gt(value,params));inst.gte=(value,params)=>inst.check(_gte(value,params));inst.min=(value,params)=>inst.check(_gte(value,params));inst.lt=(value,params)=>inst.check(_lt(value,params));inst.lte=(value,params)=>inst.check(_lte(value,params));inst.max=(value,params)=>inst.check(_lte(value,params));inst.positive=params=>inst.check(_gt(BigInt(0),params));inst.negative=params=>inst.check(_lt(BigInt(0),params));inst.nonpositive=params=>inst.check(_lte(BigInt(0),params));inst.nonnegative=params=>inst.check(_gte(BigInt(0),params));inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params));const bag=inst._zod.bag;inst.minValue=bag.minimum??null;inst.maxValue=bag.maximum??null;inst.format=bag.format??null});ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def);ZodBigInt.init(inst,def)});ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>symbolProcessor(inst,ctx,json2,params)});ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>undefinedProcessor(inst,ctx,json2,params)});ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nullProcessor(inst,ctx,json2,params)});ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>anyProcessor(inst,ctx,json2,params)});ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unknownProcessor(inst,ctx,json2,params)});ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>neverProcessor(inst,ctx,json2,params)});ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>voidProcessor(inst,ctx,json2,params)});ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>dateProcessor(inst,ctx,json2,params);inst.min=(value,params)=>inst.check(_gte(value,params));inst.max=(value,params)=>inst.check(_lte(value,params));const c=inst._zod.bag;inst.minDate=c.minimum?new Date(c.minimum):null;inst.maxDate=c.maximum?new Date(c.maximum):null});ZodArray=$constructor("ZodArray",(inst,def)=>{$ZodArray.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>arrayProcessor(inst,ctx,json2,params);inst.element=def.element;_installLazyMethods(inst,"ZodArray",{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}})});ZodObject=$constructor("ZodObject",(inst,def)=>{$ZodObjectJIT.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>objectProcessor(inst,ctx,json2,params);util_exports.defineLazy(inst,"shape",()=>{return def.shape});_installLazyMethods(inst,"ZodObject",{keyof(){return _enum2(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone({...this._zod.def,catchall})},passthrough(){return this.clone({...this._zod.def,catchall:unknown()})},loose(){return this.clone({...this._zod.def,catchall:unknown()})},strict(){return this.clone({...this._zod.def,catchall:never()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(incoming){return util_exports.extend(this,incoming)},safeExtend(incoming){return util_exports.safeExtend(this,incoming)},merge(other){return util_exports.merge(this,other)},pick(mask){return util_exports.pick(this,mask)},omit(mask){return util_exports.omit(this,mask)},partial(...args){return util_exports.partial(ZodOptional,this,args[0])},required(...args){return util_exports.required(ZodNonOptional,this,args[0])}})});ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params);inst.options=def.options});ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def);$ZodXor.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params);inst.options=def.options});ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def);$ZodDiscriminatedUnion.init(inst,def)});ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>intersectionProcessor(inst,ctx,json2,params)});ZodTuple=$constructor("ZodTuple",(inst,def)=>{$ZodTuple.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>tupleProcessor(inst,ctx,json2,params);inst.rest=rest=>inst.clone({...inst._zod.def,rest})});ZodRecord=$constructor("ZodRecord",(inst,def)=>{$ZodRecord.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>recordProcessor(inst,ctx,json2,params);inst.keyType=def.keyType;inst.valueType=def.valueType});ZodMap=$constructor("ZodMap",(inst,def)=>{$ZodMap.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>mapProcessor(inst,ctx,json2,params);inst.keyType=def.keyType;inst.valueType=def.valueType;inst.min=(...args)=>inst.check(_minSize(...args));inst.nonempty=params=>inst.check(_minSize(1,params));inst.max=(...args)=>inst.check(_maxSize(...args));inst.size=(...args)=>inst.check(_size(...args))});ZodSet=$constructor("ZodSet",(inst,def)=>{$ZodSet.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>setProcessor(inst,ctx,json2,params);inst.min=(...args)=>inst.check(_minSize(...args));inst.nonempty=params=>inst.check(_minSize(1,params));inst.max=(...args)=>inst.check(_maxSize(...args));inst.size=(...args)=>inst.check(_size(...args))});ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>enumProcessor(inst,ctx,json2,params);inst.enum=def.entries;inst.options=Object.values(def.entries);const keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{const newEntries={};for(const value of values){if(keys.has(value)){newEntries[value]=def.entries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})};inst.exclude=(values,params)=>{const newEntries={...def.entries};for(const value of values){if(keys.has(value)){delete newEntries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})}});ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>literalProcessor(inst,ctx,json2,params);inst.values=new Set(def.values);Object.defineProperty(inst,"value",{get(){if(def.values.length>1){throw new Error("This schema contains multiple valid literal values. Use `.values` instead.")}return def.values[0]}})});ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>fileProcessor(inst,ctx,json2,params);inst.min=(size,params)=>inst.check(_minSize(size,params));inst.max=(size,params)=>inst.check(_maxSize(size,params));inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});ZodTransform=$constructor("ZodTransform",(inst,def)=>{$ZodTransform.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>transformProcessor(inst,ctx,json2,params);inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward"){throw new $ZodEncodeError(inst.constructor.name)}payload.addIssue=issue2=>{if(typeof issue2==="string"){payload.issues.push(util_exports.issue(issue2,payload.value,def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");_issue.input??(_issue.input=payload.value);_issue.inst??(_issue.inst=inst);payload.issues.push(util_exports.issue(_issue))}};const output=def.transform(payload.value,payload);if(output instanceof Promise){return output.then(output2=>{payload.value=output2;payload.fallback=true;return payload})}payload.value=output;payload.fallback=true;return payload}});ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nullableProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>defaultProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType;inst.removeDefault=inst.unwrap});ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>prefaultProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nonoptionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>successProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>catchProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType;inst.removeCatch=inst.unwrap});ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nanProcessor(inst,ctx,json2,params)});ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>pipeProcessor(inst,ctx,json2,params);inst.in=def.in;inst.out=def.out});ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def);$ZodCodec.init(inst,def)});ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def);$ZodPreprocess.init(inst,def)});ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>readonlyProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>templateLiteralProcessor(inst,ctx,json2,params)});ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>lazyProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.getter()});ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>promiseProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>functionProcessor(inst,ctx,json2,params)});ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>customProcessor(inst,ctx,json2,params)});describe2=describe;meta2=meta;stringbool=(...args)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args)}});function setErrorMap(map2){config({customError:map2})}function getErrorMap(){return config().customError}var ZodIssueCode,ZodFirstPartyTypeKind;var init_compat=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js"(){init_core2();ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};(function(ZodFirstPartyTypeKind2){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}))}});function detectVersion(schema,defaultTarget){const $schema=schema.$schema;if($schema==="https://json-schema.org/draft/2020-12/schema"){return"draft-2020-12"}if($schema==="http://json-schema.org/draft-07/schema#"){return"draft-7"}if($schema==="http://json-schema.org/draft-04/schema#"){return"draft-4"}return defaultTarget??"draft-2020-12"}function resolveRef(ref,ctx){if(!ref.startsWith("#")){throw new Error("External $ref is not supported, only local refs (#/...) are allowed")}const path=ref.slice(1).split("/").filter(Boolean);if(path.length===0){return ctx.rootSchema}const defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path[0]===defsKey){const key=path[1];if(!key||!ctx.defs[key]){throw new Error(`Reference not found: ${ref}`)}return ctx.defs[key]}throw new Error(`Reference not found: ${ref}`)}function convertBaseSchema(schema,ctx){if(schema.not!==void 0){if(typeof schema.not==="object"&&Object.keys(schema.not).length===0){return z.never()}throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==void 0){throw new Error("unevaluatedItems is not supported")}if(schema.unevaluatedProperties!==void 0){throw new Error("unevaluatedProperties is not supported")}if(schema.if!==void 0||schema.then!==void 0||schema.else!==void 0){throw new Error("Conditional schemas (if/then/else) are not supported")}if(schema.dependentSchemas!==void 0||schema.dependentRequired!==void 0){throw new Error("dependentSchemas and dependentRequired are not supported")}if(schema.$ref){const refPath=schema.$ref;if(ctx.refs.has(refPath)){return ctx.refs.get(refPath)}if(ctx.processing.has(refPath)){return z.lazy(()=>{if(!ctx.refs.has(refPath)){throw new Error(`Circular reference not resolved: ${refPath}`)}return ctx.refs.get(refPath)})}ctx.processing.add(refPath);const resolved=resolveRef(refPath,ctx);const zodSchema2=convertSchema(resolved,ctx);ctx.refs.set(refPath,zodSchema2);ctx.processing.delete(refPath);return zodSchema2}if(schema.enum!==void 0){const enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===true&&enumValues.length===1&&enumValues[0]===null){return z.null()}if(enumValues.length===0){return z.never()}if(enumValues.length===1){return z.literal(enumValues[0])}if(enumValues.every(v=>typeof v==="string")){return z.enum(enumValues)}const literalSchemas=enumValues.map(v=>z.literal(v));if(literalSchemas.length<2){return literalSchemas[0]}return z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==void 0){return z.literal(schema.const)}const type=schema.type;if(Array.isArray(type)){const typeSchemas=type.map(t=>{const typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});if(typeSchemas.length===0){return z.never()}if(typeSchemas.length===1){return typeSchemas[0]}return z.union(typeSchemas)}if(!type){return z.any()}let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){const format=schema.format;if(format==="email"){stringSchema=stringSchema.check(z.email())}else if(format==="uri"||format==="uri-reference"){stringSchema=stringSchema.check(z.url())}else if(format==="uuid"||format==="guid"){stringSchema=stringSchema.check(z.uuid())}else if(format==="date-time"){stringSchema=stringSchema.check(z.iso.datetime())}else if(format==="date"){stringSchema=stringSchema.check(z.iso.date())}else if(format==="time"){stringSchema=stringSchema.check(z.iso.time())}else if(format==="duration"){stringSchema=stringSchema.check(z.iso.duration())}else if(format==="ipv4"){stringSchema=stringSchema.check(z.ipv4())}else if(format==="ipv6"){stringSchema=stringSchema.check(z.ipv6())}else if(format==="mac"){stringSchema=stringSchema.check(z.mac())}else if(format==="cidr"){stringSchema=stringSchema.check(z.cidrv4())}else if(format==="cidr-v6"){stringSchema=stringSchema.check(z.cidrv6())}else if(format==="base64"){stringSchema=stringSchema.check(z.base64())}else if(format==="base64url"){stringSchema=stringSchema.check(z.base64url())}else if(format==="e164"){stringSchema=stringSchema.check(z.e164())}else if(format==="jwt"){stringSchema=stringSchema.check(z.jwt())}else if(format==="emoji"){stringSchema=stringSchema.check(z.emoji())}else if(format==="nanoid"){stringSchema=stringSchema.check(z.nanoid())}else if(format==="cuid"){stringSchema=stringSchema.check(z.cuid())}else if(format==="cuid2"){stringSchema=stringSchema.check(z.cuid2())}else if(format==="ulid"){stringSchema=stringSchema.check(z.ulid())}else if(format==="xid"){stringSchema=stringSchema.check(z.xid())}else if(format==="ksuid"){stringSchema=stringSchema.check(z.ksuid())}}if(typeof schema.minLength==="number"){stringSchema=stringSchema.min(schema.minLength)}if(typeof schema.maxLength==="number"){stringSchema=stringSchema.max(schema.maxLength)}if(schema.pattern){stringSchema=stringSchema.regex(new RegExp(schema.pattern))}zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();if(typeof schema.minimum==="number"){numberSchema=numberSchema.min(schema.minimum)}if(typeof schema.maximum==="number"){numberSchema=numberSchema.max(schema.maximum)}if(typeof schema.exclusiveMinimum==="number"){numberSchema=numberSchema.gt(schema.exclusiveMinimum)}else if(schema.exclusiveMinimum===true&&typeof schema.minimum==="number"){numberSchema=numberSchema.gt(schema.minimum)}if(typeof schema.exclusiveMaximum==="number"){numberSchema=numberSchema.lt(schema.exclusiveMaximum)}else if(schema.exclusiveMaximum===true&&typeof schema.maximum==="number"){numberSchema=numberSchema.lt(schema.maximum)}if(typeof schema.multipleOf==="number"){numberSchema=numberSchema.multipleOf(schema.multipleOf)}zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{const shape={};const properties=schema.properties||{};const requiredSet=new Set(schema.required||[]);for(const[key,propSchema]of Object.entries(properties)){const propZodSchema=convertSchema(propSchema,ctx);shape[key]=requiredSet.has(key)?propZodSchema:propZodSchema.optional()}if(schema.propertyNames){const keySchema=convertSchema(schema.propertyNames,ctx);const valueSchema=schema.additionalProperties&&typeof schema.additionalProperties==="object"?convertSchema(schema.additionalProperties,ctx):z.any();if(Object.keys(shape).length===0){zodSchema=z.record(keySchema,valueSchema);break}const objectSchema2=z.object(shape).passthrough();const recordSchema=z.looseRecord(keySchema,valueSchema);zodSchema=z.intersection(objectSchema2,recordSchema);break}if(schema.patternProperties){const patternProps=schema.patternProperties;const patternKeys=Object.keys(patternProps);const looseRecords=[];for(const pattern of patternKeys){const patternValue=convertSchema(patternProps[pattern],ctx);const keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}const schemasToIntersect=[];if(Object.keys(shape).length>0){schemasToIntersect.push(z.object(shape).passthrough())}schemasToIntersect.push(...looseRecords);if(schemasToIntersect.length===0){zodSchema=z.object({}).passthrough()}else if(schemasToIntersect.length===1){zodSchema=schemasToIntersect[0]}else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++){result=z.intersection(result,schemasToIntersect[i])}zodSchema=result}break}const objectSchema=z.object(shape);if(schema.additionalProperties===false){zodSchema=objectSchema.strict()}else if(typeof schema.additionalProperties==="object"){zodSchema=objectSchema.catchall(convertSchema(schema.additionalProperties,ctx))}else{zodSchema=objectSchema.passthrough()}break}case"array":{const prefixItems=schema.prefixItems;const items=schema.items;if(prefixItems&&Array.isArray(prefixItems)){const tupleItems=prefixItems.map(item=>convertSchema(item,ctx));const rest=items&&typeof items==="object"&&!Array.isArray(items)?convertSchema(items,ctx):void 0;if(rest){zodSchema=z.tuple(tupleItems).rest(rest)}else{zodSchema=z.tuple(tupleItems)}if(typeof schema.minItems==="number"){zodSchema=zodSchema.check(z.minLength(schema.minItems))}if(typeof schema.maxItems==="number"){zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}}else if(Array.isArray(items)){const tupleItems=items.map(item=>convertSchema(item,ctx));const rest=schema.additionalItems&&typeof schema.additionalItems==="object"?convertSchema(schema.additionalItems,ctx):void 0;if(rest){zodSchema=z.tuple(tupleItems).rest(rest)}else{zodSchema=z.tuple(tupleItems)}if(typeof schema.minItems==="number"){zodSchema=zodSchema.check(z.minLength(schema.minItems))}if(typeof schema.maxItems==="number"){zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}}else if(items!==void 0){const element=convertSchema(items,ctx);let arraySchema=z.array(element);if(typeof schema.minItems==="number"){arraySchema=arraySchema.min(schema.minItems)}if(typeof schema.maxItems==="number"){arraySchema=arraySchema.max(schema.maxItems)}zodSchema=arraySchema}else{zodSchema=z.array(z.any())}break}default:throw new Error(`Unsupported type: ${type}`)}return zodSchema}function convertSchema(schema,ctx){if(typeof schema==="boolean"){return schema?z.any():z.never()}let baseSchema=convertBaseSchema(schema,ctx);const hasExplicitType=schema.type||schema.enum!==void 0||schema.const!==void 0;if(schema.anyOf&&Array.isArray(schema.anyOf)){const options=schema.anyOf.map(s=>convertSchema(s,ctx));const anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){const options=schema.oneOf.map(s=>convertSchema(s,ctx));const oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf)){if(schema.allOf.length===0){baseSchema=hasExplicitType?baseSchema:z.any()}else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx);const startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++){result=z.intersection(result,convertSchema(schema.allOf[i],ctx))}baseSchema=result}}if(schema.nullable===true&&ctx.version==="openapi-3.0"){baseSchema=z.nullable(baseSchema)}if(schema.readOnly===true){baseSchema=z.readonly(baseSchema)}if(schema.default!==void 0){baseSchema=baseSchema.default(schema.default)}const extraMeta={};const coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(const key of coreMetadataKeys){if(key in schema){extraMeta[key]=schema[key]}}const contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(const key of contentMetadataKeys){if(key in schema){extraMeta[key]=schema[key]}}for(const key of Object.keys(schema)){if(!RECOGNIZED_KEYS.has(key)){extraMeta[key]=schema[key]}}if(Object.keys(extraMeta).length>0){ctx.registry.add(baseSchema,extraMeta)}if(schema.description){baseSchema=baseSchema.describe(schema.description)}return baseSchema}function fromJSONSchema(schema,params){if(typeof schema==="boolean"){return schema?z.any():z.never()}let normalized;try{normalized=JSON.parse(JSON.stringify(schema))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}const version2=detectVersion(normalized,params?.defaultTarget);const defs=normalized.$defs||normalized.definitions||{};const ctx={version:version2,defs,refs:new Map,processing:new Set,rootSchema:normalized,registry:params?.registry??globalRegistry};return convertSchema(normalized,ctx)}var z,RECOGNIZED_KEYS;var init_from_json_schema=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js"(){init_registries();init_checks2();init_iso();init_schemas2();z={...schemas_exports2,...checks_exports2,iso:iso_exports};RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"])}});var coerce_exports={};__export(coerce_exports,{bigint:()=>bigint3,boolean:()=>boolean3,date:()=>date4,number:()=>number3,string:()=>string3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}var init_coerce=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js"(){init_core2();init_schemas2()}});var external_exports={};__export(external_exports,{$brand:()=>$brand,$input:()=>$input,$output:()=>$output,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodError:()=>ZodError,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodIntersection:()=>ZodIntersection,ZodIssueCode:()=>ZodIssueCode,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRealError:()=>ZodRealError,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url3,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,clone:()=>clone,codec:()=>codec,coerce:()=>coerce_exports,config:()=>config,core:()=>core_exports2,cuid:()=>cuid3,cuid2:()=>cuid22,custom:()=>custom,date:()=>date3,decode:()=>decode4,decodeAsync:()=>decodeAsync2,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,encode:()=>encode3,encodeAsync:()=>encodeAsync2,endsWith:()=>_endsWith,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,flattenError:()=>flattenError,float32:()=>float32,float64:()=>float64,formatError:()=>formatError,fromJSONSchema:()=>fromJSONSchema,function:()=>_function,getErrorMap:()=>getErrorMap,globalRegistry:()=>globalRegistry,gt:()=>_gt,gte:()=>_gte,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname4,httpUrl:()=>httpUrl,includes:()=>_includes,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,iso:()=>iso_exports,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,length:()=>_length,literal:()=>literal,locales:()=>locales_exports,looseObject:()=>looseObject,looseRecord:()=>looseRecord,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,mac:()=>mac2,map:()=>map,maxLength:()=>_maxLength,maxSize:()=>_maxSize,meta:()=>meta2,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,negative:()=>_negative,never:()=>never,nonnegative:()=>_nonnegative,nonoptional:()=>nonoptional,nonpositive:()=>_nonpositive,normalize:()=>_normalize,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,overwrite:()=>_overwrite,parse:()=>parse2,parseAsync:()=>parseAsync2,partialRecord:()=>partialRecord,pipe:()=>pipe,positive:()=>_positive,prefault:()=>prefault,preprocess:()=>preprocess,prettifyError:()=>prettifyError,promise:()=>promise,property:()=>_property,readonly:()=>readonly,record:()=>record,refine:()=>refine,regex:()=>_regex,regexes:()=>regexes_exports,registry:()=>registry3,safeDecode:()=>safeDecode2,safeDecodeAsync:()=>safeDecodeAsync2,safeEncode:()=>safeEncode2,safeEncodeAsync:()=>safeEncodeAsync2,safeParse:()=>safeParse2,safeParseAsync:()=>safeParseAsync2,set:()=>set2,setErrorMap:()=>setErrorMap,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,toJSONSchema:()=>toJSONSchema,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,transform:()=>transform,treeifyError:()=>treeifyError,trim:()=>_trim,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union2,unknown:()=>unknown,uppercase:()=>_uppercase,url:()=>url,util:()=>util_exports,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor});var init_external=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js"(){init_core2();init_schemas2();init_checks2();init_errors2();init_parse2();init_compat();init_core2();init_en();init_core2();init_json_schema_processors();init_from_json_schema();init_locales();init_iso();init_iso();init_coerce();config(en_default())}});var init_classic=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/index.js"(){init_external()}});var init_v4=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/index.js"(){init_classic()}});var RELATED_TASK_META_KEY,JSONRPC_VERSION,AssertObjectSchema,ProgressTokenSchema,CursorSchema,TaskCreationParamsSchema,TaskMetadataSchema,RelatedTaskMetadataSchema,RequestMetaSchema,BaseRequestParamsSchema,TaskAugmentedRequestParamsSchema,RequestSchema,NotificationsParamsSchema,NotificationSchema,ResultSchema,RequestIdSchema,JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,ErrorCode,JSONRPCErrorResponseSchema,JSONRPCMessageSchema,JSONRPCResponseSchema,EmptyResultSchema,CancelledNotificationParamsSchema,CancelledNotificationSchema,IconSchema,IconsSchema,BaseMetadataSchema,ImplementationSchema,FormElicitationCapabilitySchema,ElicitationCapabilitySchema,ClientTasksCapabilitySchema,ServerTasksCapabilitySchema,ClientCapabilitiesSchema,InitializeRequestParamsSchema,InitializeRequestSchema,ServerCapabilitiesSchema,InitializeResultSchema,InitializedNotificationSchema,PingRequestSchema,ProgressSchema,ProgressNotificationParamsSchema,ProgressNotificationSchema,PaginatedRequestParamsSchema,PaginatedRequestSchema,PaginatedResultSchema,TaskStatusSchema,TaskSchema,CreateTaskResultSchema,TaskStatusNotificationParamsSchema,TaskStatusNotificationSchema,GetTaskRequestSchema,GetTaskResultSchema,GetTaskPayloadRequestSchema,GetTaskPayloadResultSchema,ListTasksRequestSchema,ListTasksResultSchema,CancelTaskRequestSchema,CancelTaskResultSchema,ResourceContentsSchema,TextResourceContentsSchema,Base64Schema,BlobResourceContentsSchema,RoleSchema,AnnotationsSchema,ResourceSchema,ResourceTemplateSchema,ListResourcesRequestSchema,ListResourcesResultSchema,ListResourceTemplatesRequestSchema,ListResourceTemplatesResultSchema,ResourceRequestParamsSchema,ReadResourceRequestParamsSchema,ReadResourceRequestSchema,ReadResourceResultSchema,ResourceListChangedNotificationSchema,SubscribeRequestParamsSchema,SubscribeRequestSchema,UnsubscribeRequestParamsSchema,UnsubscribeRequestSchema,ResourceUpdatedNotificationParamsSchema,ResourceUpdatedNotificationSchema,PromptArgumentSchema,PromptSchema,ListPromptsRequestSchema,ListPromptsResultSchema,GetPromptRequestParamsSchema,GetPromptRequestSchema,TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,EmbeddedResourceSchema,ResourceLinkSchema,ContentBlockSchema,PromptMessageSchema,GetPromptResultSchema,PromptListChangedNotificationSchema,ToolAnnotationsSchema,ToolExecutionSchema,ToolSchema,ListToolsRequestSchema,ListToolsResultSchema,CallToolResultSchema,CompatibilityCallToolResultSchema,CallToolRequestParamsSchema,CallToolRequestSchema,ToolListChangedNotificationSchema,ListChangedOptionsBaseSchema,LoggingLevelSchema,SetLevelRequestParamsSchema,SetLevelRequestSchema,LoggingMessageNotificationParamsSchema,LoggingMessageNotificationSchema,ModelHintSchema,ModelPreferencesSchema,ToolChoiceSchema,ToolResultContentSchema,SamplingContentSchema,SamplingMessageContentBlockSchema,SamplingMessageSchema,CreateMessageRequestParamsSchema,CreateMessageRequestSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema,UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema,LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema,EnumSchemaSchema,PrimitiveSchemaDefinitionSchema,ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema,ElicitRequestParamsSchema,ElicitRequestSchema,ElicitationCompleteNotificationParamsSchema,ElicitationCompleteNotificationSchema,ElicitResultSchema,ResourceTemplateReferenceSchema,PromptReferenceSchema,CompleteRequestParamsSchema,CompleteRequestSchema,CompleteResultSchema,RootSchema,ListRootsRequestSchema,ListRootsResultSchema,RootsListChangedNotificationSchema,ClientRequestSchema,ClientNotificationSchema,ClientResultSchema,ServerRequestSchema,ServerNotificationSchema,ServerResultSchema;var init_types=__esm({"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js"(){init_v4();RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task";JSONRPC_VERSION="2.0";AssertObjectSchema=custom(v=>v!==null&&(typeof v==="object"||typeof v==="function"));ProgressTokenSchema=union2([string2(),number2().int()]);CursorSchema=string2();TaskCreationParamsSchema=looseObject({ttl:number2().optional(),pollInterval:number2().optional()});TaskMetadataSchema=object({ttl:number2().optional()});RelatedTaskMetadataSchema=object({taskId:string2()});RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()});BaseRequestParamsSchema=object({_meta:RequestMetaSchema.optional()});TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()});RequestSchema=object({method:string2(),params:BaseRequestParamsSchema.loose().optional()});NotificationsParamsSchema=object({_meta:RequestMetaSchema.optional()});NotificationSchema=object({method:string2(),params:NotificationsParamsSchema.loose().optional()});ResultSchema=looseObject({_meta:RequestMetaSchema.optional()});RequestIdSchema=union2([string2(),number2().int()]);JSONRPCRequestSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict();JSONRPCNotificationSchema=object({jsonrpc:literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict();JSONRPCResultResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict();(function(ErrorCode2){ErrorCode2[ErrorCode2["ConnectionClosed"]=-32e3]="ConnectionClosed";ErrorCode2[ErrorCode2["RequestTimeout"]=-32001]="RequestTimeout";ErrorCode2[ErrorCode2["ParseError"]=-32700]="ParseError";ErrorCode2[ErrorCode2["InvalidRequest"]=-32600]="InvalidRequest";ErrorCode2[ErrorCode2["MethodNotFound"]=-32601]="MethodNotFound";ErrorCode2[ErrorCode2["InvalidParams"]=-32602]="InvalidParams";ErrorCode2[ErrorCode2["InternalError"]=-32603]="InternalError";ErrorCode2[ErrorCode2["UrlElicitationRequired"]=-32042]="UrlElicitationRequired"})(ErrorCode||(ErrorCode={}));JSONRPCErrorResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:object({code:number2().int(),message:string2(),data:unknown().optional()})}).strict();JSONRPCMessageSchema=union2([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]);JSONRPCResponseSchema=union2([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]);EmptyResultSchema=ResultSchema.strict();CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string2().optional()});CancelledNotificationSchema=NotificationSchema.extend({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema});IconSchema=object({src:string2(),mimeType:string2().optional(),sizes:array(string2()).optional(),theme:_enum2(["light","dark"]).optional()});IconsSchema=object({icons:array(IconSchema).optional()});BaseMetadataSchema=object({name:string2(),title:string2().optional()});ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string2(),websiteUrl:string2().optional(),description:string2().optional()});FormElicitationCapabilitySchema=intersection(object({applyDefaults:boolean2().optional()}),record(string2(),unknown()));ElicitationCapabilitySchema=preprocess(value=>{if(value&&typeof value==="object"&&!Array.isArray(value)){if(Object.keys(value).length===0){return{form:{}}}}return value},intersection(object({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),record(string2(),unknown()).optional()));ClientTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()});ServerTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({tools:looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()});ClientCapabilitiesSchema=object({experimental:record(string2(),AssertObjectSchema).optional(),sampling:object({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object({listChanged:boolean2().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string2(),AssertObjectSchema).optional()});InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string2(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema});InitializeRequestSchema=RequestSchema.extend({method:literal("initialize"),params:InitializeRequestParamsSchema});ServerCapabilitiesSchema=object({experimental:record(string2(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object({listChanged:boolean2().optional()}).optional(),resources:object({subscribe:boolean2().optional(),listChanged:boolean2().optional()}).optional(),tools:object({listChanged:boolean2().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string2(),AssertObjectSchema).optional()});InitializeResultSchema=ResultSchema.extend({protocolVersion:string2(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string2().optional()});InitializedNotificationSchema=NotificationSchema.extend({method:literal("notifications/initialized"),params:NotificationsParamsSchema.optional()});PingRequestSchema=RequestSchema.extend({method:literal("ping"),params:BaseRequestParamsSchema.optional()});ProgressSchema=object({progress:number2(),total:optional(number2()),message:optional(string2())});ProgressNotificationParamsSchema=object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema});ProgressNotificationSchema=NotificationSchema.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema});PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()});PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()});PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()});TaskStatusSchema=_enum2(["working","input_required","completed","failed","cancelled"]);TaskSchema=object({taskId:string2(),status:TaskStatusSchema,ttl:union2([number2(),_null3()]),createdAt:string2(),lastUpdatedAt:string2(),pollInterval:optional(number2()),statusMessage:optional(string2())});CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema});TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema);TaskStatusNotificationSchema=NotificationSchema.extend({method:literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema});GetTaskRequestSchema=RequestSchema.extend({method:literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:string2()})});GetTaskResultSchema=ResultSchema.merge(TaskSchema);GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:string2()})});GetTaskPayloadResultSchema=ResultSchema.loose();ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal("tasks/list")});ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array(TaskSchema)});CancelTaskRequestSchema=RequestSchema.extend({method:literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:string2()})});CancelTaskResultSchema=ResultSchema.merge(TaskSchema);ResourceContentsSchema=object({uri:string2(),mimeType:optional(string2()),_meta:record(string2(),unknown()).optional()});TextResourceContentsSchema=ResourceContentsSchema.extend({text:string2()});Base64Schema=string2().refine(val=>{try{atob(val);return true}catch{return false}},{message:"Invalid Base64 string"});BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema});RoleSchema=_enum2(["user","assistant"]);AnnotationsSchema=object({audience:array(RoleSchema).optional(),priority:number2().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:true}).optional()});ResourceSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string2(),description:optional(string2()),mimeType:optional(string2()),size:optional(number2()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))});ResourceTemplateSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))});ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/list")});ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array(ResourceSchema)});ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/templates/list")});ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array(ResourceTemplateSchema)});ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string2()});ReadResourceRequestParamsSchema=ResourceRequestParamsSchema;ReadResourceRequestSchema=RequestSchema.extend({method:literal("resources/read"),params:ReadResourceRequestParamsSchema});ReadResourceResultSchema=ResultSchema.extend({contents:array(union2([TextResourceContentsSchema,BlobResourceContentsSchema]))});ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()});SubscribeRequestParamsSchema=ResourceRequestParamsSchema;SubscribeRequestSchema=RequestSchema.extend({method:literal("resources/subscribe"),params:SubscribeRequestParamsSchema});UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema;UnsubscribeRequestSchema=RequestSchema.extend({method:literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema});ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string2()});ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema});PromptArgumentSchema=object({name:string2(),description:optional(string2()),required:optional(boolean2())});PromptSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string2()),arguments:optional(array(PromptArgumentSchema)),_meta:optional(looseObject({}))});ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal("prompts/list")});ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array(PromptSchema)});GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string2(),arguments:record(string2(),string2()).optional()});GetPromptRequestSchema=RequestSchema.extend({method:literal("prompts/get"),params:GetPromptRequestParamsSchema});TextContentSchema=object({type:literal("text"),text:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()});ImageContentSchema=object({type:literal("image"),data:Base64Schema,mimeType:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()});AudioContentSchema=object({type:literal("audio"),data:Base64Schema,mimeType:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()});ToolUseContentSchema=object({type:literal("tool_use"),name:string2(),id:string2(),input:record(string2(),unknown()),_meta:record(string2(),unknown()).optional()});EmbeddedResourceSchema=object({type:literal("resource"),resource:union2([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()});ResourceLinkSchema=ResourceSchema.extend({type:literal("resource_link")});ContentBlockSchema=union2([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]);PromptMessageSchema=object({role:RoleSchema,content:ContentBlockSchema});GetPromptResultSchema=ResultSchema.extend({description:string2().optional(),messages:array(PromptMessageSchema)});PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()});ToolAnnotationsSchema=object({title:string2().optional(),readOnlyHint:boolean2().optional(),destructiveHint:boolean2().optional(),idempotentHint:boolean2().optional(),openWorldHint:boolean2().optional()});ToolExecutionSchema=object({taskSupport:_enum2(["required","optional","forbidden"]).optional()});ToolSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string2().optional(),inputSchema:object({type:literal("object"),properties:record(string2(),AssertObjectSchema).optional(),required:array(string2()).optional()}).catchall(unknown()),outputSchema:object({type:literal("object"),properties:record(string2(),AssertObjectSchema).optional(),required:array(string2()).optional()}).catchall(unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string2(),unknown()).optional()});ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal("tools/list")});ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)});CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:record(string2(),unknown()).optional(),isError:boolean2().optional()});CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown()}));CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string2(),arguments:record(string2(),unknown()).optional()});CallToolRequestSchema=RequestSchema.extend({method:literal("tools/call"),params:CallToolRequestParamsSchema});ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()});ListChangedOptionsBaseSchema=object({autoRefresh:boolean2().default(true),debounceMs:number2().int().nonnegative().default(300)});LoggingLevelSchema=_enum2(["debug","info","notice","warning","error","critical","alert","emergency"]);SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema});SetLevelRequestSchema=RequestSchema.extend({method:literal("logging/setLevel"),params:SetLevelRequestParamsSchema});LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string2().optional(),data:unknown()});LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema});ModelHintSchema=object({name:string2().optional()});ModelPreferencesSchema=object({hints:array(ModelHintSchema).optional(),costPriority:number2().min(0).max(1).optional(),speedPriority:number2().min(0).max(1).optional(),intelligencePriority:number2().min(0).max(1).optional()});ToolChoiceSchema=object({mode:_enum2(["auto","required","none"]).optional()});ToolResultContentSchema=object({type:literal("tool_result"),toolUseId:string2().describe("The unique identifier for the corresponding tool call."),content:array(ContentBlockSchema).default([]),structuredContent:object({}).loose().optional(),isError:boolean2().optional(),_meta:record(string2(),unknown()).optional()});SamplingContentSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]);SamplingMessageContentBlockSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]);SamplingMessageSchema=object({role:RoleSchema,content:union2([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)]),_meta:record(string2(),unknown()).optional()});CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string2().optional(),includeContext:_enum2(["none","thisServer","allServers"]).optional(),temperature:number2().optional(),maxTokens:number2().int(),stopSequences:array(string2()).optional(),metadata:AssertObjectSchema.optional(),tools:array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()});CreateMessageRequestSchema=RequestSchema.extend({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema});CreateMessageResultSchema=ResultSchema.extend({model:string2(),stopReason:optional(_enum2(["endTurn","stopSequence","maxTokens"]).or(string2())),role:RoleSchema,content:SamplingContentSchema});CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string2(),stopReason:optional(_enum2(["endTurn","stopSequence","maxTokens","toolUse"]).or(string2())),role:RoleSchema,content:union2([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])});BooleanSchemaSchema=object({type:literal("boolean"),title:string2().optional(),description:string2().optional(),default:boolean2().optional()});StringSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),minLength:number2().optional(),maxLength:number2().optional(),format:_enum2(["email","uri","date","date-time"]).optional(),default:string2().optional()});NumberSchemaSchema=object({type:_enum2(["number","integer"]),title:string2().optional(),description:string2().optional(),minimum:number2().optional(),maximum:number2().optional(),default:number2().optional()});UntitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),default:string2().optional()});TitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),oneOf:array(object({const:string2(),title:string2()})),default:string2().optional()});LegacyTitledEnumSchemaSchema=object({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),enumNames:array(string2()).optional(),default:string2().optional()});SingleSelectEnumSchemaSchema=union2([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]);UntitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({type:literal("string"),enum:array(string2())}),default:array(string2()).optional()});TitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object({anyOf:array(object({const:string2(),title:string2()}))}),default:array(string2()).optional()});MultiSelectEnumSchemaSchema=union2([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]);EnumSchemaSchema=union2([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]);PrimitiveSchemaDefinitionSchema=union2([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]);ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("form").optional(),message:string2(),requestedSchema:object({type:literal("object"),properties:record(string2(),PrimitiveSchemaDefinitionSchema),required:array(string2()).optional()})});ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("url"),message:string2(),elicitationId:string2(),url:string2().url()});ElicitRequestParamsSchema=union2([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]);ElicitRequestSchema=RequestSchema.extend({method:literal("elicitation/create"),params:ElicitRequestParamsSchema});ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string2()});ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema});ElicitResultSchema=ResultSchema.extend({action:_enum2(["accept","decline","cancel"]),content:preprocess(val=>val===null?void 0:val,record(string2(),union2([string2(),number2(),boolean2(),array(string2())])).optional())});ResourceTemplateReferenceSchema=object({type:literal("ref/resource"),uri:string2()});PromptReferenceSchema=object({type:literal("ref/prompt"),name:string2()});CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union2([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object({name:string2(),value:string2()}),context:object({arguments:record(string2(),string2()).optional()}).optional()});CompleteRequestSchema=RequestSchema.extend({method:literal("completion/complete"),params:CompleteRequestParamsSchema});CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array(string2()).max(100),total:optional(number2().int()),hasMore:optional(boolean2())})});RootSchema=object({uri:string2().startsWith("file://"),name:string2().optional(),_meta:record(string2(),unknown()).optional()});ListRootsRequestSchema=RequestSchema.extend({method:literal("roots/list"),params:BaseRequestParamsSchema.optional()});ListRootsResultSchema=ResultSchema.extend({roots:array(RootSchema)});RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()});ClientRequestSchema=union2([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]);ClientNotificationSchema=union2([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]);ClientResultSchema=union2([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]);ServerRequestSchema=union2([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]);ServerNotificationSchema=union2([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]);ServerResultSchema=union2([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema])}});var require_draft7=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/draft7.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var core_1=require_core3();var validation_1=require_validation();var applicator_1=require_applicator();var format_1=require_format2();var metadata_1=require_metadata();var draft7Vocabularies=[core_1.default,validation_1.default,(0,applicator_1.default)(),format_1.default,metadata_1.metadataVocabulary,metadata_1.contentVocabulary];exports.default=draft7Vocabularies}});var require_json_schema_draft_07=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports,module2){module2.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:true,readOnly:{type:"boolean",default:false},examples:{type:"array",items:true},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:true},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:true,enum:{type:"array",items:true,minItems:1,uniqueItems:true},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:true}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:true}}});var require_ajv=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/ajv.js"(exports,module2){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv=void 0;var core_1=require_core2();var draft7_1=require_draft7();var discriminator_1=require_discriminator();var draft7MetaSchema=require_json_schema_draft_07();var META_SUPPORT_DATA=["/properties"];var META_SCHEMA_ID="http://json-schema.org/draft-07/schema";var Ajv=class extends core_1.default{_addVocabularies(){super._addVocabularies();draft7_1.default.forEach(v=>this.addVocabulary(v));if(this.opts.discriminator)this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();if(!this.opts.meta)return;const metaSchema=this.opts.$data?this.$dataMetaSchema(draft7MetaSchema,META_SUPPORT_DATA):draft7MetaSchema;this.addMetaSchema(metaSchema,META_SCHEMA_ID,false);this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0)}};exports.Ajv=Ajv;module2.exports=exports=Ajv;module2.exports.Ajv=Ajv;Object.defineProperty(exports,"__esModule",{value:true});exports.default=Ajv;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:true,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:true,get:function(){return codegen_1._}});Object.defineProperty(exports,"str",{enumerable:true,get:function(){return codegen_1.str}});Object.defineProperty(exports,"stringify",{enumerable:true,get:function(){return codegen_1.stringify}});Object.defineProperty(exports,"nil",{enumerable:true,get:function(){return codegen_1.nil}});Object.defineProperty(exports,"Name",{enumerable:true,get:function(){return codegen_1.Name}});Object.defineProperty(exports,"CodeGen",{enumerable:true,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports,"ValidationError",{enumerable:true,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports,"MissingRefError",{enumerable:true,get:function(){return ref_error_1.default}})}});var require_formats=__commonJS({"../../node_modules/.pnpm/ajv-formats@3.0.1/node_modules/ajv-formats/dist/formats.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.formatNames=exports.fastFormats=exports.fullFormats=void 0;function fmtDef(validate2,compare){return{validate:validate2,compare}}exports.fullFormats={date:fmtDef(date5,compareDate),time:fmtDef(getTime(true),compareTime),"date-time":fmtDef(getDateTime(true),compareDateTime),"iso-time":fmtDef(getTime(),compareIsoTime),"iso-date-time":fmtDef(getDateTime(),compareIsoDateTime),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte,int32:{type:"number",validate:validateInt32},int64:{type:"number",validate:validateInt64},float:{type:"number",validate:validateNumber},double:{type:"number",validate:validateNumber},password:true,binary:true};exports.fastFormats={...exports.fullFormats,date:fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,compareDate),time:fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareTime),"date-time":fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareDateTime),"iso-time":fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoTime),"iso-date-time":fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoDateTime),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};exports.formatNames=Object.keys(exports.fullFormats);function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}var DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;var DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31];function date5(str2){const matches=DATE.exec(str2);if(!matches)return false;const year=+matches[1];const month=+matches[2];const day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month===2&&isLeapYear(year)?29:DAYS[month])}function compareDate(d1,d2){if(!(d1&&d2))return void 0;if(d1>d2)return 1;if(d1<d2)return-1;return 0}var TIME=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function getTime(strictTimeZone){return function time3(str2){const matches=TIME.exec(str2);if(!matches)return false;const hr=+matches[1];const min=+matches[2];const sec=+matches[3];const tz=matches[4];const tzSign=matches[5]==="-"?-1:1;const tzH=+(matches[6]||0);const tzM=+(matches[7]||0);if(tzH>23||tzM>59||strictTimeZone&&!tz)return false;if(hr<=23&&min<=59&&sec<60)return true;const utcMin=min-tzM*tzSign;const utcHr=hr-tzH*tzSign-(utcMin<0?1:0);return(utcHr===23||utcHr===-1)&&(utcMin===59||utcMin===-1)&&sec<61}}function compareTime(s1,s2){if(!(s1&&s2))return void 0;const t1=new Date("2020-01-01T"+s1).valueOf();const t2=new Date("2020-01-01T"+s2).valueOf();if(!(t1&&t2))return void 0;return t1-t2}function compareIsoTime(t1,t2){if(!(t1&&t2))return void 0;const a1=TIME.exec(t1);const a2=TIME.exec(t2);if(!(a1&&a2))return void 0;t1=a1[1]+a1[2]+a1[3];t2=a2[1]+a2[2]+a2[3];if(t1>t2)return 1;if(t1<t2)return-1;return 0}var DATE_TIME_SEPARATOR=/t|\s/i;function getDateTime(strictTimeZone){const time3=getTime(strictTimeZone);return function date_time(str2){const dateTime=str2.split(DATE_TIME_SEPARATOR);return dateTime.length===2&&date5(dateTime[0])&&time3(dateTime[1])}}function compareDateTime(dt1,dt2){if(!(dt1&&dt2))return void 0;const d1=new Date(dt1).valueOf();const d2=new Date(dt2).valueOf();if(!(d1&&d2))return void 0;return d1-d2}function compareIsoDateTime(dt1,dt2){if(!(dt1&&dt2))return void 0;const[d1,t1]=dt1.split(DATE_TIME_SEPARATOR);const[d2,t2]=dt2.split(DATE_TIME_SEPARATOR);const res=compareDate(d1,d2);if(res===void 0)return void 0;return res||compareTime(t1,t2)}var NOT_URI_FRAGMENT=/\/|:/;var URI=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function uri(str2){return NOT_URI_FRAGMENT.test(str2)&&URI.test(str2)}var BYTE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function byte(str2){BYTE.lastIndex=0;return BYTE.test(str2)}var MIN_INT32=-(2**31);var MAX_INT32=2**31-1;function validateInt32(value){return Number.isInteger(value)&&value<=MAX_INT32&&value>=MIN_INT32}function validateInt64(value){return Number.isInteger(value)}function validateNumber(){return true}var Z_ANCHOR=/[^\\]\\Z/;function regex(str2){if(Z_ANCHOR.test(str2))return false;try{new RegExp(str2);return true}catch(e){return false}}}});var require_limit=__commonJS({"../../node_modules/.pnpm/ajv-formats@3.0.1/node_modules/ajv-formats/dist/limit.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.formatLimitDefinition=void 0;var ajv_1=require_ajv();var codegen_1=require_codegen();var ops=codegen_1.operators;var KWDs={formatMaximum:{okStr:"<=",ok:ops.LTE,fail:ops.GT},formatMinimum:{okStr:">=",ok:ops.GTE,fail:ops.LT},formatExclusiveMaximum:{okStr:"<",ok:ops.LT,fail:ops.GTE},formatExclusiveMinimum:{okStr:">",ok:ops.GT,fail:ops.LTE}};var error51={message:({keyword,schemaCode})=>(0,codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`,params:({keyword,schemaCode})=>(0,codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`};exports.formatLimitDefinition={keyword:Object.keys(KWDs),type:"string",schemaType:"string",$data:true,error:error51,code(cxt){const{gen,data,schemaCode,keyword,it}=cxt;const{opts,self:self2}=it;if(!opts.validateFormats)return;const fCxt=new ajv_1.KeywordCxt(it,self2.RULES.all.format.definition,"format");if(fCxt.$data)validate$DataFormat();else validateFormat();function validate$DataFormat(){const fmts=gen.scopeValue("formats",{ref:self2.formats,code:opts.code.formats});const fmt=gen.const("fmt",(0,codegen_1._)`${fmts}[${fCxt.schemaCode}]`);cxt.fail$data((0,codegen_1.or)((0,codegen_1._)`typeof ${fmt} != "object"`,(0,codegen_1._)`${fmt} instanceof RegExp`,(0,codegen_1._)`typeof ${fmt}.compare != "function"`,compareCode(fmt)))}function validateFormat(){const format=fCxt.schema;const fmtDef=self2.formats[format];if(!fmtDef||fmtDef===true)return;if(typeof fmtDef!="object"||fmtDef instanceof RegExp||typeof fmtDef.compare!="function"){throw new Error(`"${keyword}": format "${format}" does not define "compare" function`)}const fmt=gen.scopeValue("formats",{key:format,ref:fmtDef,code:opts.code.formats?(0,codegen_1._)`${opts.code.formats}${(0,codegen_1.getProperty)(format)}`:void 0});cxt.fail$data(compareCode(fmt))}function compareCode(fmt){return(0,codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`}},dependencies:["format"]};var formatLimitPlugin=ajv=>{ajv.addKeyword(exports.formatLimitDefinition);return ajv};exports.default=formatLimitPlugin}});var require_dist2=__commonJS({"../../node_modules/.pnpm/ajv-formats@3.0.1/node_modules/ajv-formats/dist/index.js"(exports,module2){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var formats_1=require_formats();var limit_1=require_limit();var codegen_1=require_codegen();var fullName=new codegen_1.Name("fullFormats");var fastName=new codegen_1.Name("fastFormats");var formatsPlugin=(ajv,opts={keywords:true})=>{if(Array.isArray(opts)){addFormats(ajv,opts,formats_1.fullFormats,fullName);return ajv}const[formats,exportName]=opts.mode==="fast"?[formats_1.fastFormats,fastName]:[formats_1.fullFormats,fullName];const list=opts.formats||formats_1.formatNames;addFormats(ajv,list,formats,exportName);if(opts.keywords)(0,limit_1.default)(ajv);return ajv};formatsPlugin.get=(name,mode="full")=>{const formats=mode==="fast"?formats_1.fastFormats:formats_1.fullFormats;const f=formats[name];if(!f)throw new Error(`Unknown format "${name}"`);return f};function addFormats(ajv,list,fs,exportName){var _a3;var _b;(_a3=(_b=ajv.opts.code).formats)!==null&&_a3!==void 0?_a3:_b.formats=(0,codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;for(const f of list)ajv.addFormat(f,fs[f])}module2.exports=exports=formatsPlugin;Object.defineProperty(exports,"__esModule",{value:true});exports.default=formatsPlugin}});import{basename as basename2,dirname as dirname9,join as join10}from"node:path";import{rmSync as rmSync3}from"node:fs";import{tmpdir as tmpdir2}from"node:os";init_request_safe_reconnect();init_nkey_signer();init_secret_fs();import{execFileSync as execFileSync2}from"node:child_process";import{linkSync as linkSync2,mkdirSync as mkdirSync2,readFileSync,rmSync,statSync,unlinkSync as unlinkSync2}from"node:fs";import{randomBytes}from"node:crypto";import{dirname as dirname2}from"node:path";function processStatFields(pid){try{const stat=readFileSync(`/proc/${pid}/stat`,"utf8");const after=stat.lastIndexOf(") ");if(after<0||stat.slice(0,stat.indexOf(" "))!==String(pid))return void 0;return stat.slice(after+2).trim().split(/\s+/)}catch{return void 0}}function processStartToken(pid){if(process.platform==="win32")return void 0;if(process.platform==="linux")return processStatFields(pid)?.[19];try{const out=execFileSync2("ps",["-o","lstart=","-p",String(pid)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return out||void 0}catch{return void 0}}function sleepSync(ms){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}function pidAlive(pid){try{process.kill(pid,0);return true}catch(e){const code=e.code;if(code==="ESRCH")return false;if(code==="EPERM")return true;throw e}}function readOwner(path){let raw;try{raw=readFileSync(path,"utf8")}catch(e){const code=e.code;if(code==="ENOENT")return void 0;if(code==="EISDIR"||code==="EACCES"||code==="EPERM")throw new Error(`advisory lock path ${path} is unreadable (${code}) - remove the stray file or directory there and retry`);throw e}let ino;try{ino=statSync(path).ino}catch{}try{return{owner:JSON.parse(raw),ino}}catch{return{ino}}}function inspectLock(path){const inspection=inspectLockSnapshot(path);return inspection.state==="active"?{state:"active",owner:inspection.owner}:{state:inspection.state}}function inspectLockSnapshot(path){const found=readOwner(path);if(found===void 0)return{state:"absent"};const{owner:owner2,ino}=found;if(!owner2||typeof owner2.pid!=="number"||!Number.isInteger(owner2.pid)||owner2.pid<=0||typeof owner2.nonce!=="string"){return{state:"stale",ino}}if(!pidAlive(owner2.pid))return{state:"stale",ino};if(owner2.start!==void 0){const fields=process.platform==="linux"?processStatFields(owner2.pid):void 0;const now=process.platform==="linux"?fields?.[19]:processStartToken(owner2.pid);if(now===owner2.start&&fields?.[0]==="Z")return{state:"stale",ino};if(now!==void 0&&now!==owner2.start)return{state:"stale",ino}}return{state:"active",owner:owner2,ino}}function publishAtomic(path,content){const tmp=`${path}.${randomBytes(8).toString("hex")}.tmp`;createPrivateRecord(tmp,content);try{linkSync2(tmp,path);return true}catch(e){if(e.code==="EEXIST")return false;throw e}finally{try{unlinkSync2(tmp)}catch{}}}function reclaimStale(path,inspectedIno){const sentinel=`${path}.reclaim`;const mine=JSON.stringify({pid:process.pid,start:processStartToken(process.pid),nonce:randomBytes(8).toString("hex"),ts:Date.now()});if(!publishAtomic(sentinel,mine)){const reclaimer=inspectLock(sentinel);if(reclaimer.state==="stale")throw new Error(`a lock reclaim was interrupted and its sentinel remains (${sentinel}) - if no cotal process is running, remove it and retry`);return reclaimer.state==="active"?reclaimer.owner:void 0}try{const inspection=inspectLockSnapshot(path);if(inspection.state!=="stale")return;if(inspectedIno!==void 0&&inspection.ino!==void 0&&inspection.ino!==inspectedIno)return;unlinkSync2(path)}catch(e){if(e.code!=="ENOENT")throw e}finally{try{unlinkSync2(sentinel)}catch{}}}function newAttempt(path,opts){mkdirSync2(dirname2(path),{recursive:true,mode:448});const nonce3=randomBytes(12).toString("hex");const owner2={pid:process.pid,start:processStartToken(process.pid),nonce:nonce3,ts:Date.now(),...opts.label?{label:opts.label}:{}};return{path,nonce:nonce3,content:`${JSON.stringify(owner2)}
113
113
  `}}function tryAcquireOnce({path,nonce:nonce3,content}){if(publishAtomic(path,content)){let released=false;return{kind:"acquired",held:{nonce:nonce3,release(){if(released)return;released=true;const found=readOwner(path);if(found?.owner?.nonce===nonce3){try{unlinkSync2(path)}catch{}}}}}}const inspection=inspectLockSnapshot(path);if(inspection.state==="absent")return{kind:"retry"};if(inspection.state==="stale"){const reclaimer=reclaimStale(path,inspection.ino);return reclaimer?{kind:"reclaiming",owner:reclaimer}:{kind:"retry"}}return{kind:"held",owner:inspection.owner}}function reclaimPollMs(pollMs){return Math.min(pollMs,50)}function acquireLock(path,opts={}){const waitMs=opts.waitMs??3e5;const pollMs=opts.pollMs??200;const attempt=newAttempt(path,opts);const deadline=Date.now()+waitMs;for(;;){const result=tryAcquireOnce(attempt);if(result.kind==="acquired")return result.held;if(result.kind==="retry")continue;const left=deadline-Date.now();if(left<=0)throw lockTimeoutError(path,opts,result.owner,waitMs);sleepSync(Math.min(result.kind==="reclaiming"?reclaimPollMs(pollMs):pollMs,left))}}function lockTimeoutError(path,opts,owner2,waitMs){return opts.onTimeout?.(owner2)??new Error(`${opts.label??"a lock"} is held by a live process (pid ${owner2.pid}) and did not release within ${Math.round(waitMs/1e3)}s - retry, or if it is wedged, remove ${path}`)}import{createHash}from"node:crypto";import{lstatSync as lstatSync2,mkdirSync as mkdirSync3}from"node:fs";import{userInfo}from"node:os";import{join as join2}from"node:path";var LocalConsumerHeldError=class extends Error{};function localConsumerClaimPath(servers,space2,owner2,actor2,lifecycleUid){const user=userInfo();const root=process.platform==="linux"?`/tmp/cotal-consumers-${user.uid}`:join2(user.homedir,".cotal-consumers");mkdirSync3(root,{recursive:true,mode:448});const st=lstatSync2(root);if(!st.isDirectory()||st.isSymbolicLink()||process.platform!=="win32"&&(st.uid!==user.uid||(st.mode&63)!==0))throw new Error("local consumer custody directory is not private to this OS user");const targets=[...new Set(servers.split(",").map(s=>{const u=new URL(s.trim().includes("://")?s.trim():`nats://${s.trim()}`);u.username="";u.password="";if(!u.port)u.port=u.protocol==="nats:"?"4222":u.protocol==="wss:"?"443":"80";return u.href}))].sort();const key=createHash("sha256").update(JSON.stringify([targets,space2,owner2,actor2,lifecycleUid])).digest("hex");const path=join2(root,`${key}.lock`);try{const file2=lstatSync2(path);if(!file2.isFile()||file2.isSymbolicLink()||process.platform!=="win32"&&(file2.uid!==user.uid||(file2.mode&63)!==0))throw new Error("local consumer custody file is not private to this OS user")}catch(error51){if(error51.code!=="ENOENT")throw error51}return path}function acquireLocalConsumer(servers,space2,owner2,actor2,lifecycleUid){return acquireLock(localConsumerClaimPath(servers,space2,owner2,actor2,lifecycleUid),{waitMs:0,label:"local inbox consumer",onTimeout:()=>new LocalConsumerHeldError(`local inbox already has a consuming session for ${owner2}.${actor2} in space "${space2}"; preserve that session and choose a distinct actor for a new launch`)})}init_subjects();init_endpoint_subjects();init_canonical();init_endpoint_error();init_endpoint_grants();init_endpoint_subjects();init_issued_authority();init_subjects();init_registry_contract();init_registry_client();init_endpoint_envelope();init_endpoint_records();init_lifecycle_state();init_environment_manager_grants();init_canonical();init_endpoint_envelope();init_endpoint_subjects();init_identity();init_subjects();init_lifecycle_state();var dec5=new TextDecoder;init_endpoint_envelope();init_endpoint_records();init_subjects();init_lifecycle_state();var enc5=new TextEncoder;init_endpoint_cluster();init_endpoint_journal();init_endpoint_binding();init_endpoint_binding();init_canonical();init_space_resource_definitions();init_space_deletion_targets();init_endpoint_envelope();init_broker_identity();var import_jetstream17=__toESM(require_mod4(),1);var import_transport_node16=__toESM(require_transport_node(),1);init_jetstream_missing();init_space_resource_definitions();var import_kv9=__toESM(require_mod6(),1);init_subjects();init_channels();init_space_resource_definitions();init_canonical();init_channels();init_subjects();init_space_resource_definitions();var DEFAULT_FIELDS={replay:true,replayWindow:true,deliveryClass:true};var CHANNEL_FIELDS={...DEFAULT_FIELDS,description:true,instructions:true};init_space_resource_definitions();init_endpoint_binding();init_issued_authority();init_run_admission();init_streams();init_backup_config();init_canonical();var import_jetstream18=__toESM(require_mod4(),1);init_endpoint_service();init_endpoint_service();init_endpoint_invoke();init_endpoint_call();init_endpoint_envelope();init_kv_scan();init_canonical();init_service_gate();init_endpoint_envelope();init_endpoint_records();init_endpoint_subjects();init_lifecycle_state();var enc6=new TextEncoder;var dec6=new TextDecoder;init_endpoint_envelope();init_endpoint_subjects();init_subjects();init_subjects();init_endpoint_subjects();init_endpoint_envelope();init_schema_profile();init_endpoint_service();init_canonical();init_endpoint_envelope();init_deadline();init_schema_profile();init_endpoint_cluster();init_endpoint_envelope();init_deadline();init_canonical();init_endpoint_signing();init_endpoint_checkpoint();init_endpoint_action();var mintGuardClearance=claimGuardClearanceMint();init_endpoint_service();init_endpoint_signing();var TRAIT_SELECTORS=Object.freeze(["cluster","command","attribute","event"]);init_canonical();init_subjects();init_endpoint_subjects();init_endpoint_envelope();init_schema_profile();init_endpoint_verbs();init_endpoint_invoke();var import_jetstream19=__toESM(require_mod4(),1);var import_transport_node17=__toESM(require_transport_node(),1);init_canonical();init_endpoint_envelope();init_deadline();init_endpoint_subjects();init_endpoint_records();init_endpoint_journal();init_endpoint_binding();var import_jetstream20=__toESM(require_mod4(),1);var import_transport_node18=__toESM(require_transport_node(),1);init_endpoint_binding();init_endpoint_records();init_jetstream_missing();init_endpoint_action();init_endpoint_error();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"]};init_endpoint_error();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};init_endpoint_checkpoint();init_endpoint_contract_store();init_lifecycle_state();init_endpoint_service();init_evict();init_canonical();init_endpoint_envelope();init_endpoint_subjects();init_endpoint_signing();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;init_endpoint_envelope();init_canonical();init_subjects();init_endpoint_subjects();init_endpoint_signing();init_endpoint_error();init_endpoint_subjects();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);init_endpoint_error();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})();init_endpoint_envelope();init_endpoint_binding();var import_jetstream21=__toESM(require_mod4(),1);init_endpoint_supervisor();init_endpoint_service();init_endpoint_records();init_endpoint_subjects();init_subjects();init_endpoint_receipt();init_endpoint_signing();var RENEW_AT_FRACTION=1/3;var OVERLAP_MS=10*60*1e3;init_safe_pattern();init_resolve();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)}init_process_runtime();function oneLine(text2){return text2.replace(/[\p{Cc}\p{Cf}\p{Default_Ignorable_Code_Point}\p{Zl}\p{Zp}]/gu,c=>{let escaped="";for(let i=0;i<c.length;i++)escaped+=`\\u${c.charCodeAt(i).toString(16).padStart(4,"0")}`;return escaped})}var PRESENCE_TEXT_MAX=200;function presenceText(text2){const shown=Array.from(text2,oneLine);const width=s=>[...s].length;if(shown.reduce((n2,s)=>n2+width(s),0)<=PRESENCE_TEXT_MAX)return shown.join("");let kept="";let n=0;for(const s of shown){n+=width(s);if(n>PRESENCE_TEXT_MAX-1)break;kept+=s}return`${kept}\u2026`}init_connection_cleanup();init_native_connection();init_text_encoding();function parseJoinLink(link){const tls=link.startsWith("cotals://");if(!tls&&!link.startsWith("cotal://"))throw new Error(`not a Cotal link (expected cotal:// or cotals://): ${link}`);const u=new URL(link.replace(/^cotals?:\/\//,tls?"https://":"http://"));if(!u.hostname)throw new Error(`Cotal link has no host: ${link}`);const space2=decodeURIComponent(u.pathname.replace(/^\/+/,"").split("/")[0]??"");if(!space2)throw new Error(`Cotal link has no space (cotal://host/<space>): ${link}`);const chParam=u.searchParams.get("channels")??u.searchParams.get("channel");const channels=chParam?chParam.split(",").map(s=>s.trim()).filter(Boolean):void 0;const user=u.username?decodeURIComponent(u.username):void 0;const pass=u.password?decodeURIComponent(u.password):void 0;return{servers:`nats://${u.hostname}:${u.port||"4222"}`,space:space2,channels,tls,token:user&&!pass?user:void 0,user:pass?user:void 0,pass:pass||void 0}}function brokerUrlHasUserinfo(servers){return servers.split(",").some(entry=>/^[^:/?#]+:\/\/[^/?#]*@/.test(entry.includes("://")?entry.trim():`nats://${entry.trim()}`))}init_identity();init_secret_store();init_provision();init_jwt();var import_nkeys10=__toESM(require_mod(),1);init_identity();init_nkey_signer();init_jwt();var import_nkeys11=__toESM(require_mod(),1);init_subjects();init_streams();init_anycast_requests();init_transfer();init_backup_config();init_backup();init_channels();init_members();init_acls();init_connection_cleanup();init_native_connection();var import_transport_node19=__toESM(require_transport_node(),1);init_endpoint();var import_kv10=__toESM(require_mod6(),1);init_subjects();init_members();init_kv_scan();init_identity();init_deadline();init_jetstream_missing();init_evict();init_lease();init_liveness();init_agent_file();import{lstatSync as lstatSync4,mkdirSync as mkdirSync5,unlinkSync as unlinkSync3}from"node:fs";import{join as join3}from"node:path";function ensureDirNoSymlink(parent,...segments){let dir=parent;for(const seg of segments){dir=join3(dir,seg);let st;try{st=lstatSync4(dir)}catch(e){if(e.code==="ENOENT"){mkdirSync5(dir,{mode:448});continue}throw e}if(st.isSymbolicLink())throw new Error(`refusing to write under "${dir}": it is a symlink`);if(!st.isDirectory())throw new Error(`refusing to write under "${dir}": not a directory`)}return dir}init_secret_fs();init_secret_fs();import{mkdtempSync,readFileSync as readFileSync3,realpathSync as realpathSync2,rmSync as rmSync2,rmdirSync,statSync as statSync3}from"node:fs";import{tmpdir}from"node:os";import{basename,dirname as dirname3,join as join4,resolve as resolve2}from"node:path";var DIR_PREFIX="cotal-launch-";var MATERIAL_FILE="material.json";var LAUNCH_MATERIAL_ENV="COTAL_LAUNCH_MATERIAL";function readLaunchMaterial(path){let raw;try{if(process.platform!=="win32"){const mode=statSync3(path).mode&511;if(mode&63)throw new Error(`is readable beyond its owner (mode ${mode.toString(8)}) - refusing to read connection material out of a file other local users can open`)}raw=readFileSync3(path,"utf8")}catch(e){throw new Error(`launch material: cannot read ${path} (${e instanceof Error?e.message:String(e)})`)}let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error(`launch material: ${path} is not valid JSON`)}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))throw new Error(`launch material: ${path} must contain a JSON object`);return validate(parsed,path)}function validate(raw,path){const material={};const str2=key=>{const v=raw[key];if(v===void 0)return;if(typeof v!=="string"||!v.trim())throw new Error(`launch material: ${path} has a ${key} that is not a non-empty string`);material[key]=v};str2("servers");str2("creds");str2("token");str2("controlToken");if(raw.eventsRequired!==void 0){if(raw.eventsRequired!==true)throw new Error(`launch material: ${path} has eventsRequired that is not exactly true`);material.eventsRequired=true}if(raw.eventPayloadsWithheld!==void 0){if(raw.eventPayloadsWithheld!==true)throw new Error(`launch material: ${path} has eventPayloadsWithheld that is not true`);material.eventPayloadsWithheld=true}if(raw.userAuth!==void 0){const u=raw.userAuth;if(typeof u!=="object"||u===null||Array.isArray(u))throw new Error(`launch material: ${path} has a userAuth that is not an object`);const{owner:owner2,actor:actor2,sentinelCredsPath,bearerCmd}=u;const named={owner:owner2,actor:actor2,sentinelCredsPath};for(const[k,v]of Object.entries(named))if(typeof v!=="string"||!v.trim())throw new Error(`launch material: ${path} has a userAuth.${k} that is not a non-empty string`);if(!Array.isArray(bearerCmd)||bearerCmd.length===0||!bearerCmd.every(a=>typeof a==="string"&&a))throw new Error(`launch material: ${path} has a userAuth.bearerCmd that is not a non-empty array of strings`);material.userAuth={owner:owner2,actor:actor2,sentinelCredsPath,bearerCmd}}if(Object.keys(material).length===0)throw new Error(`launch material: ${path} carries nothing this reader recognises. A launch that references material and supplies none is a broken launcher, not an open-mode launch, so it is refused rather than defaulted.`);return material}function discardLaunchMaterial(path){const file2=resolve2(path);try{rmSync2(file2,{force:true})}catch{}const dir=dirname3(file2);if(basename(file2)!==MATERIAL_FILE||!basename(dir).startsWith(DIR_PREFIX))return;try{if(realpathSync2(dirname3(dir))!==realpathSync2(tmpdir()))return;rmdirSync(dir)}catch{}}init_secret_fs();init_kv_scan();init_jetstream_missing();init_endpoint();var import_transport_node20=__toESM(require_transport_node(),1);var import_jetstream22=__toESM(require_mod4(),1);var import_kv11=__toESM(require_mod6(),1);init_endpoint();init_subjects();init_space_deletion_targets();init_identity();init_provision();import{BlockList,isIPv4,isIPv6}from"node:net";var LOOPBACK=new BlockList;LOOPBACK.addSubnet("127.0.0.0",8,"ipv4");LOOPBACK.addAddress("::1","ipv6");init_subjects();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"]);init_subjects();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 registry2=new Registry;import{execFile}from"node:child_process";init_subjects();function bearerCommandFailure(err3,stderr,timeoutMs,stdout=""){const said=stderr.trim();const retryAfter=/^retry-after (\d+)$/.exec(stdout.trim());if(said)return Object.assign(new Error(said),retryAfter?{retryAfterSeconds:Number(retryAfter[1])}:{});if(err3.killed)return new Error(`the bearer command timed out after ${timeoutMs}ms`);if(err3.signal)return new Error(`the bearer command was killed by ${err3.signal}`);if(typeof err3.code==="number")return new Error(`the bearer command exited with code ${err3.code} and printed nothing`);return new Error(err3.message)}function runAgentBearer(argv,opts={}){const timeoutMs=opts.timeoutMs??3e4;return new Promise((resolve3,reject)=>{execFile(argv[0],argv.slice(1),{timeout:timeoutMs,maxBuffer:64*1024,env:opts.env,signal:opts.signal},(err3,stdout,stderr)=>err3?reject(bearerCommandFailure(err3,stderr,timeoutMs,stdout)):resolve3(stdout.trim()))})}init_event_channel();init_subjects();var SELECTION_MAX_ITEMS=32;init_canonical_json();var EMPTY_CONVERSATION_SELECTION=Object.freeze({v:1,channels:Object.freeze([]),role:null,capabilities:Object.freeze([]),endpoints:Object.freeze([])});init_subjects();init_base64url();function managerCallerBinding(bearer,expected){let payload;try{const parts=bearer.split(".");if(parts.length!==3)throw new Error("invalid JWT");payload=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(fromBase64url(parts[1])))}catch{throw new Error("manager control exchange returned an invalid bearer")}const act=payload?.act;if(!act||act.view!=="manager-caller"||payload.sub!==expected.owner||act.owner!==expected.owner||act.actor!==expected.actor||act.lifecycleUid!==expected.lifecycleUid||!(payload.aud===expected.space||Array.isArray(payload.aud)&&payload.aud.length===1&&payload.aud[0]===expected.space))throw new Error("manager control exchange returned different space, principal, lifecycle or view coordinates");if(typeof act.managerInstanceId!=="string")throw new Error("manager control exchange returned no concrete manager instance");const instanceId=assertLifecycleToken(act.managerInstanceId,"managerInstanceId");if(expected.instanceId!==void 0&&instanceId!==expected.instanceId)throw new Error("manager control exchange selected a different manager instance");return{caller:{owner:expected.owner,actor:expected.actor,uid:expected.lifecycleUid},instanceId,...typeof act.credentialId==="string"?{credentialId:act.credentialId}:{}}}init_remote_manager_authority();init_remote_service_authority();init_endpoint_capability_policy();init_canonical();init_endpoint_error();init_identity();init_remote_manager_authority();init_subjects();var DELEGATED_RECOVERY_REASONS=Object.freeze(["provider-unknown","store-unavailable","authority-unavailable","identity-unverified","descriptor-incomplete","retiring","authority-drift","identity-changed","scope-changed"]);init_canonical();init_artifact();function partText(p){if(p.kind==="text")return p.text;if(p.kind==="artifact")return`[artifact ${p.name} (${p.mediaType}, ${p.size} bytes) ${p.digest}]`;if(p.kind==="data"){const encoded=JSON.stringify(p.data);return encoded===void 0?`[empty data part]`:encoded}if(registry2.has("part-renderer",p.kind)){const renderer=registry2.resolve("part-renderer",p.kind);try{return renderer.render(p)}catch(e){return`[part renderer for ${JSON.stringify(p.kind)} failed: ${e.message}]`}}return`[unrenderable part kind ${JSON.stringify(p.kind)} \u2014 no renderer for it on this surface]`}function partsToText(parts){return parts.map(partText).join(" ")}var AGUI_FRAME_KIND="ag-ui.frame";var AGUI_EVENT_TYPE=Object.freeze({RUN_STARTED:"RUN_STARTED",RUN_FINISHED:"RUN_FINISHED",RUN_ERROR:"RUN_ERROR",TEXT_MESSAGE_START:"TEXT_MESSAGE_START",TEXT_MESSAGE_CONTENT:"TEXT_MESSAGE_CONTENT",TEXT_MESSAGE_END:"TEXT_MESSAGE_END",TOOL_CALL_START:"TOOL_CALL_START",TOOL_CALL_ARGS:"TOOL_CALL_ARGS",TOOL_CALL_END:"TOOL_CALL_END",TOOL_CALL_RESULT:"TOOL_CALL_RESULT",REASONING_MESSAGE_START:"REASONING_MESSAGE_START",REASONING_MESSAGE_CONTENT:"REASONING_MESSAGE_CONTENT",REASONING_MESSAGE_END:"REASONING_MESSAGE_END",CUSTOM:"CUSTOM"});function isAguiFramePart(part){if(typeof part!=="object"||part===null)return false;try{return part.kind===AGUI_FRAME_KIND}catch{return false}}init_event_channel();init_event_channel();import{createHash as createHash6}from"node:crypto";import{constants as constants3}from"node:fs";import{lstat,open,readdir}from"node:fs/promises";import{dirname as dirname4,join as join5,relative,sep}from"node:path";init_subjects();var EVENT_SUBJECT_RECORD_VERSION=1;var SubjectFrontierCorruptError=class extends Error{path;invariant;constructor(path,invariant,detail){super(`subject frontier ${path}: expected ${invariant} \u2014 ${detail}`);this.path=path;this.invariant=invariant;this.name="SubjectFrontierCorruptError"}};var EventStateConflictError=class extends Error{constructor(message){super(message);this.name="EventStateConflictError"}};function eventPrincipalLocation(opts){const h2=value=>createHash6("sha256").update(value).digest("hex").slice(0,16);const principalDir=join5(opts.workspaceRoot,".cotal","events",h2(opts.space),h2(opts.principal));return{principalDir,lockPath:join5(principalDir,".lock"),subjectPath:join5(principalDir,"subject.json")}}var isSafeNonNegInt=n=>typeof n==="number"&&Number.isSafeInteger(n)&&n>=0;async function readEventSubjectRecord(path,opts){let st;try{st=await lstat(path)}catch(e){if(e.code==="ENOENT")return void 0;throw e}if(st.isSymbolicLink())throw new SubjectFrontierCorruptError(path,"a real subject record, never a symlink","the writer never wrote a symlink");let bytes;try{const fh=await open(path,constants3.O_RDONLY|(constants3.O_NOFOLLOW??0));try{bytes=await fh.readFile()}finally{await fh.close()}}catch(e){const code=e.code;if(code==="ENOENT")return void 0;if(code==="ELOOP")throw new SubjectFrontierCorruptError(path,"a real subject record, never a symlink","the record became a symlink between the check and the open");throw e}let raw;try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new SubjectFrontierCorruptError(path,"valid UTF-8","invalid UTF-8 bytes; refusing rather than substituting U+FFFD")}if(raw.length===0)throw new SubjectFrontierCorruptError(path,"a non-empty file","the file is zero bytes \u2014 distinct from missing, and never treated as virgin");let parsed;try{parsed=JSON.parse(raw)}catch(e){throw new SubjectFrontierCorruptError(path,"parseable JSON",e.message)}const d=parsed;if(d?.v!==EVENT_SUBJECT_RECORD_VERSION)throw new SubjectFrontierCorruptError(path,`v === ${EVENT_SUBJECT_RECORD_VERSION}`,String(d?.v));if(d.space!==opts.space)throw new SubjectFrontierCorruptError(path,"space matches",`file=${String(d.space)} caller=${opts.space}`);if(d.principal!==opts.principal)throw new SubjectFrontierCorruptError(path,"principal matches",`file=${String(d.principal)} caller=${opts.principal}`);if(!isSafeNonNegInt(d.tip)||d.tip>=Number.MAX_SAFE_INTEGER)throw new SubjectFrontierCorruptError(path,"tip is a safe non-negative integer below Number.MAX_SAFE_INTEGER",String(d.tip));return{v:d.v,space:d.space,principal:d.principal,tip:d.tip}}async function recoverEventSubjectTip(principalDir,principal){let entries;try{entries=await readdir(principalDir,{withFileTypes:true})}catch(e){if(e.code==="ENOENT")return 0;throw e}let best=0;for(const ent of entries){if(ent.isSymbolicLink())throw new SubjectFrontierCorruptError(join5(principalDir,ent.name),"a real directory beside the record, never a symlink","following it would carry this scan outside the principal directory, and the writer that creates these directories refuses a symlinked component for the same reason");if(!ent.isDirectory())continue;const walPath=join5(principalDir,ent.name,"wal.json");let st;try{st=await lstat(walPath)}catch(e){const code=e.code;if(code==="ENOENT"||code==="ENOTDIR")continue;throw e}if(st.isSymbolicLink())throw new SubjectFrontierCorruptError(walPath,"a real thread log, never a symlink","following it would read a log this principal's writer never wrote");if(st.nlink>1)throw new SubjectFrontierCorruptError(walPath,"a thread log with exactly one name",`it has ${st.nlink}, so the same file is reachable from outside this principal's directory and its tip is not this principal's to read`);let raw;try{const fh=await open(walPath,constants3.O_RDONLY|(constants3.O_NOFOLLOW??0));try{raw=await fh.readFile()}finally{await fh.close()}}catch(e){const code=e.code;if(code==="ENOENT"||code==="ENOTDIR")continue;if(code==="ELOOP")throw new SubjectFrontierCorruptError(walPath,"a real thread log, never a symlink","the file became a symlink between the check and the open");throw e}let doc;try{doc=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(raw))}catch(e){throw new SubjectFrontierCorruptError(walPath,"a readable thread log while recovering the subject tip",e.message)}if(doc.principal!==principal)throw new SubjectFrontierCorruptError(walPath,`a thread log for principal ${principal}`,`found ${String(doc.principal)}`);const seq=doc.frontier?.lastSubjectSeq;if(!isSafeNonNegInt(seq))throw new SubjectFrontierCorruptError(walPath,"frontier.lastSubjectSeq is a safe non-negative integer",String(seq));if(seq>best)best=seq;const pending=doc.pending;if(pending&&pending.state==="acked"){const acked=pending.ackSeq;if(!isSafeNonNegInt(acked))throw new SubjectFrontierCorruptError(walPath,"an acked pending carries a safe non-negative ackSeq",String(acked));if(!(acked>seq))throw new SubjectFrontierCorruptError(walPath,"an acked pending is ahead of the frontier it will fold into",`ackSeq=${acked} frontier.lastSubjectSeq=${seq}`);if(acked>best)best=acked}}return best}async function recordedEventTip(path,opts){const record2=await readEventSubjectRecord(path,opts);return record2===void 0?recoverEventSubjectTip(dirname4(path),opts.principal):record2.tip}async function checkEventStartup(opts){const principal=principalKey(opts.principal.owner,opts.principal.actor).key;const loc=eventPrincipalLocation({...opts,principal});ensureDirNoSymlink(opts.workspaceRoot,...relative(opts.workspaceRoot,loc.principalDir).split(sep));if(await recordedEventTip(loc.subjectPath,{space:opts.space,principal})!==0)return;const rows=await opts.retainedMessages();if(rows.some(row=>row.sender===principal&&row.channel===eventChannel(opts.principal)&&row.messages>0)){throw new EventStateConflictError(`Cannot start events for ${principal}: this state root has no acknowledged transcript frontier, but the broker retains events for this principal. Reuse the previous state root or launch with a new principal. Refusing before work; the existing transcript and local logs are unchanged.`)}}init_schema_profile();init_broker_floor();init_endpoint_records();init_endpoint_envelope();init_endpoint_subjects();init_endpoint_records();init_canonical();init_kv_scan();init_endpoint_envelope();init_endpoint_subjects();init_endpoint_records();init_canonical();init_kv_scan();init_endpoint_envelope();init_endpoint_subjects();init_endpoint_records();init_canonical();init_kv_scan();init_endpoint_envelope();init_endpoint_records();init_run_driver_grants();init_endpoint_subjects();init_subjects();var TURN_INPUT_SCHEMA=deepFreeze({type:"object",additionalProperties:false,required:["payload"],oneOf:[{required:["deadlineMs"]},{required:["deadlineAt"]}],properties:{payload:{type:"string",minLength:1,maxLength:65536},deadlineMs:{type:"integer",minimum:1},deadlineAt:{type:"integer",minimum:1},handoffFrom:{type:"string",minLength:1,maxLength:200}}});var TURN_OUTPUT_SCHEMA=deepFreeze({type:"object",additionalProperties:false,required:["name","owner","actor","uid","goalId","fingerprint","deadlineAt","executor"],properties:{name:{type:"string"},owner:{type:"string"},actor:{type:"string"},uid:{type:"string"},goalId:{type:"string"},fingerprint:{type:"string"},deadlineAt:{type:"integer",minimum:1},executor:{type:"object",additionalProperties:false,required:["lifecycleUid","epoch"],properties:{lifecycleUid:{type:"string"},epoch:{type:"integer",minimum:0}}}}});var TURN_YIELD_OUTPUT_SCHEMA=deepFreeze({type:"object",additionalProperties:false,required:["goalId","state"],properties:{goalId:{type:"string"},state:{enum:["succeeded","failed","cancelled","expired","uncertain"]}}});var CANCEL_INPUT_SCHEMA=deepFreeze({type:"object",additionalProperties:false,required:["goalId"],properties:{goalId:{type:"string",minLength:1},mode:{enum:["graceful","terminate"]}}});function deepFreeze(v){if(v!==null&&typeof v==="object"){for(const child of Object.values(v))deepFreeze(child);Object.freeze(v)}return v}var TURN_NOTICE_NONCE="turn-pending-notice-v1";function turnNoticeFilter(space2,instanceId,seat){return[spacePrefix(space2),...epPlaneTokens(seat),"reply",endpointToken("manager"),assertLifecycleToken(instanceId,"instanceId"),"*",...callerRailTokens(seat),TURN_NOTICE_NONCE].join(".")}function shownSpawner(name,fallback){return name!==void 0&&name.trim()?name:fallback}function renderOnceTask(t){let context=t.payload;try{const p=JSON.parse(t.payload);if(typeof p.context==="string")context=p.context}catch{}const from=shownSpawner(t.spawner,"your spawner");const deadline=t.deadlineAt!==void 0?`, or at ${new Date(t.deadlineAt).toISOString()} if you are still working then`:"";return`\u{1F3AF} Cotal \u2014 ${from} started this seat for one task (goal ${t.goalId}):
114
114
  ${context}
115
- (This is the only task this seat takes. Do it with your own tools, and send your result to whoever needs it, for example with cotal_dm to ${from}, before you end your turn: this seat is stopped when your turn ends${deadline}, and a result you have not sent reaches no one. If you cannot finish, call cotal_yield with blocked or handoff and say why.)`}var nonBlank=()=>({type:"string",pattern:"^\\s*\\S"});var AGENT_ROW_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,required:["name","id","agent","space","mode","status","uptimeMs","mesh","lifecycleUid"],properties:{name:{type:"string"},id:{type:"string"},role:{type:"string"},agent:{type:"string"},space:{type:"string"},mode:{type:"string"},status:{type:"string"},uptimeMs:{type:"integer",minimum:0},mesh:{type:"string"},joinHealth:{type:"object",additionalProperties:false,required:["state","reason"],properties:{state:{type:"string",const:"degraded"},reason:{type:"string"}}},condition:{type:"object",additionalProperties:false,required:["code"],properties:{code:{type:"string"},source:{type:"string"},message:{type:"string"},since:{type:"number"}}},startupNotice:{type:"string",minLength:1,maxLength:1024},activeAt:{type:"number"},meshView:{type:"string",enum:["current","stale","unpopulated"]},presenceIdentityVerified:{type:"boolean"},presenceObservedAt:{type:"integer",minimum:0},offlineSince:{type:"integer",minimum:0},lifecycleUid:{type:"string"},authHealth:{type:"string"},authReason:{type:"string"},model:{type:"string"},variant:{type:"string"},provider:{type:"string"},cwd:{type:"string"},pid:{type:"integer",minimum:1},spawner:{type:"string"},instanceId:{type:"string"},host:{type:"string"},resume:{type:"object",additionalProperties:false,required:["source"],properties:{source:{type:"string"},title:{type:"string"},transcriptSha256:{type:"string"},host:{type:"string"},transferredAt:{type:"string"}}}}});var INSPECT_INPUT_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,required:["name"],properties:{name:{type:"string",minLength:1}}});var PERSONA_ENDPOINTS_SCHEMA=deepFreeze2({type:"array",items:{type:"object",additionalProperties:false,required:["endpoint","commands"],properties:{endpoint:{type:"string"},commands:{type:"array",items:{type:"string"}},instanceId:{type:"string"}}}});var SPAWN_INPUT_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,required:["name"],properties:{name:{type:"string",minLength:1},agent:nonBlank(),defaultAgent:nonBlank(),role:nonBlank(),config:nonBlank(),identity:nonBlank(),model:nonBlank(),variant:nonBlank(),launchOptions:{type:"object"},resume:nonBlank(),resumeClaim:nonBlank(),resumeAgent:nonBlank(),events:{type:"boolean"},eventPayloads:{type:"boolean"},cwd:nonBlank(),prompt:nonBlank(),persona:{type:"object",additionalProperties:false,required:["prompt"],properties:{prompt:nonBlank(),role:nonBlank(),model:nonBlank(),variant:nonBlank(),description:nonBlank(),subscribe:{type:"array",items:{type:"string"}},allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}},capabilities:{type:"array",items:{type:"string"}},endpoints:PERSONA_ENDPOINTS_SCHEMA,save:{type:"boolean"}}},runId:nonBlank(),subscribe:{type:"array",items:{type:"string"}},allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}},join:{type:"array",items:{type:"string"}},callerAcl:{type:"object",additionalProperties:false,required:["allowSubscribe","allowPublish"],properties:{allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}}}},shareTools:{type:"array",items:{type:"string"}},runtime:nonBlank(),supervise:{type:"object",additionalProperties:false,required:["restarts","windowMs"],properties:{restarts:{type:"integer",minimum:1},windowMs:{type:"integer",minimum:1}}},once:{type:"object",additionalProperties:false,properties:{deadlineMs:{anyOf:[{const:-1},{type:"integer",minimum:1,maximum:Number.MAX_SAFE_INTEGER}]}}}}});var SPAWN_OUTPUT_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,required:["name","owner","actor","uid","goalId","fingerprint","executor"],properties:{name:{type:"string"},owner:{type:"string"},actor:{type:"string"},uid:{type:"string"},goalId:{type:"string"},fingerprint:{type:"string"},readinessDeadlineMs:{type:"integer",minimum:1},executor:{type:"object",additionalProperties:false,required:["lifecycleUid","epoch"],properties:{lifecycleUid:{type:"string"},epoch:{type:"integer",minimum:0}}}}});var GRACEFUL_INPUT_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,properties:{graceful:{type:"boolean"}}});var STOP_OUTPUT_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,required:["name","stopped","graceful"],properties:{name:{type:"string"},stopped:{type:"boolean"},graceful:{type:"boolean"}}});function deepFreeze2(v){if(v!==null&&typeof v==="object"){for(const child of Object.values(v))deepFreeze2(child);Object.freeze(v)}return v}var import_nkeys12=__toESM(require_mod(),1);init_canonical();init_endpoint_envelope();init_identity();init_schema_profile();init_endpoint_signing();var TOOL_RESULTS_ENDPOINT="tool-results";var TOOL_RESULT_MAX_CONTENT_BYTES=64*1024;var TOOL_RESULT_MAX_RETENTION_MS=60*60*1e3;var TOOL_RESULT_CONSENT_MAX_TTL_MS=24*60*60*1e3;function deepFreeze3(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))deepFreeze3(child);Object.freeze(value)}return value}var text={type:"string",minLength:1};var id={type:"string",minLength:1,maxLength:200,pattern:"^[A-Za-z0-9_-]+$"};var actor={type:"string",minLength:1,pattern:"^[A-Za-z0-9_]+$"};var owner={type:"string",pattern:"^u_[a-z2-7]{26}$"};var uid={type:"string",pattern:"^[a-z0-9]{26,32}$"};var space={type:"string",minLength:1,pattern:"^[A-Za-z0-9_-]+$"};var uint={type:"integer",minimum:0,maximum:Number.MAX_SAFE_INTEGER};var bool={type:"boolean"};var closed2=properties=>({type:"object",additionalProperties:false,required:Object.keys(properties),properties});var target=closed2({owner,actor,lifecycleUid:uid});var pair={threadId:text,toolCallId:text};var status=(state,fields={})=>closed2({state:{const:state},...fields});var TOOL_RESULT_CONSENT_SCHEMA=deepFreeze3(closed2({v:{const:1},kind:{const:"tool-result-consent"},id,space,target,holder:closed2({owner,actor}),iat:uint,exp:uint,issuer:closed2({keyId:id}),sig:{type:"string",pattern:"^[A-Za-z0-9_-]{86}$"}}));var TOOL_RESULT_REVOCATION_SCHEMA=deepFreeze3(closed2({v:{const:1},kind:{const:"tool-result-revocation"},space,consentId:id,target,revokedAt:uint}));var TOOL_RESULT_SERVING_MATERIAL_SCHEMA=deepFreeze3(closed2({v:{const:1},kind:{const:"tool-result-serving-material"},space,accountPublicKey:{type:"string",pattern:"^A[A-Z2-7]{55}$"},target,grant:closed2({endpoint:{const:TOOL_RESULTS_ENDPOINT},instanceId:uid,epoch:uint,registrationRevision:{...uint,minimum:1}}),credential:{type:"string",minLength:1,maxLength:16384},snapshot:closed2({t0:uint,watermark:uint,watermarkTakenAt:uint,revokedConsentIds:{type:"array",uniqueItems:true,items:id}}),expiresAt:uint}));var TOOL_RESULT_INPUT_SCHEMA=deepFreeze3(closed2(pair));var TOOL_RESULT_ANSWER_SCHEMAS=deepFreeze3({available:status("available",{...pair,content:{type:"string",maxLength:TOOL_RESULT_MAX_CONTENT_BYTES},truncated:bool,byteCount:{...uint,maximum:TOOL_RESULT_MAX_CONTENT_BYTES},error:bool,capturedAt:uint}),pending:status("pending",pair),"not-shared":status("not-shared"),missing:status("missing"),expired:status("expired")});var TOOL_RESULT_OUTPUT_SCHEMA=deepFreeze3({oneOf:Object.values(TOOL_RESULT_ANSWER_SCHEMAS)});var TOOL_RESULT_CONSENT_INPUT_SCHEMA=deepFreeze3(closed2({consent:TOOL_RESULT_CONSENT_SCHEMA}));var TOOL_RESULT_CONSENT_OUTPUT_SCHEMA=deepFreeze3(status("active",{consentId:id}));var TOOL_RESULT_REVOKE_INPUT_SCHEMA=deepFreeze3(closed2({consentId:id}));var TOOL_RESULT_REVOKE_ANSWER_SCHEMAS=deepFreeze3({known:status("known",{consentId:id}),refused:status("refused",{consentId:id}),unknown:status("unknown",{consentId:id})});var TOOL_RESULT_REVOKE_OUTPUT_SCHEMA=deepFreeze3({oneOf:Object.values(TOOL_RESULT_REVOKE_ANSWER_SCHEMAS)});var TOOL_RESULTS_COMMANDS=deepFreeze3([{name:"tool-result",capability:"tool-results.read",input:TOOL_RESULT_INPUT_SCHEMA,output:TOOL_RESULT_OUTPUT_SCHEMA},{name:"tool-result-consent",capability:"tool-results.consent",input:TOOL_RESULT_CONSENT_INPUT_SCHEMA,output:TOOL_RESULT_CONSENT_OUTPUT_SCHEMA},{name:"tool-result-revoke",capability:"tool-results.revoke",input:TOOL_RESULT_REVOKE_INPUT_SCHEMA,output:TOOL_RESULT_REVOKE_OUTPUT_SCHEMA}]);var TOOL_RESULTS_CLUSTER=deepFreeze3({urn:"ai.cotal.tool-results",revision:1,attributes:[],events:[],commands:TOOL_RESULTS_COMMANDS.map(row=>({name:row.name,class:"ephemeral",targeted:true,modes:["handle"],capability:row.capability,inputDigest:singleDocumentClosure(row.input).closureDigest,outputDigest:singleDocumentClosure(row.output).closureDigest}))});init_event_payloads();var import_nkeys13=__toESM(require_mod(),1);init_base64url();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;init_issued_authority();init_provision();init_issued_authority();init_subjects();init_endpoint_subjects();init_persona_endpoints();var DELEGABLE_CAPABILITIES=Object.freeze(["spawn","run","admin"]);init_persona_endpoints();var import_jetstream23=__toESM(require_mod4(),1);var import_transport_node21=__toESM(require_transport_node(),1);init_backup();init_issued_authority();init_jetstream_missing();init_run_admission();init_endpoint_envelope();init_issued_authority();init_endpoint_subjects();init_endpoint_records();init_run_submission();init_canonical();init_endpoint_journal();init_endpoint_caller();init_endpoint_subjects();init_endpoint_error();init_connection_cleanup();var import_jetstream24=__toESM(require_mod4(),1);var import_kv12=__toESM(require_mod6(),1);init_endpoint();init_endpoint_binding();init_endpoint_envelope();init_lifecycle_state();init_endpoint_records();init_issued_authority();init_identity();init_provision();init_renewal();init_streams();init_service_gate();init_contract_manifest();init_renewal();import{readFileSync as readFileSync4}from"node:fs";import{userInfo as userInfo2}from"node:os";var DIRECT_MATERIAL_VARS=["COTAL_CREDS","COTAL_SERVERS","COTAL_TOKEN","COTAL_OWNER","COTAL_ACTOR","COTAL_SENTINEL_CREDS","COTAL_BEARER_CMD","COTAL_EVENTS_REQUIRED","COTAL_CONTROL_TOKEN","COTAL_LINK"];function readMaterial(env){const path=env[LAUNCH_MATERIAL_ENV]?.trim();if(!path)return void 0;const direct=DIRECT_MATERIAL_VARS.filter(k=>env[k]?.trim());if(direct.length)throw new Error(`COTAL config: this launch carries connection material BOTH as ${LAUNCH_MATERIAL_ENV} and as ${direct.join(", ")}. One launch carries one identity plane - drop the direct variables, or drop the material file.`);return readLaunchMaterial(path)}function controlFromEnv(env=process.env){const path=env.COTAL_CONTROL_SOCKET?.trim();const token2=readMaterial(env)?.controlToken??env.COTAL_CONTROL_TOKEN?.trim();if(path&&token2)return{path,token:token2};if(!path&&!token2)return void 0;if(path)throw new Error("COTAL config: COTAL_CONTROL_SOCKET is set but no control token could be resolved - neither the launch material nor COTAL_CONTROL_TOKEN carries one. Half a pair is not a control endpoint, so this launch is refused rather than started without the control plane it was configured to have.");throw new Error("COTAL config: a control token was supplied but COTAL_CONTROL_SOCKET is unset, so there is no socket to authenticate against. Half a pair is not a control endpoint, so this launch is refused rather than started without the control plane it was configured to have.")}function hasIdentity(env=process.env){return Boolean(env.COTAL_NAME?.trim()||env.COTAL_LINK?.trim()||env.COTAL_AGENT_FILE?.trim())}var FEEDBACK_URL="https://broker.cotal.ai/v1/feedback";var PUBLIC_FEEDBACK_URL="https://cotal.ai/v1/feedback";function isAuthed(config2){return Boolean(config2.creds)||Boolean(config2.userAuth)}function splitList(v){if(!v)return[];return v.split(",").map(s=>s.trim()).filter(Boolean)}function endpointsEnv(v){let raw;try{raw=JSON.parse(v)}catch{raw=void 0}if(!Array.isArray(raw))throw new Error("COTAL_ENDPOINTS: expected the JSON list the launcher writes");return parsePersonaEndpoints(raw,"COTAL_ENDPOINTS")}function envList(v){return v===void 0?void 0:splitList(v)}var EnvFlagError=class extends Error{};function envFlag(env,name){const value=env[name]?.trim();if(!value)return void 0;if(/^(1|true|yes|on)$/i.test(value))return true;if(/^(0|false|no|off)$/i.test(value))return false;throw new EnvFlagError(`COTAL config: ${name} must be 1/true/yes/on or 0/false/no/off, got "${env[name]}"`)}function scrubLaunchMaterial(env=process.env){const path=env[LAUNCH_MATERIAL_ENV]?.trim();delete env[LAUNCH_MATERIAL_ENV];if(path)discardLaunchMaterial(path)}function configFromEnv(env=process.env){const link=env.COTAL_LINK?.trim()?parseJoinLink(env.COTAL_LINK.trim()):void 0;const def=env.COTAL_AGENT_FILE?.trim()?loadAgentFile(env.COTAL_AGENT_FILE.trim()):void 0;const name=env.COTAL_NAME?.trim()||def?.name||(link?userInfo2().username:void 0);if(!name)throw new Error("COTAL_NAME, COTAL_AGENT_FILE or COTAL_LINK is required \u2014 a Cotal session needs an explicit identity from its launcher");const resolvedSubscribe=envList(env.COTAL_SUBSCRIBE)??def?.subscribe??link?.channels??[];let resolvedAllowSub;try{resolvedAllowSub=resolveReadAcl(resolvedSubscribe,envList(env.COTAL_ALLOW_SUBSCRIBE)??def?.allowSubscribe)}catch(e){throw new Error(`COTAL config: ${e.message}`)}const resolvedAllowPub=envList(env.COTAL_ALLOW_PUBLISH)??def?.allowPublish??[];for(const ch of[...resolvedSubscribe,...resolvedAllowSub,...resolvedAllowPub])assertValidChannel(ch);const qEnv=splitList(env.COTAL_QUIET),mEnv=splitList(env.COTAL_MUTED);const resolvedQuiet=qEnv.length?qEnv:def?.quiet??[];const resolvedMuted=mEnv.length?mEnv:def?.muted??[];const bothModes=resolvedQuiet.filter(c=>resolvedMuted.includes(c));if(bothModes.length)throw new Error(`COTAL config: channel(s) [${bothModes.join(", ")}] are in both quiet and muted`);for(const[field,chans]of[["quiet",resolvedQuiet],["muted",resolvedMuted]])for(const ch of chans){assertValidChannel(ch);if(!isConcreteChannel(ch))throw new Error(`COTAL config: ${field} channel "${ch}" must be concrete (no wildcard)`);if(!channelInAllow(resolvedAllowSub,ch))throw new Error(`COTAL config: ${field} channel "${ch}" is not within allowSubscribe [${resolvedAllowSub.join(", ")}]`)}const material=readMaterial(env);if(env.COTAL_SERVERS?.trim()&&brokerUrlHasUserinfo(env.COTAL_SERVERS))throw new Error("COTAL config: COTAL_SERVERS must not embed credentials; name the broker URL without user:password@, and pass the credential in COTAL_CREDS, COTAL_TOKEN or a COTAL_LINK");const credsPath=material?.creds??env.COTAL_CREDS?.trim();const initialCreds=credsPath?readFileSync4(credsPath,"utf8"):void 0;const credsId=initialCreds?idFromCreds(initialCreds):void 0;const boundedCreds=initialCreds!==void 0&&typeof credsClaims(initialCreds).exp==="number";const declaredId=env.COTAL_ID?.trim()||void 0;if(declaredId&&credsId&&declaredId!==credsId)throw new Error(`COTAL config: COTAL_ID ${declaredId} != creds identity ${credsId} - they must be the same nkey`);const userVars=material?.userAuth?{owner:material.userAuth.owner,actor:material.userAuth.actor,sentinel:material.userAuth.sentinelCredsPath,bearerCmd:JSON.stringify(material.userAuth.bearerCmd)}:{owner:env.COTAL_OWNER?.trim(),actor:env.COTAL_ACTOR?.trim(),sentinel:env.COTAL_SENTINEL_CREDS?.trim(),bearerCmd:env.COTAL_BEARER_CMD?.trim()};const userSet=Object.values(userVars).filter(Boolean).length;if(userSet>0&&userSet<4)throw new Error("COTAL config: user-mode launch needs ALL of COTAL_OWNER, COTAL_ACTOR, COTAL_SENTINEL_CREDS, COTAL_BEARER_CMD \u2014 a partial set is a broken launcher, not a mode");if(userSet&&credsPath)throw new Error("COTAL config: COTAL_CREDS (static auth) and COTAL_OWNER/... (user-mode auth) are mutually exclusive");const lifecycleUid=env.COTAL_LIFECYCLE_UID?.trim()||void 0;const backfillFloorRaw=env.COTAL_BACKFILL_FLOOR?.trim()||void 0;let backfillFloor;if(backfillFloorRaw!==void 0){const n=Number(backfillFloorRaw);if(!Number.isInteger(n)||n<0)throw new Error(`COTAL config: COTAL_BACKFILL_FLOOR must be a non-negative integer stream sequence, got "${backfillFloorRaw}" (a broken launcher, not a mode)`);backfillFloor=n}const acceptedToken=env.COTAL_ACCEPTED_TOKEN?.trim()||void 0;const managerInstanceId=env.COTAL_MANAGER_INSTANCE?.trim()||void 0;if(managerInstanceId!==void 0)assertLifecycleToken(managerInstanceId,"COTAL_MANAGER_INSTANCE");if(acceptedToken&&!credsPath)throw new Error("COTAL config: COTAL_ACCEPTED_TOKEN names a static issuance and needs COTAL_CREDS beside it (a broken launcher, not a mode)");if((credsPath||userSet===4)&&!lifecycleUid)throw new Error("COTAL config: an authed launch (COTAL_CREDS or user-mode) requires COTAL_LIFECYCLE_UID - the launcher mints it at provision time (a broken launcher, not a mode)");let userAuth;if(userSet===4){let bearerCmd;try{bearerCmd=JSON.parse(userVars.bearerCmd)}catch{throw new Error("COTAL config: COTAL_BEARER_CMD must be a JSON argv array")}if(!Array.isArray(bearerCmd)||!bearerCmd.length||!bearerCmd.every(a=>typeof a==="string"))throw new Error("COTAL config: COTAL_BEARER_CMD must be a non-empty JSON array of strings");userAuth={owner:userVars.owner,actor:userVars.actor,sentinelCreds:readFileSync4(userVars.sentinel,"utf8"),bearerCmd}}const eventsRequired=material?.eventsRequired===true||!material&&envFlag(env,"COTAL_EVENTS_REQUIRED")===true;if(eventsRequired&&!userAuth)throw new Error("COTAL config: COTAL_EVENTS_REQUIRED is valid only for a user-mode registration launch");if(eventsRequired){const principal=userSet===4?{owner:userVars.owner,actor:userVars.actor}:{owner:DEV_OWNER,actor:credsId??declaredId??""};if(!principal.actor)throw new Error("COTAL config: this space requires events, but the session has no stable principal to derive its event channel");const channel=eventChannel(principal);if(!channelInAllow(resolvedAllowPub,channel))throw new Error(`COTAL config: space "${env.COTAL_SPACE?.trim()||link?.space||"demo"}" requires events, but this session's grant does not cover its event channel "${channel}". Widen the whole user-auth actor row with \`cotal actor grant ${principal.actor} --owner ${principal.owner} --scope <current-scope> --allow-subscribe <current-read> --allow-publish '<current-post>,${channel}' --role <current-role> --label <current-label>\`; actor grant replaces the whole row, so preserve every current field.`)}return{space:env.COTAL_SPACE?.trim()||link?.space||"demo",id:credsId??declaredId,lifecycleUid,backfillFloor,acceptedToken,managerInstanceId,creds:boundedCreds?async()=>readFileSync4(credsPath,"utf8"):initialCreds,userAuth,name,role:env.COTAL_ROLE||def?.role||void 0,description:def?.description,tags:def?.tags,meta:def?.meta,capabilities:splitList(env.COTAL_CAPABILITIES).length?splitList(env.COTAL_CAPABILITIES):def?.capabilities,endpoints:env.COTAL_ENDPOINTS!==void 0?endpointsEnv(env.COTAL_ENDPOINTS):def?.endpoints,model:env.COTAL_MODEL?.trim()||void 0,variant:env.COTAL_VARIANT?.trim()||void 0,servers:material?.servers||env.COTAL_SERVERS?.trim()||link?.servers||DEFAULT_SERVER,subscribe:resolvedSubscribe,allowSubscribe:resolvedAllowSub,allowPublish:resolvedAllowPub,eventsRequired,eventPayloadsWithheld:material?.eventPayloadsWithheld===true||envFlag(env,"COTAL_EVENT_PAYLOADS")===false,quiet:resolvedQuiet,muted:resolvedMuted,kind:assertValidKind(env.COTAL_KIND?.trim()||def?.kind||"agent"),token:material?.token||env.COTAL_TOKEN?.trim()||link?.token,user:link?.user,pass:link?.pass,tls:envFlag(env,"COTAL_TLS")||link?.tls||false,feedbackKey:env.COTAL_FEEDBACK_KEY?.trim()||void 0,feedbackUrl:env.COTAL_FEEDBACK_URL?.trim()||void 0}}function eventPlaneArmed(config2,env=process.env){return envFlag(env,"COTAL_EVENTS")===true||config2.eventsRequired===true}function feedbackLine(config2){const dest=config2.feedbackKey?"":`Without a feedback key it goes to the public cotal.ai intake and needs a contact email \u2014 the tool will tell you to ask the user for one if it can't find it. `;return`Use cotal_feedback with origin="human" when the user asks you to send feedback or gives you feedback to pass along. If you independently hit a major Cotal issue \u2014 for example repeated Cotal tool failures, inability to connect, lost/incorrect mesh messages, or a workflow-blocking bug \u2014 send cotal_feedback yourself with origin="agent". Do not send minor noise or secrets; include diagnostics only when they help debug the Cotal issue. `+dest}import{AsyncLocalStorage as AsyncLocalStorage2}from"node:async_hooks";import{EventEmitter as EventEmitter2}from"node:events";import{hostname as hostname2}from"node:os";import{createHash as createHash8,randomUUID as randomUUID5}from"node:crypto";import{open as open3,readFile as readFile2,unlink as unlink2}from"node:fs/promises";import{hostname}from"node:os";import{dirname as dirname6,join as join7}from"node:path";import{createHash as createHash7,randomUUID as randomUUID4}from"node:crypto";import{constants as constants4}from"node:fs";import{open as open2,readFile,rename,unlink}from"node:fs/promises";import{dirname as dirname5,join as join6}from"node:path";var EVENT_WAL_VERSION=4;var WalCorruptError=class extends Error{path;invariant;constructor(path,invariant,detail){super(`event WAL at ${path} is unusable (${invariant}): ${detail}`);this.path=path;this.invariant=invariant;this.name="WalCorruptError"}};var WalStaleWriterError=class extends Error{path;expectedGen;foundGen;constructor(path,expectedGen,foundGen){super(`event WAL at ${path} was written by another handle since this one read it (this handle expects generation ${expectedGen}, the file is at ${foundGen===void 0?"no file at all":`generation ${foundGen}`}) \u2014 refusing to overwrite it. A second emitter or a stale handle is writing this principal's log.`);this.path=path;this.expectedGen=expectedGen;this.foundGen=foundGen;this.name="WalStaleWriterError"}};var isSafeNonNegInt2=n=>Number.isSafeInteger(n)&&n>=0;function docGeneration(path,doc){if(typeof doc.v==="number"&&doc.v<3)return 0;if(!isSafeNonNegInt2(doc.gen))throw new WalCorruptError(path,"gen is a safe non-negative integer",`found gen=${String(doc.gen)} on a v${String(doc.v)} document`);return doc.gen}async function openExclusiveNoFollow(path){return open2(path,constants4.O_WRONLY|constants4.O_CREAT|constants4.O_EXCL|(constants4.O_NOFOLLOW??0),384)}function assertPendingVintage(path,p,f){if(p.E!==f.lastSubjectSeq)throw new WalCorruptError(path,"pending.E === frontier.lastSubjectSeq",`pending.E=${p.E} frontier.lastSubjectSeq=${f.lastSubjectSeq} \u2014 the frozen expectation is not the tip this WAL believes, so retrying it can only CAS-halt or append at the wrong position`);if(p.seq!==f.seq+1)throw new WalCorruptError(path,"pending.seq === frontier.seq + 1",`pending.seq=${p.seq} frontier.seq=${f.seq} \u2014 a pending frame must be exactly the frontier's successor`);if(p.state==="sent_unacked"){if(p.ackSeq!==void 0)throw new WalCorruptError(path,"sent_unacked has no ackSeq",`state is "sent_unacked" but ackSeq=${String(p.ackSeq)} \u2014 the document contradicts its own tag`);return}if(!isSafeNonNegInt2(p.ackSeq))throw new WalCorruptError(path,"acked.ackSeq present",`state is "acked" but ackSeq is ${String(p.ackSeq)}`);if(!(p.ackSeq>f.lastSubjectSeq))throw new WalCorruptError(path,"acked.ackSeq > frontier.lastSubjectSeq",`ackSeq=${p.ackSeq} frontier.lastSubjectSeq=${f.lastSubjectSeq} \u2014 the frontier is of a later vintage than the acked frame, so its sourceCursor may already have passed events that were never published; resuming would drop them with no gap for a consumer to see`)}function parseBrackets(path,field,v,nullable2){if(v===null&&nullable2)return null;if(typeof v!=="object"||v===null)throw new WalCorruptError(path,`${field} is an object${nullable2?" or null":""}`,JSON.stringify(v));const b=v;if(b.run!==void 0&&typeof b.run!=="string")throw new WalCorruptError(path,`${field}.run is a string or absent`,JSON.stringify(b.run));const lists={text:b.text,reasoning:b.reasoning,tools:b.tools};for(const[k,list]of Object.entries(lists)){if(!Array.isArray(list)||list.some(x=>typeof x!=="string"))throw new WalCorruptError(path,`${field}.${k} is an array of strings`,JSON.stringify(list))}if(b.run===void 0&&b.text.concat(b.reasoning,b.tools).length>0)throw new WalCorruptError(path,`${field} has no open run while messages or tool calls are open`,JSON.stringify(b));return{run:b.run,text:b.text,reasoning:b.reasoning,tools:b.tools}}function parsePayloadCalls(path,value){if(value===void 0)return void 0;if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).length>4096||Object.entries(value).some(([id2,allowed])=>!id2||typeof allowed!=="boolean"))throw new WalCorruptError(path,"payloadCalls is a bounded boolean record","invalid call classification");return{...value}}function parseDoc(path,raw,space2,threadId,principal){let d;try{d=JSON.parse(raw)}catch(e){throw new WalCorruptError(path,"parseable JSON",e.message)}if(typeof d!=="object"||d===null)throw new WalCorruptError(path,"document is an object",typeof d);const doc=d;if(typeof doc.v!=="number"||!Number.isSafeInteger(doc.v)||doc.v<1)throw new WalCorruptError(path,"v is a positive integer",`found v=${String(doc.v)}`);if(doc.v>EVENT_WAL_VERSION)throw new WalCorruptError(path,`v <= ${EVENT_WAL_VERSION}`,`this WAL is v${doc.v} and this build understands v${EVENT_WAL_VERSION} \u2014 THE STATE IS NEWER THAN THE CODE, which is what a code rollback across the v2 migration (persisted bracket state) or the v3 one (the write generation) leaves behind. The migration is forward-only by design: there is no downgrade, because a lossy one would silently discard state this file exists to preserve. Run the newer build, or move this WAL aside and accept that the thread restarts from a new epoch.`);if(doc.space!==space2)throw new WalCorruptError(path,"space matches",`WAL space=${String(doc.space)} caller=${space2}`);if(doc.threadId!==threadId)throw new WalCorruptError(path,"threadId matches",`WAL threadId=${String(doc.threadId)} caller=${threadId}`);if(doc.principal!==principal)throw new WalCorruptError(path,"principal matches",`WAL principal=${String(doc.principal)} caller=${principal}`);if(typeof doc.epoch!=="string"||doc.epoch.length===0)throw new WalCorruptError(path,"epoch is a non-empty string",String(doc.epoch));const f=doc.frontier;if(!f||!isSafeNonNegInt2(f.seq)||!isSafeNonNegInt2(f.lastSubjectSeq))throw new WalCorruptError(path,"frontier is well-formed",JSON.stringify(doc.frontier));if(f.sourceCursor!==void 0&&typeof f.sourceCursor!=="string")throw new WalCorruptError(path,"frontier.sourceCursor is a string or absent",typeof f.sourceCursor);if(f.seq===0!==(f.lastSubjectSeq===0))throw new WalCorruptError(path,"frontier.seq and lastSubjectSeq are both zero or both nonzero",JSON.stringify(f));if((f.seq>0||f.lastSubjectSeq>0)&&typeof f.sourceCursor!=="string")throw new WalCorruptError(path,"a nonzero frontier carries its sourceCursor",JSON.stringify(f));if(doc.pending!==null&&typeof doc.pending!=="object")throw new WalCorruptError(path,"pending is present (null or an object)",doc.pending===void 0?"the key is absent, which is not the same as null":typeof doc.pending);let pending=null;if(doc.pending!==null){const p=doc.pending;if(p.state!=="sent_unacked"&&p.state!=="acked")throw new WalCorruptError(path,"pending.state is a known tag",String(p.state));if(typeof p.id!=="string"||p.id.length===0)throw new WalCorruptError(path,"pending.id is a non-empty string",String(p.id));try{assertIdToken(p.id,"event WAL pending.id")}catch(e){throw new WalCorruptError(path,"pending.id satisfies the wire id grammar",e.message)}if(!isSafeNonNegInt2(p.E)||!isSafeNonNegInt2(p.seq))throw new WalCorruptError(path,"pending E/seq are safe non-negative integers",JSON.stringify(p));if(typeof p.sourceCursor!=="string")throw new WalCorruptError(path,"pending.sourceCursor is a string",typeof p.sourceCursor);if(!Array.isArray(p.body)||p.body.length===0)throw new WalCorruptError(path,"pending.body is a non-empty array of parts",JSON.stringify(p.body));if(doc.v===1)throw new WalCorruptError(path,"a v1 WAL has no frame in flight",`this v1 document holds a ${String(p.state)} frame, and v2 requires the bracket state that belongs to it \u2014 which v1 never recorded and nothing here can reconstruct. Let the older build settle this frame first, then start the newer one.`);p.brackets=parseBrackets(path,"pending.brackets",p.brackets,false);if(p.payload!==void 0){const payload=p.payload;if(doc.v<4||!payload||typeof payload!=="object"||!Array.isArray(payload.body)||payload.body.length===0||!isSafeNonNegInt2(payload.E)||payload.ackSeq!==void 0&&(!isSafeNonNegInt2(payload.ackSeq)||payload.ackSeq<=payload.E))throw new WalCorruptError(path,"pending payload is a v4 frozen publication",JSON.stringify(payload));assertIdToken(payload.id,"event WAL payload id")}p.payloadCalls=parsePayloadCalls(path,p.payloadCalls);pending=p;assertPendingVintage(path,pending,f)}const brackets=doc.v===1?null:parseBrackets(path,"brackets",doc.brackets,true);return{v:EVENT_WAL_VERSION,gen:docGeneration(path,doc),space:space2,epoch:doc.epoch,threadId,principal,frontier:f,pending,payloadCalls:parsePayloadCalls(path,doc.payloadCalls),brackets}}var EventWal=class _EventWal{path;doc;chain=Promise.resolve();serialize(op){const next=this.chain.then(op,op);this.chain=next.catch(()=>void 0);return next}constructor(path,doc){this.path=path;this.doc=doc}get payloadCalls(){return{...this.doc.pending?.payloadCalls??this.doc.payloadCalls??{}}}get epoch(){return this.doc.epoch}get space(){return this.doc.space}get principal(){return this.doc.principal}get threadId(){return this.doc.threadId}get brackets(){return this.doc.brackets}get frontier(){return{...this.doc.frontier}}get pending(){return this.doc.pending?{...this.doc.pending}:null}subject;static async open(path,opts){let raw;let bytes;try{bytes=await readFile(path)}catch(e){if(e.code!=="ENOENT")throw e}if(bytes!==void 0){try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new WalCorruptError(path,"the file is valid UTF-8","invalid UTF-8 bytes; refusing rather than substituting U+FFFD")}}if(raw===void 0){if(opts.subjectMayExist)throw new WalCorruptError(path,"WAL exists when the subject may","no WAL file, but this thread may already have published");return new _EventWal(path,_EventWal.virgin(opts.space,opts.threadId,opts.principal))}if(raw.length===0)throw new WalCorruptError(path,"WAL is non-empty","the file is zero bytes \u2014 distinct from missing and never treated as a virgin thread");return new _EventWal(path,parseDoc(path,raw,opts.space,opts.threadId,opts.principal))}static virgin(space2,threadId,principal){return{v:EVENT_WAL_VERSION,gen:0,space:space2,epoch:randomUUID4(),threadId,principal,frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}}}async bindSubjectFrontier(frontier){if(this.subject===frontier)return;if(this.subject)throw new Error(`event WAL ${this.path}: a DIFFERENT subject frontier is already bound`);this.subject=frontier}get expectedTip(){if(!this.subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so there is no expectation to publish. The subject is shared by every thread of this principal, so this document's own last ack is not it; bind the principal's record with bindSubjectFrontier first.`);return this.subject.tip}async beginSend(frame){return this.serialize(async()=>{if(this.doc.pending)throw new Error(`event WAL ${this.path}: a frame is already pending; one emit unit is one pending frame`);assertIdToken(frame.id,"event WAL pending id");if(frame.E!==this.expectedTip)throw new Error(`event WAL ${this.path}: E=${frame.E} is not the subject's tip ${this.expectedTip}`);if(frame.seq!==this.doc.frontier.seq+1)throw new Error(`event WAL ${this.path}: seq=${frame.seq} is not the frontier's successor ${this.doc.frontier.seq+1}`);if(!Array.isArray(frame.body)||frame.body.length===0)throw new Error(`event WAL ${this.path}: a frame body must be a non-empty array of parts`);parsePayloadCalls(this.path,frame.payloadCalls);if(frame.payload){assertIdToken(frame.payload.id,"event WAL payload id");if(!isSafeNonNegInt2(frame.payload.E)||!Array.isArray(frame.payload.body)||frame.payload.body.length===0||frame.payload.ackSeq!==void 0)throw new Error("event WAL payload must be an unacknowledged frozen publication")}await this.write({...this.doc,pending:{state:"sent_unacked",...frame}})})}async recordPayloadAck(ackSeq){return this.serialize(async()=>{const p=this.doc.pending;if(!p?.payload||p.state!=="sent_unacked"||p.payload.ackSeq!==void 0)throw new Error("event WAL has no unacknowledged sibling payload");if(!isSafeNonNegInt2(ackSeq)||ackSeq<=p.payload.E)throw new Error("payload ack must advance its frozen expectation");await this.write({...this.doc,pending:{...p,payload:{...p.payload,ackSeq}}})})}async recordAck(ackSeq){return this.serialize(async()=>{const p=this.doc.pending;if(!p||p.state!=="sent_unacked")throw new Error(`event WAL ${this.path}: no sent_unacked frame to ack`);if(p.payload&&p.payload.ackSeq===void 0)throw new Error("event WAL cannot acknowledge public frame before sibling payload");if(!isSafeNonNegInt2(ackSeq))throw new Error(`event WAL ${this.path}: ackSeq must be a safe non-negative integer, got ${String(ackSeq)}`);if(ackSeq<=this.expectedTip)throw new Error(`event WAL ${this.path}: ackSeq=${ackSeq} is not ahead of the subject's tip ${this.expectedTip}`);const subject=this.subject;if(!subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so this ack has no shared record to advance`);await this.assertNotClobbering();await subject.advance(ackSeq);await this.write({...this.doc,pending:{...p,state:"acked",ackSeq}})})}async fold(){return this.serialize(async()=>{const p=this.doc.pending;if(!p||p.state!=="acked"||p.ackSeq===void 0)throw new Error(`event WAL ${this.path}: no acked frame to fold`);await this.write({...this.doc,frontier:{seq:p.seq,lastSubjectSeq:p.ackSeq,sourceCursor:p.sourceCursor},pending:null,brackets:p.brackets,payloadCalls:p.payloadCalls??this.doc.payloadCalls})})}async advanceCursorOnly(rangeEnd){return this.serialize(async()=>{if(this.doc.pending)throw new Error(`event WAL ${this.path}: cannot advance the cursor while a frame is pending`);await this.write({...this.doc,frontier:{...this.doc.frontier,sourceCursor:rangeEnd}})})}async abandon(){return this.serialize(async()=>{await this.assertNotClobbering();if(!this.subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so an abandonment here would clear this log and leave the principal's shared tip standing, which is the partial abandonment this method refuses to produce; bind the principal's record with bindSubjectFrontier first.`);await this.subject.reset();await this.write({...this.doc,epoch:randomUUID4(),frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}})})}async write(next){await this.assertNotClobbering();const stamped={...next,gen:this.doc.gen+1};const tmp=join6(dirname5(this.path),`.${createHash7("sha256").update(this.path).digest("hex").slice(0,12)}.${process.pid}.${randomUUID4().slice(0,8)}.wal.tmp`);const body=JSON.stringify(stamped);const fh=await openExclusiveNoFollow(tmp);try{await fh.writeFile(body,"utf8");await fh.sync()}finally{await fh.close()}try{await rename(tmp,this.path)}catch(e){await unlink(tmp).catch(()=>{});throw e}this.doc=stamped}async assertNotClobbering(){let bytes;try{bytes=await readFile(this.path)}catch(e){if(e.code!=="ENOENT")throw e}if(bytes===void 0){if(this.doc.gen!==0)throw new WalStaleWriterError(this.path,this.doc.gen,void 0);return}let raw;try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new WalCorruptError(this.path,"the file is valid UTF-8","invalid UTF-8 bytes on the file about to be replaced; refusing rather than substituting U+FFFD")}let d;try{d=JSON.parse(raw)}catch(e){throw new WalCorruptError(this.path,"parseable JSON",e.message)}if(typeof d!=="object"||d===null)throw new WalCorruptError(this.path,"document is an object",typeof d);const onDisk=docGeneration(this.path,d);if(onDisk!==this.doc.gen)throw new WalStaleWriterError(this.path,this.doc.gen,onDisk)}};var EventsStateRootMissing=class extends Error{constructor(message){super(message);this.name="EventsStateRootMissing"}};function resolveEventsStateRoot(env){const root=env.COTAL_WORKSPACE_ROOT;if(typeof root!=="string"||root.trim()==="")throw new EventsStateRootMissing("events are enabled for this session but COTAL_WORKSPACE_ROOT is not set, so there is nowhere to put the event write-ahead log. The launcher forwards it from LaunchOpts.workspaceRoot; a session started outside a manager has no workspace root and must not publish events. Refusing rather than defaulting to the working directory, which would put the WAL somewhere no later start looks.");return root}function h(value){return createHash8("sha256").update(value).digest("hex").slice(0,16)}function eventWalLocation(opts){const principal=eventPrincipalLocation(opts);const threadDir=join7(principal.principalDir,h(opts.threadId));return{...principal,threadDir,walPath:join7(threadDir,"wal.json")}}var PrincipalLockError=class extends Error{path;invariant;constructor(path,invariant,detail){super(`event WAL principal lock at ${path} (${invariant}): ${detail}`);this.path=path;this.invariant=invariant;this.name="PrincipalLockError"}};var held=new Map;function ownerIsAlive(pid){try{process.kill(pid,0);return true}catch(e){return e.code!=="ESRCH"}}async function createLockFile(path){try{return await openExclusiveNoFollow(path)}catch(e){if(e.code==="EEXIST")return void 0;throw e}}async function reclaimIfOwnerIsGone(path){let raw;try{raw=await readFile2(path,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}let record2;try{record2=JSON.parse(raw)}catch{throw new PrincipalLockError(path,"the lock names its owner","the file is not readable JSON, so its owner cannot be checked; refusing rather than reclaiming a lock that may be held")}const r=record2;if(!Number.isSafeInteger(r.pid)||r.pid<=0||typeof r.host!=="string"||r.host.length===0)throw new PrincipalLockError(path,"the lock names its owner",`the record carries pid=${String(r.pid)} host=${String(r.host)}, which names nobody checkable`);const here=hostname();if(r.host!==here)throw new PrincipalLockError(path,"the recorded owner is on THIS host",`held by pid ${r.pid} on ${r.host} while this process runs on ${here}; liveness on another machine is not observable from here`);if(ownerIsAlive(r.pid))throw new PrincipalLockError(path,"the recorded owner is gone",`pid ${r.pid} on ${here} is still running and holds this principal's emitter`);await unlink2(path).catch(e=>{if(e.code!=="ENOENT")throw e})}async function acquirePrincipalLock(lockPath){const already=held.get(lockPath);if(already)return already;let fh=await createLockFile(lockPath);if(fh===void 0){await reclaimIfOwnerIsGone(lockPath);fh=await createLockFile(lockPath);if(fh===void 0)throw new PrincipalLockError(lockPath,"the reclaimed lock is free when this process takes it","another process created the lock between the reclaim and this open, and now holds this principal")}const record2=JSON.stringify({pid:process.pid,host:hostname(),token:randomUUID5(),acquiredAt:new Date().toISOString()});try{await fh.writeFile(record2,"utf8");await fh.sync()}catch(e){await fh.close().catch(()=>{});await unlink2(lockPath).catch(()=>{});throw e}const lock={path:lockPath,async release(){if(held.get(lockPath)!==lock)return;held.delete(lockPath);await fh.close().catch(()=>{});await unlink2(lockPath).catch(e=>{if(e.code!=="ENOENT")throw e})}};held.set(lockPath,lock);return lock}async function fsyncDir(dir){let fh;try{fh=await open3(dir,"r")}catch(e){const code=e.code;if(code==="EPERM"||code==="EACCES")return;throw e}try{await fh.sync()}catch(e){const code=e.code;if(code!=="EBADF"&&code!=="EINVAL"&&code!=="EPERM"&&code!=="EISDIR")throw e}finally{await fh.close()}}async function ensureEventWalDir(opts){const loc=eventWalLocation(opts);ensureDirNoSymlink(opts.workspaceRoot,".cotal","events",h(opts.space),h(opts.principal),h(opts.threadId));for(let dir=loc.threadDir;;dir=dirname6(dir)){await fsyncDir(dir);if(dir===opts.workspaceRoot||dirname6(dir)===dir)break}const lock=await acquirePrincipalLock(loc.lockPath);return{...loc,lock}}async function checkEventStartup2(ep,env){await checkEventStartup({workspaceRoot:resolveEventsStateRoot(env),space:ep.space,principal:ep.principal,retainedMessages:async()=>(await ep.chatRetention()).senders})}var TURN_PULL_RETRY_MS=15e3;var ONCE_HANDOFF_MS=6e4;var ONCE_EXIT_GRACE_MS=1e4;var KEY=Symbol.for("cotal.once-handoff");function proc(){const g=globalThis;return g[KEY]??={handoffs:new Map}}var keyOf=(uid2,goalId)=>`${uid2}:${goalId}`;function onceHandoffState(uid2,goalId){return proc().handoffs.get(keyOf(uid2,goalId))?.state??"pending"}function claimOnceHandoff(uid2,goalIds){const p=proc();if(goalIds.some(id2=>onceHandoffState(uid2,id2)!=="pending"))return false;for(const id2 of goalIds){const timer=setTimeout(()=>p.timedOut?.(uid2,id2),ONCE_HANDOFF_MS);timer.unref?.();p.handoffs.set(keyOf(uid2,id2),{state:"claimed",timer})}return true}function confirmOnceHandoff(uid2,goalId){const h2=proc().handoffs.get(keyOf(uid2,goalId));if(h2?.state==="sealed")return false;if(h2?.timer!==void 0)clearTimeout(h2.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"confirmed"});return true}function sealOnceHandoff(uid2,goalId){const h2=proc().handoffs.get(keyOf(uid2,goalId));if(h2?.state!=="claimed")return false;if(h2.timer!==void 0)clearTimeout(h2.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"sealed"});return true}function endOnceHandoff(uid2,goalId){const h2=proc().handoffs.get(keyOf(uid2,goalId));if(h2?.state==="confirmed"||h2?.state==="sealed")return;if(h2?.timer!==void 0)clearTimeout(h2.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"sealed"})}function stopOnceHandoffTimer(uid2,goalId){const h2=proc().handoffs.get(keyOf(uid2,goalId));if(h2?.state!=="claimed"||h2.timer===void 0)return;clearTimeout(h2.timer);h2.timer=void 0}function onOnceHandoffTimeout(fn){proc().timedOut=fn}function registerOnceExit(fn){proc().exit=fn}function exitOnceSeat(){const p=proc();if(p.exiting)return p.exiting;const exiting=askOnceExit(p.exit).then(ending=>{if(!ending){p.exiting=void 0;return false}setTimeout(()=>process.exit(1),ONCE_EXIT_GRACE_MS);return true});p.exiting=exiting;return exiting}async function askOnceExit(exit){let ending;try{ending=exit?.()}catch{return true}if(ending instanceof Promise)ending=await ending.catch(()=>false);return ending!==false}init_peer_label();function attributionSafe(s){return peerLabel({name:s})}function fmtFrom(i){const name=i.fromName.trim()?i.fromName:i.fromId;return peerLabel({name,...i.fromRole?{role:i.fromRole}:{}})}function fmtBody(text2){return text2.split(LINE_BREAK).join("\n ")}function fmtItem(i){return formatItem(i)}function fmtDeliveryItem(i){const field=value=>Array.from(JSON.stringify(value),char=>[91,93,133,8232,8233].includes(char.charCodeAt(0))?`\\u${char.charCodeAt(0).toString(16).padStart(4,"0")}`:char).join("");const metadata2=[`sender_id=${field(i.fromId)}`,...i.id?[`message_id=${field(i.id)}`]:[],...i.contextId?[`context_id=${field(i.contextId)}`]:[],...i.replyTo?[`reply_to=${field(i.replyTo)}`]:[]];return formatItem(i,`[${metadata2.join(" ")}] `)}function formatItem(i,metadata2=""){const h2=i.historical?"(history) ":"";const r=i.deliveryCount!==void 0&&i.deliveryCount>1?`(broker redelivery, delivery ${i.deliveryCount}: prior model handoff unknown) `:"";const body=`${metadata2}${h2}${r}${fmtBody(i.text)}`;if(i.notice==="anycast")return`[anycast notice from the delivery daemon] ${body}`;if(i.kind==="dm")return`[DM from ${fmtFrom(i)}] ${body}`;if(i.kind==="anycast")return`[@${attributionSafe(i.service??"")} from ${fmtFrom(i)}] ${body}`;return`[#${attributionSafe(i.channel??"")}${i.mentionsMe?" @you":""} ${fmtFrom(i)}] ${body}`}var legacyRail=new Map;var LEGACY_RAIL_RECHECK_MS=60*6e4;var LEGACY_RAIL_MAX=32;function onLegacyRail(key){const until=legacyRail.get(key);if(until===void 0)return false;if(Date.now()<until)return true;legacyRail.delete(key);return false}function rememberLegacyRail(key){legacyRail.set(key,Date.now()+LEGACY_RAIL_RECHECK_MS);if(legacyRail.size>LEGACY_RAIL_MAX)legacyRail.delete(legacyRail.keys().next().value)}async function withUserManagerListing(config2,token2,exp,ask){const user=config2.userAuth;const binding=managerCallerBinding(token2,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId});const railKey=binding.credentialId??token2;const connectOpts=standaloneConnectOpts({bearer:token2,sentinelCreds:user.sentinelCreds,tls:config2.tls});const connId=String(connectOpts.name);const nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:1e4});const issued=async()=>{try{const caller=await issuedUserCaller(nc,config2.space,connId,binding.caller);legacyRail.delete(railKey);return caller}catch(e){if(!isPermissionDenied(e))throw e;rememberLegacyRail(railKey);return void 0}};try{const skipped=onLegacyRail(railKey);const caller=skipped?void 0:await issued();const listing=caller??await registryListingCaller(nc,config2.space,binding.caller,{connId,...exp!==void 0?{exp}:{}});return await ask(nc,listing??(skipped?await issued():void 0))}finally{await drainAndClose(nc)}}async function invokeUserManager(config2,bearer,command,args,opts={}){opts.signal?.throwIfAborted();const user=config2.userAuth;const endpoint=BASELINE_LIFECYCLE_ENDPOINT;let nc;let caller;let instanceId;let service;let skippedAcceptedRead;const onAbort=()=>{void nc?.close()};const resolve3=(signal=opts.signal,deadlineMs=opts.deadlineMs??1e4)=>resolveService(nc,config2.space,endpoint,caller,{instanceId,deadlineMs,signal,commands:opts.follow?[command,"goal-result"]:[command],...opts.follow&&command!=="goal-result"?{optionalCommands:["goal-result"]}:{}});const resolvePrepared=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const remaining=()=>{signal?.throwIfAborted();const left=deadline-Date.now();if(left<=0)throw new EpEnvelopeError("deadline-exceeded","the deadline passed before the manager was resolved; the manager request WAS NOT RUN",void 0,"not-executed");return left};try{return await resolve3(signal,remaining())}catch(error51){if(!skippedAcceptedRead||!isPermissionDenied(error51))throw error51;const{key,connId}=skippedAcceptedRead;skippedAcceptedRead=void 0;remaining();caller=await issuedUserCaller(nc,config2.space,connId,caller);legacyRail.delete(key);return resolve3(signal,remaining())}};const connect3=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const token2=await bearer(signal);let credentialId;({caller,instanceId,credentialId}=managerCallerBinding(token2,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId}));const connectOpts=standaloneConnectOpts({bearer:token2,sentinelCreds:user.sentinelCreds,tls:config2.tls});signal?.throwIfAborted();const left=deadline-Date.now();if(left<=0)throw new EpEnvelopeError("deadline-exceeded","the deadline passed before the manager was connected; the manager request WAS NOT RUN",void 0,"not-executed");nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:left});if(signal?.aborted)onAbort();signal?.throwIfAborted();const railKey=credentialId??token2;if(onLegacyRail(railKey)){skippedAcceptedRead={key:railKey,connId:String(connectOpts.name)}}else{try{caller=await issuedUserCaller(nc,config2.space,String(connectOpts.name),caller)}catch(e){if(!isPermissionDenied(e))throw e;rememberLegacyRail(railKey)}}};const prepare=async(signal,deadline)=>{await connect3(signal,deadline);service=await resolvePrepared(signal,deadline)};const invoke=async(signal=opts.signal)=>{const unfollowable=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable)return unfollowable;const invokeOpts={target:opts.target,deadlineMs:opts.deadlineMs,signal};const result=await invokeCommand(nc,config2.space,service,command,args,invokeOpts);if(result.reply.ok===false&&replyRefusedBeforeEffect(result.reply.error)){try{service=await resolve3(signal);const unfollowable2=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable2)throw new Error(unfollowable2.reply.error.message)}catch(error51){return{...result,reply:{...result.reply,error:{...result.reply.error,message:`${command} WAS NOT RUN; manager instance ${instanceId} refused before effects, and re-resolution failed: ${error51 instanceof Error?error51.message:String(error51)}`}}}}return invokeCommand(nc,config2.space,service,command,args,invokeOpts)}return result};opts.signal?.addEventListener("abort",onAbort,{once:true});try{if(opts.follow)return await opts.follow(invoke,prepare);await connect3();service=await resolvePrepared();return await invoke()}finally{opts.signal?.removeEventListener("abort",onAbort);const control=nc;if(control)await drainAndClose(control,2e3)}}var CONNECTOR_VERSION="0.164.15";import{createHash as createHash9,randomUUID as randomUUID6}from"node:crypto";var SPAWN_TIMEOUT_MS=4e4;var MANAGER_BEARER_MARGIN_MS=12e4;var CONNECT_GRACE_MS=1e4;function isLocalServer(servers){return servers.split(",").every(s=>/^(?:[a-z]+:\/\/)?(?:[^@/]*@)?(?:localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(?::\d+)?(?:\/|$)/i.test(s.trim()))}var EVENTS_META_KEY="ai.cotal.events";function buildMeta(config2,processCwd,eventsArmed){const meta3={...config2.meta??{}};if(config2.model)meta3.model=config2.model;if(config2.variant)meta3.variant=config2.variant;if(config2.connector)meta3.connector=config2.connector;meta3.host=hostname2();delete meta3["ai.cotal.manager.instance"];if(config2.managerInstanceId)meta3["ai.cotal.manager.instance"]=config2.managerInstanceId;meta3[EVENTS_META_KEY]=eventsArmed??eventPlaneArmed(config2)?"on":"off";if(processCwd)meta3.cwd=process.cwd();else delete meta3.cwd;return Object.keys(meta3).length?meta3:void 0}function afterRecallMark(a,b){return a.ts!==b.ts?a.ts>b.ts:a.id>b.id}var MAX_INBOX=200;var TAKE_WAIT_MS=2e3;var TAKE_RETRY_MS=1e4;var MAX_IN_FLIGHT=MAX_INBOX*2;var MAX_AHEAD=256;var CLASSIFICATION_CAP=4096;var FOCUS_EXCLUSION_CAP=4096;var IDLESS_READS=3;var PROTECTED_DISPOSITION_CAP=4096;var MAX_CORRELATIONS=1024;var ENDPOINT_ERROR_LOG_WINDOW_MS=3e4;var MAX_ENDPOINT_NOTICES=16;var NAMED_SIMILAR=5;var MAX_SETTLED_TURNS=32;function settledTurnError(goalId,t){if(t.yielded!==void 0)return`turn "${goalId}" was already yielded ${t.yielded} by this seat${t.yielded==="done"?" (ending a session turn yields done)":""}, so this yield was not recorded`;const deadline=t.deadlineAt!==void 0?` (deadline ${new Date(t.deadlineAt).toISOString()})`:"";return`turn "${goalId}" was already settled ${t.once!==void 0?"by its manager":"by the run"}${deadline}, so this yield was not recorded`}function compareRelease(a,b){const[x,y]=[a,b].map(v=>v.split(/[-+]/)[0].split(".").map(Number));for(let i=0;i<3;i++)if(x[i]!==y[i])return(x[i]??0)-(y[i]??0);return 0}var MAX_DATE_MS=864e13;function isPendingTurn(t){const r=t;if(typeof r!=="object"||r===null||typeof r.goalId!=="string"||typeof r.payload!=="string")return false;if(!Number.isSafeInteger(r.acceptedAt)||r.acceptedAt<0)return false;if(r.once!==void 0&&r.once!==true)return false;if(r.deadlineAt===void 0)return r.once===true;return Number.isSafeInteger(r.deadlineAt)&&r.deadlineAt>=1&&r.deadlineAt<=MAX_DATE_MS}function onceSpawner(payload){try{const spawner=JSON.parse(payload).once?.spawner;return typeof spawner==="string"&&spawner.length>0?spawner:void 0}catch{return void 0}}function carriesAnycastNotice(m){return m.parts.some(p=>p.kind==="data"&&typeof p.data==="object"&&p.data!==null&&!Array.isArray(p.data)&&ANYCAST_NOTICE_KEY in p.data)}function idlessDigest(m){return createHash9("sha256").update(JSON.stringify(m)).digest("base64url")}function sleep(ms){return new Promise(r=>setTimeout(r,ms))}function ingestDedupKey(id2){return id2===""?void 0:id2}var AUTOMATIC_QUEUE_STALL_MS=6e5;function renderAskRequest(p){const escalation=renderEscalation(p);if(escalation!=="")return escalation;const ask=p.ask;if(ask===null||typeof ask!=="object")return"";const a=ask;const entries=a.schema!==null&&typeof a.schema==="object"?Object.entries(a.schema):[];const fields=entries.length===0?"any record":entries.map(([k,v])=>`${k}: ${String(v)}`).join(", ");const by=typeof a.deadlineAt==="number"?`, by ${new Date(a.deadlineAt).toISOString()}`:"";const refused=typeof a.refused==="string"?`
115
+ (This is the only task this seat takes. Do it with your own tools, and send your result to whoever needs it, for example with cotal_dm to ${from}, before you end your turn: this seat is stopped when your turn ends${deadline}, and a result you have not sent reaches no one. If you cannot finish, call cotal_yield with blocked or handoff and say why.)`}var nonBlank=()=>({type:"string",pattern:"^\\s*\\S"});var AGENT_ROW_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,required:["name","id","agent","space","mode","status","uptimeMs","mesh","lifecycleUid"],properties:{name:{type:"string"},id:{type:"string"},role:{type:"string"},agent:{type:"string"},space:{type:"string"},mode:{type:"string"},status:{type:"string"},uptimeMs:{type:"integer",minimum:0},mesh:{type:"string"},joinHealth:{type:"object",additionalProperties:false,required:["state","reason"],properties:{state:{type:"string",const:"degraded"},reason:{type:"string"}}},condition:{type:"object",additionalProperties:false,required:["code"],properties:{code:{type:"string"},source:{type:"string"},message:{type:"string"},since:{type:"number"}}},startupNotice:{type:"string",minLength:1,maxLength:1024},activeAt:{type:"number"},meshView:{type:"string",enum:["current","stale","unpopulated"]},presenceIdentityVerified:{type:"boolean"},presenceObservedAt:{type:"integer",minimum:0},offlineSince:{type:"integer",minimum:0},lifecycleUid:{type:"string"},authHealth:{type:"string"},authReason:{type:"string"},model:{type:"string"},variant:{type:"string"},provider:{type:"string"},cwd:{type:"string"},pid:{type:"integer",minimum:1},spawner:{type:"string"},instanceId:{type:"string"},host:{type:"string"},resume:{type:"object",additionalProperties:false,required:["source"],properties:{source:{type:"string"},title:{type:"string"},transcriptSha256:{type:"string"},host:{type:"string"},transferredAt:{type:"string"}}}}});var INSPECT_INPUT_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,required:["name"],properties:{name:{type:"string",minLength:1}}});var PERSONA_ENDPOINTS_SCHEMA=deepFreeze2({type:"array",items:{type:"object",additionalProperties:false,required:["endpoint","commands"],properties:{endpoint:{type:"string"},commands:{type:"array",items:{type:"string"}},instanceId:{type:"string"}}}});var SPAWN_INPUT_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,required:["name"],properties:{name:{type:"string",minLength:1},agent:nonBlank(),defaultAgent:nonBlank(),role:nonBlank(),config:nonBlank(),identity:nonBlank(),model:nonBlank(),variant:nonBlank(),launchOptions:{type:"object"},resume:nonBlank(),resumeClaim:nonBlank(),resumeAgent:nonBlank(),events:{type:"boolean"},eventPayloads:{type:"boolean"},cwd:nonBlank(),prompt:nonBlank(),persona:{type:"object",additionalProperties:false,required:["prompt"],properties:{prompt:nonBlank(),role:nonBlank(),model:nonBlank(),variant:nonBlank(),description:nonBlank(),subscribe:{type:"array",items:{type:"string"}},allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}},capabilities:{type:"array",items:{type:"string"}},endpoints:PERSONA_ENDPOINTS_SCHEMA,save:{type:"boolean"}}},runId:nonBlank(),subscribe:{type:"array",items:{type:"string"}},allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}},join:{type:"array",items:{type:"string"}},callerAcl:{type:"object",additionalProperties:false,required:["allowSubscribe","allowPublish"],properties:{allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}}}},shareTools:{type:"array",items:{type:"string"}},runtime:nonBlank(),supervise:{type:"object",additionalProperties:false,required:["restarts","windowMs"],properties:{restarts:{type:"integer",minimum:1},windowMs:{type:"integer",minimum:1}}},once:{type:"object",additionalProperties:false,properties:{deadlineMs:{anyOf:[{const:-1},{type:"integer",minimum:1,maximum:Number.MAX_SAFE_INTEGER}]}}}}});var SPAWN_OUTPUT_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,required:["name","owner","actor","uid","goalId","fingerprint","executor"],properties:{name:{type:"string"},owner:{type:"string"},actor:{type:"string"},uid:{type:"string"},goalId:{type:"string"},fingerprint:{type:"string"},readinessDeadlineMs:{type:"integer",minimum:1},executor:{type:"object",additionalProperties:false,required:["lifecycleUid","epoch"],properties:{lifecycleUid:{type:"string"},epoch:{type:"integer",minimum:0}}}}});var GRACEFUL_INPUT_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,properties:{graceful:{type:"boolean"}}});var STOP_OUTPUT_SCHEMA=deepFreeze2({type:"object",additionalProperties:false,required:["name","stopped","graceful"],properties:{name:{type:"string"},stopped:{type:"boolean"},graceful:{type:"boolean"}}});function deepFreeze2(v){if(v!==null&&typeof v==="object"){for(const child of Object.values(v))deepFreeze2(child);Object.freeze(v)}return v}var import_nkeys12=__toESM(require_mod(),1);init_canonical();init_endpoint_envelope();init_identity();init_schema_profile();init_endpoint_signing();var TOOL_RESULTS_ENDPOINT="tool-results";var TOOL_RESULT_MAX_CONTENT_BYTES=64*1024;var TOOL_RESULT_MAX_RETENTION_MS=60*60*1e3;var TOOL_RESULT_CONSENT_MAX_TTL_MS=24*60*60*1e3;function deepFreeze3(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))deepFreeze3(child);Object.freeze(value)}return value}var text={type:"string",minLength:1};var id={type:"string",minLength:1,maxLength:200,pattern:"^[A-Za-z0-9_-]+$"};var actor={type:"string",minLength:1,pattern:"^[A-Za-z0-9_]+$"};var owner={type:"string",pattern:"^u_[a-z2-7]{26}$"};var uid={type:"string",pattern:"^[a-z0-9]{26,32}$"};var space={type:"string",minLength:1,pattern:"^[A-Za-z0-9_-]+$"};var uint={type:"integer",minimum:0,maximum:Number.MAX_SAFE_INTEGER};var bool={type:"boolean"};var closed2=properties=>({type:"object",additionalProperties:false,required:Object.keys(properties),properties});var target=closed2({owner,actor,lifecycleUid:uid});var pair={threadId:text,toolCallId:text};var status=(state,fields={})=>closed2({state:{const:state},...fields});var TOOL_RESULT_CONSENT_SCHEMA=deepFreeze3(closed2({v:{const:1},kind:{const:"tool-result-consent"},id,space,target,holder:closed2({owner,actor}),iat:uint,exp:uint,issuer:closed2({keyId:id}),sig:{type:"string",pattern:"^[A-Za-z0-9_-]{86}$"}}));var TOOL_RESULT_REVOCATION_SCHEMA=deepFreeze3(closed2({v:{const:1},kind:{const:"tool-result-revocation"},space,consentId:id,target,revokedAt:uint}));var TOOL_RESULT_SERVING_MATERIAL_SCHEMA=deepFreeze3(closed2({v:{const:1},kind:{const:"tool-result-serving-material"},space,accountPublicKey:{type:"string",pattern:"^A[A-Z2-7]{55}$"},target,grant:closed2({endpoint:{const:TOOL_RESULTS_ENDPOINT},instanceId:uid,epoch:uint,registrationRevision:{...uint,minimum:1}}),credential:{type:"string",minLength:1,maxLength:16384},snapshot:closed2({t0:uint,watermark:uint,watermarkTakenAt:uint,revokedConsentIds:{type:"array",uniqueItems:true,items:id}}),expiresAt:uint}));var TOOL_RESULT_INPUT_SCHEMA=deepFreeze3(closed2(pair));var TOOL_RESULT_ANSWER_SCHEMAS=deepFreeze3({available:status("available",{...pair,content:{type:"string",maxLength:TOOL_RESULT_MAX_CONTENT_BYTES},truncated:bool,byteCount:{...uint,maximum:TOOL_RESULT_MAX_CONTENT_BYTES},error:bool,capturedAt:uint}),pending:status("pending",pair),"not-shared":status("not-shared"),missing:status("missing"),expired:status("expired")});var TOOL_RESULT_OUTPUT_SCHEMA=deepFreeze3({oneOf:Object.values(TOOL_RESULT_ANSWER_SCHEMAS)});var TOOL_RESULT_CONSENT_INPUT_SCHEMA=deepFreeze3(closed2({consent:TOOL_RESULT_CONSENT_SCHEMA}));var TOOL_RESULT_CONSENT_OUTPUT_SCHEMA=deepFreeze3(status("active",{consentId:id}));var TOOL_RESULT_REVOKE_INPUT_SCHEMA=deepFreeze3(closed2({consentId:id}));var TOOL_RESULT_REVOKE_ANSWER_SCHEMAS=deepFreeze3({known:status("known",{consentId:id}),refused:status("refused",{consentId:id}),unknown:status("unknown",{consentId:id})});var TOOL_RESULT_REVOKE_OUTPUT_SCHEMA=deepFreeze3({oneOf:Object.values(TOOL_RESULT_REVOKE_ANSWER_SCHEMAS)});var TOOL_RESULTS_COMMANDS=deepFreeze3([{name:"tool-result",capability:"tool-results.read",input:TOOL_RESULT_INPUT_SCHEMA,output:TOOL_RESULT_OUTPUT_SCHEMA},{name:"tool-result-consent",capability:"tool-results.consent",input:TOOL_RESULT_CONSENT_INPUT_SCHEMA,output:TOOL_RESULT_CONSENT_OUTPUT_SCHEMA},{name:"tool-result-revoke",capability:"tool-results.revoke",input:TOOL_RESULT_REVOKE_INPUT_SCHEMA,output:TOOL_RESULT_REVOKE_OUTPUT_SCHEMA}]);var TOOL_RESULTS_CLUSTER=deepFreeze3({urn:"ai.cotal.tool-results",revision:1,attributes:[],events:[],commands:TOOL_RESULTS_COMMANDS.map(row=>({name:row.name,class:"ephemeral",targeted:true,modes:["handle"],capability:row.capability,inputDigest:singleDocumentClosure(row.input).closureDigest,outputDigest:singleDocumentClosure(row.output).closureDigest}))});init_event_payloads();var import_nkeys13=__toESM(require_mod(),1);init_base64url();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;init_issued_authority();init_provision();init_issued_authority();init_subjects();init_endpoint_subjects();init_persona_endpoints();var DELEGABLE_CAPABILITIES=Object.freeze(["spawn","run","admin"]);init_persona_endpoints();var import_jetstream23=__toESM(require_mod4(),1);var import_transport_node21=__toESM(require_transport_node(),1);init_backup();init_issued_authority();init_jetstream_missing();init_run_admission();init_endpoint_envelope();init_issued_authority();init_endpoint_subjects();init_endpoint_records();init_run_submission();init_canonical();init_endpoint_journal();init_endpoint_caller();init_endpoint_subjects();init_endpoint_error();init_connection_cleanup();var import_jetstream24=__toESM(require_mod4(),1);var import_kv12=__toESM(require_mod6(),1);init_endpoint();init_endpoint_binding();init_endpoint_envelope();init_lifecycle_state();init_endpoint_records();init_issued_authority();init_identity();init_provision();init_renewal();init_streams();init_service_gate();init_contract_manifest();init_renewal();import{readFileSync as readFileSync4}from"node:fs";import{userInfo as userInfo2}from"node:os";var DIRECT_MATERIAL_VARS=["COTAL_CREDS","COTAL_SERVERS","COTAL_TOKEN","COTAL_OWNER","COTAL_ACTOR","COTAL_SENTINEL_CREDS","COTAL_BEARER_CMD","COTAL_EVENTS_REQUIRED","COTAL_CONTROL_TOKEN","COTAL_LINK"];function readMaterial(env){const path=env[LAUNCH_MATERIAL_ENV]?.trim();if(!path)return void 0;const direct=DIRECT_MATERIAL_VARS.filter(k=>env[k]?.trim());if(direct.length)throw new Error(`COTAL config: this launch carries connection material BOTH as ${LAUNCH_MATERIAL_ENV} and as ${direct.join(", ")}. One launch carries one identity plane - drop the direct variables, or drop the material file.`);return readLaunchMaterial(path)}function controlFromEnv(env=process.env){const path=env.COTAL_CONTROL_SOCKET?.trim();const token2=readMaterial(env)?.controlToken??env.COTAL_CONTROL_TOKEN?.trim();if(path&&token2)return{path,token:token2};if(!path&&!token2)return void 0;if(path)throw new Error("COTAL config: COTAL_CONTROL_SOCKET is set but no control token could be resolved - neither the launch material nor COTAL_CONTROL_TOKEN carries one. Half a pair is not a control endpoint, so this launch is refused rather than started without the control plane it was configured to have.");throw new Error("COTAL config: a control token was supplied but COTAL_CONTROL_SOCKET is unset, so there is no socket to authenticate against. Half a pair is not a control endpoint, so this launch is refused rather than started without the control plane it was configured to have.")}function hasIdentity(env=process.env){return Boolean(env.COTAL_NAME?.trim()||env.COTAL_LINK?.trim()||env.COTAL_AGENT_FILE?.trim())}var FEEDBACK_URL="https://broker.cotal.ai/v1/feedback";var PUBLIC_FEEDBACK_URL="https://cotal.ai/v1/feedback";function isAuthed(config2){return Boolean(config2.creds)||Boolean(config2.userAuth)}function splitList(v){if(!v)return[];return v.split(",").map(s=>s.trim()).filter(Boolean)}function endpointsEnv(v){let raw;try{raw=JSON.parse(v)}catch{raw=void 0}if(!Array.isArray(raw))throw new Error("COTAL_ENDPOINTS: expected the JSON list the launcher writes");return parsePersonaEndpoints(raw,"COTAL_ENDPOINTS")}function envList(v){return v===void 0?void 0:splitList(v)}var EnvFlagError=class extends Error{};function envFlag(env,name){const value=env[name]?.trim();if(!value)return void 0;if(/^(1|true|yes|on)$/i.test(value))return true;if(/^(0|false|no|off)$/i.test(value))return false;throw new EnvFlagError(`COTAL config: ${name} must be 1/true/yes/on or 0/false/no/off, got "${env[name]}"`)}function scrubLaunchMaterial(env=process.env){const path=env[LAUNCH_MATERIAL_ENV]?.trim();delete env[LAUNCH_MATERIAL_ENV];if(path)discardLaunchMaterial(path)}function configFromEnv(env=process.env){const link=env.COTAL_LINK?.trim()?parseJoinLink(env.COTAL_LINK.trim()):void 0;const def=env.COTAL_AGENT_FILE?.trim()?loadAgentFile(env.COTAL_AGENT_FILE.trim()):void 0;const name=env.COTAL_NAME?.trim()||def?.name||(link?userInfo2().username:void 0);if(!name)throw new Error("COTAL_NAME, COTAL_AGENT_FILE or COTAL_LINK is required \u2014 a Cotal session needs an explicit identity from its launcher");const resolvedSubscribe=envList(env.COTAL_SUBSCRIBE)??def?.subscribe??link?.channels??[];let resolvedAllowSub;try{resolvedAllowSub=resolveReadAcl(resolvedSubscribe,envList(env.COTAL_ALLOW_SUBSCRIBE)??def?.allowSubscribe)}catch(e){throw new Error(`COTAL config: ${e.message}`)}const resolvedAllowPub=envList(env.COTAL_ALLOW_PUBLISH)??def?.allowPublish??[];for(const ch of[...resolvedSubscribe,...resolvedAllowSub,...resolvedAllowPub])assertValidChannel(ch);const qEnv=splitList(env.COTAL_QUIET),mEnv=splitList(env.COTAL_MUTED);const resolvedQuiet=qEnv.length?qEnv:def?.quiet??[];const resolvedMuted=mEnv.length?mEnv:def?.muted??[];const bothModes=resolvedQuiet.filter(c=>resolvedMuted.includes(c));if(bothModes.length)throw new Error(`COTAL config: channel(s) [${bothModes.join(", ")}] are in both quiet and muted`);for(const[field,chans]of[["quiet",resolvedQuiet],["muted",resolvedMuted]])for(const ch of chans){assertValidChannel(ch);if(!isConcreteChannel(ch))throw new Error(`COTAL config: ${field} channel "${ch}" must be concrete (no wildcard)`);if(!channelInAllow(resolvedAllowSub,ch))throw new Error(`COTAL config: ${field} channel "${ch}" is not within allowSubscribe [${resolvedAllowSub.join(", ")}]`)}const material=readMaterial(env);if(env.COTAL_SERVERS?.trim()&&brokerUrlHasUserinfo(env.COTAL_SERVERS))throw new Error("COTAL config: COTAL_SERVERS must not embed credentials; name the broker URL without user:password@, and pass the credential in COTAL_CREDS, COTAL_TOKEN or a COTAL_LINK");const credsPath=material?.creds??env.COTAL_CREDS?.trim();const initialCreds=credsPath?readFileSync4(credsPath,"utf8"):void 0;const credsId=initialCreds?idFromCreds(initialCreds):void 0;const boundedCreds=initialCreds!==void 0&&typeof credsClaims(initialCreds).exp==="number";const declaredId=env.COTAL_ID?.trim()||void 0;if(declaredId&&credsId&&declaredId!==credsId)throw new Error(`COTAL config: COTAL_ID ${declaredId} != creds identity ${credsId} - they must be the same nkey`);const userVars=material?.userAuth?{owner:material.userAuth.owner,actor:material.userAuth.actor,sentinel:material.userAuth.sentinelCredsPath,bearerCmd:JSON.stringify(material.userAuth.bearerCmd)}:{owner:env.COTAL_OWNER?.trim(),actor:env.COTAL_ACTOR?.trim(),sentinel:env.COTAL_SENTINEL_CREDS?.trim(),bearerCmd:env.COTAL_BEARER_CMD?.trim()};const userSet=Object.values(userVars).filter(Boolean).length;if(userSet>0&&userSet<4)throw new Error("COTAL config: user-mode launch needs ALL of COTAL_OWNER, COTAL_ACTOR, COTAL_SENTINEL_CREDS, COTAL_BEARER_CMD \u2014 a partial set is a broken launcher, not a mode");if(userSet&&credsPath)throw new Error("COTAL config: COTAL_CREDS (static auth) and COTAL_OWNER/... (user-mode auth) are mutually exclusive");const lifecycleUid=env.COTAL_LIFECYCLE_UID?.trim()||void 0;const backfillFloorRaw=env.COTAL_BACKFILL_FLOOR?.trim()||void 0;let backfillFloor;if(backfillFloorRaw!==void 0){const n=Number(backfillFloorRaw);if(!Number.isInteger(n)||n<0)throw new Error(`COTAL config: COTAL_BACKFILL_FLOOR must be a non-negative integer stream sequence, got "${backfillFloorRaw}" (a broken launcher, not a mode)`);backfillFloor=n}const acceptedToken=env.COTAL_ACCEPTED_TOKEN?.trim()||void 0;const managerInstanceId=env.COTAL_MANAGER_INSTANCE?.trim()||void 0;if(managerInstanceId!==void 0)assertLifecycleToken(managerInstanceId,"COTAL_MANAGER_INSTANCE");if(acceptedToken&&!credsPath)throw new Error("COTAL config: COTAL_ACCEPTED_TOKEN names a static issuance and needs COTAL_CREDS beside it (a broken launcher, not a mode)");if((credsPath||userSet===4)&&!lifecycleUid)throw new Error("COTAL config: an authed launch (COTAL_CREDS or user-mode) requires COTAL_LIFECYCLE_UID - the launcher mints it at provision time (a broken launcher, not a mode)");let userAuth;if(userSet===4){let bearerCmd;try{bearerCmd=JSON.parse(userVars.bearerCmd)}catch{throw new Error("COTAL config: COTAL_BEARER_CMD must be a JSON argv array")}if(!Array.isArray(bearerCmd)||!bearerCmd.length||!bearerCmd.every(a=>typeof a==="string"))throw new Error("COTAL config: COTAL_BEARER_CMD must be a non-empty JSON array of strings");userAuth={owner:userVars.owner,actor:userVars.actor,sentinelCreds:readFileSync4(userVars.sentinel,"utf8"),bearerCmd}}const eventsRequired=material?.eventsRequired===true||!material&&envFlag(env,"COTAL_EVENTS_REQUIRED")===true;if(eventsRequired&&!userAuth)throw new Error("COTAL config: COTAL_EVENTS_REQUIRED is valid only for a user-mode registration launch");if(eventsRequired){const principal=userSet===4?{owner:userVars.owner,actor:userVars.actor}:{owner:DEV_OWNER,actor:credsId??declaredId??""};if(!principal.actor)throw new Error("COTAL config: this space requires events, but the session has no stable principal to derive its event channel");const channel=eventChannel(principal);if(!channelInAllow(resolvedAllowPub,channel))throw new Error(`COTAL config: space "${env.COTAL_SPACE?.trim()||link?.space||"demo"}" requires events, but this session's grant does not cover its event channel "${channel}". Widen the whole user-auth actor row with \`cotal actor grant ${principal.actor} --owner ${principal.owner} --scope <current-scope> --allow-subscribe <current-read> --allow-publish '<current-post>,${channel}' --role <current-role> --label <current-label>\`; actor grant replaces the whole row, so preserve every current field.`)}return{space:env.COTAL_SPACE?.trim()||link?.space||"demo",id:credsId??declaredId,lifecycleUid,backfillFloor,acceptedToken,managerInstanceId,creds:boundedCreds?async()=>readFileSync4(credsPath,"utf8"):initialCreds,userAuth,name,role:env.COTAL_ROLE||def?.role||void 0,description:def?.description,tags:def?.tags,meta:def?.meta,capabilities:splitList(env.COTAL_CAPABILITIES).length?splitList(env.COTAL_CAPABILITIES):def?.capabilities,endpoints:env.COTAL_ENDPOINTS!==void 0?endpointsEnv(env.COTAL_ENDPOINTS):def?.endpoints,model:env.COTAL_MODEL?.trim()||void 0,variant:env.COTAL_VARIANT?.trim()||void 0,servers:material?.servers||env.COTAL_SERVERS?.trim()||link?.servers||DEFAULT_SERVER,subscribe:resolvedSubscribe,allowSubscribe:resolvedAllowSub,allowPublish:resolvedAllowPub,eventsRequired,eventPayloadsWithheld:material?.eventPayloadsWithheld===true||envFlag(env,"COTAL_EVENT_PAYLOADS")===false,quiet:resolvedQuiet,muted:resolvedMuted,kind:assertValidKind(env.COTAL_KIND?.trim()||def?.kind||"agent"),token:material?.token||env.COTAL_TOKEN?.trim()||link?.token,user:link?.user,pass:link?.pass,tls:envFlag(env,"COTAL_TLS")||link?.tls||false,feedbackKey:env.COTAL_FEEDBACK_KEY?.trim()||void 0,feedbackUrl:env.COTAL_FEEDBACK_URL?.trim()||void 0}}function eventPlaneArmed(config2,env=process.env){return envFlag(env,"COTAL_EVENTS")===true||config2.eventsRequired===true}function feedbackLine(config2){const dest=config2.feedbackKey?"":`Without a feedback key it goes to the public cotal.ai intake and needs a contact email \u2014 the tool will tell you to ask the user for one if it can't find it. `;return`Use cotal_feedback with origin="human" when the user asks you to send feedback or gives you feedback to pass along. If you independently hit a major Cotal issue \u2014 for example repeated Cotal tool failures, inability to connect, lost/incorrect mesh messages, or a workflow-blocking bug \u2014 send cotal_feedback yourself with origin="agent". Do not send minor noise or secrets; include diagnostics only when they help debug the Cotal issue. `+dest}import{AsyncLocalStorage as AsyncLocalStorage2}from"node:async_hooks";import{EventEmitter as EventEmitter2}from"node:events";import{hostname as hostname2}from"node:os";import{createHash as createHash8,randomUUID as randomUUID5}from"node:crypto";import{open as open3,readFile as readFile2,unlink as unlink2}from"node:fs/promises";import{hostname}from"node:os";import{dirname as dirname6,join as join7}from"node:path";import{createHash as createHash7,randomUUID as randomUUID4}from"node:crypto";import{constants as constants4}from"node:fs";import{open as open2,readFile,rename,unlink}from"node:fs/promises";import{dirname as dirname5,join as join6}from"node:path";var EVENT_WAL_VERSION=4;var WalCorruptError=class extends Error{path;invariant;constructor(path,invariant,detail){super(`event WAL at ${path} is unusable (${invariant}): ${detail}`);this.path=path;this.invariant=invariant;this.name="WalCorruptError"}};var WalStaleWriterError=class extends Error{path;expectedGen;foundGen;constructor(path,expectedGen,foundGen){super(`event WAL at ${path} was written by another handle since this one read it (this handle expects generation ${expectedGen}, the file is at ${foundGen===void 0?"no file at all":`generation ${foundGen}`}) \u2014 refusing to overwrite it. A second emitter or a stale handle is writing this principal's log.`);this.path=path;this.expectedGen=expectedGen;this.foundGen=foundGen;this.name="WalStaleWriterError"}};var isSafeNonNegInt2=n=>Number.isSafeInteger(n)&&n>=0;function docGeneration(path,doc){if(typeof doc.v==="number"&&doc.v<3)return 0;if(!isSafeNonNegInt2(doc.gen))throw new WalCorruptError(path,"gen is a safe non-negative integer",`found gen=${String(doc.gen)} on a v${String(doc.v)} document`);return doc.gen}async function openExclusiveNoFollow(path){return open2(path,constants4.O_WRONLY|constants4.O_CREAT|constants4.O_EXCL|(constants4.O_NOFOLLOW??0),384)}function assertPendingVintage(path,p,f){if(p.E!==f.lastSubjectSeq)throw new WalCorruptError(path,"pending.E === frontier.lastSubjectSeq",`pending.E=${p.E} frontier.lastSubjectSeq=${f.lastSubjectSeq} \u2014 the frozen expectation is not the tip this WAL believes, so retrying it can only CAS-halt or append at the wrong position`);if(p.seq!==f.seq+1)throw new WalCorruptError(path,"pending.seq === frontier.seq + 1",`pending.seq=${p.seq} frontier.seq=${f.seq} \u2014 a pending frame must be exactly the frontier's successor`);if(p.state==="sent_unacked"){if(p.ackSeq!==void 0)throw new WalCorruptError(path,"sent_unacked has no ackSeq",`state is "sent_unacked" but ackSeq=${String(p.ackSeq)} \u2014 the document contradicts its own tag`);return}if(!isSafeNonNegInt2(p.ackSeq))throw new WalCorruptError(path,"acked.ackSeq present",`state is "acked" but ackSeq is ${String(p.ackSeq)}`);if(!(p.ackSeq>f.lastSubjectSeq))throw new WalCorruptError(path,"acked.ackSeq > frontier.lastSubjectSeq",`ackSeq=${p.ackSeq} frontier.lastSubjectSeq=${f.lastSubjectSeq} \u2014 the frontier is of a later vintage than the acked frame, so its sourceCursor may already have passed events that were never published; resuming would drop them with no gap for a consumer to see`)}function parseBrackets(path,field,v,nullable2){if(v===null&&nullable2)return null;if(typeof v!=="object"||v===null)throw new WalCorruptError(path,`${field} is an object${nullable2?" or null":""}`,JSON.stringify(v));const b=v;if(b.run!==void 0&&typeof b.run!=="string")throw new WalCorruptError(path,`${field}.run is a string or absent`,JSON.stringify(b.run));const lists={text:b.text,reasoning:b.reasoning,tools:b.tools};for(const[k,list]of Object.entries(lists)){if(!Array.isArray(list)||list.some(x=>typeof x!=="string"))throw new WalCorruptError(path,`${field}.${k} is an array of strings`,JSON.stringify(list))}if(b.run===void 0&&b.text.concat(b.reasoning,b.tools).length>0)throw new WalCorruptError(path,`${field} has no open run while messages or tool calls are open`,JSON.stringify(b));return{run:b.run,text:b.text,reasoning:b.reasoning,tools:b.tools}}function parsePayloadCalls(path,value){if(value===void 0)return void 0;if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).length>4096||Object.entries(value).some(([id2,allowed])=>!id2||typeof allowed!=="boolean"))throw new WalCorruptError(path,"payloadCalls is a bounded boolean record","invalid call classification");return{...value}}function parseDoc(path,raw,space2,threadId,principal){let d;try{d=JSON.parse(raw)}catch(e){throw new WalCorruptError(path,"parseable JSON",e.message)}if(typeof d!=="object"||d===null)throw new WalCorruptError(path,"document is an object",typeof d);const doc=d;if(typeof doc.v!=="number"||!Number.isSafeInteger(doc.v)||doc.v<1)throw new WalCorruptError(path,"v is a positive integer",`found v=${String(doc.v)}`);if(doc.v>EVENT_WAL_VERSION)throw new WalCorruptError(path,`v <= ${EVENT_WAL_VERSION}`,`this WAL is v${doc.v} and this build understands v${EVENT_WAL_VERSION} \u2014 THE STATE IS NEWER THAN THE CODE, which is what a code rollback across the v2 migration (persisted bracket state) or the v3 one (the write generation) leaves behind. The migration is forward-only by design: there is no downgrade, because a lossy one would silently discard state this file exists to preserve. Run the newer build, or move this WAL aside and accept that the thread restarts from a new epoch.`);if(doc.space!==space2)throw new WalCorruptError(path,"space matches",`WAL space=${String(doc.space)} caller=${space2}`);if(doc.threadId!==threadId)throw new WalCorruptError(path,"threadId matches",`WAL threadId=${String(doc.threadId)} caller=${threadId}`);if(doc.principal!==principal)throw new WalCorruptError(path,"principal matches",`WAL principal=${String(doc.principal)} caller=${principal}`);if(typeof doc.epoch!=="string"||doc.epoch.length===0)throw new WalCorruptError(path,"epoch is a non-empty string",String(doc.epoch));const f=doc.frontier;if(!f||!isSafeNonNegInt2(f.seq)||!isSafeNonNegInt2(f.lastSubjectSeq))throw new WalCorruptError(path,"frontier is well-formed",JSON.stringify(doc.frontier));if(f.sourceCursor!==void 0&&typeof f.sourceCursor!=="string")throw new WalCorruptError(path,"frontier.sourceCursor is a string or absent",typeof f.sourceCursor);if(f.seq===0!==(f.lastSubjectSeq===0))throw new WalCorruptError(path,"frontier.seq and lastSubjectSeq are both zero or both nonzero",JSON.stringify(f));if((f.seq>0||f.lastSubjectSeq>0)&&typeof f.sourceCursor!=="string")throw new WalCorruptError(path,"a nonzero frontier carries its sourceCursor",JSON.stringify(f));if(doc.pending!==null&&typeof doc.pending!=="object")throw new WalCorruptError(path,"pending is present (null or an object)",doc.pending===void 0?"the key is absent, which is not the same as null":typeof doc.pending);let pending=null;if(doc.pending!==null){const p=doc.pending;if(p.state!=="sent_unacked"&&p.state!=="acked")throw new WalCorruptError(path,"pending.state is a known tag",String(p.state));if(typeof p.id!=="string"||p.id.length===0)throw new WalCorruptError(path,"pending.id is a non-empty string",String(p.id));try{assertIdToken(p.id,"event WAL pending.id")}catch(e){throw new WalCorruptError(path,"pending.id satisfies the wire id grammar",e.message)}if(!isSafeNonNegInt2(p.E)||!isSafeNonNegInt2(p.seq))throw new WalCorruptError(path,"pending E/seq are safe non-negative integers",JSON.stringify(p));if(typeof p.sourceCursor!=="string")throw new WalCorruptError(path,"pending.sourceCursor is a string",typeof p.sourceCursor);if(!Array.isArray(p.body)||p.body.length===0)throw new WalCorruptError(path,"pending.body is a non-empty array of parts",JSON.stringify(p.body));if(doc.v===1)throw new WalCorruptError(path,"a v1 WAL has no frame in flight",`this v1 document holds a ${String(p.state)} frame, and v2 requires the bracket state that belongs to it \u2014 which v1 never recorded and nothing here can reconstruct. Let the older build settle this frame first, then start the newer one.`);p.brackets=parseBrackets(path,"pending.brackets",p.brackets,false);if(p.payload!==void 0){const payload=p.payload;if(doc.v<4||!payload||typeof payload!=="object"||!Array.isArray(payload.body)||payload.body.length===0||!isSafeNonNegInt2(payload.E)||payload.ackSeq!==void 0&&(!isSafeNonNegInt2(payload.ackSeq)||payload.ackSeq<=payload.E))throw new WalCorruptError(path,"pending payload is a v4 frozen publication",JSON.stringify(payload));assertIdToken(payload.id,"event WAL payload id")}p.payloadCalls=parsePayloadCalls(path,p.payloadCalls);pending=p;assertPendingVintage(path,pending,f)}const brackets=doc.v===1?null:parseBrackets(path,"brackets",doc.brackets,true);return{v:EVENT_WAL_VERSION,gen:docGeneration(path,doc),space:space2,epoch:doc.epoch,threadId,principal,frontier:f,pending,payloadCalls:parsePayloadCalls(path,doc.payloadCalls),brackets}}var EventWal=class _EventWal{path;doc;chain=Promise.resolve();serialize(op){const next=this.chain.then(op,op);this.chain=next.catch(()=>void 0);return next}constructor(path,doc){this.path=path;this.doc=doc}get payloadCalls(){return{...this.doc.pending?.payloadCalls??this.doc.payloadCalls??{}}}get epoch(){return this.doc.epoch}get space(){return this.doc.space}get principal(){return this.doc.principal}get threadId(){return this.doc.threadId}get brackets(){return this.doc.brackets}get frontier(){return{...this.doc.frontier}}get pending(){return this.doc.pending?{...this.doc.pending}:null}subject;static async open(path,opts){let raw;let bytes;try{bytes=await readFile(path)}catch(e){if(e.code!=="ENOENT")throw e}if(bytes!==void 0){try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new WalCorruptError(path,"the file is valid UTF-8","invalid UTF-8 bytes; refusing rather than substituting U+FFFD")}}if(raw===void 0){if(opts.subjectMayExist)throw new WalCorruptError(path,"WAL exists when the subject may","no WAL file, but this thread may already have published");return new _EventWal(path,_EventWal.virgin(opts.space,opts.threadId,opts.principal))}if(raw.length===0)throw new WalCorruptError(path,"WAL is non-empty","the file is zero bytes \u2014 distinct from missing and never treated as a virgin thread");return new _EventWal(path,parseDoc(path,raw,opts.space,opts.threadId,opts.principal))}static virgin(space2,threadId,principal){return{v:EVENT_WAL_VERSION,gen:0,space:space2,epoch:randomUUID4(),threadId,principal,frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}}}async bindSubjectFrontier(frontier){if(this.subject===frontier)return;if(this.subject)throw new Error(`event WAL ${this.path}: a DIFFERENT subject frontier is already bound`);this.subject=frontier}get expectedTip(){if(!this.subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so there is no expectation to publish. The subject is shared by every thread of this principal, so this document's own last ack is not it; bind the principal's record with bindSubjectFrontier first.`);return this.subject.tip}async beginSend(frame){return this.serialize(async()=>{if(this.doc.pending)throw new Error(`event WAL ${this.path}: a frame is already pending; one emit unit is one pending frame`);assertIdToken(frame.id,"event WAL pending id");if(frame.E!==this.expectedTip)throw new Error(`event WAL ${this.path}: E=${frame.E} is not the subject's tip ${this.expectedTip}`);if(frame.seq!==this.doc.frontier.seq+1)throw new Error(`event WAL ${this.path}: seq=${frame.seq} is not the frontier's successor ${this.doc.frontier.seq+1}`);if(!Array.isArray(frame.body)||frame.body.length===0)throw new Error(`event WAL ${this.path}: a frame body must be a non-empty array of parts`);parsePayloadCalls(this.path,frame.payloadCalls);if(frame.payload){assertIdToken(frame.payload.id,"event WAL payload id");if(!isSafeNonNegInt2(frame.payload.E)||!Array.isArray(frame.payload.body)||frame.payload.body.length===0||frame.payload.ackSeq!==void 0)throw new Error("event WAL payload must be an unacknowledged frozen publication")}await this.write({...this.doc,pending:{state:"sent_unacked",...frame}})})}async recordPayloadAck(ackSeq){return this.serialize(async()=>{const p=this.doc.pending;if(!p?.payload||p.state!=="sent_unacked"||p.payload.ackSeq!==void 0)throw new Error("event WAL has no unacknowledged sibling payload");if(!isSafeNonNegInt2(ackSeq)||ackSeq<=p.payload.E)throw new Error("payload ack must advance its frozen expectation");await this.write({...this.doc,pending:{...p,payload:{...p.payload,ackSeq}}})})}async recordAck(ackSeq){return this.serialize(async()=>{const p=this.doc.pending;if(!p||p.state!=="sent_unacked")throw new Error(`event WAL ${this.path}: no sent_unacked frame to ack`);if(p.payload&&p.payload.ackSeq===void 0)throw new Error("event WAL cannot acknowledge public frame before sibling payload");if(!isSafeNonNegInt2(ackSeq))throw new Error(`event WAL ${this.path}: ackSeq must be a safe non-negative integer, got ${String(ackSeq)}`);if(ackSeq<=this.expectedTip)throw new Error(`event WAL ${this.path}: ackSeq=${ackSeq} is not ahead of the subject's tip ${this.expectedTip}`);const subject=this.subject;if(!subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so this ack has no shared record to advance`);await this.assertNotClobbering();await subject.advance(ackSeq);await this.write({...this.doc,pending:{...p,state:"acked",ackSeq}})})}async fold(){return this.serialize(async()=>{const p=this.doc.pending;if(!p||p.state!=="acked"||p.ackSeq===void 0)throw new Error(`event WAL ${this.path}: no acked frame to fold`);await this.write({...this.doc,frontier:{seq:p.seq,lastSubjectSeq:p.ackSeq,sourceCursor:p.sourceCursor},pending:null,brackets:p.brackets,payloadCalls:p.payloadCalls??this.doc.payloadCalls})})}async advanceCursorOnly(rangeEnd){return this.serialize(async()=>{if(this.doc.pending)throw new Error(`event WAL ${this.path}: cannot advance the cursor while a frame is pending`);await this.write({...this.doc,frontier:{...this.doc.frontier,sourceCursor:rangeEnd}})})}async abandon(){return this.serialize(async()=>{await this.assertNotClobbering();if(!this.subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so an abandonment here would clear this log and leave the principal's shared tip standing, which is the partial abandonment this method refuses to produce; bind the principal's record with bindSubjectFrontier first.`);await this.subject.reset();await this.write({...this.doc,epoch:randomUUID4(),frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}})})}async write(next){await this.assertNotClobbering();const stamped={...next,gen:this.doc.gen+1};const tmp=join6(dirname5(this.path),`.${createHash7("sha256").update(this.path).digest("hex").slice(0,12)}.${process.pid}.${randomUUID4().slice(0,8)}.wal.tmp`);const body=JSON.stringify(stamped);const fh=await openExclusiveNoFollow(tmp);try{await fh.writeFile(body,"utf8");await fh.sync()}finally{await fh.close()}try{await rename(tmp,this.path)}catch(e){await unlink(tmp).catch(()=>{});throw e}this.doc=stamped}async assertNotClobbering(){let bytes;try{bytes=await readFile(this.path)}catch(e){if(e.code!=="ENOENT")throw e}if(bytes===void 0){if(this.doc.gen!==0)throw new WalStaleWriterError(this.path,this.doc.gen,void 0);return}let raw;try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new WalCorruptError(this.path,"the file is valid UTF-8","invalid UTF-8 bytes on the file about to be replaced; refusing rather than substituting U+FFFD")}let d;try{d=JSON.parse(raw)}catch(e){throw new WalCorruptError(this.path,"parseable JSON",e.message)}if(typeof d!=="object"||d===null)throw new WalCorruptError(this.path,"document is an object",typeof d);const onDisk=docGeneration(this.path,d);if(onDisk!==this.doc.gen)throw new WalStaleWriterError(this.path,this.doc.gen,onDisk)}};var EventsStateRootMissing=class extends Error{constructor(message){super(message);this.name="EventsStateRootMissing"}};function resolveEventsStateRoot(env){const root=env.COTAL_WORKSPACE_ROOT;if(typeof root!=="string"||root.trim()==="")throw new EventsStateRootMissing("events are enabled for this session but COTAL_WORKSPACE_ROOT is not set, so there is nowhere to put the event write-ahead log. The launcher forwards it from LaunchOpts.workspaceRoot; a session started outside a manager has no workspace root and must not publish events. Refusing rather than defaulting to the working directory, which would put the WAL somewhere no later start looks.");return root}function h(value){return createHash8("sha256").update(value).digest("hex").slice(0,16)}function eventWalLocation(opts){const principal=eventPrincipalLocation(opts);const threadDir=join7(principal.principalDir,h(opts.threadId));return{...principal,threadDir,walPath:join7(threadDir,"wal.json")}}var PrincipalLockError=class extends Error{path;invariant;constructor(path,invariant,detail){super(`event WAL principal lock at ${path} (${invariant}): ${detail}`);this.path=path;this.invariant=invariant;this.name="PrincipalLockError"}};var held=new Map;function ownerIsAlive(pid){try{process.kill(pid,0);return true}catch(e){return e.code!=="ESRCH"}}async function createLockFile(path){try{return await openExclusiveNoFollow(path)}catch(e){if(e.code==="EEXIST")return void 0;throw e}}async function reclaimIfOwnerIsGone(path){let raw;try{raw=await readFile2(path,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}let record2;try{record2=JSON.parse(raw)}catch{throw new PrincipalLockError(path,"the lock names its owner","the file is not readable JSON, so its owner cannot be checked; refusing rather than reclaiming a lock that may be held")}const r=record2;if(!Number.isSafeInteger(r.pid)||r.pid<=0||typeof r.host!=="string"||r.host.length===0)throw new PrincipalLockError(path,"the lock names its owner",`the record carries pid=${String(r.pid)} host=${String(r.host)}, which names nobody checkable`);const here=hostname();if(r.host!==here)throw new PrincipalLockError(path,"the recorded owner is on THIS host",`held by pid ${r.pid} on ${r.host} while this process runs on ${here}; liveness on another machine is not observable from here`);if(ownerIsAlive(r.pid))throw new PrincipalLockError(path,"the recorded owner is gone",`pid ${r.pid} on ${here} is still running and holds this principal's emitter`);await unlink2(path).catch(e=>{if(e.code!=="ENOENT")throw e})}async function acquirePrincipalLock(lockPath){const already=held.get(lockPath);if(already)return already;let fh=await createLockFile(lockPath);if(fh===void 0){await reclaimIfOwnerIsGone(lockPath);fh=await createLockFile(lockPath);if(fh===void 0)throw new PrincipalLockError(lockPath,"the reclaimed lock is free when this process takes it","another process created the lock between the reclaim and this open, and now holds this principal")}const record2=JSON.stringify({pid:process.pid,host:hostname(),token:randomUUID5(),acquiredAt:new Date().toISOString()});try{await fh.writeFile(record2,"utf8");await fh.sync()}catch(e){await fh.close().catch(()=>{});await unlink2(lockPath).catch(()=>{});throw e}const lock={path:lockPath,async release(){if(held.get(lockPath)!==lock)return;held.delete(lockPath);await fh.close().catch(()=>{});await unlink2(lockPath).catch(e=>{if(e.code!=="ENOENT")throw e})}};held.set(lockPath,lock);return lock}async function fsyncDir(dir){let fh;try{fh=await open3(dir,"r")}catch(e){const code=e.code;if(code==="EPERM"||code==="EACCES")return;throw e}try{await fh.sync()}catch(e){const code=e.code;if(code!=="EBADF"&&code!=="EINVAL"&&code!=="EPERM"&&code!=="EISDIR")throw e}finally{await fh.close()}}async function ensureEventWalDir(opts){const loc=eventWalLocation(opts);ensureDirNoSymlink(opts.workspaceRoot,".cotal","events",h(opts.space),h(opts.principal),h(opts.threadId));for(let dir=loc.threadDir;;dir=dirname6(dir)){await fsyncDir(dir);if(dir===opts.workspaceRoot||dirname6(dir)===dir)break}const lock=await acquirePrincipalLock(loc.lockPath);return{...loc,lock}}async function checkEventStartup2(ep,env){await checkEventStartup({workspaceRoot:resolveEventsStateRoot(env),space:ep.space,principal:ep.principal,retainedMessages:async()=>(await ep.chatRetention()).senders})}var TURN_PULL_RETRY_MS=15e3;var ONCE_HANDOFF_MS=6e4;var ONCE_EXIT_GRACE_MS=1e4;var KEY=Symbol.for("cotal.once-handoff");function proc(){const g=globalThis;return g[KEY]??={handoffs:new Map}}var keyOf=(uid2,goalId)=>`${uid2}:${goalId}`;function onceHandoffState(uid2,goalId){return proc().handoffs.get(keyOf(uid2,goalId))?.state??"pending"}function claimOnceHandoff(uid2,goalIds){const p=proc();if(goalIds.some(id2=>onceHandoffState(uid2,id2)!=="pending"))return false;for(const id2 of goalIds){const timer=setTimeout(()=>p.timedOut?.(uid2,id2),ONCE_HANDOFF_MS);timer.unref?.();p.handoffs.set(keyOf(uid2,id2),{state:"claimed",timer})}return true}function confirmOnceHandoff(uid2,goalId){const h2=proc().handoffs.get(keyOf(uid2,goalId));if(h2?.state==="sealed")return false;if(h2?.timer!==void 0)clearTimeout(h2.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"confirmed"});return true}function sealOnceHandoff(uid2,goalId){const h2=proc().handoffs.get(keyOf(uid2,goalId));if(h2?.state!=="claimed")return false;if(h2.timer!==void 0)clearTimeout(h2.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"sealed"});return true}function endOnceHandoff(uid2,goalId){const h2=proc().handoffs.get(keyOf(uid2,goalId));if(h2?.state==="confirmed"||h2?.state==="sealed")return;if(h2?.timer!==void 0)clearTimeout(h2.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"sealed"})}function stopOnceHandoffTimer(uid2,goalId){const h2=proc().handoffs.get(keyOf(uid2,goalId));if(h2?.state!=="claimed"||h2.timer===void 0)return;clearTimeout(h2.timer);h2.timer=void 0}function onOnceHandoffTimeout(fn){proc().timedOut=fn}function registerOnceExit(fn){proc().exit=fn}function exitOnceSeat(){const p=proc();if(p.exiting)return p.exiting;const exiting=askOnceExit(p.exit).then(ending=>{if(!ending){p.exiting=void 0;return false}setTimeout(()=>process.exit(1),ONCE_EXIT_GRACE_MS);return true});p.exiting=exiting;return exiting}async function askOnceExit(exit){let ending;try{ending=exit?.()}catch{return true}if(ending instanceof Promise)ending=await ending.catch(()=>false);return ending!==false}init_peer_label();function attributionSafe(s){return peerLabel({name:s})}function fmtFrom(i){const name=i.fromName.trim()?i.fromName:i.fromId;return peerLabel({name,...i.fromRole?{role:i.fromRole}:{}})}function fmtBody(text2){return text2.split(LINE_BREAK).join("\n ")}function fmtItem(i){return formatItem(i)}function fmtDeliveryItem(i){const field=value=>Array.from(JSON.stringify(value),char=>[91,93,133,8232,8233].includes(char.charCodeAt(0))?`\\u${char.charCodeAt(0).toString(16).padStart(4,"0")}`:char).join("");const metadata2=[`sender_id=${field(i.fromId)}`,...i.id?[`message_id=${field(i.id)}`]:[],...i.contextId?[`context_id=${field(i.contextId)}`]:[],...i.replyTo?[`reply_to=${field(i.replyTo)}`]:[]];return formatItem(i,`[${metadata2.join(" ")}] `)}function formatItem(i,metadata2=""){const h2=i.historical?"(history) ":"";const r=i.deliveryCount!==void 0&&i.deliveryCount>1?`(broker redelivery, delivery ${i.deliveryCount}: prior model handoff unknown) `:"";const body=`${metadata2}${h2}${r}${fmtBody(i.text)}`;if(i.notice==="anycast")return`[anycast notice from the delivery daemon] ${body}`;if(i.kind==="dm")return`[DM from ${fmtFrom(i)}] ${body}`;if(i.kind==="anycast")return`[@${attributionSafe(i.service??"")} from ${fmtFrom(i)}] ${body}`;return`[#${attributionSafe(i.channel??"")}${i.mentionsMe?" @you":""} ${fmtFrom(i)}] ${body}`}var legacyRail=new Map;var LEGACY_RAIL_RECHECK_MS=60*6e4;var LEGACY_RAIL_MAX=32;function onLegacyRail(key){const until=legacyRail.get(key);if(until===void 0)return false;if(Date.now()<until)return true;legacyRail.delete(key);return false}function rememberLegacyRail(key){legacyRail.set(key,Date.now()+LEGACY_RAIL_RECHECK_MS);if(legacyRail.size>LEGACY_RAIL_MAX)legacyRail.delete(legacyRail.keys().next().value)}async function withUserManagerListing(config2,token2,exp,ask){const user=config2.userAuth;const binding=managerCallerBinding(token2,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId});const railKey=binding.credentialId??token2;const connectOpts=standaloneConnectOpts({bearer:token2,sentinelCreds:user.sentinelCreds,tls:config2.tls});const connId=String(connectOpts.name);const nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:1e4});const issued=async()=>{try{const caller=await issuedUserCaller(nc,config2.space,connId,binding.caller);legacyRail.delete(railKey);return caller}catch(e){if(!isPermissionDenied(e))throw e;rememberLegacyRail(railKey);return void 0}};try{const skipped=onLegacyRail(railKey);const caller=skipped?void 0:await issued();const listing=caller??await registryListingCaller(nc,config2.space,binding.caller,{connId,...exp!==void 0?{exp}:{}});return await ask(nc,listing??(skipped?await issued():void 0))}finally{await drainAndClose(nc)}}async function invokeUserManager(config2,bearer,command,args,opts={}){opts.signal?.throwIfAborted();const user=config2.userAuth;const endpoint=BASELINE_LIFECYCLE_ENDPOINT;let nc;let caller;let instanceId;let service;let skippedAcceptedRead;const onAbort=()=>{void nc?.close()};const resolve3=(signal=opts.signal,deadlineMs=opts.deadlineMs??1e4)=>resolveService(nc,config2.space,endpoint,caller,{instanceId,deadlineMs,signal,commands:opts.follow?[command,"goal-result"]:[command],...opts.follow&&command!=="goal-result"?{optionalCommands:["goal-result"]}:{}});const resolvePrepared=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const remaining=()=>{signal?.throwIfAborted();const left=deadline-Date.now();if(left<=0)throw new EpEnvelopeError("deadline-exceeded","the deadline passed before the manager was resolved; the manager request WAS NOT RUN",void 0,"not-executed");return left};try{return await resolve3(signal,remaining())}catch(error51){if(!skippedAcceptedRead||!isPermissionDenied(error51))throw error51;const{key,connId}=skippedAcceptedRead;skippedAcceptedRead=void 0;remaining();caller=await issuedUserCaller(nc,config2.space,connId,caller);legacyRail.delete(key);return resolve3(signal,remaining())}};const connect3=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const token2=await bearer(signal);let credentialId;({caller,instanceId,credentialId}=managerCallerBinding(token2,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId}));const connectOpts=standaloneConnectOpts({bearer:token2,sentinelCreds:user.sentinelCreds,tls:config2.tls});signal?.throwIfAborted();const left=deadline-Date.now();if(left<=0)throw new EpEnvelopeError("deadline-exceeded","the deadline passed before the manager was connected; the manager request WAS NOT RUN",void 0,"not-executed");nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:left});if(signal?.aborted)onAbort();signal?.throwIfAborted();const railKey=credentialId??token2;if(onLegacyRail(railKey)){skippedAcceptedRead={key:railKey,connId:String(connectOpts.name)}}else{try{caller=await issuedUserCaller(nc,config2.space,String(connectOpts.name),caller)}catch(e){if(!isPermissionDenied(e))throw e;rememberLegacyRail(railKey)}}};const prepare=async(signal,deadline)=>{await connect3(signal,deadline);service=await resolvePrepared(signal,deadline)};const invoke=async(signal=opts.signal)=>{const unfollowable=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable)return unfollowable;const invokeOpts={target:opts.target,deadlineMs:opts.deadlineMs,signal};const result=await invokeCommand(nc,config2.space,service,command,args,invokeOpts);if(result.reply.ok===false&&replyRefusedBeforeEffect(result.reply.error)){try{service=await resolve3(signal);const unfollowable2=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable2)throw new Error(unfollowable2.reply.error.message)}catch(error51){return{...result,reply:{...result.reply,error:{...result.reply.error,message:`${command} WAS NOT RUN; manager instance ${instanceId} refused before effects, and re-resolution failed: ${error51 instanceof Error?error51.message:String(error51)}`}}}}return invokeCommand(nc,config2.space,service,command,args,invokeOpts)}return result};opts.signal?.addEventListener("abort",onAbort,{once:true});try{if(opts.follow)return await opts.follow(invoke,prepare);await connect3();service=await resolvePrepared();return await invoke()}finally{opts.signal?.removeEventListener("abort",onAbort);const control=nc;if(control)await drainAndClose(control,2e3)}}var CONNECTOR_VERSION="0.164.17";import{createHash as createHash9,randomUUID as randomUUID6}from"node:crypto";var SPAWN_TIMEOUT_MS=4e4;var MANAGER_BEARER_MARGIN_MS=12e4;var CONNECT_GRACE_MS=1e4;function isLocalServer(servers){return servers.split(",").every(s=>/^(?:[a-z]+:\/\/)?(?:[^@/]*@)?(?:localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(?::\d+)?(?:\/|$)/i.test(s.trim()))}var EVENTS_META_KEY="ai.cotal.events";function buildMeta(config2,processCwd,eventsArmed){const meta3={...config2.meta??{}};if(config2.model)meta3.model=config2.model;if(config2.variant)meta3.variant=config2.variant;if(config2.connector)meta3.connector=config2.connector;meta3.host=hostname2();delete meta3["ai.cotal.manager.instance"];if(config2.managerInstanceId)meta3["ai.cotal.manager.instance"]=config2.managerInstanceId;meta3[EVENTS_META_KEY]=eventsArmed??eventPlaneArmed(config2)?"on":"off";if(processCwd)meta3.cwd=process.cwd();else delete meta3.cwd;return Object.keys(meta3).length?meta3:void 0}function afterRecallMark(a,b){return a.ts!==b.ts?a.ts>b.ts:a.id>b.id}var MAX_INBOX=200;var TAKE_WAIT_MS=2e3;var TAKE_RETRY_MS=1e4;var MAX_IN_FLIGHT=MAX_INBOX*2;var MAX_AHEAD=256;var CLASSIFICATION_CAP=4096;var FOCUS_EXCLUSION_CAP=4096;var IDLESS_READS=3;var PROTECTED_DISPOSITION_CAP=4096;var MAX_CORRELATIONS=1024;var ENDPOINT_ERROR_LOG_WINDOW_MS=3e4;var MAX_ENDPOINT_NOTICES=16;var NAMED_SIMILAR=5;var MAX_SETTLED_TURNS=32;function settledTurnError(goalId,t){if(t.yielded!==void 0)return`turn "${goalId}" was already yielded ${t.yielded} by this seat${t.yielded==="done"?" (ending a session turn yields done)":""}, so this yield was not recorded`;const deadline=t.deadlineAt!==void 0?` (deadline ${new Date(t.deadlineAt).toISOString()})`:"";return`turn "${goalId}" was already settled ${t.once!==void 0?"by its manager":"by the run"}${deadline}, so this yield was not recorded`}function compareRelease(a,b){const[x,y]=[a,b].map(v=>v.split(/[-+]/)[0].split(".").map(Number));for(let i=0;i<3;i++)if(x[i]!==y[i])return(x[i]??0)-(y[i]??0);return 0}var MAX_DATE_MS=864e13;function isPendingTurn(t){const r=t;if(typeof r!=="object"||r===null||typeof r.goalId!=="string"||typeof r.payload!=="string")return false;if(!Number.isSafeInteger(r.acceptedAt)||r.acceptedAt<0)return false;if(r.once!==void 0&&r.once!==true)return false;if(r.deadlineAt===void 0)return r.once===true;return Number.isSafeInteger(r.deadlineAt)&&r.deadlineAt>=1&&r.deadlineAt<=MAX_DATE_MS}function onceSpawner(payload){try{const spawner=JSON.parse(payload).once?.spawner;return typeof spawner==="string"&&spawner.length>0?spawner:void 0}catch{return void 0}}function carriesAnycastNotice(m){return m.parts.some(p=>p.kind==="data"&&typeof p.data==="object"&&p.data!==null&&!Array.isArray(p.data)&&ANYCAST_NOTICE_KEY in p.data)}function idlessDigest(m){return createHash9("sha256").update(JSON.stringify(m)).digest("base64url")}function sleep(ms){return new Promise(r=>setTimeout(r,ms))}function ingestDedupKey(id2){return id2===""?void 0:id2}var AUTOMATIC_QUEUE_STALL_MS=6e5;function renderAskRequest(p){const escalation=renderEscalation(p);if(escalation!=="")return escalation;const ask=p.ask;if(ask===null||typeof ask!=="object")return"";const a=ask;const entries=a.schema!==null&&typeof a.schema==="object"?Object.entries(a.schema):[];const fields=entries.length===0?"any record":entries.map(([k,v])=>`${k}: ${String(v)}`).join(", ");const by=typeof a.deadlineAt==="number"?`, by ${new Date(a.deadlineAt).toISOString()}`:"";const refused=typeof a.refused==="string"?`
116
116
  Your last answer was refused: ${a.refused}`:"";return`
117
117
  This turn is an ask: the run needs a record from you at step ${String(p.step)} with fields ${fields} (attempt ${String(a.attempt)} of ${String(a.attempts)}${by}).${refused}`+renderPauseAnswer(p,"<json record>")}function renderPauseAnswer(p,value){return`
118
118
  Answer through your native Cotal tools: call cotal_describe for endpoint "manager", then cotal_invoke with endpoint="manager", command="run-answer", self=true and args={"runId":${JSON.stringify(p.run)},"stepKey":${JSON.stringify(p.step)},"value":${value}}.
@@ -125,7 +125,7 @@ ${context}${ask}`});const text2=`\u{1F3AF} Cotal \u2014 a run handed you ${waiti
125
125
  ${blocks.join("\n")}
126
126
  (Do the work now with your own tools. ${asked?"An ask must be answered through its native route above before ending your host turn. ":""}For ordinary turns, ending your turn yields "done" automatically; call cotal_yield when blocked or handing off an ordinary turn.)`;return{text:text2,goalIds:waiting.map(t=>t.goalId)}}commitSurfacedTurns(goalIds){if(this.config.turnRelay===false&&!this.nativeTurnLeaseValid())return;for(const id2 of goalIds){const t=this.activeTurns.get(id2);if(t?.once!==void 0&&!confirmOnceHandoff(this.onceUid(),id2))continue;if(t)t.surfaced=true}}claimTurns(goalIds){return claimOnceHandoff(this.onceUid(),goalIds.filter(id2=>(this.activeTurns.get(id2)??this.settledTurns.get(id2))?.once!==void 0))}releaseTurns(goalIds){for(const id2 of goalIds){if(this.activeTurns.get(id2)?.once===void 0)continue;if(sealOnceHandoff(this.onceUid(),id2))void this.reportUnconfirmed(id2)}}noteTurnsDispatched(goalIds){for(const id2 of goalIds)if(this.activeTurns.get(id2)?.once!==void 0)stopOnceHandoffTimer(this.onceUid(),id2)}boundOnceClaim(goalId){const timer=setTimeout(()=>{if(!this.activeTurns.has(goalId)||onceHandoffState(this.onceUid(),goalId)!=="pending")return;this.log(`once task ${goalId}: pulled ${ONCE_HANDOFF_MS}ms ago and never handed to the session; reporting it unconfirmed`);if(this.claimTurns([goalId]))this.releaseTurns([goalId])},ONCE_HANDOFF_MS);timer.unref?.()}offerable(t){return t.once===void 0||onceHandoffState(this.onceUid(),t.goalId)==="pending"}onceUid(){return this.config.lifecycleUid??this.config.name}async reportUnconfirmed(goalId){const until=Date.now()+ONCE_HANDOFF_MS;let delay2=1e3;let exitTried=false;for(;;){const r=await this.managerInvoke("turn-unconfirmed",{goalId},{target:{mode:"self"}}).catch(e=>({ok:false,error:e.message,code:void 0}));const transient=!r.ok&&(r.code===void 0||r.code==="unavailable"||r.code==="deadline-exceeded");if(!transient){this.log(`once task ${goalId}: its handoff was not confirmed; reported to the manager (${r.ok?"the task failed":r.error??"refused"})`);return}if(!exitTried&&Date.now()+delay2>until){exitTried=true;this.log(`once task ${goalId}: its handoff was not confirmed and the manager could not be told; ending this seat so its exit settles the task`);if(await exitOnceSeat())return;this.log(`once task ${goalId}: this seat cannot end itself; reporting until a manager answers`)}if(this._stopping)return;await new Promise(resolve3=>setTimeout(resolve3,delay2));delay2=Math.min(delay2*2,exitTried?6e4:1e4)}}async yieldTurn(status2,opts={}){if(this.config.turnRelay===false&&!this.nativeTurnLeaseValid())return{ok:false,error:"this personal connection has no valid workflow turn participation lease; opt in or renew it first"};try{await this.requireConnected()}catch(error51){throw new Error(`${error51.message}. The yield was not sent.`,{cause:error51})}const t=opts.turn!==void 0?this.activeTurns.get(opts.turn):[...this.activeTurns.values()].filter(x=>x.surfaced).sort((a,b)=>a.acceptedAt-b.acceptedAt)[0];if(!t){const id2=opts.turn??[...this.settledTurns.keys()].at(-1);const settled=id2===void 0?void 0:this.settledTurns.get(id2);if(id2!==void 0&&settled!==void 0)return{ok:false,error:settledTurnError(id2,settled)};return{ok:false,error:opts.turn!==void 0?`no active turn "${opts.turn}" on this seat`:"no turn is active \u2014 nothing to yield"}}if(!t.surfaced)return{ok:false,error:`turn "${t.goalId}" has not been surfaced into this session yet; nothing was seen, so nothing can be yielded for it`};if(status2==="handoff"&&(opts.to===void 0||opts.to.length===0))return{ok:false,error:"a handoff yield names its addressee (to)"};const r=await this.managerInvoke("turn-yield",{goalId:t.goalId,status:status2,to:opts.to,note:opts.note},{target:{mode:"self"}});if(!r.ok)return r;this.yieldedSincePull.add(t.goalId);if(r.data?.state!=="succeeded"){this.settleTurn(t);return{ok:false,error:settledTurnError(t.goalId,t)}}this.activeTurns.delete(t.goalId);this.rememberSettled(t.goalId,{yielded:status2});return r}settleTurn(t){if(t.once!==void 0)endOnceHandoff(this.onceUid(),t.goalId);this.activeTurns.delete(t.goalId);this.rememberSettled(t.goalId,{...t.deadlineAt!==void 0?{deadlineAt:t.deadlineAt}:{},...t.once!==void 0?{once:true}:{}})}rememberSettled(goalId,settled){this.settledTurns.delete(goalId);this.settledTurns.set(goalId,settled);if(this.settledTurns.size>MAX_SETTLED_TURNS)this.settledTurns.delete(this.settledTurns.keys().next().value)}async purgeHistory(opts){await this.requireConnected();const args={includeDms:opts?.includeDms??false};return this.managerInvoke("purge",args)}async definePersona(def){await this.requireConnected();const pin=this.managerPin(def.instance??this.openManagerInstance());if("error"in pin)return pin.error;if(def.announce!==void 0){if(def.announce.trim()==="")throw new Error("announce: empty channel \u2014 omit it to define silently, or name a concrete channel");try{assertValidChannel(def.announce)}catch(e){throw new Error(`announce: ${e?.message??String(e)}`)}if(!isConcreteChannel(def.announce))throw new Error(`announce: "${def.announce}" is a wildcard \u2014 announce to one concrete channel`)}const args={name:def.name,model:def.model,persona:def.prompt,role:def.role,agent:def.agent,subscribe:def.subscribe,allowSubscribe:def.allowSubscribe,allowPublish:def.allowPublish,capabilities:def.capabilities,endpoints:def.endpoints};const reply=await this.managerInvoke("define-persona",args,pin);if(!reply.ok&&reply.outcome!=="not-executed"&&(reply.outcome==="unknown"||reply.code==="deadline-exceeded"&&reply.details?.some(d=>d.kind===EP_UNANSWERED&&d.command==="define-persona")))return{...reply,definitionOutcome:"unknown"};if(!reply.ok||!def.announce)return reply;try{await this.send(`defined persona \`${def.name}\` \u2014 in this workspace's persona catalog, spawnable with cotal_spawn`,def.announce)}catch(e){return{...reply,announceError:e?.message??String(e),announceOutcome:isPublishPermissionDenied(e)?"denied":"unknown"}}return reply}async listPersonas(instance){await this.requireConnected();const pin=this.managerPin(instance??this.openManagerInstance());if("error"in pin)return pin.error;return this.managerInvoke("list-personas",void 0,pin)}async showPersona(name,instance){await this.requireConnected();const pin=this.managerPin(instance??this.openManagerInstance());if("error"in pin)return pin.error;return this.managerInvoke("show-persona",{name},pin)}async readRoster(){try{return{roster:await this.ep.readPresence()}}catch(e){return{roster:this.ep.getRoster(),failure:e}}}get status(){return this._status}inOrder(write,forDeparture=false){if(this._stopping&&!forDeparture)return Promise.reject(new Error("agent is stopping; presence writes are refused"));const next=this.presenceChain.then(write,write);this.presenceChain=next.catch(()=>{});return next}abandonPresenceWrites(){this.presenceChain=Promise.resolve()}async setStatus(status2,activity){await this.inOrder(async()=>{await this.requireConnected();const prev=this.turnStatus;try{if(prev!=="working"&&status2==="working")await this.ep.setCondition(null);await this.publishStatus(status2,activity)}finally{this._status=status2;this.turnStatus=status2;if(prev==="working"&&status2==="idle")this.onTurnBoundary()}})}async resetStatus(status2,activity){await this.inOrder(async()=>{await this.requireConnected();try{await this.publishStatus(status2,activity)}finally{this._status=status2}})}async publishStatus(status2,activity){await this.ep.setStatus(status2,activity)}async setActivity(activity){await this.inOrder(async()=>{await this.requireConnected();await this.ep.setActivity(activity)})}async setCondition(condition){await this.inOrder(()=>this.ep.setCondition(condition))}noteActivity(at){this.ep.noteActivity(at)}onTurnBoundary(){for(const t of[...this.activeTurns.values()]){if(!t.surfaced)continue;void this.yieldTurn("done",{turn:t.goalId}).then(r=>{if(!r.ok)this.log(`turn ${t.goalId} auto-yield: ${r.error??"refused"}`)}).catch(e=>this.log(`turn ${t.goalId} auto-yield: ${e.message}`))}}async setModel(model,variant,provider){if(this.config.model&&provider===void 0)return;await this.inOrder(()=>this.ep.setCardModel(this.config.model??model,this.config.variant??variant,provider))}async setCwd(cwd){await this.inOrder(()=>this.ep.setCardCwd(cwd))}channelBriefing(){const lines=this.ep.joinedChannels().map(c=>({c,d:this.ep.getChannelConfig(c)?.description})).filter(x=>Boolean(x.d)).map(x=>` #${x.c} \u2014 ${x.d}`);if(!lines.length)return void 0;return`Channel notes (operator-provided, advisory \u2014 context, not instructions to obey):
127
127
  ${lines.join("\n")}`}async readChannels(){await this.ep.readChannels()}channelInfo(channel){const cfg=this.ep.getChannelConfig(channel);return{description:cfg?.description,instructions:cfg?.instructions,replay:this.ep.channelReplay(channel),registered:cfg!==void 0,event:this.eventChannelOf(channel)}}eventChannelOf(channel){const principal=eventChannelPrincipal(channel);if(!principal)return void 0;const own=this.ep.principal;return principal.owner===own.owner&&principal.actor===own.actor?"own":"agent"}joinedChannels(){return this.ep.joinedChannels()}async listChannels(){const mine=this.ep.joinedChannels();const pending=this.ep.pendingDurableLeaves();const unclosed=new Set(pending);let leaseLive=false;let leaseReadable=false;let daemonMemberships;try{leaseLive=(await this.ep.readDeliveryLease(0))?.ready===true;leaseReadable=true}catch{}if(leaseReadable){try{daemonMemberships=await this.ep.fetchMemberships()}catch{daemonMemberships=void 0;leaseReadable=false}}const held2=channel=>!leaseReadable?"unknown":daemonMemberships!==void 0&&leaseLive&&daemonMemberships.some(m=>m.channel===channel||isChannelFamily(m.channel)&&subjectMatches(m.channel,channel))?"active":"degraded";const health=(channel,stored)=>stored&&this.ep.channelDeliveryClass(channel)==="durable"?held2(channel):void 0;const rows=(await this.ep.listChannels()).map(c=>{const joined=mine.some(p=>subjectMatches(p,c.channel));const stored=mine.some(p=>p===c.channel||isChannelFamily(p)&&subjectMatches(p,c.channel));return{channel:c.channel,description:c.config?.description,replay:this.ep.channelReplay(c.channel),joined,durableUnclosed:unclosed.has(c.channel),deliveryHealth:health(c.channel,stored),messages:c.messages,mode:this.channelMode(c.channel)??"normal",event:this.eventChannelOf(c.channel)}});for(const pattern of mine){if(isConcreteChannel(pattern))continue;const family=isChannelFamily(pattern);rows.push({channel:pattern,replay:this.ep.channelReplay(pattern),joined:true,durableUnclosed:unclosed.has(pattern),deliveryHealth:family?held2(pattern):void 0,messages:0,mode:"normal",follow:family?"family":"live"})}const present=new Set(rows.map(r=>r.channel));for(const ch of pending){if(present.has(ch))continue;rows.push({channel:ch,description:void 0,replay:this.ep.channelReplay(ch),joined:false,durableUnclosed:true,deliveryHealth:void 0,messages:0,mode:this.channelMode(ch)??"normal",event:this.eventChannelOf(ch),...isChannelFamily(ch)?{follow:"family"}:{}})}return rows}async joinChannel(channel){await this.requireConnected();return this.ep.joinChannel(channel)}async leaveChannel(channel){await this.requireConnected();return this.ep.leaveChannel(channel)}async requireConnected(){return this.whenConnected(CONNECT_GRACE_MS)}async whenConnected(timeoutMs=CONNECT_GRACE_MS){if(this._connected)return;if(!await this.awaitConnection(timeoutMs))throw new Error(this.notConnectedMessage())}awaitConnection(timeoutMs){return new Promise(resolve3=>{let settled=false;const finish=ok3=>{if(settled)return;settled=true;clearTimeout(timer);this.ep.off("connection",onConnection);resolve3(ok3)};const onConnection=e=>{if(e.connected)finish(true)};const timer=setTimeout(()=>finish(false),Math.max(1,timeoutMs));this.ep.on("connection",onConnection);if(this._connected)finish(true)})}notConnectedMessage(){const issue2=this.connectionIssue;if(issue2)return`not connected to the mesh at ${this.config.servers}: ${issue2}`;const remedy=isLocalServer(this.config.servers)?"is it running? (`cotal up`)":"it did not become reachable \u2014 check that the mesh is up and that this machine can reach it.";return`not connected to the mesh at ${this.config.servers} \u2014 ${remedy}`}handleEndpointError(error51){if(!this._connected&&!this._stopping)this.lastConnectionError=error51.message;this.logEndpointNotice("error",error51)}handleEndpointWarning(error51){this.logEndpointNotice("warning",error51)}logEndpointNotice(kind,error51){const now=Date.now();const fingerprint=error51.message.replace(/oc_[A-Za-z0-9]+_\d+/g,"oc_*");const prior=this.endpointNoticeLog.get(fingerprint);if(prior&&now-prior.lastLoggedAt<ENDPOINT_ERROR_LOG_WINDOW_MS){prior.suppressed++;return}const suffix=prior?.suppressed?` (${prior.suppressed} repeats suppressed)`:"";this.endpointNoticeLog.set(fingerprint,{lastLoggedAt:now,suppressed:0});if(this.endpointNoticeLog.size>MAX_ENDPOINT_NOTICES)this.endpointNoticeLog.delete(this.endpointNoticeLog.keys().next().value);this.log(`endpoint ${kind}: ${error51.message}${suffix}`)}log(msg){process.stderr.write(`[cotal-connector] ${msg}
128
- `)}};function presenceReadCondition(failure){return`the presence read failed (${failure.message})`}function closeChannelNames(channel,known){const out=[];for(const name of known){if(name!==channel&&editDistanceAtMostOne(channel,name))out.push(name)}out.sort((a,b)=>a.localeCompare(b));return out.slice(0,3)}function editDistanceAtMostOne(a,b){if(a===b)return true;const da=a.length-b.length;if(da>1||da<-1)return false;let i=0;let j=0;let skipped=false;while(i<a.length&&j<b.length){if(a[i]===b[j]){i++;j++;continue}if(skipped)return false;skipped=true;if(a.length>b.length)i++;else if(b.length>a.length)j++;else{i++;j++}}return true}var SUN_PATH_MAX_BYTES=process.platform==="darwin"?104:108;function eventChannelForSession(ep){if(ep.actorIsEphemeral)throw new Error("events are not available for a session with a self-minted identity: this endpoint has no declared id and no credentials, so its actor is a fresh random token per process and its event channel could never match a grant. Launch it with an identity (an authed mesh, or an explicit id) to publish events.");return eventChannel(ep.principal)}var TOOL_RESULT_EVENT="cotal.toolResult";var COTAL_CUSTOM_EVENTS=[TOOL_RESULT_EVENT];var AGUI_PROTOCOL="ag-ui/0.0.57";var AguiVocabularyError=class extends Error{constructor(message){super(message);this.name="AguiVocabularyError"}};var AguiBrackets=class _AguiBrackets{run;text=new Set;reasoning=new Set;tools=new Set;snapshot(){return{run:this.run,text:[...this.text].sort(),reasoning:[...this.reasoning].sort(),tools:[...this.tools].sort()}}static restore(s){const b=new _AguiBrackets;b.run=s.run;for(const id2 of s.text)b.text.add(id2);for(const id2 of s.reasoning)b.reasoning.add(id2);for(const id2 of s.tools)b.tools.add(id2);return b}clone(){return _AguiBrackets.restore(this.snapshot())}get open(){return this.run!==void 0}get runId(){return this.run}accept(event){const e=event;const t=e.type;if(t===AGUI_EVENT_TYPE.RUN_STARTED){if(this.run!==void 0)throw new AguiVocabularyError(`RUN_STARTED for "${String(e.runId)}" while run "${this.run}" is still open`);this.run=String(e.runId);return}if(this.run===void 0)throw new AguiVocabularyError(`${t} emitted outside an open run`);if(t===AGUI_EVENT_TYPE.RUN_FINISHED||t===AGUI_EVENT_TYPE.RUN_ERROR){if(t===AGUI_EVENT_TYPE.RUN_FINISHED&&String(e.runId)!==this.run)throw new AguiVocabularyError(`RUN_FINISHED for "${String(e.runId)}" but the open run is "${this.run}"`);const dangling=[...this.text,...this.reasoning,...this.tools];if(dangling.length>0)throw new AguiVocabularyError(`${t} while still open: ${dangling.join(", ")}`);this.run=void 0;return}switch(t){case AGUI_EVENT_TYPE.TEXT_MESSAGE_START:return this.openId(this.text,String(e.messageId),t);case AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT:return this.requireOpen(this.text,String(e.messageId),t);case AGUI_EVENT_TYPE.TEXT_MESSAGE_END:return this.closeId(this.text,String(e.messageId),t);case AGUI_EVENT_TYPE.REASONING_MESSAGE_START:return this.openId(this.reasoning,String(e.messageId),t);case AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT:return this.requireOpen(this.reasoning,String(e.messageId),t);case AGUI_EVENT_TYPE.REASONING_MESSAGE_END:return this.closeId(this.reasoning,String(e.messageId),t);case AGUI_EVENT_TYPE.TOOL_CALL_START:return this.openId(this.tools,String(e.toolCallId),t);case AGUI_EVENT_TYPE.TOOL_CALL_ARGS:return this.requireOpen(this.tools,String(e.toolCallId),t);case AGUI_EVENT_TYPE.TOOL_CALL_END:return this.closeId(this.tools,String(e.toolCallId),t);case AGUI_EVENT_TYPE.TOOL_CALL_RESULT:if(this.tools.has(String(e.toolCallId)))throw new AguiVocabularyError(`TOOL_CALL_RESULT for "${String(e.toolCallId)}" while its call is still open`);return;case AGUI_EVENT_TYPE.CUSTOM:if(!COTAL_CUSTOM_EVENTS.includes(String(e.name)))throw new AguiVocabularyError(`CUSTOM "${String(e.name)}" is not declared in COTAL_CUSTOM_EVENTS, the reviewed table of cotal.* names`);if(e.name===TOOL_RESULT_EVENT){const defect=toolResultMarkerDefect(e);if(defect!==void 0)throw new AguiVocabularyError(`${TOOL_RESULT_EVENT} ${defect}`);const id2=e.value.toolCallId;if(this.tools.has(id2))throw new AguiVocabularyError(`${TOOL_RESULT_EVENT} for "${id2}" while its call is still open`)}return;default:throw new AguiVocabularyError(`${t} is not in the mapped subset this plane emits`)}}assertClosed(){if(this.run!==void 0)throw new AguiVocabularyError(`run "${this.run}" was never closed`)}openId(set3,id2,t){if(set3.has(id2))throw new AguiVocabularyError(`${t} re-opened "${id2}" while already open`);set3.add(id2)}requireOpen(set3,id2,t){if(!set3.has(id2))throw new AguiVocabularyError(`${t} for "${id2}" which is not open`)}closeId(set3,id2,t){if(!set3.delete(id2))throw new AguiVocabularyError(`${t} for "${id2}" which is not open`)}};function aguiFrame(opts){for(const[field,value]of[["threadId",opts.threadId],["runId",opts.runId],["epoch",opts.epoch]])if(typeof value!=="string"||value.length===0)throw new AguiVocabularyError(`frame ${field} must be a non-empty string`);if(!Number.isSafeInteger(opts.seq)||opts.seq<0)throw new AguiVocabularyError(`frame seq must be a non-negative safe integer, got ${JSON.stringify(opts.seq)}`);if(!Array.isArray(opts.events)||opts.events.length===0)throw new AguiVocabularyError("a frame must carry at least one event");return{kind:AGUI_FRAME_KIND,protocol:AGUI_PROTOCOL,threadId:opts.threadId,runId:opts.runId,epoch:opts.epoch,seq:opts.seq,events:opts.events}}function parseAguiFrame(part){if(!isAguiFramePart(part))throw new AguiVocabularyError(`not an AG-UI frame: expected kind ${JSON.stringify(AGUI_FRAME_KIND)}, got ${JSON.stringify(part?.kind??null)}. Route with isAguiFramePart before calling this.`);const f=part;if(f.protocol!==AGUI_PROTOCOL)throw new AguiVocabularyError(`AG-UI protocol mismatch: this consumer understands ${JSON.stringify(AGUI_PROTOCOL)}, the frame declares ${JSON.stringify(f.protocol??null)}. Refusing rather than rendering the fields that happen to still parse.`);for(const field of["threadId","runId","epoch"])if(typeof f[field]!=="string"||f[field].length===0)throw new AguiVocabularyError(`frame ${field} must be a non-empty string`);if(!Number.isSafeInteger(f.seq)||f.seq<0)throw new AguiVocabularyError(`frame seq must be a non-negative safe integer, got ${JSON.stringify(f.seq??null)}`);if(!Array.isArray(f.events)||f.events.length===0)throw new AguiVocabularyError("a frame must carry at least one event");const known=new Set(Object.values(AGUI_EVENT_TYPE));f.events.forEach((e,i)=>{if(typeof e!=="object"||e===null)throw new AguiVocabularyError(`frame events[${i}] is not an object`);const t=e.type;if(typeof t!=="string"||!known.has(t))throw new AguiVocabularyError(`frame events[${i}] carries an unrecognised type ${JSON.stringify(t??null)}. A renderer must refuse an event it cannot display rather than skip it: a skipped event is a hole in a transcript that still looks complete.`)});return part}function runStarted(o){return{type:AGUI_EVENT_TYPE.RUN_STARTED,threadId:o.threadId,runId:o.runId,timestamp:o.timestamp,...o.cotal?{cotal:o.cotal}:{}}}function assertInterrupts(list){if(!Array.isArray(list)||list.length===0)throw new AguiVocabularyError("outcome.interrupts must be a non-empty array when the outcome is an interrupt");for(const[i,entry]of list.entries()){const e=entry;if(typeof e!=="object"||e===null)throw new AguiVocabularyError(`outcome.interrupts[${i}] is not an object`);if(typeof e.id!=="string")throw new AguiVocabularyError(`outcome.interrupts[${i}].id must be a string`);if(typeof e.reason!=="string")throw new AguiVocabularyError(`outcome.interrupts[${i}].reason must be a string`)}}function runFinished(o){if(o.outcome?.type==="interrupt")assertInterrupts(o.outcome.interrupts);return{type:AGUI_EVENT_TYPE.RUN_FINISHED,threadId:o.threadId,runId:o.runId,timestamp:o.timestamp,...o.outcome?{outcome:o.outcome}:{},...o.cotal?{cotal:o.cotal}:{}}}function runError(o){return{type:AGUI_EVENT_TYPE.RUN_ERROR,message:o.message,timestamp:o.timestamp,...o.code?{code:o.code}:{},...o.cotal?{cotal:o.cotal}:{}}}function textMessageStart(o){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_START,messageId:o.messageId,timestamp:o.timestamp,...o.role?{role:o.role}:{},...o.cotal?{cotal:o.cotal}:{}}}function textMessageContent(o){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,messageId:o.messageId,delta:o.delta,timestamp:o.timestamp,...o.cotal?{cotal:o.cotal}:{}}}function textMessageEnd(o){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_END,messageId:o.messageId,timestamp:o.timestamp,...o.cotal?{cotal:o.cotal}:{}}}function toolCallStart(o){return{type:AGUI_EVENT_TYPE.TOOL_CALL_START,toolCallId:o.toolCallId,toolCallName:o.toolCallName,timestamp:o.timestamp,...o.parentMessageId?{parentMessageId:o.parentMessageId}:{},...o.cotal?{cotal:o.cotal}:{}}}function toolCallEnd(o){return{type:AGUI_EVENT_TYPE.TOOL_CALL_END,toolCallId:o.toolCallId,timestamp:o.timestamp,...o.cotal?{cotal:o.cotal}:{}}}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_FRAME_KEYS=new Set(["kind","protocol","threadId","runId","epoch","seq","events"]);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 toolResultMarkerDefect(e){if("rawEvent"in e)return"carries rawEvent, which the content-free marker never does";const defect=toolResultValueDefect(e.value);if(defect===void 0)return void 0;return defect==="value"?"value is not { toolCallId: string, isError: boolean }":`${defect} is not a key the marker's value carries`}function toolResultValue(value){if(toolResultValueDefect(value)!==void 0)return void 0;const v=value;return{toolCallId:v.toolCallId,isError:v.isError}}function extraPropertyPath(part){for(const key of Object.keys(part)){if(!KNOWN_FRAME_KEYS.has(key))return key}const events=part.events;if(!Array.isArray(events))return void 0;for(let i=0;i<events.length;i++){const e=events[i];if(typeof e!=="object"||e===null)continue;const t=e.type;const allowed=KNOWN_EVENT_KEYS_BY_TYPE.get(t);if(!allowed)return`events[${i}]`;for(const key of Object.keys(e)){if(!allowed.has(key))return`events[${i}].${key}`}if(t===AGUI_EVENT_TYPE.CUSTOM&&e.name===TOOL_RESULT_EVENT){if("rawEvent"in e)return`events[${i}].rawEvent`;const defect=toolResultValueDefect(e.value);if(defect!==void 0)return`events[${i}].${defect}`}}return void 0}function isForbiddenEgressEventType(type){return typeof type==="string"&&EGRESS_FORBIDDEN_TYPES.has(type)}var RUN_ERROR_EGRESS_MESSAGE="run failed";function egressRunError(o){return{type:AGUI_EVENT_TYPE.RUN_ERROR,message:RUN_ERROR_EGRESS_MESSAGE,...o.timestamp!==void 0?{timestamp:o.timestamp}:{},...o.cotal?{cotal:o.cotal}:{}}}function isEgressRunError(e){return e.message===RUN_ERROR_EGRESS_MESSAGE&&!("code"in e)&&!("rawEvent"in e)}function isToolResultMarker(e){return e.type===AGUI_EVENT_TYPE.CUSTOM&&e.name===TOOL_RESULT_EVENT}function egressToolResultMarker(e){if(!("rawEvent"in e))return e;const{rawEvent:_dropped,...rest}=e;return rest}function applyAguiEgressPolicy(events){return events.filter(e=>!isForbiddenEgressEventType(e.type)).map(e=>e.type===AGUI_EVENT_TYPE.RUN_ERROR?egressRunError(e):isToolResultMarker(e)?egressToolResultMarker(e):e)}function frozenBodyEgressVerdict(body){let unreadable=false;try{for(const part of body){try{if(!isAguiFramePart(part))continue;const frame=parseAguiFrame(part);for(const e of frame.events){if(isForbiddenEgressEventType(e.type))return"forbidden-kind"}for(const e of frame.events){if(e.type===AGUI_EVENT_TYPE.RUN_ERROR&&!isEgressRunError(e))return"run-error-content"}const extra=extraPropertyPath(part);if(extra!==void 0)return"extra-property"}catch{unreadable=true}}}catch{unreadable=true}return unreadable?"unreadable":"clean"}import{createHash as createHash11,randomUUID as randomUUID8}from"node:crypto";import{dirname as dirname8,join as join9}from"node:path";import{execFileSync as execFileSync3}from"node:child_process";init_external();init_external();var ok=text2=>({text:text2});var err=text2=>({text:text2,isError:true});function receipt(status2,value){if(status2!==202||typeof value!=="object"||value===null||Array.isArray(value))return void 0;const body=value;if(body.ok!==true||typeof body.id!=="string"||body.id.length===0||body.id.length>200)return void 0;if(/[\u0000-\u001f\u007f]/.test(body.id)||body.id.trim()!==body.id)return void 0;if(typeof body.published!=="boolean")return void 0;return{id:body.id,published:body.published}}async function submitFeedback(input,options={}){const url2=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const headers3={"content-type":"application/json"};const body={...input};if(options.key){headers3.authorization=`Bearer ${options.key}`}else{if(!options.email)return err("Keyless feedback goes to the public cotal.ai intake, which requires a traceable contact email \u2014 ask the user for one and retry with the email argument (or set COTAL_FEEDBACK_EMAIL).");body.email=options.email}let res;let raw;try{res=await fetch(url2,{method:"POST",headers:headers3,body:JSON.stringify(body),redirect:"error"});raw=await res.text()}catch(e){return err(`Couldn't reach the feedback intake at ${url2}: ${e.message} The submission was not retried.`)}let reply=void 0;if(raw)try{reply=JSON.parse(raw)}catch{reply=void 0}const stored=receipt(res.status,reply);if(stored){const note=stored.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent (id ${stored.id})${note}. Thanks!`)}const errorText=typeof reply==="object"&&reply!==null&&typeof reply.error==="string"?reply.error:void 0;if(!res.ok)return err(`Feedback rejected (${res.status}${errorText?`: ${errorText}`:""}).`);return err(`Feedback acceptance is unconfirmed (${res.status}). The request may have reached the intake and was not retried.`)}import{createHash as createHash10}from"node:crypto";import{readFileSync as readFileSync5}from"node:fs";import{join as join8}from"node:path";import{gunzipSync}from"node:zlib";var DOCS_VERSION="0.164.15";function loadDocsMetadata(){return{"version":"0.164.15","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here (informative)","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here (informative)","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept (informative)","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference: the `cotal_*` tool surface every connected agent gets.","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference (informative task card)","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept (informative)","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference (the persisted form of an agent's identity + persona, read by every launcher)","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference (informative)","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide: describes the TypeScript reference implementation, not the wire contract.","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide (informative)","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI), not the wire contract.","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI and connectors), not the wire contract.","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide (informative)","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide (informative)","category":"Guide","summary":"Launch Codex on a Cotal mesh, connect your own Codex conversations, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide (informative)","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-opencode","title":"Connect OpenCode","kind":"Guide (informative)","category":"Guide","summary":"Launch OpenCode on a Cotal mesh and choose the model and options for your installed version."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Launch pi on a Cotal mesh or load the Cotal extension into your own pi host."},{"slug":"connector-runtime-reference","title":"Connector runtime reference","kind":"Reference","category":"Reference","summary":"Shared connection recovery, presence display, send receipts, delivery acknowledgement, reply correlation, and resume records."},{"slug":"connectors","title":"Connectors","kind":"Guide (informative)","category":"Guide","summary":"Choose an agent application and connect its sessions to a Cotal mesh."},{"slug":"console","title":"Use the console","kind":"Guide","category":"Guide","summary":"Inspect a mesh from the terminal and use authorized operator controls."},{"slug":"control-discovery","title":"Endpoint discovery","kind":"Reference","category":"Reference","summary":"Command contracts, manager instance selection, request outcomes, and service registration."},{"slug":"control-lifecycle","title":"Manager lifecycle contracts","kind":"Reference","category":"Reference","summary":"Managed identities, static slots, spawn goals, chat sessions, terminal access, and grants."},{"slug":"control-surface","title":"The control surface","kind":"Concept (informative)","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide (informative)","category":"Guide","summary":"Describe agents and channels in a manifest, then boot or deploy that team."},{"slug":"delivery-daemon","title":"The delivery daemon","kind":"Concept (informative)","category":"Concept","summary":"Why durable channel delivery needs a trusted service, and what happens without it."},{"slug":"delivery-service-reference","title":"Delivery service contracts","kind":"Reference","category":"Reference","summary":"Fan-out, trusted reads, leases, membership retirement, credential adoption, and daemon lifetime."},{"slug":"deploy","title":"Deploy agent teams","kind":"Guide (informative)","category":"Guide","summary":"Review the container example, its current build limitation, and the credentials it needs."},{"slug":"embedding-daemons","title":"Embedded daemon lifecycle","kind":"Reference","category":"Reference","summary":"Process runners, account-scoped hosted services, and delivery credential renewal."},{"slug":"embedding-delegated-seats","title":"Delegated seat contracts","kind":"Reference","category":"Reference","summary":"Managed lifecycle handoff, provider closure guarantees, and the limits of delegated recovery contracts."},{"slug":"embedding-endpoints","title":"CotalEndpoint reference","kind":"Reference","category":"Reference","summary":"Presence metadata, observer freshness, write diagnosis, liveness probes, and DM-only endpoint readers."},{"slug":"embedding-exports","title":"Embedding package exports","kind":"Reference","category":"Reference","summary":"Public package entry points, endpoint credentials, and Manager execution contracts."},{"slug":"embedding-manager","title":"Manager embedding authority","kind":"Reference","category":"Reference","summary":"Manager startup, signer custody, remote authority callbacks, and delegated user intent contracts."},{"slug":"embedding-provisioning","title":"Embedded space provisioning","kind":"Reference","category":"Reference","summary":"Broker trust, space credentials, durable host state, and current hosting limitations."},{"slug":"embedding-remote-clients","title":"Embedded remote clients","kind":"Reference","category":"Reference","summary":"MCP conversation routing, browser callers, remote Manager clients, and private-result prerequisites."},{"slug":"embedding-schema-inspection","title":"Space schema inspection","kind":"Reference","category":"Reference","summary":"Resource definitions, bounded read-only observations, and the limits of schema and initialization comparisons."},{"slug":"embedding-service-access","title":"Service endpoint access","kind":"Reference","category":"Reference","summary":"Authority proofs, serving credentials, verified grants, and renewal."},{"slug":"embedding-service-authority","title":"Service authority contracts","kind":"Reference","category":"Reference","summary":"Service authority contracts, platform supervisors, revocation prerequisites, and native custody limits."},{"slug":"embedding-service-callers","title":"Service endpoint callers","kind":"Reference","category":"Reference","summary":"Caller policy grants, broker payload prerequisites, revocation, and recovery limits."},{"slug":"embedding-service-custody","title":"Native service custody","kind":"Reference","category":"Reference","summary":"Immutable service reservations, bootstrap, cancellation, and bounded writer guarantees."},{"slug":"embedding-service-host","title":"Service endpoint hosting","kind":"Reference","category":"Reference","summary":"Owner approvals, native host operations, registration, and lifecycle custody."},{"slug":"embedding","title":"Embedding Cotal","kind":"Concept (informative)","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here (informative)","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference (informative)","category":"Reference","summary":"Definitions of Cotal's identity, messaging, delivery, and operator terms."},{"slug":"hermes-connector-reference","title":"Hermes connector reference","kind":"Reference","category":"Reference","summary":"Hermes gateway ownership, profile state, delivery rules, presence hooks, and session forks."},{"slug":"identity-authority","title":"Credential authority","kind":"Reference","category":"Reference","summary":"Credential minting, profile grants, endpoint generations, and capability limits."},{"slug":"identity-service-auth","title":"Auth service integration","kind":"Reference","category":"Reference","summary":"Auth-service listeners, pinned IdP proofs, bridge hooks, and owner derivation."},{"slug":"identity-user-auth","title":"User-auth lifecycle","kind":"Reference","category":"Reference","summary":"Actor grants, delegation, catalogs, enrollment, sessions, views, and remote managers."},{"slug":"installation","title":"Install Cotal","kind":"Start here","category":"Start here","summary":"Install the cotal command with the shell installer or npm."},{"slug":"jcode-connector-reference","title":"Jcode connector reference","kind":"Reference","category":"Reference","summary":"Private Jcode process ownership, session forks, readiness checks, model selection, and event delivery."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference (informative)","category":"Reference","summary":"Effect signatures, result shapes, concurrency rules, and common refusals for cotal-lang programs."},{"slug":"launch-agents","title":"Launch agents","kind":"Guide","category":"Guide","summary":"Launch an agent through a manager, attach to its terminal, and choose its persona and runtime."},{"slug":"manager-console-api","title":"Manager console HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference: every field of the mesh manifest.","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-commands","title":"Mesh command catalog","kind":"Reference (informative)","category":"Reference","summary":"Built-in endpoint command declarations, capabilities, targeting modes and JSON schemas."},{"slug":"mesh-view","title":"MeshView","kind":"Reference: TypeScript observer surfaces (`MeshView`)","category":"Reference","summary":"The TypeScript observer model used by the terminal console and line stream, with dashboard feature coverage."},{"slug":"opencode-connector-reference","title":"OpenCode connector reference","kind":"Reference","category":"Reference","summary":"OpenCode version support, injected configuration, session delivery, and structured event limits."},{"slug":"overview","title":"API reference","kind":"Reference","category":"Reference","summary":"Find Cotal CLI commands, agent tools, configuration fields, and data models."},{"slug":"pi-connector-reference","title":"pi connector reference","kind":"Reference","category":"Reference","summary":"pi host lifecycle, delivery confirmation, continuation attempts, managed recovery, and event persistence."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept (informative)","category":"Concept","summary":"How presence, routing, durable delivery, and attention determine what peers can observe and receive."},{"slug":"recover-a-mesh","title":"Recover a mesh","kind":"Guide","category":"Guide","summary":"Use status and logs to diagnose service failures, stuck presence, or a frozen registration gate."},{"slug":"register-a-mesh","title":"Register a mesh","kind":"Guide","category":"Guide","summary":"Choose the mesh a command targets and register remote brokers with verified trust."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal releases with pnpm, Changesets, and one GitHub Actions workflow, changesets.yml."},{"slug":"remote-supervision","title":"Supervise a remote mesh","kind":"Guide","category":"Guide","summary":"Separate broker and manager hosts, publish an exchange, and enroll remote agents."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0, and the v0.x wire contract can still change under the change process."},{"slug":"run-a-mesh","title":"Run a mesh","kind":"Guide (informative)","category":"Guide","summary":"Start, inspect, and stop the local stack in a prepared project."},{"slug":"security-boundaries","title":"Host boundaries","kind":"Reference","category":"Reference","summary":"Credential lifetimes, metadata exposure, launch authority, and local process risks."},{"slug":"security","title":"Security model","kind":"Concept (informative threat model)","category":"Concept","summary":"Threats, guarantees, and limits for peers sharing a trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"How cotal setup works, and the cross-repo couplings it depends on."},{"slug":"setup","title":"Configure a space","kind":"Guide","category":"Guide","summary":"Prepare a project, choose its agent application, and save its space settings."},{"slug":"spaces","title":"Spaces","kind":"Concept (informative)","category":"Concept","summary":"How spaces isolate collaboration, and how channels, permissions, membership, and conversation ids organize work within them."},{"slug":"stability","title":"Interface stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"supervise-processes","title":"Supervise the stack","kind":"Guide","category":"Guide","summary":"Choose process ownership under systemd and monitor actual component health."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"CLI usage telemetry fields, levels, storage, delivery, and opt-outs."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept (informative)","category":"Concept","summary":"How Cotal's wire contract uses NATS and JetStream, and what another transport binding would have to preserve."},{"slug":"upgrade-cotal","title":"Upgrade Cotal","kind":"Guide","category":"Guide","summary":"Choose an exact release, prepare the deployment, and verify the upgraded installation."},{"slug":"upgrade-matrix","title":"Run the upgrade matrix","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal's upgrade matrix uses the same native harness for release checks and operator diagnostics."},{"slug":"upgrading","title":"Upgrading a running deployment","kind":"Guide (informative)","category":"Guide","summary":"Upgrading starts publishing mapped tool inputs and results by default for Claude and Jcode seats with an event plane."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Start here (informative)","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide (informative)","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept (informative)","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=readFileSync5(join8(import.meta.dirname,"docs-bundle.bin"));if(packed.length!==1267992||createHash10("sha256").update(packed).digest("hex")!=="07cf214866642a57875339eb92659af2557176db482f2e9017d0d0a0e8b8c398")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,31698],[31698,36095],[36095,40476],[40476,44204],[44204,51007],[51007,55111],[55111,64908],[64908,69060],[69060,73578],[73578,75862],[75862,79873],[79873,112753],[112753,128938],[128938,144736],[144736,163005],[163005,180854],[180854,196067],[196067,212098],[212098,237041],[237041,242771],[242771,253755],[253755,274687],[274687,279441],[279441,318646],[318646,328601],[328601,359803],[359803,377475],[377475,401959],[401959,432957],[432957,447458],[447458,449405],[449405,458390],[458390,475217],[475217,483301],[483301,487182],[487182,490563],[490563,493866],[493866,495997],[495997,498770],[498770,504291],[504291,506188],[506188,509892],[509892,522036],[522036,531056],[531056,534581],[534581,541934],[541934,546978],[546978,549982],[549982,560601],[560601,563578],[563578,572298],[572298,575288],[575288,580242],[580242,594083],[594083,606887],[606887,614537],[614537,622321],[622321,625670],[625670,628619],[628619,636176],[636176,639892],[639892,642102],[642102,645564],[645564,648981],[648981,650095],[650095,651844],[651844,655507],[655507,660237],[660237,666873],[666873,677383],[677383,690699],[690699,692572],[692572,705907],[705907,711294],[711294,715250],[715250,717759],[717759,722801],[722801,736996],[736996,743801],[743801,751186],[751186,752003],[752003,756549],[756549,762469],[762469,765987],[765987,770195],[770195,775366],[775366,780947],[780947,784369],[784369,787960],[787960,793125],[793125,796768],[796768,810226],[810226,813044],[813044,815727],[815727,818394],[818394,820885],[820885,824905],[824905,829969],[829969,838324],[838324,846245],[846245,917340],[917340,920603],[920603,921796],[921796,928430],[928430,937175],[937175,947953],[947953,956764],[956764,961947],[961947,1223445],[1223445,1262780],[1262780,1267992]];var sourceLengths=[4844,4048,13310,89885,12190,10741,38583,17849,9941,85121,37758,11019,5079,9872,89707,43585,44478,51779,49478,43948,43919,70708,14399,29244,60576,10713,116274,27646,94172,50005,73544,95605,39939,8216,22437,45309,21923,9498,8035,7790,4874,6360,14056,4537,8812,32337,22530,8745,47738,12743,7373,27977,7140,22854,6860,12415,36774,33984,19825,19100,8355,7031,19589,8312,5100,8160,9930,2248,5412,9845,11336,16082,26828,34218,4327,36240,12378,9651,8201,13306,98109,16917,18280,1638,10433,15381,8214,10170,12927,14071,7511,9014,12695,8527,35983,6519,6405,6095,6007,9711,12679,22701,20234,209339,7380,2473,15900,22395,27911,21160,12616,758135,111238,21676];var decodedBodies=[];function loadDocsSourceLengths(){corpusData();return sourceLengths.slice()}function decodeDocsSource(source){const bounds=sourceBounds[source];if(!Number.isInteger(source)||!bounds)throw new Error("docs source index is out of bounds");const body=JSON.parse(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=readFileSync5(join8(import.meta.dirname,"docs-index.bin"));if(packed.length!==647125||createHash10("sha256").update(packed).digest("hex")!=="7ff9426c981b22f4a0490a244f43020233d464d63d16b802ac4b33b2c118a42c")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}
128
+ `)}};function presenceReadCondition(failure){return`the presence read failed (${failure.message})`}function closeChannelNames(channel,known){const out=[];for(const name of known){if(name!==channel&&editDistanceAtMostOne(channel,name))out.push(name)}out.sort((a,b)=>a.localeCompare(b));return out.slice(0,3)}function editDistanceAtMostOne(a,b){if(a===b)return true;const da=a.length-b.length;if(da>1||da<-1)return false;let i=0;let j=0;let skipped=false;while(i<a.length&&j<b.length){if(a[i]===b[j]){i++;j++;continue}if(skipped)return false;skipped=true;if(a.length>b.length)i++;else if(b.length>a.length)j++;else{i++;j++}}return true}var SUN_PATH_MAX_BYTES=process.platform==="darwin"?104:108;function eventChannelForSession(ep){if(ep.actorIsEphemeral)throw new Error("events are not available for a session with a self-minted identity: this endpoint has no declared id and no credentials, so its actor is a fresh random token per process and its event channel could never match a grant. Launch it with an identity (an authed mesh, or an explicit id) to publish events.");return eventChannel(ep.principal)}var TOOL_RESULT_EVENT="cotal.toolResult";var COTAL_CUSTOM_EVENTS=[TOOL_RESULT_EVENT];var AGUI_PROTOCOL="ag-ui/0.0.57";var AguiVocabularyError=class extends Error{constructor(message){super(message);this.name="AguiVocabularyError"}};var AguiBrackets=class _AguiBrackets{run;text=new Set;reasoning=new Set;tools=new Set;snapshot(){return{run:this.run,text:[...this.text].sort(),reasoning:[...this.reasoning].sort(),tools:[...this.tools].sort()}}static restore(s){const b=new _AguiBrackets;b.run=s.run;for(const id2 of s.text)b.text.add(id2);for(const id2 of s.reasoning)b.reasoning.add(id2);for(const id2 of s.tools)b.tools.add(id2);return b}clone(){return _AguiBrackets.restore(this.snapshot())}get open(){return this.run!==void 0}get runId(){return this.run}accept(event){const e=event;const t=e.type;if(t===AGUI_EVENT_TYPE.RUN_STARTED){if(this.run!==void 0)throw new AguiVocabularyError(`RUN_STARTED for "${String(e.runId)}" while run "${this.run}" is still open`);this.run=String(e.runId);return}if(this.run===void 0)throw new AguiVocabularyError(`${t} emitted outside an open run`);if(t===AGUI_EVENT_TYPE.RUN_FINISHED||t===AGUI_EVENT_TYPE.RUN_ERROR){if(t===AGUI_EVENT_TYPE.RUN_FINISHED&&String(e.runId)!==this.run)throw new AguiVocabularyError(`RUN_FINISHED for "${String(e.runId)}" but the open run is "${this.run}"`);const dangling=[...this.text,...this.reasoning,...this.tools];if(dangling.length>0)throw new AguiVocabularyError(`${t} while still open: ${dangling.join(", ")}`);this.run=void 0;return}switch(t){case AGUI_EVENT_TYPE.TEXT_MESSAGE_START:return this.openId(this.text,String(e.messageId),t);case AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT:return this.requireOpen(this.text,String(e.messageId),t);case AGUI_EVENT_TYPE.TEXT_MESSAGE_END:return this.closeId(this.text,String(e.messageId),t);case AGUI_EVENT_TYPE.REASONING_MESSAGE_START:return this.openId(this.reasoning,String(e.messageId),t);case AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT:return this.requireOpen(this.reasoning,String(e.messageId),t);case AGUI_EVENT_TYPE.REASONING_MESSAGE_END:return this.closeId(this.reasoning,String(e.messageId),t);case AGUI_EVENT_TYPE.TOOL_CALL_START:return this.openId(this.tools,String(e.toolCallId),t);case AGUI_EVENT_TYPE.TOOL_CALL_ARGS:return this.requireOpen(this.tools,String(e.toolCallId),t);case AGUI_EVENT_TYPE.TOOL_CALL_END:return this.closeId(this.tools,String(e.toolCallId),t);case AGUI_EVENT_TYPE.TOOL_CALL_RESULT:if(this.tools.has(String(e.toolCallId)))throw new AguiVocabularyError(`TOOL_CALL_RESULT for "${String(e.toolCallId)}" while its call is still open`);return;case AGUI_EVENT_TYPE.CUSTOM:if(!COTAL_CUSTOM_EVENTS.includes(String(e.name)))throw new AguiVocabularyError(`CUSTOM "${String(e.name)}" is not declared in COTAL_CUSTOM_EVENTS, the reviewed table of cotal.* names`);if(e.name===TOOL_RESULT_EVENT){const defect=toolResultMarkerDefect(e);if(defect!==void 0)throw new AguiVocabularyError(`${TOOL_RESULT_EVENT} ${defect}`);const id2=e.value.toolCallId;if(this.tools.has(id2))throw new AguiVocabularyError(`${TOOL_RESULT_EVENT} for "${id2}" while its call is still open`)}return;default:throw new AguiVocabularyError(`${t} is not in the mapped subset this plane emits`)}}assertClosed(){if(this.run!==void 0)throw new AguiVocabularyError(`run "${this.run}" was never closed`)}openId(set3,id2,t){if(set3.has(id2))throw new AguiVocabularyError(`${t} re-opened "${id2}" while already open`);set3.add(id2)}requireOpen(set3,id2,t){if(!set3.has(id2))throw new AguiVocabularyError(`${t} for "${id2}" which is not open`)}closeId(set3,id2,t){if(!set3.delete(id2))throw new AguiVocabularyError(`${t} for "${id2}" which is not open`)}};function aguiFrame(opts){for(const[field,value]of[["threadId",opts.threadId],["runId",opts.runId],["epoch",opts.epoch]])if(typeof value!=="string"||value.length===0)throw new AguiVocabularyError(`frame ${field} must be a non-empty string`);if(!Number.isSafeInteger(opts.seq)||opts.seq<0)throw new AguiVocabularyError(`frame seq must be a non-negative safe integer, got ${JSON.stringify(opts.seq)}`);if(!Array.isArray(opts.events)||opts.events.length===0)throw new AguiVocabularyError("a frame must carry at least one event");return{kind:AGUI_FRAME_KIND,protocol:AGUI_PROTOCOL,threadId:opts.threadId,runId:opts.runId,epoch:opts.epoch,seq:opts.seq,events:opts.events}}function parseAguiFrame(part){if(!isAguiFramePart(part))throw new AguiVocabularyError(`not an AG-UI frame: expected kind ${JSON.stringify(AGUI_FRAME_KIND)}, got ${JSON.stringify(part?.kind??null)}. Route with isAguiFramePart before calling this.`);const f=part;if(f.protocol!==AGUI_PROTOCOL)throw new AguiVocabularyError(`AG-UI protocol mismatch: this consumer understands ${JSON.stringify(AGUI_PROTOCOL)}, the frame declares ${JSON.stringify(f.protocol??null)}. Refusing rather than rendering the fields that happen to still parse.`);for(const field of["threadId","runId","epoch"])if(typeof f[field]!=="string"||f[field].length===0)throw new AguiVocabularyError(`frame ${field} must be a non-empty string`);if(!Number.isSafeInteger(f.seq)||f.seq<0)throw new AguiVocabularyError(`frame seq must be a non-negative safe integer, got ${JSON.stringify(f.seq??null)}`);if(!Array.isArray(f.events)||f.events.length===0)throw new AguiVocabularyError("a frame must carry at least one event");const known=new Set(Object.values(AGUI_EVENT_TYPE));f.events.forEach((e,i)=>{if(typeof e!=="object"||e===null)throw new AguiVocabularyError(`frame events[${i}] is not an object`);const t=e.type;if(typeof t!=="string"||!known.has(t))throw new AguiVocabularyError(`frame events[${i}] carries an unrecognised type ${JSON.stringify(t??null)}. A renderer must refuse an event it cannot display rather than skip it: a skipped event is a hole in a transcript that still looks complete.`)});return part}function runStarted(o){return{type:AGUI_EVENT_TYPE.RUN_STARTED,threadId:o.threadId,runId:o.runId,timestamp:o.timestamp,...o.cotal?{cotal:o.cotal}:{}}}function assertInterrupts(list){if(!Array.isArray(list)||list.length===0)throw new AguiVocabularyError("outcome.interrupts must be a non-empty array when the outcome is an interrupt");for(const[i,entry]of list.entries()){const e=entry;if(typeof e!=="object"||e===null)throw new AguiVocabularyError(`outcome.interrupts[${i}] is not an object`);if(typeof e.id!=="string")throw new AguiVocabularyError(`outcome.interrupts[${i}].id must be a string`);if(typeof e.reason!=="string")throw new AguiVocabularyError(`outcome.interrupts[${i}].reason must be a string`)}}function runFinished(o){if(o.outcome?.type==="interrupt")assertInterrupts(o.outcome.interrupts);return{type:AGUI_EVENT_TYPE.RUN_FINISHED,threadId:o.threadId,runId:o.runId,timestamp:o.timestamp,...o.outcome?{outcome:o.outcome}:{},...o.cotal?{cotal:o.cotal}:{}}}function runError(o){return{type:AGUI_EVENT_TYPE.RUN_ERROR,message:o.message,timestamp:o.timestamp,...o.code?{code:o.code}:{},...o.cotal?{cotal:o.cotal}:{}}}function textMessageStart(o){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_START,messageId:o.messageId,timestamp:o.timestamp,...o.role?{role:o.role}:{},...o.cotal?{cotal:o.cotal}:{}}}function textMessageContent(o){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,messageId:o.messageId,delta:o.delta,timestamp:o.timestamp,...o.cotal?{cotal:o.cotal}:{}}}function textMessageEnd(o){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_END,messageId:o.messageId,timestamp:o.timestamp,...o.cotal?{cotal:o.cotal}:{}}}function toolCallStart(o){return{type:AGUI_EVENT_TYPE.TOOL_CALL_START,toolCallId:o.toolCallId,toolCallName:o.toolCallName,timestamp:o.timestamp,...o.parentMessageId?{parentMessageId:o.parentMessageId}:{},...o.cotal?{cotal:o.cotal}:{}}}function toolCallEnd(o){return{type:AGUI_EVENT_TYPE.TOOL_CALL_END,toolCallId:o.toolCallId,timestamp:o.timestamp,...o.cotal?{cotal:o.cotal}:{}}}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_FRAME_KEYS=new Set(["kind","protocol","threadId","runId","epoch","seq","events"]);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 toolResultMarkerDefect(e){if("rawEvent"in e)return"carries rawEvent, which the content-free marker never does";const defect=toolResultValueDefect(e.value);if(defect===void 0)return void 0;return defect==="value"?"value is not { toolCallId: string, isError: boolean }":`${defect} is not a key the marker's value carries`}function toolResultValue(value){if(toolResultValueDefect(value)!==void 0)return void 0;const v=value;return{toolCallId:v.toolCallId,isError:v.isError}}function extraPropertyPath(part){for(const key of Object.keys(part)){if(!KNOWN_FRAME_KEYS.has(key))return key}const events=part.events;if(!Array.isArray(events))return void 0;for(let i=0;i<events.length;i++){const e=events[i];if(typeof e!=="object"||e===null)continue;const t=e.type;const allowed=KNOWN_EVENT_KEYS_BY_TYPE.get(t);if(!allowed)return`events[${i}]`;for(const key of Object.keys(e)){if(!allowed.has(key))return`events[${i}].${key}`}if(t===AGUI_EVENT_TYPE.CUSTOM&&e.name===TOOL_RESULT_EVENT){if("rawEvent"in e)return`events[${i}].rawEvent`;const defect=toolResultValueDefect(e.value);if(defect!==void 0)return`events[${i}].${defect}`}}return void 0}function isForbiddenEgressEventType(type){return typeof type==="string"&&EGRESS_FORBIDDEN_TYPES.has(type)}var RUN_ERROR_EGRESS_MESSAGE="run failed";function egressRunError(o){return{type:AGUI_EVENT_TYPE.RUN_ERROR,message:RUN_ERROR_EGRESS_MESSAGE,...o.timestamp!==void 0?{timestamp:o.timestamp}:{},...o.cotal?{cotal:o.cotal}:{}}}function isEgressRunError(e){return e.message===RUN_ERROR_EGRESS_MESSAGE&&!("code"in e)&&!("rawEvent"in e)}function isToolResultMarker(e){return e.type===AGUI_EVENT_TYPE.CUSTOM&&e.name===TOOL_RESULT_EVENT}function egressToolResultMarker(e){if(!("rawEvent"in e))return e;const{rawEvent:_dropped,...rest}=e;return rest}function applyAguiEgressPolicy(events){return events.filter(e=>!isForbiddenEgressEventType(e.type)).map(e=>e.type===AGUI_EVENT_TYPE.RUN_ERROR?egressRunError(e):isToolResultMarker(e)?egressToolResultMarker(e):e)}function frozenBodyEgressVerdict(body){let unreadable=false;try{for(const part of body){try{if(!isAguiFramePart(part))continue;const frame=parseAguiFrame(part);for(const e of frame.events){if(isForbiddenEgressEventType(e.type))return"forbidden-kind"}for(const e of frame.events){if(e.type===AGUI_EVENT_TYPE.RUN_ERROR&&!isEgressRunError(e))return"run-error-content"}const extra=extraPropertyPath(part);if(extra!==void 0)return"extra-property"}catch{unreadable=true}}}catch{unreadable=true}return unreadable?"unreadable":"clean"}import{createHash as createHash11,randomUUID as randomUUID8}from"node:crypto";import{dirname as dirname8,join as join9}from"node:path";import{execFileSync as execFileSync3}from"node:child_process";init_external();init_external();var ok=text2=>({text:text2});var err=text2=>({text:text2,isError:true});function receipt(status2,value){if(status2!==202||typeof value!=="object"||value===null||Array.isArray(value))return void 0;const body=value;if(body.ok!==true||typeof body.id!=="string"||body.id.length===0||body.id.length>200)return void 0;if(/[\u0000-\u001f\u007f]/.test(body.id)||body.id.trim()!==body.id)return void 0;if(typeof body.published!=="boolean")return void 0;return{id:body.id,published:body.published}}async function submitFeedback(input,options={}){const url2=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const headers3={"content-type":"application/json"};const body={...input};if(options.key){headers3.authorization=`Bearer ${options.key}`}else{if(!options.email)return err("Keyless feedback goes to the public cotal.ai intake, which requires a traceable contact email \u2014 ask the user for one and retry with the email argument (or set COTAL_FEEDBACK_EMAIL).");body.email=options.email}let res;let raw;try{res=await fetch(url2,{method:"POST",headers:headers3,body:JSON.stringify(body),redirect:"error"});raw=await res.text()}catch(e){return err(`Couldn't reach the feedback intake at ${url2}: ${e.message} The submission was not retried.`)}let reply=void 0;if(raw)try{reply=JSON.parse(raw)}catch{reply=void 0}const stored=receipt(res.status,reply);if(stored){const note=stored.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent (id ${stored.id})${note}. Thanks!`)}const errorText=typeof reply==="object"&&reply!==null&&typeof reply.error==="string"?reply.error:void 0;if(!res.ok)return err(`Feedback rejected (${res.status}${errorText?`: ${errorText}`:""}).`);return err(`Feedback acceptance is unconfirmed (${res.status}). The request may have reached the intake and was not retried.`)}import{createHash as createHash10}from"node:crypto";import{readFileSync as readFileSync5}from"node:fs";import{join as join8}from"node:path";import{gunzipSync}from"node:zlib";var DOCS_VERSION="0.164.17";function loadDocsMetadata(){return{"version":"0.164.17","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here (informative)","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here (informative)","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept (informative)","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference: the `cotal_*` tool surface every connected agent gets.","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference (informative task card)","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept (informative)","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference (the persisted form of an agent's identity + persona, read by every launcher)","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference (informative)","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide: describes the TypeScript reference implementation, not the wire contract.","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide (informative)","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI), not the wire contract.","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI and connectors), not the wire contract.","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide (informative)","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide (informative)","category":"Guide","summary":"Launch Codex on a Cotal mesh, connect your own Codex conversations, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide (informative)","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-opencode","title":"Connect OpenCode","kind":"Guide (informative)","category":"Guide","summary":"Launch OpenCode on a Cotal mesh and choose the model and options for your installed version."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Launch pi on a Cotal mesh or load the Cotal extension into your own pi host."},{"slug":"connector-runtime-reference","title":"Connector runtime reference","kind":"Reference","category":"Reference","summary":"Shared connection recovery, presence display, send receipts, delivery acknowledgement, reply correlation, and resume records."},{"slug":"connectors","title":"Connectors","kind":"Guide (informative)","category":"Guide","summary":"Choose an agent application and connect its sessions to a Cotal mesh."},{"slug":"console","title":"Use the console","kind":"Guide","category":"Guide","summary":"Inspect a mesh from the terminal and use authorized operator controls."},{"slug":"control-discovery","title":"Endpoint discovery","kind":"Reference","category":"Reference","summary":"Command contracts, manager instance selection, request outcomes, and service registration."},{"slug":"control-lifecycle","title":"Manager lifecycle contracts","kind":"Reference","category":"Reference","summary":"Managed identities, static slots, spawn goals, chat sessions, terminal access, and grants."},{"slug":"control-surface","title":"The control surface","kind":"Concept (informative)","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide (informative)","category":"Guide","summary":"Describe agents and channels in a manifest, then boot or deploy that team."},{"slug":"delivery-daemon","title":"The delivery daemon","kind":"Concept (informative)","category":"Concept","summary":"Why durable channel delivery needs a trusted service, and what happens without it."},{"slug":"delivery-service-reference","title":"Delivery service contracts","kind":"Reference","category":"Reference","summary":"Fan-out, trusted reads, leases, membership retirement, credential adoption, and daemon lifetime."},{"slug":"deploy","title":"Deploy agent teams","kind":"Guide (informative)","category":"Guide","summary":"Review the container example, its current build limitation, and the credentials it needs."},{"slug":"embedding-daemons","title":"Embedded daemon lifecycle","kind":"Reference","category":"Reference","summary":"Process runners, account-scoped hosted services, and delivery credential renewal."},{"slug":"embedding-delegated-seats","title":"Delegated seat contracts","kind":"Reference","category":"Reference","summary":"Managed lifecycle handoff, provider closure guarantees, and the limits of delegated recovery contracts."},{"slug":"embedding-endpoints","title":"CotalEndpoint reference","kind":"Reference","category":"Reference","summary":"Presence metadata, observer freshness, write diagnosis, liveness probes, and DM-only endpoint readers."},{"slug":"embedding-exports","title":"Embedding package exports","kind":"Reference","category":"Reference","summary":"Public package entry points, endpoint credentials, and Manager execution contracts."},{"slug":"embedding-manager","title":"Manager embedding authority","kind":"Reference","category":"Reference","summary":"Manager startup, signer custody, remote authority callbacks, and delegated user intent contracts."},{"slug":"embedding-provisioning","title":"Embedded space provisioning","kind":"Reference","category":"Reference","summary":"Broker trust, space credentials, durable host state, and current hosting limitations."},{"slug":"embedding-remote-clients","title":"Embedded remote clients","kind":"Reference","category":"Reference","summary":"MCP conversation routing, browser callers, remote Manager clients, and private-result prerequisites."},{"slug":"embedding-schema-inspection","title":"Space schema inspection","kind":"Reference","category":"Reference","summary":"Resource definitions, bounded read-only observations, and the limits of schema and initialization comparisons."},{"slug":"embedding-service-access","title":"Service endpoint access","kind":"Reference","category":"Reference","summary":"Authority proofs, serving credentials, verified grants, and renewal."},{"slug":"embedding-service-authority","title":"Service authority contracts","kind":"Reference","category":"Reference","summary":"Service authority contracts, platform supervisors, revocation prerequisites, and native custody limits."},{"slug":"embedding-service-callers","title":"Service endpoint callers","kind":"Reference","category":"Reference","summary":"Caller policy grants, broker payload prerequisites, revocation, and recovery limits."},{"slug":"embedding-service-custody","title":"Native service custody","kind":"Reference","category":"Reference","summary":"Immutable service reservations, bootstrap, cancellation, and bounded writer guarantees."},{"slug":"embedding-service-host","title":"Service endpoint hosting","kind":"Reference","category":"Reference","summary":"Owner approvals, native host operations, registration, and lifecycle custody."},{"slug":"embedding","title":"Embedding Cotal","kind":"Concept (informative)","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here (informative)","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference (informative)","category":"Reference","summary":"Definitions of Cotal's identity, messaging, delivery, and operator terms."},{"slug":"hermes-connector-reference","title":"Hermes connector reference","kind":"Reference","category":"Reference","summary":"Hermes gateway ownership, profile state, delivery rules, presence hooks, and session forks."},{"slug":"identity-authority","title":"Credential authority","kind":"Reference","category":"Reference","summary":"Credential minting, profile grants, endpoint generations, and capability limits."},{"slug":"identity-service-auth","title":"Auth service integration","kind":"Reference","category":"Reference","summary":"Auth-service listeners, pinned IdP proofs, bridge hooks, and owner derivation."},{"slug":"identity-user-auth","title":"User-auth lifecycle","kind":"Reference","category":"Reference","summary":"Actor grants, delegation, catalogs, enrollment, sessions, views, and remote managers."},{"slug":"installation","title":"Install Cotal","kind":"Start here","category":"Start here","summary":"Install the cotal command with the shell installer or npm."},{"slug":"jcode-connector-reference","title":"Jcode connector reference","kind":"Reference","category":"Reference","summary":"Private Jcode process ownership, session forks, readiness checks, model selection, and event delivery."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference (informative)","category":"Reference","summary":"Effect signatures, result shapes, concurrency rules, and common refusals for cotal-lang programs."},{"slug":"launch-agents","title":"Launch agents","kind":"Guide","category":"Guide","summary":"Launch an agent through a manager, attach to its terminal, and choose its persona and runtime."},{"slug":"manager-console-api","title":"Manager console HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference: every field of the mesh manifest.","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-commands","title":"Mesh command catalog","kind":"Reference (informative)","category":"Reference","summary":"Built-in endpoint command declarations, capabilities, targeting modes and JSON schemas."},{"slug":"mesh-view","title":"MeshView","kind":"Reference: TypeScript observer surfaces (`MeshView`)","category":"Reference","summary":"The TypeScript observer model used by the terminal console and line stream, with dashboard feature coverage."},{"slug":"opencode-connector-reference","title":"OpenCode connector reference","kind":"Reference","category":"Reference","summary":"OpenCode version support, injected configuration, session delivery, and structured event limits."},{"slug":"overview","title":"API reference","kind":"Reference","category":"Reference","summary":"Find Cotal CLI commands, agent tools, configuration fields, and data models."},{"slug":"pi-connector-reference","title":"pi connector reference","kind":"Reference","category":"Reference","summary":"pi host lifecycle, delivery confirmation, continuation attempts, managed recovery, and event persistence."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept (informative)","category":"Concept","summary":"How presence, routing, durable delivery, and attention determine what peers can observe and receive."},{"slug":"recover-a-mesh","title":"Recover a mesh","kind":"Guide","category":"Guide","summary":"Use status and logs to diagnose service failures, stuck presence, or a frozen registration gate."},{"slug":"register-a-mesh","title":"Register a mesh","kind":"Guide","category":"Guide","summary":"Choose the mesh a command targets and register remote brokers with verified trust."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal releases with pnpm, Changesets, and one GitHub Actions workflow, changesets.yml."},{"slug":"remote-supervision","title":"Supervise a remote mesh","kind":"Guide","category":"Guide","summary":"Separate broker and manager hosts, publish an exchange, and enroll remote agents."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0, and the v0.x wire contract can still change under the change process."},{"slug":"run-a-mesh","title":"Run a mesh","kind":"Guide (informative)","category":"Guide","summary":"Start, inspect, and stop the local stack in a prepared project."},{"slug":"security-boundaries","title":"Host boundaries","kind":"Reference","category":"Reference","summary":"Credential lifetimes, metadata exposure, launch authority, and local process risks."},{"slug":"security","title":"Security model","kind":"Concept (informative threat model)","category":"Concept","summary":"Threats, guarantees, and limits for peers sharing a trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"How cotal setup works, and the cross-repo couplings it depends on."},{"slug":"setup","title":"Configure a space","kind":"Guide","category":"Guide","summary":"Prepare a project, choose its agent application, and save its space settings."},{"slug":"spaces","title":"Spaces","kind":"Concept (informative)","category":"Concept","summary":"How spaces isolate collaboration, and how channels, permissions, membership, and conversation ids organize work within them."},{"slug":"stability","title":"Interface stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"supervise-processes","title":"Supervise the stack","kind":"Guide","category":"Guide","summary":"Choose process ownership under systemd and monitor actual component health."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"CLI usage telemetry fields, levels, storage, delivery, and opt-outs."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept (informative)","category":"Concept","summary":"How Cotal's wire contract uses NATS and JetStream, and what another transport binding would have to preserve."},{"slug":"upgrade-cotal","title":"Upgrade Cotal","kind":"Guide","category":"Guide","summary":"Choose an exact release, prepare the deployment, and verify the upgraded installation."},{"slug":"upgrade-matrix","title":"Run the upgrade matrix","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal's upgrade matrix uses the same native harness for release checks and operator diagnostics."},{"slug":"upgrading","title":"Upgrading a running deployment","kind":"Guide (informative)","category":"Guide","summary":"Upgrading starts publishing mapped tool inputs and results by default for Claude and Jcode seats with an event plane."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Start here (informative)","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide (informative)","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept (informative)","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=readFileSync5(join8(import.meta.dirname,"docs-bundle.bin"));if(packed.length!==1269854||createHash10("sha256").update(packed).digest("hex")!=="72ea33472fdce512e2491d49cb46a3aa87e3024f6180e9ea2ab082362e989579")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,31698],[31698,36095],[36095,40476],[40476,44204],[44204,51007],[51007,55111],[55111,64908],[64908,69060],[69060,73578],[73578,75862],[75862,79873],[79873,112753],[112753,128938],[128938,144736],[144736,163005],[163005,180854],[180854,196067],[196067,212098],[212098,237030],[237030,242760],[242760,253744],[253744,274676],[274676,279430],[279430,318635],[318635,328590],[328590,359792],[359792,377464],[377464,401948],[401948,432946],[432946,447447],[447447,449394],[449394,458379],[458379,475206],[475206,483290],[483290,487171],[487171,490552],[490552,493855],[493855,495986],[495986,498759],[498759,504280],[504280,506177],[506177,509881],[509881,522025],[522025,531045],[531045,534570],[534570,541923],[541923,546967],[546967,549971],[549971,560590],[560590,563567],[563567,572287],[572287,575277],[575277,580231],[580231,594072],[594072,606876],[606876,614526],[614526,622310],[622310,625659],[625659,628608],[628608,636165],[636165,639881],[639881,642091],[642091,645553],[645553,648970],[648970,650084],[650084,651833],[651833,655496],[655496,660226],[660226,666862],[666862,677372],[677372,690688],[690688,692561],[692561,705896],[705896,711283],[711283,715239],[715239,717748],[717748,722790],[722790,736985],[736985,743790],[743790,751175],[751175,751992],[751992,756538],[756538,762458],[762458,765976],[765976,770184],[770184,775355],[775355,780936],[780936,784358],[784358,787949],[787949,793114],[793114,796757],[796757,810238],[810238,813056],[813056,815739],[815739,818406],[818406,820897],[820897,824917],[824917,829981],[829981,839956],[839956,848107],[848107,919202],[919202,922465],[922465,923658],[923658,930292],[930292,939037],[939037,949815],[949815,958626],[958626,963809],[963809,1225307],[1225307,1264642],[1264642,1269854]];var sourceLengths=[4844,4048,13310,89885,12190,10741,38583,17849,9941,85121,37758,11019,5079,9872,89707,43585,44478,51779,49478,43948,43919,70695,14399,29244,60576,10713,116274,27646,94172,50005,73544,95605,39939,8216,22437,45309,21923,9498,8035,7790,4874,6360,14056,4537,8812,32337,22530,8745,47738,12743,7373,27977,7140,22854,6860,12415,36774,33984,19825,19100,8355,7031,19589,8312,5100,8160,9930,2248,5412,9845,11336,16082,26828,34218,4327,36240,12378,9651,8201,13306,98109,16917,18280,1638,10433,15381,8214,10170,12927,14071,7511,9014,12695,8527,36070,6519,6405,6095,6007,9711,12679,27616,21116,209339,7380,2473,15900,22395,27911,21160,12616,758135,111238,21676];var decodedBodies=[];function loadDocsSourceLengths(){corpusData();return sourceLengths.slice()}function decodeDocsSource(source){const bounds=sourceBounds[source];if(!Number.isInteger(source)||!bounds)throw new Error("docs source index is out of bounds");const body=JSON.parse(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=readFileSync5(join8(import.meta.dirname,"docs-index.bin"));if(packed.length!==647720||createHash10("sha256").update(packed).digest("hex")!=="7580cd1aa7a20923bb78928136547c533d5783418675d060fccaa6cb1dda124b")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}
129
129
  ${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}
130
130
 
131
131
  ${p.body}`.trimStart()}var K1=1.2;var B=.75;function sources(){const b=metadata();return[...b.pages.map((page,source)=>pages.get(source)??page),{slug:"spec",...b.spec},{slug:"lang",...b.lang},{slug:"schema",...b.schema}]}var index;function searchIndex(){if(index)return index;const lengths=loadDocsSourceLengths();for(const[source,page]of pages)lengths[source]=page.body.length;return index=decodeIndex(loadDocsIndex(),lengths,DOCS_VERSION)}function termId(terms,term){let low=0;let high=terms.length-1;while(low<=high){const mid=low+high>>>1;const candidate2=terms[mid];if(candidate2===term)return mid;if(candidate2<term)low=mid+1;else high=mid-1}return-1}function searchDocs(query,limit=5){if(limit<=0)return[];let terms=tokenize(query).filter(t=>!STOP.has(t));if(!terms.length)terms=tokenize(query);const termSet=new Set(terms);if(!termSet.size)return[];const idx=searchIndex();const N=idx.sections;const scores=new Float64Array(N);for(const t of termSet){const id2=termId(idx.terms,t);if(id2<0)continue;const from=idx.offsets[id2];const to=idx.offsets[id2+1];const n=to-from;const idf=Math.log(1+(N-n+.5)/(n+.5));for(let p=from;p<to;p++){const s=idx.postSection[p];const f=idx.postWeight[p];scores[s]+=idf*(f*(K1+1)/(f+K1*(1-B+B*idx.length[s]/idx.avgdl)))}}const scored=[];for(let s=0;s<N;s++)if(scores[s]>0)scored.push({s,score:scores[s]});scored.sort((a,b)=>b.score-a.score);const all=sources();const perPage=new Map;const hits=[];for(const{s,score}of scored){const source=all[idx.source[s]];const seen=perPage.get(source.slug)??0;if(seen>=2)continue;perPage.set(source.slug,seen+1);hits.push({slug:source.slug,pageTitle:source.title,heading:idx.headings[s],text:sourceBody(idx.source[s]).slice(idx.start[s],idx.end[s]),score});if(hits.length>=limit)break}return hits}function capSection(text2,maxLines=48){const lines=text2.split("\n");if(lines.length<=maxLines)return text2.trim();return lines.slice(0,maxLines).join("\n").trimEnd()+"\n\n\u2026 (section continues; read the full page)"}function renderSearch(query,hits){loadDocsSourceLengths();if(!hits.length){return`No matches for "${query}" in the Cotal v${DOCS_VERSION} docs. Call cotal_docs() for the page index, or search an exact identifier (a subject, a cotal_* tool, a field name).`}const blocks=hits.map(h2=>`## ${h2.heading}