@cotal-ai/pi 0.164.6 → 0.164.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/docs-bundle.bin +0 -0
- package/dist/docs-index.bin +0 -0
- package/dist/index.js +2 -2
- package/dist/standalone.js +2 -2
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -65,7 +65,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
65
65
|
|| ${dataType} === "boolean" || ${data} === null`).assign(coerced,(0,codegen_1._)`[${data}]`)}}}function assignParentData({gen,parentData,parentDataProperty},expr){gen.if((0,codegen_1._)`${parentData} !== undefined`,()=>gen.assign((0,codegen_1._)`${parentData}[${parentDataProperty}]`,expr))}function checkDataType(dataType,data,strictNums,correct=DataType.Correct){const EQ=correct===DataType.Correct?codegen_1.operators.EQ:codegen_1.operators.NEQ;let cond;switch(dataType){case"null":return(0,codegen_1._)`${data} ${EQ} null`;case"array":cond=(0,codegen_1._)`Array.isArray(${data})`;break;case"object":cond=(0,codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`;break;case"integer":cond=numCond((0,codegen_1._)`!(${data} % 1) && !isNaN(${data})`);break;case"number":cond=numCond();break;default:return(0,codegen_1._)`typeof ${data} ${EQ} ${dataType}`}return correct===DataType.Correct?cond:(0,codegen_1.not)(cond);function numCond(_cond=codegen_1.nil){return(0,codegen_1.and)((0,codegen_1._)`typeof ${data} == "number"`,_cond,strictNums?(0,codegen_1._)`isFinite(${data})`:codegen_1.nil)}}exports.checkDataType=checkDataType;function checkDataTypes(dataTypes,data,strictNums,correct){if(dataTypes.length===1){return checkDataType(dataTypes[0],data,strictNums,correct)}let cond;const types=(0,util_1.toHash)(dataTypes);if(types.array&&types.object){const notObj=(0,codegen_1._)`typeof ${data} != "object"`;cond=types.null?notObj:(0,codegen_1._)`!${data} || ${notObj}`;delete types.null;delete types.array;delete types.object}else{cond=codegen_1.nil}if(types.number)delete types.integer;for(const t in types)cond=(0,codegen_1.and)(cond,checkDataType(t,data,strictNums,correct));return cond}exports.checkDataTypes=checkDataTypes;var typeError={message:({schema})=>`must be ${schema}`,params:({schema,schemaValue})=>typeof schema=="string"?(0,codegen_1._)`{type: ${schema}}`:(0,codegen_1._)`{type: ${schemaValue}}`};function reportTypeError(it){const cxt=getTypeErrorContext(it);(0,errors_1.reportError)(cxt,typeError)}exports.reportTypeError=reportTypeError;function getTypeErrorContext(it){const{gen,data,schema}=it;const schemaCode=(0,util_1.schemaRefOrVal)(it,schema,"type");return{gen,keyword:"type",data,schema:schema.type,schemaCode,schemaValue:schemaCode,parentSchema:schema,params:{},it}}}});var require_defaults=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/defaults.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.assignDefaults=void 0;var codegen_1=require_codegen();var util_1=require_util();function assignDefaults(it,ty){const{properties,items}=it.schema;if(ty==="object"&&properties){for(const key in properties){assignDefault(it,key,properties[key].default)}}else if(ty==="array"&&Array.isArray(items)){items.forEach((sch,i)=>assignDefault(it,i,sch.default))}}exports.assignDefaults=assignDefaults;function assignDefault(it,prop,defaultValue){const{gen,compositeRule,data,opts}=it;if(defaultValue===void 0)return;const childData=(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(prop)}`;if(compositeRule){(0,util_1.checkStrictMode)(it,`default is ignored for: ${childData}`);return}let condition=(0,codegen_1._)`${childData} === undefined`;if(opts.useDefaults==="empty"){condition=(0,codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`}gen.if(condition,(0,codegen_1._)`${childData} = ${(0,codegen_1.stringify)(defaultValue)}`)}}});var require_code2=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/code.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.validateUnion=exports.validateArray=exports.usePattern=exports.callValidateCode=exports.schemaProperties=exports.allSchemaProperties=exports.noPropertyInData=exports.propertyInData=exports.isOwnProperty=exports.hasPropFunc=exports.reportMissingProp=exports.checkMissingProp=exports.checkReportMissingProp=void 0;var codegen_1=require_codegen();var util_1=require_util();var names_1=require_names();var util_2=require_util();function checkReportMissingProp(cxt,prop){const{gen,data,it}=cxt;gen.if(noPropertyInData(gen,data,prop,it.opts.ownProperties),()=>{cxt.setParams({missingProperty:(0,codegen_1._)`${prop}`},true);cxt.error()})}exports.checkReportMissingProp=checkReportMissingProp;function checkMissingProp({gen,data,it:{opts}},properties,missing){return(0,codegen_1.or)(...properties.map(prop=>(0,codegen_1.and)(noPropertyInData(gen,data,prop,opts.ownProperties),(0,codegen_1._)`${missing} = ${prop}`)))}exports.checkMissingProp=checkMissingProp;function reportMissingProp(cxt,missing){cxt.setParams({missingProperty:missing},true);cxt.error()}exports.reportMissingProp=reportMissingProp;function hasPropFunc(gen){return gen.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,codegen_1._)`Object.prototype.hasOwnProperty`})}exports.hasPropFunc=hasPropFunc;function isOwnProperty(gen,data,property){return(0,codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`}exports.isOwnProperty=isOwnProperty;function propertyInData(gen,data,property,ownProperties){const cond=(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(property)} !== undefined`;return ownProperties?(0,codegen_1._)`${cond} && ${isOwnProperty(gen,data,property)}`:cond}exports.propertyInData=propertyInData;function noPropertyInData(gen,data,property,ownProperties){const cond=(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(property)} === undefined`;return ownProperties?(0,codegen_1.or)(cond,(0,codegen_1.not)(isOwnProperty(gen,data,property))):cond}exports.noPropertyInData=noPropertyInData;function allSchemaProperties(schemaMap){return schemaMap?Object.keys(schemaMap).filter(p=>p!=="__proto__"):[]}exports.allSchemaProperties=allSchemaProperties;function schemaProperties(it,schemaMap){return allSchemaProperties(schemaMap).filter(p=>!(0,util_1.alwaysValidSchema)(it,schemaMap[p]))}exports.schemaProperties=schemaProperties;function callValidateCode({schemaCode,data,it:{gen,topSchemaRef,schemaPath,errorPath},it},func,context,passSchema){const dataAndSchema=passSchema?(0,codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}`:data;const valCxt=[[names_1.default.instancePath,(0,codegen_1.strConcat)(names_1.default.instancePath,errorPath)],[names_1.default.parentData,it.parentData],[names_1.default.parentDataProperty,it.parentDataProperty],[names_1.default.rootData,names_1.default.rootData]];if(it.opts.dynamicRef)valCxt.push([names_1.default.dynamicAnchors,names_1.default.dynamicAnchors]);const args=(0,codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;return context!==codegen_1.nil?(0,codegen_1._)`${func}.call(${context}, ${args})`:(0,codegen_1._)`${func}(${args})`}exports.callValidateCode=callValidateCode;var newRegExp=(0,codegen_1._)`new RegExp`;function usePattern({gen,it:{opts}},pattern){const u=opts.unicodeRegExp?"u":"";const{regExp}=opts.code;const rx=regExp(pattern,u);return gen.scopeValue("pattern",{key:rx.toString(),ref:rx,code:(0,codegen_1._)`${regExp.code==="new RegExp"?newRegExp:(0,util_2.useFunc)(gen,regExp)}(${pattern}, ${u})`})}exports.usePattern=usePattern;function validateArray(cxt){const{gen,data,keyword,it}=cxt;const valid=gen.name("valid");if(it.allErrors){const validArr=gen.let("valid",true);validateItems(()=>gen.assign(validArr,false));return validArr}gen.var(valid,true);validateItems(()=>gen.break());return valid;function validateItems(notValid){const len=gen.const("len",(0,codegen_1._)`${data}.length`);gen.forRange("i",0,len,i=>{cxt.subschema({keyword,dataProp:i,dataPropType:util_1.Type.Num},valid);gen.if((0,codegen_1.not)(valid),notValid)})}}exports.validateArray=validateArray;function validateUnion(cxt){const{gen,schema,keyword,it}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");const alwaysValid=schema.some(sch=>(0,util_1.alwaysValidSchema)(it,sch));if(alwaysValid&&!it.opts.unevaluated)return;const valid=gen.let("valid",false);const schValid=gen.name("_valid");gen.block(()=>schema.forEach((_sch,i)=>{const schCxt=cxt.subschema({keyword,schemaProp:i,compositeRule:true},schValid);gen.assign(valid,(0,codegen_1._)`${valid} || ${schValid}`);const merged=cxt.mergeValidEvaluated(schCxt,schValid);if(!merged)gen.if((0,codegen_1.not)(valid))}));cxt.result(valid,()=>cxt.reset(),()=>cxt.error(true))}exports.validateUnion=validateUnion}});var require_keyword=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/keyword.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.validateKeywordUsage=exports.validSchemaType=exports.funcKeywordCode=exports.macroKeywordCode=void 0;var codegen_1=require_codegen();var names_1=require_names();var code_1=require_code2();var errors_1=require_errors();function macroKeywordCode(cxt,def){const{gen,keyword,schema,parentSchema,it}=cxt;const macroSchema=def.macro.call(it.self,schema,parentSchema,it);const schemaRef=useKeyword(gen,keyword,macroSchema);if(it.opts.validateSchema!==false)it.self.validateSchema(macroSchema,true);const valid=gen.name("valid");cxt.subschema({schema:macroSchema,schemaPath:codegen_1.nil,errSchemaPath:`${it.errSchemaPath}/${keyword}`,topSchemaRef:schemaRef,compositeRule:true},valid);cxt.pass(valid,()=>cxt.error(true))}exports.macroKeywordCode=macroKeywordCode;function funcKeywordCode(cxt,def){var _a3;const{gen,keyword,schema,parentSchema,$data,it}=cxt;checkAsyncKeyword(it,def);const validate2=!$data&&def.compile?def.compile.call(it.self,schema,parentSchema,it):def.validate;const validateRef=useKeyword(gen,keyword,validate2);const valid=gen.let("valid");cxt.block$data(valid,validateKeyword);cxt.ok((_a3=def.valid)!==null&&_a3!==void 0?_a3:valid);function validateKeyword(){if(def.errors===false){assignValid();if(def.modifying)modifyData(cxt);reportErrs(()=>cxt.error())}else{const ruleErrs=def.async?validateAsync():validateSync();if(def.modifying)modifyData(cxt);reportErrs(()=>addErrs(cxt,ruleErrs))}}function validateAsync(){const ruleErrs=gen.let("ruleErrs",null);gen.try(()=>assignValid((0,codegen_1._)`await `),e=>gen.assign(valid,false).if((0,codegen_1._)`${e} instanceof ${it.ValidationError}`,()=>gen.assign(ruleErrs,(0,codegen_1._)`${e}.errors`),()=>gen.throw(e)));return ruleErrs}function validateSync(){const validateErrs=(0,codegen_1._)`${validateRef}.errors`;gen.assign(validateErrs,null);assignValid(codegen_1.nil);return validateErrs}function assignValid(_await=def.async?(0,codegen_1._)`await `:codegen_1.nil){const passCxt=it.opts.passContext?names_1.default.this:names_1.default.self;const passSchema=!("compile"in def&&!$data||def.schema===false);gen.assign(valid,(0,codegen_1._)`${_await}${(0,code_1.callValidateCode)(cxt,validateRef,passCxt,passSchema)}`,def.modifying)}function reportErrs(errors){var _a4;gen.if((0,codegen_1.not)((_a4=def.valid)!==null&&_a4!==void 0?_a4:valid),errors)}}exports.funcKeywordCode=funcKeywordCode;function modifyData(cxt){const{gen,data,it}=cxt;gen.if(it.parentData,()=>gen.assign(data,(0,codegen_1._)`${it.parentData}[${it.parentDataProperty}]`))}function addErrs(cxt,errs){const{gen}=cxt;gen.if((0,codegen_1._)`Array.isArray(${errs})`,()=>{gen.assign(names_1.default.vErrors,(0,codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors,(0,codegen_1._)`${names_1.default.vErrors}.length`);(0,errors_1.extendErrors)(cxt)},()=>cxt.error())}function checkAsyncKeyword({schemaEnv},def){if(def.async&&!schemaEnv.$async)throw new Error("async keyword in sync schema")}function useKeyword(gen,keyword,result){if(result===void 0)throw new Error(`keyword "${keyword}" failed to compile`);return gen.scopeValue("keyword",typeof result=="function"?{ref:result}:{ref:result,code:(0,codegen_1.stringify)(result)})}function validSchemaType(schema,schemaType,allowUndefined=false){return!schemaType.length||schemaType.some(st2=>st2==="array"?Array.isArray(schema):st2==="object"?schema&&typeof schema=="object"&&!Array.isArray(schema):typeof schema==st2||allowUndefined&&typeof schema=="undefined")}exports.validSchemaType=validSchemaType;function validateKeywordUsage({schema,opts,self,errSchemaPath},def,keyword){if(Array.isArray(def.keyword)?!def.keyword.includes(keyword):def.keyword!==keyword){throw new Error("ajv implementation error")}const deps=def.dependencies;if(deps===null||deps===void 0?void 0:deps.some(kwd=>!Object.prototype.hasOwnProperty.call(schema,kwd))){throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`)}if(def.validateSchema){const valid=def.validateSchema(schema[keyword]);if(!valid){const msg=`keyword "${keyword}" value is invalid at path "${errSchemaPath}": `+self.errorsText(def.validateSchema.errors);if(opts.validateSchema==="log")self.logger.error(msg);else throw new Error(msg)}}}exports.validateKeywordUsage=validateKeywordUsage}});var require_subschema=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/subschema.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.extendSubschemaMode=exports.extendSubschemaData=exports.getSubschema=void 0;var codegen_1=require_codegen();var util_1=require_util();function getSubschema(it,{keyword,schemaProp,schema,schemaPath,errSchemaPath,topSchemaRef}){if(keyword!==void 0&&schema!==void 0){throw new Error('both "keyword" and "schema" passed, only one allowed')}if(keyword!==void 0){const sch=it.schema[keyword];return schemaProp===void 0?{schema:sch,schemaPath:(0,codegen_1._)`${it.schemaPath}${(0,codegen_1.getProperty)(keyword)}`,errSchemaPath:`${it.errSchemaPath}/${keyword}`}:{schema:sch[schemaProp],schemaPath:(0,codegen_1._)`${it.schemaPath}${(0,codegen_1.getProperty)(keyword)}${(0,codegen_1.getProperty)(schemaProp)}`,errSchemaPath:`${it.errSchemaPath}/${keyword}/${(0,util_1.escapeFragment)(schemaProp)}`}}if(schema!==void 0){if(schemaPath===void 0||errSchemaPath===void 0||topSchemaRef===void 0){throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"')}return{schema,schemaPath,topSchemaRef,errSchemaPath}}throw new Error('either "keyword" or "schema" must be passed')}exports.getSubschema=getSubschema;function extendSubschemaData(subschema,it,{dataProp,dataPropType:dpType,data,dataTypes,propertyName}){if(data!==void 0&&dataProp!==void 0){throw new Error('both "data" and "dataProp" passed, only one allowed')}const{gen}=it;if(dataProp!==void 0){const{errorPath,dataPathArr,opts}=it;const nextData=gen.let("data",(0,codegen_1._)`${it.data}${(0,codegen_1.getProperty)(dataProp)}`,true);dataContextProps(nextData);subschema.errorPath=(0,codegen_1.str)`${errorPath}${(0,util_1.getErrorPath)(dataProp,dpType,opts.jsPropertySyntax)}`;subschema.parentDataProperty=(0,codegen_1._)`${dataProp}`;subschema.dataPathArr=[...dataPathArr,subschema.parentDataProperty]}if(data!==void 0){const nextData=data instanceof codegen_1.Name?data:gen.let("data",data,true);dataContextProps(nextData);if(propertyName!==void 0)subschema.propertyName=propertyName}if(dataTypes)subschema.dataTypes=dataTypes;function dataContextProps(_nextData){subschema.data=_nextData;subschema.dataLevel=it.dataLevel+1;subschema.dataTypes=[];it.definedProperties=new Set;subschema.parentData=it.data;subschema.dataNames=[...it.dataNames,_nextData]}}exports.extendSubschemaData=extendSubschemaData;function extendSubschemaMode(subschema,{jtdDiscriminator,jtdMetadata,compositeRule,createErrors,allErrors}){if(compositeRule!==void 0)subschema.compositeRule=compositeRule;if(createErrors!==void 0)subschema.createErrors=createErrors;if(allErrors!==void 0)subschema.allErrors=allErrors;subschema.jtdDiscriminator=jtdDiscriminator;subschema.jtdMetadata=jtdMetadata}exports.extendSubschemaMode=extendSubschemaMode}});var require_fast_deep_equal=__commonJS({"../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports,module){"use strict";module.exports=function equal(a,b2){if(a===b2)return true;if(a&&b2&&typeof a=="object"&&typeof b2=="object"){if(a.constructor!==b2.constructor)return false;var length,i,keys;if(Array.isArray(a)){length=a.length;if(length!=b2.length)return false;for(i=length;i--!==0;)if(!equal(a[i],b2[i]))return false;return true}if(a.constructor===RegExp)return a.source===b2.source&&a.flags===b2.flags;if(a.valueOf!==Object.prototype.valueOf)return a.valueOf()===b2.valueOf();if(a.toString!==Object.prototype.toString)return a.toString()===b2.toString();keys=Object.keys(a);length=keys.length;if(length!==Object.keys(b2).length)return false;for(i=length;i--!==0;)if(!Object.prototype.hasOwnProperty.call(b2,keys[i]))return false;for(i=length;i--!==0;){var key=keys[i];if(!equal(a[key],b2[key]))return false}return true}return a!==a&&b2!==b2}}});var require_json_schema_traverse=__commonJS({"../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js"(exports,module){"use strict";var traverse=module.exports=function(schema,opts,cb){if(typeof opts=="function"){cb=opts;opts={}}cb=opts.cb||cb;var pre=typeof cb=="function"?cb:cb.pre||function(){};var post=cb.post||function(){};_traverse(opts,pre,post,schema,"",schema)};traverse.keywords={additionalItems:true,items:true,contains:true,additionalProperties:true,propertyNames:true,not:true,if:true,then:true,else:true};traverse.arrayKeywords={items:true,allOf:true,anyOf:true,oneOf:true};traverse.propsKeywords={$defs:true,definitions:true,properties:true,patternProperties:true,dependencies:true};traverse.skipKeywords={default:true,enum:true,const:true,required:true,maximum:true,minimum:true,exclusiveMaximum:true,exclusiveMinimum:true,multipleOf:true,maxLength:true,minLength:true,pattern:true,format:true,maxItems:true,minItems:true,uniqueItems:true,maxProperties:true,minProperties:true};function _traverse(opts,pre,post,schema,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex){if(schema&&typeof schema=="object"&&!Array.isArray(schema)){pre(schema,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex);for(var key in schema){var sch=schema[key];if(Array.isArray(sch)){if(key in traverse.arrayKeywords){for(var i=0;i<sch.length;i++)_traverse(opts,pre,post,sch[i],jsonPtr+"/"+key+"/"+i,rootSchema,jsonPtr,key,schema,i)}}else if(key in traverse.propsKeywords){if(sch&&typeof sch=="object"){for(var prop in sch)_traverse(opts,pre,post,sch[prop],jsonPtr+"/"+key+"/"+escapeJsonPtr(prop),rootSchema,jsonPtr,key,schema,prop)}}else if(key in traverse.keywords||opts.allKeys&&!(key in traverse.skipKeywords)){_traverse(opts,pre,post,sch,jsonPtr+"/"+key,rootSchema,jsonPtr,key,schema)}}post(schema,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex)}}function escapeJsonPtr(str2){return str2.replace(/~/g,"~0").replace(/\//g,"~1")}}});var require_resolve=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/resolve.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getSchemaRefs=exports.resolveUrl=exports.normalizeId=exports._getFullPath=exports.getFullPath=exports.inlineRef=void 0;var util_1=require_util();var equal=require_fast_deep_equal();var traverse=require_json_schema_traverse();var SIMPLE_INLINED=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function inlineRef(schema,limit=true){if(typeof schema=="boolean")return true;if(limit===true)return!hasRef(schema);if(!limit)return false;return countKeys(schema)<=limit}exports.inlineRef=inlineRef;var REF_KEYWORDS=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function hasRef(schema){for(const key in schema){if(REF_KEYWORDS.has(key))return true;const sch=schema[key];if(Array.isArray(sch)&&sch.some(hasRef))return true;if(typeof sch=="object"&&hasRef(sch))return true}return false}function countKeys(schema){let count=0;for(const key in schema){if(key==="$ref")return Infinity;count++;if(SIMPLE_INLINED.has(key))continue;if(typeof schema[key]=="object"){(0,util_1.eachItem)(schema[key],sch=>count+=countKeys(sch))}if(count===Infinity)return Infinity}return count}function getFullPath(resolver,id="",normalize){if(normalize!==false)id=normalizeId(id);const p=resolver.parse(id);return _getFullPath(resolver,p)}exports.getFullPath=getFullPath;function _getFullPath(resolver,p){const serialized=resolver.serialize(p);return serialized.split("#")[0]+"#"}exports._getFullPath=_getFullPath;var TRAILING_SLASH_HASH=/#\/?$/;function normalizeId(id){return id?id.replace(TRAILING_SLASH_HASH,""):""}exports.normalizeId=normalizeId;function resolveUrl(resolver,baseId,id){id=normalizeId(id);return resolver.resolve(baseId,id)}exports.resolveUrl=resolveUrl;var ANCHOR=/^[a-z_][-a-z0-9._]*$/i;function getSchemaRefs(schema,baseId){if(typeof schema=="boolean")return{};const{schemaId,uriResolver}=this.opts;const schId=normalizeId(schema[schemaId]||baseId);const baseIds={"":schId};const pathPrefix=getFullPath(uriResolver,schId,false);const localRefs={};const schemaRefs=new Set;traverse(schema,{allKeys:true},(sch,jsonPtr,_2,parentJsonPtr)=>{if(parentJsonPtr===void 0)return;const fullPath=pathPrefix+jsonPtr;let innerBaseId=baseIds[parentJsonPtr];if(typeof sch[schemaId]=="string")innerBaseId=addRef.call(this,sch[schemaId]);addAnchor.call(this,sch.$anchor);addAnchor.call(this,sch.$dynamicAnchor);baseIds[jsonPtr]=innerBaseId;function addRef(ref){const _resolve=this.opts.uriResolver.resolve;ref=normalizeId(innerBaseId?_resolve(innerBaseId,ref):ref);if(schemaRefs.has(ref))throw ambiguos(ref);schemaRefs.add(ref);let schOrRef=this.refs[ref];if(typeof schOrRef=="string")schOrRef=this.refs[schOrRef];if(typeof schOrRef=="object"){checkAmbiguosRef(sch,schOrRef.schema,ref)}else if(ref!==normalizeId(fullPath)){if(ref[0]==="#"){checkAmbiguosRef(sch,localRefs[ref],ref);localRefs[ref]=sch}else{this.refs[ref]=fullPath}}return ref}function addAnchor(anchor){if(typeof anchor=="string"){if(!ANCHOR.test(anchor))throw new Error(`invalid anchor "${anchor}"`);addRef.call(this,`#${anchor}`)}}});return localRefs;function checkAmbiguosRef(sch1,sch2,ref){if(sch2!==void 0&&!equal(sch1,sch2))throw ambiguos(ref)}function ambiguos(ref){return new Error(`reference "${ref}" resolves to more than one schema`)}}exports.getSchemaRefs=getSchemaRefs}});var require_validate=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getData=exports.KeywordCxt=exports.validateFunctionCode=void 0;var boolSchema_1=require_boolSchema();var dataType_1=require_dataType();var applicability_1=require_applicability();var dataType_2=require_dataType();var defaults_1=require_defaults();var keyword_1=require_keyword();var subschema_1=require_subschema();var codegen_1=require_codegen();var names_1=require_names();var resolve_1=require_resolve();var util_1=require_util();var errors_1=require_errors();function validateFunctionCode(it){if(isSchemaObj(it)){checkKeywords(it);if(schemaCxtHasRules(it)){topSchemaObjCode(it);return}}validateFunction(it,()=>(0,boolSchema_1.topBoolOrEmptySchema)(it))}exports.validateFunctionCode=validateFunctionCode;function validateFunction({gen,validateName,schema,schemaEnv,opts},body){if(opts.code.es5){gen.func(validateName,(0,codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`,schemaEnv.$async,()=>{gen.code((0,codegen_1._)`"use strict"; ${funcSourceUrl(schema,opts)}`);destructureValCxtES5(gen,opts);gen.code(body)})}else{gen.func(validateName,(0,codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`,schemaEnv.$async,()=>gen.code(funcSourceUrl(schema,opts)).code(body))}}function destructureValCxt(opts){return(0,codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef?(0,codegen_1._)`, ${names_1.default.dynamicAnchors}={}`:codegen_1.nil}}={}`}function destructureValCxtES5(gen,opts){gen.if(names_1.default.valCxt,()=>{gen.var(names_1.default.instancePath,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`);gen.var(names_1.default.parentData,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`);gen.var(names_1.default.parentDataProperty,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);gen.var(names_1.default.rootData,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`);if(opts.dynamicRef)gen.var(names_1.default.dynamicAnchors,(0,codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`)},()=>{gen.var(names_1.default.instancePath,(0,codegen_1._)`""`);gen.var(names_1.default.parentData,(0,codegen_1._)`undefined`);gen.var(names_1.default.parentDataProperty,(0,codegen_1._)`undefined`);gen.var(names_1.default.rootData,names_1.default.data);if(opts.dynamicRef)gen.var(names_1.default.dynamicAnchors,(0,codegen_1._)`{}`)})}function topSchemaObjCode(it){const{schema,opts,gen}=it;validateFunction(it,()=>{if(opts.$comment&&schema.$comment)commentKeyword(it);checkNoDefault(it);gen.let(names_1.default.vErrors,null);gen.let(names_1.default.errors,0);if(opts.unevaluated)resetEvaluated(it);typeAndKeywords(it);returnResults(it)});return}function resetEvaluated(it){const{gen,validateName}=it;it.evaluated=gen.const("evaluated",(0,codegen_1._)`${validateName}.evaluated`);gen.if((0,codegen_1._)`${it.evaluated}.dynamicProps`,()=>gen.assign((0,codegen_1._)`${it.evaluated}.props`,(0,codegen_1._)`undefined`));gen.if((0,codegen_1._)`${it.evaluated}.dynamicItems`,()=>gen.assign((0,codegen_1._)`${it.evaluated}.items`,(0,codegen_1._)`undefined`))}function funcSourceUrl(schema,opts){const schId=typeof schema=="object"&&schema[opts.schemaId];return schId&&(opts.code.source||opts.code.process)?(0,codegen_1._)`/*# sourceURL=${schId} */`:codegen_1.nil}function subschemaCode(it,valid){if(isSchemaObj(it)){checkKeywords(it);if(schemaCxtHasRules(it)){subSchemaObjCode(it,valid);return}}(0,boolSchema_1.boolOrEmptySchema)(it,valid)}function schemaCxtHasRules({schema,self}){if(typeof schema=="boolean")return!schema;for(const key in schema)if(self.RULES.all[key])return true;return false}function isSchemaObj(it){return typeof it.schema!="boolean"}function subSchemaObjCode(it,valid){const{schema,gen,opts}=it;if(opts.$comment&&schema.$comment)commentKeyword(it);updateContext(it);checkAsyncSchema(it);const errsCount=gen.const("_errs",names_1.default.errors);typeAndKeywords(it,errsCount);gen.var(valid,(0,codegen_1._)`${errsCount} === ${names_1.default.errors}`)}function checkKeywords(it){(0,util_1.checkUnknownRules)(it);checkRefsAndKeywords(it)}function typeAndKeywords(it,errsCount){if(it.opts.jtd)return schemaKeywords(it,[],false,errsCount);const types=(0,dataType_1.getSchemaTypes)(it.schema);const checkedTypes=(0,dataType_1.coerceAndCheckDataType)(it,types);schemaKeywords(it,types,!checkedTypes,errsCount)}function checkRefsAndKeywords(it){const{schema,errSchemaPath,opts,self}=it;if(schema.$ref&&opts.ignoreKeywordsWithRef&&(0,util_1.schemaHasRulesButRef)(schema,self.RULES)){self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`)}}function checkNoDefault(it){const{schema,opts}=it;if(schema.default!==void 0&&opts.useDefaults&&opts.strictSchema){(0,util_1.checkStrictMode)(it,"default is ignored in the schema root")}}function updateContext(it){const schId=it.schema[it.opts.schemaId];if(schId)it.baseId=(0,resolve_1.resolveUrl)(it.opts.uriResolver,it.baseId,schId)}function checkAsyncSchema(it){if(it.schema.$async&&!it.schemaEnv.$async)throw new Error("async schema in sync schema")}function commentKeyword({gen,schemaEnv,schema,errSchemaPath,opts}){const msg=schema.$comment;if(opts.$comment===true){gen.code((0,codegen_1._)`${names_1.default.self}.logger.log(${msg})`)}else if(typeof opts.$comment=="function"){const schemaPath=(0,codegen_1.str)`${errSchemaPath}/$comment`;const rootName=gen.scopeValue("root",{ref:schemaEnv.root});gen.code((0,codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)}}function returnResults(it){const{gen,schemaEnv,validateName,ValidationError,opts}=it;if(schemaEnv.$async){gen.if((0,codegen_1._)`${names_1.default.errors} === 0`,()=>gen.return(names_1.default.data),()=>gen.throw((0,codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`))}else{gen.assign((0,codegen_1._)`${validateName}.errors`,names_1.default.vErrors);if(opts.unevaluated)assignEvaluated(it);gen.return((0,codegen_1._)`${names_1.default.errors} === 0`)}}function assignEvaluated({gen,evaluated,props,items}){if(props instanceof codegen_1.Name)gen.assign((0,codegen_1._)`${evaluated}.props`,props);if(items instanceof codegen_1.Name)gen.assign((0,codegen_1._)`${evaluated}.items`,items)}function schemaKeywords(it,types,typeErrors,errsCount){const{gen,schema,data,allErrors,opts,self}=it;const{RULES}=self;if(schema.$ref&&(opts.ignoreKeywordsWithRef||!(0,util_1.schemaHasRulesButRef)(schema,RULES))){gen.block(()=>keywordCode(it,"$ref",RULES.all.$ref.definition));return}if(!opts.jtd)checkStrictTypes(it,types);gen.block(()=>{for(const group of RULES.rules)groupKeywords(group);groupKeywords(RULES.post)});function groupKeywords(group){if(!(0,applicability_1.shouldUseGroup)(schema,group))return;if(group.type){gen.if((0,dataType_2.checkDataType)(group.type,data,opts.strictNumbers));iterateKeywords(it,group);if(types.length===1&&types[0]===group.type&&typeErrors){gen.else();(0,dataType_2.reportTypeError)(it)}gen.endIf()}else{iterateKeywords(it,group)}if(!allErrors)gen.if((0,codegen_1._)`${names_1.default.errors} === ${errsCount||0}`)}}function iterateKeywords(it,group){const{gen,schema,opts:{useDefaults}}=it;if(useDefaults)(0,defaults_1.assignDefaults)(it,group.type);gen.block(()=>{for(const rule of group.rules){if((0,applicability_1.shouldUseRule)(schema,rule)){keywordCode(it,rule.keyword,rule.definition,group.type)}}})}function checkStrictTypes(it,types){if(it.schemaEnv.meta||!it.opts.strictTypes)return;checkContextTypes(it,types);if(!it.opts.allowUnionTypes)checkMultipleTypes(it,types);checkKeywordTypes(it,it.dataTypes)}function checkContextTypes(it,types){if(!types.length)return;if(!it.dataTypes.length){it.dataTypes=types;return}types.forEach(t=>{if(!includesType(it.dataTypes,t)){strictTypesError(it,`type "${t}" not allowed by context "${it.dataTypes.join(",")}"`)}});narrowSchemaTypes(it,types)}function checkMultipleTypes(it,ts){if(ts.length>1&&!(ts.length===2&&ts.includes("null"))){strictTypesError(it,"use allowUnionTypes to allow union type keyword")}}function checkKeywordTypes(it,ts){const rules=it.self.RULES.all;for(const keyword in rules){const rule=rules[keyword];if(typeof rule=="object"&&(0,applicability_1.shouldUseRule)(it.schema,rule)){const{type}=rule.definition;if(type.length&&!type.some(t=>hasApplicableType(ts,t))){strictTypesError(it,`missing type "${type.join(",")}" for keyword "${keyword}"`)}}}}function hasApplicableType(schTs,kwdT){return schTs.includes(kwdT)||kwdT==="number"&&schTs.includes("integer")}function includesType(ts,t){return ts.includes(t)||t==="integer"&&ts.includes("number")}function narrowSchemaTypes(it,withTypes){const ts=[];for(const t of it.dataTypes){if(includesType(withTypes,t))ts.push(t);else if(withTypes.includes("integer")&&t==="number")ts.push("integer")}it.dataTypes=ts}function strictTypesError(it,msg){const schemaPath=it.schemaEnv.baseId+it.errSchemaPath;msg+=` at "${schemaPath}" (strictTypes)`;(0,util_1.checkStrictMode)(it,msg,it.opts.strictTypes)}var KeywordCxt=class{constructor(it,def,keyword){(0,keyword_1.validateKeywordUsage)(it,def,keyword);this.gen=it.gen;this.allErrors=it.allErrors;this.keyword=keyword;this.data=it.data;this.schema=it.schema[keyword];this.$data=def.$data&&it.opts.$data&&this.schema&&this.schema.$data;this.schemaValue=(0,util_1.schemaRefOrVal)(it,this.schema,keyword,this.$data);this.schemaType=def.schemaType;this.parentSchema=it.schema;this.params={};this.it=it;this.def=def;if(this.$data){this.schemaCode=it.gen.const("vSchema",getData(this.$data,it))}else{this.schemaCode=this.schemaValue;if(!(0,keyword_1.validSchemaType)(this.schema,def.schemaType,def.allowUndefined)){throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)}}if("code"in def?def.trackErrors:def.errors!==false){this.errsCount=it.gen.const("_errs",names_1.default.errors)}}result(condition,successAction,failAction){this.failResult((0,codegen_1.not)(condition),successAction,failAction)}failResult(condition,successAction,failAction){this.gen.if(condition);if(failAction)failAction();else this.error();if(successAction){this.gen.else();successAction();if(this.allErrors)this.gen.endIf()}else{if(this.allErrors)this.gen.endIf();else this.gen.else()}}pass(condition,failAction){this.failResult((0,codegen_1.not)(condition),void 0,failAction)}fail(condition){if(condition===void 0){this.error();if(!this.allErrors)this.gen.if(false);return}this.gen.if(condition);this.error();if(this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(condition){if(!this.$data)return this.fail(condition);const{schemaCode}=this;this.fail((0,codegen_1._)`${schemaCode} !== undefined && (${(0,codegen_1.or)(this.invalid$data(),condition)})`)}error(append,errorParams,errorPaths){if(errorParams){this.setParams(errorParams);this._error(append,errorPaths);this.setParams({});return}this._error(append,errorPaths)}_error(append,errorPaths){;(append?errors_1.reportExtraError:errors_1.reportError)(this,this.def.error,errorPaths)}$dataError(){(0,errors_1.reportError)(this,this.def.$dataError||errors_1.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,errors_1.resetErrorsCount)(this.gen,this.errsCount)}ok(cond){if(!this.allErrors)this.gen.if(cond)}setParams(obj,assign){if(assign)Object.assign(this.params,obj);else this.params=obj}block$data(valid,codeBlock,$dataValid=codegen_1.nil){this.gen.block(()=>{this.check$data(valid,$dataValid);codeBlock()})}check$data(valid=codegen_1.nil,$dataValid=codegen_1.nil){if(!this.$data)return;const{gen,schemaCode,schemaType,def}=this;gen.if((0,codegen_1.or)((0,codegen_1._)`${schemaCode} === undefined`,$dataValid));if(valid!==codegen_1.nil)gen.assign(valid,true);if(schemaType.length||def.validateSchema){gen.elseIf(this.invalid$data());this.$dataError();if(valid!==codegen_1.nil)gen.assign(valid,false)}gen.else()}invalid$data(){const{gen,schemaCode,schemaType,def,it}=this;return(0,codegen_1.or)(wrong$DataType(),invalid$DataSchema());function wrong$DataType(){if(schemaType.length){if(!(schemaCode instanceof codegen_1.Name))throw new Error("ajv implementation error");const st2=Array.isArray(schemaType)?schemaType:[schemaType];return(0,codegen_1._)`${(0,dataType_2.checkDataTypes)(st2,schemaCode,it.opts.strictNumbers,dataType_2.DataType.Wrong)}`}return codegen_1.nil}function invalid$DataSchema(){if(def.validateSchema){const validateSchemaRef=gen.scopeValue("validate$data",{ref:def.validateSchema});return(0,codegen_1._)`!${validateSchemaRef}(${schemaCode})`}return codegen_1.nil}}subschema(appl,valid){const subschema=(0,subschema_1.getSubschema)(this.it,appl);(0,subschema_1.extendSubschemaData)(subschema,this.it,appl);(0,subschema_1.extendSubschemaMode)(subschema,appl);const nextContext={...this.it,...subschema,items:void 0,props:void 0};subschemaCode(nextContext,valid);return nextContext}mergeEvaluated(schemaCxt,toName){const{it,gen}=this;if(!it.opts.unevaluated)return;if(it.props!==true&&schemaCxt.props!==void 0){it.props=util_1.mergeEvaluated.props(gen,schemaCxt.props,it.props,toName)}if(it.items!==true&&schemaCxt.items!==void 0){it.items=util_1.mergeEvaluated.items(gen,schemaCxt.items,it.items,toName)}}mergeValidEvaluated(schemaCxt,valid){const{it,gen}=this;if(it.opts.unevaluated&&(it.props!==true||it.items!==true)){gen.if(valid,()=>this.mergeEvaluated(schemaCxt,codegen_1.Name));return true}}};exports.KeywordCxt=KeywordCxt;function keywordCode(it,keyword,def,ruleType){const cxt=new KeywordCxt(it,def,keyword);if("code"in def){def.code(cxt,ruleType)}else if(cxt.$data&&def.validate){(0,keyword_1.funcKeywordCode)(cxt,def)}else if("macro"in def){(0,keyword_1.macroKeywordCode)(cxt,def)}else if(def.compile||def.validate){(0,keyword_1.funcKeywordCode)(cxt,def)}}var JSON_POINTER=/^\/(?:[^~]|~0|~1)*$/;var RELATIVE_JSON_POINTER=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function getData($data,{dataLevel,dataNames,dataPathArr}){let jsonPointer;let data;if($data==="")return names_1.default.rootData;if($data[0]==="/"){if(!JSON_POINTER.test($data))throw new Error(`Invalid JSON-pointer: ${$data}`);jsonPointer=$data;data=names_1.default.rootData}else{const matches=RELATIVE_JSON_POINTER.exec($data);if(!matches)throw new Error(`Invalid JSON-pointer: ${$data}`);const up=+matches[1];jsonPointer=matches[2];if(jsonPointer==="#"){if(up>=dataLevel)throw new Error(errorMsg("property/index",up));return dataPathArr[dataLevel-up]}if(up>dataLevel)throw new Error(errorMsg("data",up));data=dataNames[dataLevel-up];if(!jsonPointer)return data}let expr=data;const segments=jsonPointer.split("/");for(const segment of segments){if(segment){data=(0,codegen_1._)`${data}${(0,codegen_1.getProperty)((0,util_1.unescapeJsonPointer)(segment))}`;expr=(0,codegen_1._)`${expr} && ${data}`}}return expr;function errorMsg(pointerType,up){return`Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`}}exports.getData=getData}});var require_validation_error=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/validation_error.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var ValidationError=class extends Error{constructor(errors){super("validation failed");this.errors=errors;this.ajv=this.validation=true}};exports.default=ValidationError}});var require_ref_error=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/ref_error.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var resolve_1=require_resolve();var MissingRefError=class extends Error{constructor(resolver,baseId,ref,msg){super(msg||`can't resolve reference ${ref} from id ${baseId}`);this.missingRef=(0,resolve_1.resolveUrl)(resolver,baseId,ref);this.missingSchema=(0,resolve_1.normalizeId)((0,resolve_1.getFullPath)(resolver,this.missingRef))}};exports.default=MissingRefError}});var require_compile=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.resolveSchema=exports.getCompilingSchema=exports.resolveRef=exports.compileSchema=exports.SchemaEnv=void 0;var codegen_1=require_codegen();var validation_error_1=require_validation_error();var names_1=require_names();var resolve_1=require_resolve();var util_1=require_util();var validate_1=require_validate();var SchemaEnv=class{constructor(env){var _a3;this.refs={};this.dynamicAnchors={};let schema;if(typeof env.schema=="object")schema=env.schema;this.schema=env.schema;this.schemaId=env.schemaId;this.root=env.root||this;this.baseId=(_a3=env.baseId)!==null&&_a3!==void 0?_a3:(0,resolve_1.normalizeId)(schema===null||schema===void 0?void 0:schema[env.schemaId||"$id"]);this.schemaPath=env.schemaPath;this.localRefs=env.localRefs;this.meta=env.meta;this.$async=schema===null||schema===void 0?void 0:schema.$async;this.refs={}}};exports.SchemaEnv=SchemaEnv;function compileSchema(sch){const _sch=getCompilingSchema.call(this,sch);if(_sch)return _sch;const rootId=(0,resolve_1.getFullPath)(this.opts.uriResolver,sch.root.baseId);const{es5,lines}=this.opts.code;const{ownProperties}=this.opts;const gen=new codegen_1.CodeGen(this.scope,{es5,lines,ownProperties});let _ValidationError;if(sch.$async){_ValidationError=gen.scopeValue("Error",{ref:validation_error_1.default,code:(0,codegen_1._)`require("ajv/dist/runtime/validation_error").default`})}const validateName=gen.scopeName("validate");sch.validateName=validateName;const schemaCxt={gen,allErrors:this.opts.allErrors,data:names_1.default.data,parentData:names_1.default.parentData,parentDataProperty:names_1.default.parentDataProperty,dataNames:[names_1.default.data],dataPathArr:[codegen_1.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:gen.scopeValue("schema",this.opts.code.source===true?{ref:sch.schema,code:(0,codegen_1.stringify)(sch.schema)}:{ref:sch.schema}),validateName,ValidationError:_ValidationError,schema:sch.schema,schemaEnv:sch,rootId,baseId:sch.baseId||rootId,schemaPath:codegen_1.nil,errSchemaPath:sch.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,codegen_1._)`""`,opts:this.opts,self:this};let sourceCode;try{this._compilations.add(sch);(0,validate_1.validateFunctionCode)(schemaCxt);gen.optimize(this.opts.code.optimize);const validateCode=gen.toString();sourceCode=`${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;if(this.opts.code.process)sourceCode=this.opts.code.process(sourceCode,sch);const makeValidate=new Function(`${names_1.default.self}`,`${names_1.default.scope}`,sourceCode);const validate2=makeValidate(this,this.scope.get());this.scope.value(validateName,{ref:validate2});validate2.errors=null;validate2.schema=sch.schema;validate2.schemaEnv=sch;if(sch.$async)validate2.$async=true;if(this.opts.code.source===true){validate2.source={validateName,validateCode,scopeValues:gen._values}}if(this.opts.unevaluated){const{props,items}=schemaCxt;validate2.evaluated={props:props instanceof codegen_1.Name?void 0:props,items:items instanceof codegen_1.Name?void 0:items,dynamicProps:props instanceof codegen_1.Name,dynamicItems:items instanceof codegen_1.Name};if(validate2.source)validate2.source.evaluated=(0,codegen_1.stringify)(validate2.evaluated)}sch.validate=validate2;return sch}catch(e){delete sch.validate;delete sch.validateName;if(sourceCode)this.logger.error("Error compiling schema, function code:",sourceCode);throw e}finally{this._compilations.delete(sch)}}exports.compileSchema=compileSchema;function resolveRef2(root,baseId,ref){var _a3;ref=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,ref);const schOrFunc=root.refs[ref];if(schOrFunc)return schOrFunc;let _sch=resolve.call(this,root,ref);if(_sch===void 0){const schema=(_a3=root.localRefs)===null||_a3===void 0?void 0:_a3[ref];const{schemaId}=this.opts;if(schema)_sch=new SchemaEnv({schema,schemaId,root,baseId})}if(_sch===void 0)return;return root.refs[ref]=inlineOrCompile.call(this,_sch)}exports.resolveRef=resolveRef2;function inlineOrCompile(sch){if((0,resolve_1.inlineRef)(sch.schema,this.opts.inlineRefs))return sch.schema;return sch.validate?sch:compileSchema.call(this,sch)}function getCompilingSchema(schEnv){for(const sch of this._compilations){if(sameSchemaEnv(sch,schEnv))return sch}}exports.getCompilingSchema=getCompilingSchema;function sameSchemaEnv(s1,s2){return s1.schema===s2.schema&&s1.root===s2.root&&s1.baseId===s2.baseId}function resolve(root,ref){let sch;while(typeof(sch=this.refs[ref])=="string")ref=sch;return sch||this.schemas[ref]||resolveSchema.call(this,root,ref)}function resolveSchema(root,ref){const p=this.opts.uriResolver.parse(ref);const refPath=(0,resolve_1._getFullPath)(this.opts.uriResolver,p);let baseId=(0,resolve_1.getFullPath)(this.opts.uriResolver,root.baseId,void 0);if(Object.keys(root.schema).length>0&&refPath===baseId){return getJsonPointer.call(this,p,root)}const id=(0,resolve_1.normalizeId)(refPath);const schOrRef=this.refs[id]||this.schemas[id];if(typeof schOrRef=="string"){const sch=resolveSchema.call(this,root,schOrRef);if(typeof(sch===null||sch===void 0?void 0:sch.schema)!=="object")return;return getJsonPointer.call(this,p,sch)}if(typeof(schOrRef===null||schOrRef===void 0?void 0:schOrRef.schema)!=="object")return;if(!schOrRef.validate)compileSchema.call(this,schOrRef);if(id===(0,resolve_1.normalizeId)(ref)){const{schema}=schOrRef;const{schemaId}=this.opts;const schId=schema[schemaId];if(schId)baseId=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,schId);return new SchemaEnv({schema,schemaId,root,baseId})}return getJsonPointer.call(this,p,schOrRef)}exports.resolveSchema=resolveSchema;var PREVENT_SCOPE_CHANGE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function getJsonPointer(parsedRef,{baseId,schema,root}){var _a3;if(((_a3=parsedRef.fragment)===null||_a3===void 0?void 0:_a3[0])!=="/")return;for(const part of parsedRef.fragment.slice(1).split("/")){if(typeof schema==="boolean")return;const partSchema=schema[(0,util_1.unescapeFragment)(part)];if(partSchema===void 0)return;schema=partSchema;const schId=typeof schema==="object"&&schema[this.opts.schemaId];if(!PREVENT_SCOPE_CHANGE.has(part)&&schId){baseId=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,schId)}}let env;if(typeof schema!="boolean"&&schema.$ref&&!(0,util_1.schemaHasRulesButRef)(schema,this.RULES)){const $ref=(0,resolve_1.resolveUrl)(this.opts.uriResolver,baseId,schema.$ref);env=resolveSchema.call(this,root,$ref)}const{schemaId}=this.opts;env=env||new SchemaEnv({schema,schemaId,root,baseId});if(env.schema!==env.root.schema)return env;return void 0}}});var require_data=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/data.json"(exports,module){module.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:false}}});var require_utils=__commonJS({"../../node_modules/.pnpm/fast-uri@3.1.2/node_modules/fast-uri/lib/utils.js"(exports,module){"use strict";var isUUID=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);var isIPv4=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);var isHexPair=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);var isUnreserved=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu);var isPathCharacter=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function stringArrayToHexStripped(input){let acc="";let code=0;let i=0;for(i=0;i<input.length;i++){code=input[i].charCodeAt(0);if(code===48){continue}if(!(code>=48&&code<=57||code>=65&&code<=70||code>=97&&code<=102)){return""}acc+=input[i];break}for(i+=1;i<input.length;i++){code=input[i].charCodeAt(0);if(!(code>=48&&code<=57||code>=65&&code<=70||code>=97&&code<=102)){return""}acc+=input[i]}return acc}var nonSimpleDomain=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function consumeIsZone(buffer){buffer.length=0;return true}function consumeHextets(buffer,address,output){if(buffer.length){const hex3=stringArrayToHexStripped(buffer);if(hex3!==""){address.push(hex3)}else{output.error=true;return false}buffer.length=0}return true}function getIPV6(input){let tokenCount=0;const output={error:false,address:"",zone:""};const address=[];const buffer=[];let endipv6Encountered=false;let endIpv6=false;let consume=consumeHextets;for(let i=0;i<input.length;i++){const cursor=input[i];if(cursor==="["||cursor==="]"){continue}if(cursor===":"){if(endipv6Encountered===true){endIpv6=true}if(!consume(buffer,address,output)){break}if(++tokenCount>7){output.error=true;break}if(i>0&&input[i-1]===":"){endipv6Encountered=true}address.push(":");continue}else if(cursor==="%"){if(!consume(buffer,address,output)){break}consume=consumeIsZone}else{buffer.push(cursor);continue}}if(buffer.length){if(consume===consumeIsZone){output.zone=buffer.join("")}else if(endIpv6){address.push(buffer.join(""))}else{address.push(stringArrayToHexStripped(buffer))}}output.address=address.join("");return output}function normalizeIPv6(host){if(findToken(host,":")<2){return{host,isIPV6:false}}const ipv63=getIPV6(host);if(!ipv63.error){let newHost=ipv63.address;let escapedHost=ipv63.address;if(ipv63.zone){newHost+="%"+ipv63.zone;escapedHost+="%25"+ipv63.zone}return{host:newHost,isIPV6:true,escapedHost}}else{return{host,isIPV6:false}}}function findToken(str2,token){let ind=0;for(let i=0;i<str2.length;i++){if(str2[i]===token)ind++}return ind}function removeDotSegments(path){let input=path;const output=[];let nextSlash=-1;let len=0;while(len=input.length){if(len===1){if(input==="."){break}else if(input==="/"){output.push("/");break}else{output.push(input);break}}else if(len===2){if(input[0]==="."){if(input[1]==="."){break}else if(input[1]==="/"){input=input.slice(2);continue}}else if(input[0]==="/"){if(input[1]==="."||input[1]==="/"){output.push("/");break}}}else if(len===3){if(input==="/.."){if(output.length!==0){output.pop()}output.push("/");break}}if(input[0]==="."){if(input[1]==="."){if(input[2]==="/"){input=input.slice(3);continue}}else if(input[1]==="/"){input=input.slice(2);continue}}else if(input[0]==="/"){if(input[1]==="."){if(input[2]==="/"){input=input.slice(2);continue}else if(input[2]==="."){if(input[3]==="/"){input=input.slice(3);if(output.length!==0){output.pop()}continue}}}}if((nextSlash=input.indexOf("/",1))===-1){output.push(input);break}else{output.push(input.slice(0,nextSlash));input=input.slice(nextSlash)}}return output.join("")}var HOST_DELIMS={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"};var HOST_DELIM_RE=/[@/?#:]/g;var HOST_DELIM_NO_COLON_RE=/[@/?#]/g;function reescapeHostDelimiters(host,isIP){const re=isIP?HOST_DELIM_NO_COLON_RE:HOST_DELIM_RE;re.lastIndex=0;return host.replace(re,ch=>HOST_DELIMS[ch])}function normalizePercentEncoding(input,decodeUnreserved=false){if(input.indexOf("%")===-1){return input}let output="";for(let i=0;i<input.length;i++){if(input[i]==="%"&&i+2<input.length){const hex3=input.slice(i+1,i+3);if(isHexPair(hex3)){const normalizedHex=hex3.toUpperCase();const decoded=String.fromCharCode(parseInt(normalizedHex,16));if(decodeUnreserved&&isUnreserved(decoded)){output+=decoded}else{output+="%"+normalizedHex}i+=2;continue}}output+=input[i]}return output}function normalizePathEncoding(input){let output="";for(let i=0;i<input.length;i++){if(input[i]==="%"&&i+2<input.length){const hex3=input.slice(i+1,i+3);if(isHexPair(hex3)){const normalizedHex=hex3.toUpperCase();const decoded=String.fromCharCode(parseInt(normalizedHex,16));if(decoded!=="."&&isUnreserved(decoded)){output+=decoded}else{output+="%"+normalizedHex}i+=2;continue}}if(isPathCharacter(input[i])){output+=input[i]}else{output+=escape(input[i])}}return output}function escapePreservingEscapes(input){let output="";for(let i=0;i<input.length;i++){if(input[i]==="%"&&i+2<input.length){const hex3=input.slice(i+1,i+3);if(isHexPair(hex3)){output+="%"+hex3.toUpperCase();i+=2;continue}}output+=escape(input[i])}return output}function recomposeAuthority(component){const uriTokens=[];if(component.userinfo!==void 0){uriTokens.push(component.userinfo);uriTokens.push("@")}if(component.host!==void 0){let host=unescape(component.host);if(!isIPv4(host)){const ipV6res=normalizeIPv6(host);if(ipV6res.isIPV6===true){host=`[${ipV6res.escapedHost}]`}else{host=reescapeHostDelimiters(host,false)}}uriTokens.push(host)}if(typeof component.port==="number"||typeof component.port==="string"){uriTokens.push(":");uriTokens.push(String(component.port))}return uriTokens.length?uriTokens.join(""):void 0}module.exports={nonSimpleDomain,recomposeAuthority,reescapeHostDelimiters,normalizePercentEncoding,normalizePathEncoding,escapePreservingEscapes,removeDotSegments,isIPv4,isUUID,normalizeIPv6,stringArrayToHexStripped}}});var require_schemes=__commonJS({"../../node_modules/.pnpm/fast-uri@3.1.2/node_modules/fast-uri/lib/schemes.js"(exports,module){"use strict";var{isUUID}=require_utils();var URN_REG=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;var supportedSchemeNames=["http","https","ws","wss","urn","urn:uuid"];function isValidSchemeName(name){return supportedSchemeNames.indexOf(name)!==-1}function wsIsSecure(wsComponent){if(wsComponent.secure===true){return true}else if(wsComponent.secure===false){return false}else if(wsComponent.scheme){return wsComponent.scheme.length===3&&(wsComponent.scheme[0]==="w"||wsComponent.scheme[0]==="W")&&(wsComponent.scheme[1]==="s"||wsComponent.scheme[1]==="S")&&(wsComponent.scheme[2]==="s"||wsComponent.scheme[2]==="S")}else{return false}}function httpParse(component){if(!component.host){component.error=component.error||"HTTP URIs must have a host."}return component}function httpSerialize(component){const secure=String(component.scheme).toLowerCase()==="https";if(component.port===(secure?443:80)||component.port===""){component.port=void 0}if(!component.path){component.path="/"}return component}function wsParse(wsComponent){wsComponent.secure=wsIsSecure(wsComponent);wsComponent.resourceName=(wsComponent.path||"/")+(wsComponent.query?"?"+wsComponent.query:"");wsComponent.path=void 0;wsComponent.query=void 0;return wsComponent}function wsSerialize(wsComponent){if(wsComponent.port===(wsIsSecure(wsComponent)?443:80)||wsComponent.port===""){wsComponent.port=void 0}if(typeof wsComponent.secure==="boolean"){wsComponent.scheme=wsComponent.secure?"wss":"ws";wsComponent.secure=void 0}if(wsComponent.resourceName){const[path,query]=wsComponent.resourceName.split("?");wsComponent.path=path&&path!=="/"?path:void 0;wsComponent.query=query;wsComponent.resourceName=void 0}wsComponent.fragment=void 0;return wsComponent}function urnParse(urnComponent,options){if(!urnComponent.path){urnComponent.error="URN can not be parsed";return urnComponent}const matches=urnComponent.path.match(URN_REG);if(matches){const scheme=options.scheme||urnComponent.scheme||"urn";urnComponent.nid=matches[1].toLowerCase();urnComponent.nss=matches[2];const urnScheme=`${scheme}:${options.nid||urnComponent.nid}`;const schemeHandler=getSchemeHandler(urnScheme);urnComponent.path=void 0;if(schemeHandler){urnComponent=schemeHandler.parse(urnComponent,options)}}else{urnComponent.error=urnComponent.error||"URN can not be parsed."}return urnComponent}function urnSerialize(urnComponent,options){if(urnComponent.nid===void 0){throw new Error("URN without nid cannot be serialized")}const scheme=options.scheme||urnComponent.scheme||"urn";const nid=urnComponent.nid.toLowerCase();const urnScheme=`${scheme}:${options.nid||nid}`;const schemeHandler=getSchemeHandler(urnScheme);if(schemeHandler){urnComponent=schemeHandler.serialize(urnComponent,options)}const uriComponent=urnComponent;const nss=urnComponent.nss;uriComponent.path=`${nid||options.nid}:${nss}`;options.skipEscape=true;return uriComponent}function urnuuidParse(urnComponent,options){const uuidComponent=urnComponent;uuidComponent.uuid=uuidComponent.nss;uuidComponent.nss=void 0;if(!options.tolerant&&(!uuidComponent.uuid||!isUUID(uuidComponent.uuid))){uuidComponent.error=uuidComponent.error||"UUID is not valid."}return uuidComponent}function urnuuidSerialize(uuidComponent){const urnComponent=uuidComponent;urnComponent.nss=(uuidComponent.uuid||"").toLowerCase();return urnComponent}var http={scheme:"http",domainHost:true,parse:httpParse,serialize:httpSerialize};var https={scheme:"https",domainHost:http.domainHost,parse:httpParse,serialize:httpSerialize};var ws={scheme:"ws",domainHost:true,parse:wsParse,serialize:wsSerialize};var wss={scheme:"wss",domainHost:ws.domainHost,parse:ws.parse,serialize:ws.serialize};var urn={scheme:"urn",parse:urnParse,serialize:urnSerialize,skipNormalize:true};var urnuuid={scheme:"urn:uuid",parse:urnuuidParse,serialize:urnuuidSerialize,skipNormalize:true};var SCHEMES={http,https,ws,wss,urn,"urn:uuid":urnuuid};Object.setPrototypeOf(SCHEMES,null);function getSchemeHandler(scheme){return scheme&&(SCHEMES[scheme]||SCHEMES[scheme.toLowerCase()])||void 0}module.exports={wsIsSecure,SCHEMES,isValidSchemeName,getSchemeHandler}}});var require_fast_uri=__commonJS({"../../node_modules/.pnpm/fast-uri@3.1.2/node_modules/fast-uri/index.js"(exports,module){"use strict";var{normalizeIPv6,removeDotSegments,recomposeAuthority,normalizePercentEncoding,normalizePathEncoding,escapePreservingEscapes,reescapeHostDelimiters,isIPv4,nonSimpleDomain}=require_utils();var{SCHEMES,getSchemeHandler}=require_schemes();function normalize(uri,options){if(typeof uri==="string"){uri=normalizeString(uri,options)}else if(typeof uri==="object"){uri=parse3(serialize(uri,options),options)}return uri}function resolve(baseURI,relativeURI,options){const schemelessOptions=options?Object.assign({scheme:"null"},options):{scheme:"null"};const resolved=resolveComponent(parse3(baseURI,schemelessOptions),parse3(relativeURI,schemelessOptions),schemelessOptions,true);schemelessOptions.skipEscape=true;return serialize(resolved,schemelessOptions)}function resolveComponent(base,relative,options,skipNormalization){const target={};if(!skipNormalization){base=parse3(serialize(base,options),options);relative=parse3(serialize(relative,options),options)}options=options||{};if(!options.tolerant&&relative.scheme){target.scheme=relative.scheme;target.userinfo=relative.userinfo;target.host=relative.host;target.port=relative.port;target.path=removeDotSegments(relative.path||"");target.query=relative.query}else{if(relative.userinfo!==void 0||relative.host!==void 0||relative.port!==void 0){target.userinfo=relative.userinfo;target.host=relative.host;target.port=relative.port;target.path=removeDotSegments(relative.path||"");target.query=relative.query}else{if(!relative.path){target.path=base.path;if(relative.query!==void 0){target.query=relative.query}else{target.query=base.query}}else{if(relative.path[0]==="/"){target.path=removeDotSegments(relative.path)}else{if((base.userinfo!==void 0||base.host!==void 0||base.port!==void 0)&&!base.path){target.path="/"+relative.path}else if(!base.path){target.path=relative.path}else{target.path=base.path.slice(0,base.path.lastIndexOf("/")+1)+relative.path}target.path=removeDotSegments(target.path)}target.query=relative.query}target.userinfo=base.userinfo;target.host=base.host;target.port=base.port}target.scheme=base.scheme}target.fragment=relative.fragment;return target}function equal(uriA,uriB,options){const normalizedA=normalizeComparableURI(uriA,options);const normalizedB=normalizeComparableURI(uriB,options);return normalizedA!==void 0&&normalizedB!==void 0&&normalizedA.toLowerCase()===normalizedB.toLowerCase()}function serialize(cmpts,opts){const component={host:cmpts.host,scheme:cmpts.scheme,userinfo:cmpts.userinfo,port:cmpts.port,path:cmpts.path,query:cmpts.query,nid:cmpts.nid,nss:cmpts.nss,uuid:cmpts.uuid,fragment:cmpts.fragment,reference:cmpts.reference,resourceName:cmpts.resourceName,secure:cmpts.secure,error:""};const options=Object.assign({},opts);const uriTokens=[];const schemeHandler=getSchemeHandler(options.scheme||component.scheme);if(schemeHandler&&schemeHandler.serialize)schemeHandler.serialize(component,options);if(component.path!==void 0){if(!options.skipEscape){component.path=escapePreservingEscapes(component.path);if(component.scheme!==void 0){component.path=component.path.split("%3A").join(":")}}else{component.path=normalizePercentEncoding(component.path)}}if(options.reference!=="suffix"&&component.scheme){uriTokens.push(component.scheme,":")}const authority=recomposeAuthority(component);if(authority!==void 0){if(options.reference!=="suffix"){uriTokens.push("//")}uriTokens.push(authority);if(component.path&&component.path[0]!=="/"){uriTokens.push("/")}}if(component.path!==void 0){let s=component.path;if(!options.absolutePath&&(!schemeHandler||!schemeHandler.absolutePath)){s=removeDotSegments(s)}if(authority===void 0&&s[0]==="/"&&s[1]==="/"){s="/%2F"+s.slice(2)}uriTokens.push(s)}if(component.query!==void 0){uriTokens.push("?",component.query)}if(component.fragment!==void 0){uriTokens.push("#",component.fragment)}return uriTokens.join("")}var URI_PARSE=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function getParseError(parsed,matches){if(matches[2]!==void 0&&parsed.path&&parsed.path[0]!=="/"){return'URI path must start with "/" when authority is present.'}if(typeof parsed.port==="number"&&(parsed.port<0||parsed.port>65535)){return"URI port is malformed."}return void 0}function parseWithStatus(uri,opts){const options=Object.assign({},opts);const parsed={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let malformedAuthorityOrPort=false;let isIP=false;if(options.reference==="suffix"){if(options.scheme){uri=options.scheme+":"+uri}else{uri="//"+uri}}const matches=uri.match(URI_PARSE);if(matches){parsed.scheme=matches[1];parsed.userinfo=matches[3];parsed.host=matches[4];parsed.port=parseInt(matches[5],10);parsed.path=matches[6]||"";parsed.query=matches[7];parsed.fragment=matches[8];if(isNaN(parsed.port)){parsed.port=matches[5]}const parseError=getParseError(parsed,matches);if(parseError!==void 0){parsed.error=parsed.error||parseError;malformedAuthorityOrPort=true}if(parsed.host){const ipv4result=isIPv4(parsed.host);if(ipv4result===false){const ipv6result=normalizeIPv6(parsed.host);parsed.host=ipv6result.host.toLowerCase();isIP=ipv6result.isIPV6}else{isIP=true}}if(parsed.scheme===void 0&&parsed.userinfo===void 0&&parsed.host===void 0&&parsed.port===void 0&&parsed.query===void 0&&!parsed.path){parsed.reference="same-document"}else if(parsed.scheme===void 0){parsed.reference="relative"}else if(parsed.fragment===void 0){parsed.reference="absolute"}else{parsed.reference="uri"}if(options.reference&&options.reference!=="suffix"&&options.reference!==parsed.reference){parsed.error=parsed.error||"URI is not a "+options.reference+" reference."}const schemeHandler=getSchemeHandler(options.scheme||parsed.scheme);if(!options.unicodeSupport&&(!schemeHandler||!schemeHandler.unicodeSupport)){if(parsed.host&&(options.domainHost||schemeHandler&&schemeHandler.domainHost)&&isIP===false&&nonSimpleDomain(parsed.host)){try{parsed.host=URL.domainToASCII(parsed.host.toLowerCase())}catch(e){parsed.error=parsed.error||"Host's domain name can not be converted to ASCII: "+e}}}if(!schemeHandler||schemeHandler&&!schemeHandler.skipNormalize){if(uri.indexOf("%")!==-1){if(parsed.scheme!==void 0){parsed.scheme=unescape(parsed.scheme)}if(parsed.host!==void 0){parsed.host=reescapeHostDelimiters(unescape(parsed.host),isIP)}}if(parsed.path){parsed.path=normalizePathEncoding(parsed.path)}if(parsed.fragment){try{parsed.fragment=encodeURI(decodeURIComponent(parsed.fragment))}catch{parsed.error=parsed.error||"URI malformed"}}}if(schemeHandler&&schemeHandler.parse){schemeHandler.parse(parsed,options)}}else{parsed.error=parsed.error||"URI can not be parsed."}return{parsed,malformedAuthorityOrPort}}function parse3(uri,opts){return parseWithStatus(uri,opts).parsed}function normalizeString(uri,opts){return normalizeStringWithStatus(uri,opts).normalized}function normalizeStringWithStatus(uri,opts){const{parsed,malformedAuthorityOrPort}=parseWithStatus(uri,opts);return{normalized:malformedAuthorityOrPort?uri:serialize(parsed,opts),malformedAuthorityOrPort}}function normalizeComparableURI(uri,opts){if(typeof uri==="string"){const{normalized,malformedAuthorityOrPort}=normalizeStringWithStatus(uri,opts);return malformedAuthorityOrPort?void 0:normalized}if(typeof uri==="object"){return serialize(uri,opts)}}var fastUri={SCHEMES,normalize,resolve,resolveComponent,equal,serialize,parse:parse3};module.exports=fastUri;module.exports.default=fastUri;module.exports.fastUri=fastUri}});var require_uri=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/uri.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var uri=require_fast_uri();uri.code='require("ajv/dist/runtime/uri").default';exports.default=uri}});var require_core=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/core.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=void 0;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();var ref_error_1=require_ref_error();var rules_1=require_rules();var compile_1=require_compile();var codegen_2=require_codegen();var resolve_1=require_resolve();var dataType_1=require_dataType();var util_1=require_util();var $dataRefSchema=require_data();var uri_1=require_uri();var defaultRegExp=(str2,flags)=>new RegExp(str2,flags);defaultRegExp.code="new RegExp";var META_IGNORE_OPTIONS=["removeAdditional","useDefaults","coerceTypes"];var EXT_SCOPE_NAMES=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]);var removedOptions={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."};var deprecatedOptions={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};var MAX_EXPRESSION=200;function requiredOptions(o){var _a3,_b,_c,_d,_e2,_f,_g,_h,_j,_k,_l,_m,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x,_y,_z,_0;const s=o.strict;const _optz=(_a3=o.code)===null||_a3===void 0?void 0:_a3.optimize;const optimize=_optz===true||_optz===void 0?1:_optz||0;const regExp=(_c=(_b=o.code)===null||_b===void 0?void 0:_b.regExp)!==null&&_c!==void 0?_c:defaultRegExp;const uriResolver=(_d=o.uriResolver)!==null&&_d!==void 0?_d:uri_1.default;return{strictSchema:(_f=(_e2=o.strictSchema)!==null&&_e2!==void 0?_e2:s)!==null&&_f!==void 0?_f:true,strictNumbers:(_h=(_g=o.strictNumbers)!==null&&_g!==void 0?_g:s)!==null&&_h!==void 0?_h:true,strictTypes:(_k=(_j=o.strictTypes)!==null&&_j!==void 0?_j:s)!==null&&_k!==void 0?_k:"log",strictTuples:(_m=(_l=o.strictTuples)!==null&&_l!==void 0?_l:s)!==null&&_m!==void 0?_m:"log",strictRequired:(_p=(_o=o.strictRequired)!==null&&_o!==void 0?_o:s)!==null&&_p!==void 0?_p:false,code:o.code?{...o.code,optimize,regExp}:{optimize,regExp},loopRequired:(_q=o.loopRequired)!==null&&_q!==void 0?_q:MAX_EXPRESSION,loopEnum:(_r=o.loopEnum)!==null&&_r!==void 0?_r:MAX_EXPRESSION,meta:(_s=o.meta)!==null&&_s!==void 0?_s:true,messages:(_t=o.messages)!==null&&_t!==void 0?_t:true,inlineRefs:(_u=o.inlineRefs)!==null&&_u!==void 0?_u:true,schemaId:(_v=o.schemaId)!==null&&_v!==void 0?_v:"$id",addUsedSchema:(_w=o.addUsedSchema)!==null&&_w!==void 0?_w:true,validateSchema:(_x=o.validateSchema)!==null&&_x!==void 0?_x:true,validateFormats:(_y=o.validateFormats)!==null&&_y!==void 0?_y:true,unicodeRegExp:(_z=o.unicodeRegExp)!==null&&_z!==void 0?_z:true,int32range:(_0=o.int32range)!==null&&_0!==void 0?_0:true,uriResolver}}var Ajv=class{constructor(opts={}){this.schemas={};this.refs={};this.formats=Object.create(null);this._compilations=new Set;this._loading={};this._cache=new Map;opts=this.opts={...opts,...requiredOptions(opts)};const{es5,lines}=this.opts.code;this.scope=new codegen_2.ValueScope({scope:{},prefixes:EXT_SCOPE_NAMES,es5,lines});this.logger=getLogger(opts.logger);const formatOpt=opts.validateFormats;opts.validateFormats=false;this.RULES=(0,rules_1.getRules)();checkOptions.call(this,removedOptions,opts,"NOT SUPPORTED");checkOptions.call(this,deprecatedOptions,opts,"DEPRECATED","warn");this._metaOpts=getMetaSchemaOptions.call(this);if(opts.formats)addInitialFormats.call(this);this._addVocabularies();this._addDefaultMetaSchema();if(opts.keywords)addInitialKeywords.call(this,opts.keywords);if(typeof opts.meta=="object")this.addMetaSchema(opts.meta);addInitialSchemas.call(this);opts.validateFormats=formatOpt}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data,meta:meta3,schemaId}=this.opts;let _dataRefSchema=$dataRefSchema;if(schemaId==="id"){_dataRefSchema={...$dataRefSchema};_dataRefSchema.id=_dataRefSchema.$id;delete _dataRefSchema.$id}if(meta3&&$data)this.addMetaSchema(_dataRefSchema,_dataRefSchema[schemaId],false)}defaultMeta(){const{meta:meta3,schemaId}=this.opts;return this.opts.defaultMeta=typeof meta3=="object"?meta3[schemaId]||meta3:void 0}validate(schemaKeyRef,data){let v2;if(typeof schemaKeyRef=="string"){v2=this.getSchema(schemaKeyRef);if(!v2)throw new Error(`no schema with key or ref "${schemaKeyRef}"`)}else{v2=this.compile(schemaKeyRef)}const valid=v2(data);if(!("$async"in v2))this.errors=v2.errors;return valid}compile(schema,_meta){const sch=this._addSchema(schema,_meta);return sch.validate||this._compileSchemaEnv(sch)}compileAsync(schema,meta3){if(typeof this.opts.loadSchema!="function"){throw new Error("options.loadSchema should be a function")}const{loadSchema}=this.opts;return runCompileAsync.call(this,schema,meta3);async function runCompileAsync(_schema,_meta){await loadMetaSchema.call(this,_schema.$schema);const sch=this._addSchema(_schema,_meta);return sch.validate||_compileAsync.call(this,sch)}async function loadMetaSchema($ref){if($ref&&!this.getSchema($ref)){await runCompileAsync.call(this,{$ref},true)}}async function _compileAsync(sch){try{return this._compileSchemaEnv(sch)}catch(e){if(!(e instanceof ref_error_1.default))throw e;checkLoaded.call(this,e);await loadMissingSchema.call(this,e.missingSchema);return _compileAsync.call(this,sch)}}function checkLoaded({missingSchema:ref,missingRef}){if(this.refs[ref]){throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)}}async function loadMissingSchema(ref){const _schema=await _loadSchema.call(this,ref);if(!this.refs[ref])await loadMetaSchema.call(this,_schema.$schema);if(!this.refs[ref])this.addSchema(_schema,ref,meta3)}async function _loadSchema(ref){const p=this._loading[ref];if(p)return p;try{return await(this._loading[ref]=loadSchema(ref))}finally{delete this._loading[ref]}}}addSchema(schema,key,_meta,_validateSchema=this.opts.validateSchema){if(Array.isArray(schema)){for(const sch of schema)this.addSchema(sch,void 0,_meta,_validateSchema);return this}let id;if(typeof schema==="object"){const{schemaId}=this.opts;id=schema[schemaId];if(id!==void 0&&typeof id!="string"){throw new Error(`schema ${schemaId} must be string`)}}key=(0,resolve_1.normalizeId)(key||id);this._checkUnique(key);this.schemas[key]=this._addSchema(schema,_meta,key,_validateSchema,true);return this}addMetaSchema(schema,key,_validateSchema=this.opts.validateSchema){this.addSchema(schema,key,true,_validateSchema);return this}validateSchema(schema,throwOrLogError){if(typeof schema=="boolean")return true;let $schema;$schema=schema.$schema;if($schema!==void 0&&typeof $schema!="string"){throw new Error("$schema must be a string")}$schema=$schema||this.opts.defaultMeta||this.defaultMeta();if(!$schema){this.logger.warn("meta-schema not available");this.errors=null;return true}const valid=this.validate($schema,schema);if(!valid&&throwOrLogError){const message="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(message);else throw new Error(message)}return valid}getSchema(keyRef){let sch;while(typeof(sch=getSchEnv.call(this,keyRef))=="string")keyRef=sch;if(sch===void 0){const{schemaId}=this.opts;const root=new compile_1.SchemaEnv({schema:{},schemaId});sch=compile_1.resolveSchema.call(this,root,keyRef);if(!sch)return;this.refs[keyRef]=sch}return sch.validate||this._compileSchemaEnv(sch)}removeSchema(schemaKeyRef){if(schemaKeyRef instanceof RegExp){this._removeAllSchemas(this.schemas,schemaKeyRef);this._removeAllSchemas(this.refs,schemaKeyRef);return this}switch(typeof schemaKeyRef){case"undefined":this._removeAllSchemas(this.schemas);this._removeAllSchemas(this.refs);this._cache.clear();return this;case"string":{const sch=getSchEnv.call(this,schemaKeyRef);if(typeof sch=="object")this._cache.delete(sch.schema);delete this.schemas[schemaKeyRef];delete this.refs[schemaKeyRef];return this}case"object":{const cacheKey=schemaKeyRef;this._cache.delete(cacheKey);let id=schemaKeyRef[this.opts.schemaId];if(id){id=(0,resolve_1.normalizeId)(id);delete this.schemas[id];delete this.refs[id]}return this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(definitions){for(const def of definitions)this.addKeyword(def);return this}addKeyword(kwdOrDef,def){let keyword;if(typeof kwdOrDef=="string"){keyword=kwdOrDef;if(typeof def=="object"){this.logger.warn("these parameters are deprecated, see docs for addKeyword");def.keyword=keyword}}else if(typeof kwdOrDef=="object"&&def===void 0){def=kwdOrDef;keyword=def.keyword;if(Array.isArray(keyword)&&!keyword.length){throw new Error("addKeywords: keyword must be string or non-empty array")}}else{throw new Error("invalid addKeywords parameters")}checkKeyword.call(this,keyword,def);if(!def){(0,util_1.eachItem)(keyword,kwd=>addRule.call(this,kwd));return this}keywordMetaschema.call(this,def);const definition={...def,type:(0,dataType_1.getJSONTypes)(def.type),schemaType:(0,dataType_1.getJSONTypes)(def.schemaType)};(0,util_1.eachItem)(keyword,definition.type.length===0?k=>addRule.call(this,k,definition):k=>definition.type.forEach(t=>addRule.call(this,k,definition,t)));return this}getKeyword(keyword){const rule=this.RULES.all[keyword];return typeof rule=="object"?rule.definition:!!rule}removeKeyword(keyword){const{RULES}=this;delete RULES.keywords[keyword];delete RULES.all[keyword];for(const group of RULES.rules){const i=group.rules.findIndex(rule=>rule.keyword===keyword);if(i>=0)group.rules.splice(i,1)}return this}addFormat(name,format){if(typeof format=="string")format=new RegExp(format);this.formats[name]=format;return this}errorsText(errors=this.errors,{separator=", ",dataVar="data"}={}){if(!errors||errors.length===0)return"No errors";return errors.map(e=>`${dataVar}${e.instancePath} ${e.message}`).reduce((text,msg)=>text+separator+msg)}$dataMetaSchema(metaSchema,keywordsJsonPointers){const rules=this.RULES.all;metaSchema=JSON.parse(JSON.stringify(metaSchema));for(const jsonPointer of keywordsJsonPointers){const segments=jsonPointer.split("/").slice(1);let keywords=metaSchema;for(const seg of segments)keywords=keywords[seg];for(const key in rules){const rule=rules[key];if(typeof rule!="object")continue;const{$data}=rule.definition;const schema=keywords[key];if($data&&schema)keywords[key]=schemaOrData(schema)}}return metaSchema}_removeAllSchemas(schemas,regex){for(const keyRef in schemas){const sch=schemas[keyRef];if(!regex||regex.test(keyRef)){if(typeof sch=="string"){delete schemas[keyRef]}else if(sch&&!sch.meta){this._cache.delete(sch.schema);delete schemas[keyRef]}}}}_addSchema(schema,meta3,baseId,validateSchema=this.opts.validateSchema,addSchema=this.opts.addUsedSchema){let id;const{schemaId}=this.opts;if(typeof schema=="object"){id=schema[schemaId]}else{if(this.opts.jtd)throw new Error("schema must be object");else if(typeof schema!="boolean")throw new Error("schema must be object or boolean")}let sch=this._cache.get(schema);if(sch!==void 0)return sch;baseId=(0,resolve_1.normalizeId)(id||baseId);const localRefs=resolve_1.getSchemaRefs.call(this,schema,baseId);sch=new compile_1.SchemaEnv({schema,schemaId,meta:meta3,baseId,localRefs});this._cache.set(sch.schema,sch);if(addSchema&&!baseId.startsWith("#")){if(baseId)this._checkUnique(baseId);this.refs[baseId]=sch}if(validateSchema)this.validateSchema(schema,true);return sch}_checkUnique(id){if(this.schemas[id]||this.refs[id]){throw new Error(`schema with key or id "${id}" already exists`)}}_compileSchemaEnv(sch){if(sch.meta)this._compileMetaSchema(sch);else compile_1.compileSchema.call(this,sch);if(!sch.validate)throw new Error("ajv implementation error");return sch.validate}_compileMetaSchema(sch){const currentOpts=this.opts;this.opts=this._metaOpts;try{compile_1.compileSchema.call(this,sch)}finally{this.opts=currentOpts}}};Ajv.ValidationError=validation_error_1.default;Ajv.MissingRefError=ref_error_1.default;exports.default=Ajv;function checkOptions(checkOpts,options,msg,log="error"){for(const key in checkOpts){const opt=key;if(opt in options)this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`)}}function getSchEnv(keyRef){keyRef=(0,resolve_1.normalizeId)(keyRef);return this.schemas[keyRef]||this.refs[keyRef]}function addInitialSchemas(){const optsSchemas=this.opts.schemas;if(!optsSchemas)return;if(Array.isArray(optsSchemas))this.addSchema(optsSchemas);else for(const key in optsSchemas)this.addSchema(optsSchemas[key],key)}function addInitialFormats(){for(const name in this.opts.formats){const format=this.opts.formats[name];if(format)this.addFormat(name,format)}}function addInitialKeywords(defs){if(Array.isArray(defs)){this.addVocabulary(defs);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const keyword in defs){const def=defs[keyword];if(!def.keyword)def.keyword=keyword;this.addKeyword(def)}}function getMetaSchemaOptions(){const metaOpts={...this.opts};for(const opt of META_IGNORE_OPTIONS)delete metaOpts[opt];return metaOpts}var noLogs={log(){},warn(){},error(){}};function getLogger(logger){if(logger===false)return noLogs;if(logger===void 0)return console;if(logger.log&&logger.warn&&logger.error)return logger;throw new Error("logger must implement log, warn and error methods")}var KEYWORD_NAME=/^[a-z_$][a-z0-9_$:-]*$/i;function checkKeyword(keyword,def){const{RULES}=this;(0,util_1.eachItem)(keyword,kwd=>{if(RULES.keywords[kwd])throw new Error(`Keyword ${kwd} is already defined`);if(!KEYWORD_NAME.test(kwd))throw new Error(`Keyword ${kwd} has invalid name`)});if(!def)return;if(def.$data&&!("code"in def||"validate"in def)){throw new Error('$data keyword must have "code" or "validate" function')}}function addRule(keyword,definition,dataType){var _a3;const post=definition===null||definition===void 0?void 0:definition.post;if(dataType&&post)throw new Error('keyword with "post" flag cannot have "type"');const{RULES}=this;let ruleGroup=post?RULES.post:RULES.rules.find(({type:t})=>t===dataType);if(!ruleGroup){ruleGroup={type:dataType,rules:[]};RULES.rules.push(ruleGroup)}RULES.keywords[keyword]=true;if(!definition)return;const rule={keyword,definition:{...definition,type:(0,dataType_1.getJSONTypes)(definition.type),schemaType:(0,dataType_1.getJSONTypes)(definition.schemaType)}};if(definition.before)addBeforeRule.call(this,ruleGroup,rule,definition.before);else ruleGroup.rules.push(rule);RULES.all[keyword]=rule;(_a3=definition.implements)===null||_a3===void 0?void 0:_a3.forEach(kwd=>this.addKeyword(kwd))}function addBeforeRule(ruleGroup,rule,before){const i=ruleGroup.rules.findIndex(_rule=>_rule.keyword===before);if(i>=0){ruleGroup.rules.splice(i,0,rule)}else{ruleGroup.rules.push(rule);this.logger.warn(`rule ${before} is not defined`)}}function keywordMetaschema(def){let{metaSchema}=def;if(metaSchema===void 0)return;if(def.$data&&this.opts.$data)metaSchema=schemaOrData(metaSchema);def.validateSchema=this.compile(metaSchema,true)}var $dataRef={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function schemaOrData(schema){return{anyOf:[schema,$dataRef]}}}});var require_id=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/id.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var def={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};exports.default=def}});var require_ref=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/ref.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.callRef=exports.getValidate=void 0;var ref_error_1=require_ref_error();var code_1=require_code2();var codegen_1=require_codegen();var names_1=require_names();var compile_1=require_compile();var util_1=require_util();var def={keyword:"$ref",schemaType:"string",code(cxt){const{gen,schema:$ref,it}=cxt;const{baseId,schemaEnv:env,validateName,opts,self}=it;const{root}=env;if(($ref==="#"||$ref==="#/")&&baseId===root.baseId)return callRootRef();const schOrEnv=compile_1.resolveRef.call(self,root,baseId,$ref);if(schOrEnv===void 0)throw new ref_error_1.default(it.opts.uriResolver,baseId,$ref);if(schOrEnv instanceof compile_1.SchemaEnv)return callValidate(schOrEnv);return inlineRefSchema(schOrEnv);function callRootRef(){if(env===root)return callRef(cxt,validateName,env,env.$async);const rootName=gen.scopeValue("root",{ref:root});return callRef(cxt,(0,codegen_1._)`${rootName}.validate`,root,root.$async)}function callValidate(sch){const v2=getValidate(cxt,sch);callRef(cxt,v2,sch,sch.$async)}function inlineRefSchema(sch){const schName=gen.scopeValue("schema",opts.code.source===true?{ref:sch,code:(0,codegen_1.stringify)(sch)}:{ref:sch});const valid=gen.name("valid");const schCxt=cxt.subschema({schema:sch,dataTypes:[],schemaPath:codegen_1.nil,topSchemaRef:schName,errSchemaPath:$ref},valid);cxt.mergeEvaluated(schCxt);cxt.ok(valid)}}};function getValidate(cxt,sch){const{gen}=cxt;return sch.validate?gen.scopeValue("validate",{ref:sch.validate}):(0,codegen_1._)`${gen.scopeValue("wrapper",{ref:sch})}.validate`}exports.getValidate=getValidate;function callRef(cxt,v2,sch,$async){const{gen,it}=cxt;const{allErrors,schemaEnv:env,opts}=it;const passCxt=opts.passContext?names_1.default.this:codegen_1.nil;if($async)callAsyncRef();else callSyncRef();function callAsyncRef(){if(!env.$async)throw new Error("async schema referenced by sync schema");const valid=gen.let("valid");gen.try(()=>{gen.code((0,codegen_1._)`await ${(0,code_1.callValidateCode)(cxt,v2,passCxt)}`);addEvaluatedFrom(v2);if(!allErrors)gen.assign(valid,true)},e=>{gen.if((0,codegen_1._)`!(${e} instanceof ${it.ValidationError})`,()=>gen.throw(e));addErrorsFrom(e);if(!allErrors)gen.assign(valid,false)});cxt.ok(valid)}function callSyncRef(){cxt.result((0,code_1.callValidateCode)(cxt,v2,passCxt),()=>addEvaluatedFrom(v2),()=>addErrorsFrom(v2))}function addErrorsFrom(source){const errs=(0,codegen_1._)`${source}.errors`;gen.assign(names_1.default.vErrors,(0,codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`);gen.assign(names_1.default.errors,(0,codegen_1._)`${names_1.default.vErrors}.length`)}function addEvaluatedFrom(source){var _a3;if(!it.opts.unevaluated)return;const schEvaluated=(_a3=sch===null||sch===void 0?void 0:sch.validate)===null||_a3===void 0?void 0:_a3.evaluated;if(it.props!==true){if(schEvaluated&&!schEvaluated.dynamicProps){if(schEvaluated.props!==void 0){it.props=util_1.mergeEvaluated.props(gen,schEvaluated.props,it.props)}}else{const props=gen.var("props",(0,codegen_1._)`${source}.evaluated.props`);it.props=util_1.mergeEvaluated.props(gen,props,it.props,codegen_1.Name)}}if(it.items!==true){if(schEvaluated&&!schEvaluated.dynamicItems){if(schEvaluated.items!==void 0){it.items=util_1.mergeEvaluated.items(gen,schEvaluated.items,it.items)}}else{const items=gen.var("items",(0,codegen_1._)`${source}.evaluated.items`);it.items=util_1.mergeEvaluated.items(gen,items,it.items,codegen_1.Name)}}}}exports.callRef=callRef;exports.default=def}});var require_core2=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var id_1=require_id();var ref_1=require_ref();var core=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",id_1.default,ref_1.default];exports.default=core}});var require_limitNumber=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var ops=codegen_1.operators;var KWDs={maximum:{okStr:"<=",ok:ops.LTE,fail:ops.GT},minimum:{okStr:">=",ok:ops.GTE,fail:ops.LT},exclusiveMaximum:{okStr:"<",ok:ops.LT,fail:ops.GTE},exclusiveMinimum:{okStr:">",ok:ops.GT,fail:ops.LTE}};var error51={message:({keyword,schemaCode})=>(0,codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`,params:({keyword,schemaCode})=>(0,codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`};var def={keyword:Object.keys(KWDs),type:"number",schemaType:"number",$data:true,error:error51,code(cxt){const{keyword,data,schemaCode}=cxt;cxt.fail$data((0,codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`)}};exports.default=def}});var require_multipleOf=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var error51={message:({schemaCode})=>(0,codegen_1.str)`must be multiple of ${schemaCode}`,params:({schemaCode})=>(0,codegen_1._)`{multipleOf: ${schemaCode}}`};var def={keyword:"multipleOf",type:"number",schemaType:"number",$data:true,error:error51,code(cxt){const{gen,data,schemaCode,it}=cxt;const prec=it.opts.multipleOfPrecision;const res=gen.let("res");const invalid=prec?(0,codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`:(0,codegen_1._)`${res} !== parseInt(${res})`;cxt.fail$data((0,codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`)}};exports.default=def}});var require_ucs2length=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/ucs2length.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});function ucs2length(str2){const len=str2.length;let length=0;let pos=0;let value;while(pos<len){length++;value=str2.charCodeAt(pos++);if(value>=55296&&value<=56319&&pos<len){value=str2.charCodeAt(pos);if((value&64512)===56320)pos++}}return length}exports.default=ucs2length;ucs2length.code='require("ajv/dist/runtime/ucs2length").default'}});var require_limitLength=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var ucs2length_1=require_ucs2length();var error51={message({keyword,schemaCode}){const comp=keyword==="maxLength"?"more":"fewer";return(0,codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`},params:({schemaCode})=>(0,codegen_1._)`{limit: ${schemaCode}}`};var def={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:true,error:error51,code(cxt){const{keyword,data,schemaCode,it}=cxt;const op=keyword==="maxLength"?codegen_1.operators.GT:codegen_1.operators.LT;const len=it.opts.unicode===false?(0,codegen_1._)`${data}.length`:(0,codegen_1._)`${(0,util_1.useFunc)(cxt.gen,ucs2length_1.default)}(${data})`;cxt.fail$data((0,codegen_1._)`${len} ${op} ${schemaCode}`)}};exports.default=def}});var require_pattern=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var code_1=require_code2();var util_1=require_util();var codegen_1=require_codegen();var error51={message:({schemaCode})=>(0,codegen_1.str)`must match pattern "${schemaCode}"`,params:({schemaCode})=>(0,codegen_1._)`{pattern: ${schemaCode}}`};var def={keyword:"pattern",type:"string",schemaType:"string",$data:true,error:error51,code(cxt){const{gen,data,$data,schema,schemaCode,it}=cxt;const u=it.opts.unicodeRegExp?"u":"";if($data){const{regExp}=it.opts.code;const regExpCode=regExp.code==="new RegExp"?(0,codegen_1._)`new RegExp`:(0,util_1.useFunc)(gen,regExp);const valid=gen.let("valid");gen.try(()=>gen.assign(valid,(0,codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`),()=>gen.assign(valid,false));cxt.fail$data((0,codegen_1._)`!${valid}`)}else{const regExp=(0,code_1.usePattern)(cxt,schema);cxt.fail$data((0,codegen_1._)`!${regExp}.test(${data})`)}}};exports.default=def}});var require_limitProperties=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var error51={message({keyword,schemaCode}){const comp=keyword==="maxProperties"?"more":"fewer";return(0,codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`},params:({schemaCode})=>(0,codegen_1._)`{limit: ${schemaCode}}`};var def={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:true,error:error51,code(cxt){const{keyword,data,schemaCode}=cxt;const op=keyword==="maxProperties"?codegen_1.operators.GT:codegen_1.operators.LT;cxt.fail$data((0,codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`)}};exports.default=def}});var require_required=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/required.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var code_1=require_code2();var codegen_1=require_codegen();var util_1=require_util();var error51={message:({params:{missingProperty}})=>(0,codegen_1.str)`must have required property '${missingProperty}'`,params:({params:{missingProperty}})=>(0,codegen_1._)`{missingProperty: ${missingProperty}}`};var def={keyword:"required",type:"object",schemaType:"array",$data:true,error:error51,code(cxt){const{gen,schema,schemaCode,data,$data,it}=cxt;const{opts}=it;if(!$data&&schema.length===0)return;const useLoop=schema.length>=opts.loopRequired;if(it.allErrors)allErrorsMode();else exitOnErrorMode();if(opts.strictRequired){const props=cxt.parentSchema.properties;const{definedProperties}=cxt.it;for(const requiredKey of schema){if((props===null||props===void 0?void 0:props[requiredKey])===void 0&&!definedProperties.has(requiredKey)){const schemaPath=it.schemaEnv.baseId+it.errSchemaPath;const msg=`required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;(0,util_1.checkStrictMode)(it,msg,it.opts.strictRequired)}}}function allErrorsMode(){if(useLoop||$data){cxt.block$data(codegen_1.nil,loopAllRequired)}else{for(const prop of schema){(0,code_1.checkReportMissingProp)(cxt,prop)}}}function exitOnErrorMode(){const missing=gen.let("missing");if(useLoop||$data){const valid=gen.let("valid",true);cxt.block$data(valid,()=>loopUntilMissing(missing,valid));cxt.ok(valid)}else{gen.if((0,code_1.checkMissingProp)(cxt,schema,missing));(0,code_1.reportMissingProp)(cxt,missing);gen.else()}}function loopAllRequired(){gen.forOf("prop",schemaCode,prop=>{cxt.setParams({missingProperty:prop});gen.if((0,code_1.noPropertyInData)(gen,data,prop,opts.ownProperties),()=>cxt.error())})}function loopUntilMissing(missing,valid){cxt.setParams({missingProperty:missing});gen.forOf(missing,schemaCode,()=>{gen.assign(valid,(0,code_1.propertyInData)(gen,data,missing,opts.ownProperties));gen.if((0,codegen_1.not)(valid),()=>{cxt.error();gen.break()})},codegen_1.nil)}}};exports.default=def}});var require_limitItems=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var error51={message({keyword,schemaCode}){const comp=keyword==="maxItems"?"more":"fewer";return(0,codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`},params:({schemaCode})=>(0,codegen_1._)`{limit: ${schemaCode}}`};var def={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:true,error:error51,code(cxt){const{keyword,data,schemaCode}=cxt;const op=keyword==="maxItems"?codegen_1.operators.GT:codegen_1.operators.LT;cxt.fail$data((0,codegen_1._)`${data}.length ${op} ${schemaCode}`)}};exports.default=def}});var require_equal=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/equal.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var equal=require_fast_deep_equal();equal.code='require("ajv/dist/runtime/equal").default';exports.default=equal}});var require_uniqueItems=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var dataType_1=require_dataType();var codegen_1=require_codegen();var util_1=require_util();var equal_1=require_equal();var error51={message:({params:{i,j:j2}})=>(0,codegen_1.str)`must NOT have duplicate items (items ## ${j2} and ${i} are identical)`,params:({params:{i,j:j2}})=>(0,codegen_1._)`{i: ${i}, j: ${j2}}`};var def={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:true,error:error51,code(cxt){const{gen,data,$data,schema,parentSchema,schemaCode,it}=cxt;if(!$data&&!schema)return;const valid=gen.let("valid");const itemTypes=parentSchema.items?(0,dataType_1.getSchemaTypes)(parentSchema.items):[];cxt.block$data(valid,validateUniqueItems,(0,codegen_1._)`${schemaCode} === false`);cxt.ok(valid);function validateUniqueItems(){const i=gen.let("i",(0,codegen_1._)`${data}.length`);const j2=gen.let("j");cxt.setParams({i,j:j2});gen.assign(valid,true);gen.if((0,codegen_1._)`${i} > 1`,()=>(canOptimize()?loopN:loopN2)(i,j2))}function canOptimize(){return itemTypes.length>0&&!itemTypes.some(t=>t==="object"||t==="array")}function loopN(i,j2){const item=gen.name("item");const wrongType=(0,dataType_1.checkDataTypes)(itemTypes,item,it.opts.strictNumbers,dataType_1.DataType.Wrong);const indices=gen.const("indices",(0,codegen_1._)`{}`);gen.for((0,codegen_1._)`;${i}--;`,()=>{gen.let(item,(0,codegen_1._)`${data}[${i}]`);gen.if(wrongType,(0,codegen_1._)`continue`);if(itemTypes.length>1)gen.if((0,codegen_1._)`typeof ${item} == "string"`,(0,codegen_1._)`${item} += "_"`);gen.if((0,codegen_1._)`typeof ${indices}[${item}] == "number"`,()=>{gen.assign(j2,(0,codegen_1._)`${indices}[${item}]`);cxt.error();gen.assign(valid,false).break()}).code((0,codegen_1._)`${indices}[${item}] = ${i}`)})}function loopN2(i,j2){const eql=(0,util_1.useFunc)(gen,equal_1.default);const outer=gen.name("outer");gen.label(outer).for((0,codegen_1._)`;${i}--;`,()=>gen.for((0,codegen_1._)`${j2} = ${i}; ${j2}--;`,()=>gen.if((0,codegen_1._)`${eql}(${data}[${i}], ${data}[${j2}])`,()=>{cxt.error();gen.assign(valid,false).break(outer)})))}}};exports.default=def}});var require_const=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/const.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var equal_1=require_equal();var error51={message:"must be equal to constant",params:({schemaCode})=>(0,codegen_1._)`{allowedValue: ${schemaCode}}`};var def={keyword:"const",$data:true,error:error51,code(cxt){const{gen,data,$data,schemaCode,schema}=cxt;if($data||schema&&typeof schema=="object"){cxt.fail$data((0,codegen_1._)`!${(0,util_1.useFunc)(gen,equal_1.default)}(${data}, ${schemaCode})`)}else{cxt.fail((0,codegen_1._)`${schema} !== ${data}`)}}};exports.default=def}});var require_enum=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var equal_1=require_equal();var error51={message:"must be equal to one of the allowed values",params:({schemaCode})=>(0,codegen_1._)`{allowedValues: ${schemaCode}}`};var def={keyword:"enum",schemaType:"array",$data:true,error:error51,code(cxt){const{gen,data,$data,schema,schemaCode,it}=cxt;if(!$data&&schema.length===0)throw new Error("enum must have non-empty array");const useLoop=schema.length>=it.opts.loopEnum;let eql;const getEql=()=>eql!==null&&eql!==void 0?eql:eql=(0,util_1.useFunc)(gen,equal_1.default);let valid;if(useLoop||$data){valid=gen.let("valid");cxt.block$data(valid,loopEnum)}else{if(!Array.isArray(schema))throw new Error("ajv implementation error");const vSchema=gen.const("vSchema",schemaCode);valid=(0,codegen_1.or)(...schema.map((_x,i)=>equalCode(vSchema,i)))}cxt.pass(valid);function loopEnum(){gen.assign(valid,false);gen.forOf("v",schemaCode,v2=>gen.if((0,codegen_1._)`${getEql()}(${data}, ${v2})`,()=>gen.assign(valid,true).break()))}function equalCode(vSchema,i){const sch=schema[i];return typeof sch==="object"&&sch!==null?(0,codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])`:(0,codegen_1._)`${data} === ${sch}`}}};exports.default=def}});var require_validation=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var limitNumber_1=require_limitNumber();var multipleOf_1=require_multipleOf();var limitLength_1=require_limitLength();var pattern_1=require_pattern();var limitProperties_1=require_limitProperties();var required_1=require_required();var limitItems_1=require_limitItems();var uniqueItems_1=require_uniqueItems();var const_1=require_const();var enum_1=require_enum();var validation=[limitNumber_1.default,multipleOf_1.default,limitLength_1.default,pattern_1.default,limitProperties_1.default,required_1.default,limitItems_1.default,uniqueItems_1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},const_1.default,enum_1.default];exports.default=validation}});var require_additionalItems=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.validateAdditionalItems=void 0;var codegen_1=require_codegen();var util_1=require_util();var error51={message:({params:{len}})=>(0,codegen_1.str)`must NOT have more than ${len} items`,params:({params:{len}})=>(0,codegen_1._)`{limit: ${len}}`};var def={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:error51,code(cxt){const{parentSchema,it}=cxt;const{items}=parentSchema;if(!Array.isArray(items)){(0,util_1.checkStrictMode)(it,'"additionalItems" is ignored when "items" is not an array of schemas');return}validateAdditionalItems(cxt,items)}};function validateAdditionalItems(cxt,items){const{gen,schema,data,keyword,it}=cxt;it.items=true;const len=gen.const("len",(0,codegen_1._)`${data}.length`);if(schema===false){cxt.setParams({len:items.length});cxt.pass((0,codegen_1._)`${len} <= ${items.length}`)}else if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it,schema)){const valid=gen.var("valid",(0,codegen_1._)`${len} <= ${items.length}`);gen.if((0,codegen_1.not)(valid),()=>validateItems(valid));cxt.ok(valid)}function validateItems(valid){gen.forRange("i",items.length,len,i=>{cxt.subschema({keyword,dataProp:i,dataPropType:util_1.Type.Num},valid);if(!it.allErrors)gen.if((0,codegen_1.not)(valid),()=>gen.break())})}}exports.validateAdditionalItems=validateAdditionalItems;exports.default=def}});var require_items=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.validateTuple=void 0;var codegen_1=require_codegen();var util_1=require_util();var code_1=require_code2();var def={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(cxt){const{schema,it}=cxt;if(Array.isArray(schema))return validateTuple(cxt,"additionalItems",schema);it.items=true;if((0,util_1.alwaysValidSchema)(it,schema))return;cxt.ok((0,code_1.validateArray)(cxt))}};function validateTuple(cxt,extraItems,schArr=cxt.schema){const{gen,parentSchema,data,keyword,it}=cxt;checkStrictTuple(parentSchema);if(it.opts.unevaluated&&schArr.length&&it.items!==true){it.items=util_1.mergeEvaluated.items(gen,schArr.length,it.items)}const valid=gen.name("valid");const len=gen.const("len",(0,codegen_1._)`${data}.length`);schArr.forEach((sch,i)=>{if((0,util_1.alwaysValidSchema)(it,sch))return;gen.if((0,codegen_1._)`${len} > ${i}`,()=>cxt.subschema({keyword,schemaProp:i,dataProp:i},valid));cxt.ok(valid)});function checkStrictTuple(sch){const{opts,errSchemaPath}=it;const l3=schArr.length;const fullTuple=l3===sch.minItems&&(l3===sch.maxItems||sch[extraItems]===false);if(opts.strictTuples&&!fullTuple){const msg=`"${keyword}" is ${l3}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;(0,util_1.checkStrictMode)(it,msg,opts.strictTuples)}}}exports.validateTuple=validateTuple;exports.default=def}});var require_prefixItems=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var items_1=require_items();var def={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:cxt=>(0,items_1.validateTuple)(cxt,"items")};exports.default=def}});var require_items2020=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var code_1=require_code2();var additionalItems_1=require_additionalItems();var error51={message:({params:{len}})=>(0,codegen_1.str)`must NOT have more than ${len} items`,params:({params:{len}})=>(0,codegen_1._)`{limit: ${len}}`};var def={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:error51,code(cxt){const{schema,parentSchema,it}=cxt;const{prefixItems}=parentSchema;it.items=true;if((0,util_1.alwaysValidSchema)(it,schema))return;if(prefixItems)(0,additionalItems_1.validateAdditionalItems)(cxt,prefixItems);else cxt.ok((0,code_1.validateArray)(cxt))}};exports.default=def}});var require_contains=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var error51={message:({params:{min,max}})=>max===void 0?(0,codegen_1.str)`must contain at least ${min} valid item(s)`:(0,codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`,params:({params:{min,max}})=>max===void 0?(0,codegen_1._)`{minContains: ${min}}`:(0,codegen_1._)`{minContains: ${min}, maxContains: ${max}}`};var def={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:true,error:error51,code(cxt){const{gen,schema,parentSchema,data,it}=cxt;let min;let max;const{minContains,maxContains}=parentSchema;if(it.opts.next){min=minContains===void 0?1:minContains;max=maxContains}else{min=1}const len=gen.const("len",(0,codegen_1._)`${data}.length`);cxt.setParams({min,max});if(max===void 0&&min===0){(0,util_1.checkStrictMode)(it,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(max!==void 0&&min>max){(0,util_1.checkStrictMode)(it,`"minContains" > "maxContains" is always invalid`);cxt.fail();return}if((0,util_1.alwaysValidSchema)(it,schema)){let cond=(0,codegen_1._)`${len} >= ${min}`;if(max!==void 0)cond=(0,codegen_1._)`${cond} && ${len} <= ${max}`;cxt.pass(cond);return}it.items=true;const valid=gen.name("valid");if(max===void 0&&min===1){validateItems(valid,()=>gen.if(valid,()=>gen.break()))}else if(min===0){gen.let(valid,true);if(max!==void 0)gen.if((0,codegen_1._)`${data}.length > 0`,validateItemsWithCount)}else{gen.let(valid,false);validateItemsWithCount()}cxt.result(valid,()=>cxt.reset());function validateItemsWithCount(){const schValid=gen.name("_valid");const count=gen.let("count",0);validateItems(schValid,()=>gen.if(schValid,()=>checkLimits(count)))}function validateItems(_valid,block){gen.forRange("i",0,len,i=>{cxt.subschema({keyword:"contains",dataProp:i,dataPropType:util_1.Type.Num,compositeRule:true},_valid);block()})}function checkLimits(count){gen.code((0,codegen_1._)`${count}++`);if(max===void 0){gen.if((0,codegen_1._)`${count} >= ${min}`,()=>gen.assign(valid,true).break())}else{gen.if((0,codegen_1._)`${count} > ${max}`,()=>gen.assign(valid,false).break());if(min===1)gen.assign(valid,true);else gen.if((0,codegen_1._)`${count} >= ${min}`,()=>gen.assign(valid,true))}}}};exports.default=def}});var require_dependencies=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.validateSchemaDeps=exports.validatePropertyDeps=exports.error=void 0;var codegen_1=require_codegen();var util_1=require_util();var code_1=require_code2();exports.error={message:({params:{property,depsCount,deps}})=>{const property_ies=depsCount===1?"property":"properties";return(0,codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`},params:({params:{property,depsCount,deps,missingProperty}})=>(0,codegen_1._)`{property: ${property},
|
|
66
66
|
missingProperty: ${missingProperty},
|
|
67
67
|
depsCount: ${depsCount},
|
|
68
|
-
deps: ${deps}}`};var def={keyword:"dependencies",type:"object",schemaType:"object",error:exports.error,code(cxt){const[propDeps,schDeps]=splitDependencies(cxt);validatePropertyDeps(cxt,propDeps);validateSchemaDeps(cxt,schDeps)}};function splitDependencies({schema}){const propertyDeps={};const schemaDeps={};for(const key in schema){if(key==="__proto__")continue;const deps=Array.isArray(schema[key])?propertyDeps:schemaDeps;deps[key]=schema[key]}return[propertyDeps,schemaDeps]}function validatePropertyDeps(cxt,propertyDeps=cxt.schema){const{gen,data,it}=cxt;if(Object.keys(propertyDeps).length===0)return;const missing=gen.let("missing");for(const prop in propertyDeps){const deps=propertyDeps[prop];if(deps.length===0)continue;const hasProperty=(0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties);cxt.setParams({property:prop,depsCount:deps.length,deps:deps.join(", ")});if(it.allErrors){gen.if(hasProperty,()=>{for(const depProp of deps){(0,code_1.checkReportMissingProp)(cxt,depProp)}})}else{gen.if((0,codegen_1._)`${hasProperty} && (${(0,code_1.checkMissingProp)(cxt,deps,missing)})`);(0,code_1.reportMissingProp)(cxt,missing);gen.else()}}}exports.validatePropertyDeps=validatePropertyDeps;function validateSchemaDeps(cxt,schemaDeps=cxt.schema){const{gen,data,keyword,it}=cxt;const valid=gen.name("valid");for(const prop in schemaDeps){if((0,util_1.alwaysValidSchema)(it,schemaDeps[prop]))continue;gen.if((0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties),()=>{const schCxt=cxt.subschema({keyword,schemaProp:prop},valid);cxt.mergeValidEvaluated(schCxt,valid)},()=>gen.var(valid,true));cxt.ok(valid)}}exports.validateSchemaDeps=validateSchemaDeps;exports.default=def}});var require_propertyNames=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var error51={message:"property name must be valid",params:({params})=>(0,codegen_1._)`{propertyName: ${params.propertyName}}`};var def={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:error51,code(cxt){const{gen,schema,data,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema))return;const valid=gen.name("valid");gen.forIn("key",data,key=>{cxt.setParams({propertyName:key});cxt.subschema({keyword:"propertyNames",data:key,dataTypes:["string"],propertyName:key,compositeRule:true},valid);gen.if((0,codegen_1.not)(valid),()=>{cxt.error(true);if(!it.allErrors)gen.break()})});cxt.ok(valid)}};exports.default=def}});var require_additionalProperties=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var code_1=require_code2();var codegen_1=require_codegen();var names_1=require_names();var util_1=require_util();var error51={message:"must NOT have additional properties",params:({params})=>(0,codegen_1._)`{additionalProperty: ${params.additionalProperty}}`};var def={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:true,trackErrors:true,error:error51,code(cxt){const{gen,schema,parentSchema,data,errsCount,it}=cxt;if(!errsCount)throw new Error("ajv implementation error");const{allErrors,opts}=it;it.props=true;if(opts.removeAdditional!=="all"&&(0,util_1.alwaysValidSchema)(it,schema))return;const props=(0,code_1.allSchemaProperties)(parentSchema.properties);const patProps=(0,code_1.allSchemaProperties)(parentSchema.patternProperties);checkAdditionalProperties();cxt.ok((0,codegen_1._)`${errsCount} === ${names_1.default.errors}`);function checkAdditionalProperties(){gen.forIn("key",data,key=>{if(!props.length&&!patProps.length)additionalPropertyCode(key);else gen.if(isAdditional(key),()=>additionalPropertyCode(key))})}function isAdditional(key){let definedProp;if(props.length>8){const propsSchema=(0,util_1.schemaRefOrVal)(it,parentSchema.properties,"properties");definedProp=(0,code_1.isOwnProperty)(gen,propsSchema,key)}else if(props.length){definedProp=(0,codegen_1.or)(...props.map(p=>(0,codegen_1._)`${key} === ${p}`))}else{definedProp=codegen_1.nil}if(patProps.length){definedProp=(0,codegen_1.or)(definedProp,...patProps.map(p=>(0,codegen_1._)`${(0,code_1.usePattern)(cxt,p)}.test(${key})`))}return(0,codegen_1.not)(definedProp)}function deleteAdditional(key){gen.code((0,codegen_1._)`delete ${data}[${key}]`)}function additionalPropertyCode(key){if(opts.removeAdditional==="all"||opts.removeAdditional&&schema===false){deleteAdditional(key);return}if(schema===false){cxt.setParams({additionalProperty:key});cxt.error();if(!allErrors)gen.break();return}if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it,schema)){const valid=gen.name("valid");if(opts.removeAdditional==="failing"){applyAdditionalSchema(key,valid,false);gen.if((0,codegen_1.not)(valid),()=>{cxt.reset();deleteAdditional(key)})}else{applyAdditionalSchema(key,valid);if(!allErrors)gen.if((0,codegen_1.not)(valid),()=>gen.break())}}}function applyAdditionalSchema(key,valid,errors){const subschema={keyword:"additionalProperties",dataProp:key,dataPropType:util_1.Type.Str};if(errors===false){Object.assign(subschema,{compositeRule:true,createErrors:false,allErrors:false})}cxt.subschema(subschema,valid)}}};exports.default=def}});var require_properties=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var validate_1=require_validate();var code_1=require_code2();var util_1=require_util();var additionalProperties_1=require_additionalProperties();var def={keyword:"properties",type:"object",schemaType:"object",code(cxt){const{gen,schema,parentSchema,data,it}=cxt;if(it.opts.removeAdditional==="all"&&parentSchema.additionalProperties===void 0){additionalProperties_1.default.code(new validate_1.KeywordCxt(it,additionalProperties_1.default,"additionalProperties"))}const allProps=(0,code_1.allSchemaProperties)(schema);for(const prop of allProps){it.definedProperties.add(prop)}if(it.opts.unevaluated&&allProps.length&&it.props!==true){it.props=util_1.mergeEvaluated.props(gen,(0,util_1.toHash)(allProps),it.props)}const properties=allProps.filter(p=>!(0,util_1.alwaysValidSchema)(it,schema[p]));if(properties.length===0)return;const valid=gen.name("valid");for(const prop of properties){if(hasDefault(prop)){applyPropertySchema(prop)}else{gen.if((0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties));applyPropertySchema(prop);if(!it.allErrors)gen.else().var(valid,true);gen.endIf()}cxt.it.definedProperties.add(prop);cxt.ok(valid)}function hasDefault(prop){return it.opts.useDefaults&&!it.compositeRule&&schema[prop].default!==void 0}function applyPropertySchema(prop){cxt.subschema({keyword:"properties",schemaProp:prop,dataProp:prop},valid)}}};exports.default=def}});var require_patternProperties=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var code_1=require_code2();var codegen_1=require_codegen();var util_1=require_util();var util_2=require_util();var def={keyword:"patternProperties",type:"object",schemaType:"object",code(cxt){const{gen,schema,data,parentSchema,it}=cxt;const{opts}=it;const patterns=(0,code_1.allSchemaProperties)(schema);const alwaysValidPatterns=patterns.filter(p=>(0,util_1.alwaysValidSchema)(it,schema[p]));if(patterns.length===0||alwaysValidPatterns.length===patterns.length&&(!it.opts.unevaluated||it.props===true)){return}const checkProperties=opts.strictSchema&&!opts.allowMatchingProperties&&parentSchema.properties;const valid=gen.name("valid");if(it.props!==true&&!(it.props instanceof codegen_1.Name)){it.props=(0,util_2.evaluatedPropsToName)(gen,it.props)}const{props}=it;validatePatternProperties();function validatePatternProperties(){for(const pat of patterns){if(checkProperties)checkMatchingProperties(pat);if(it.allErrors){validateProperties(pat)}else{gen.var(valid,true);validateProperties(pat);gen.if(valid)}}}function checkMatchingProperties(pat){for(const prop in checkProperties){if(new RegExp(pat).test(prop)){(0,util_1.checkStrictMode)(it,`property ${prop} matches pattern ${pat} (use allowMatchingProperties)`)}}}function validateProperties(pat){gen.forIn("key",data,key=>{gen.if((0,codegen_1._)`${(0,code_1.usePattern)(cxt,pat)}.test(${key})`,()=>{const alwaysValid=alwaysValidPatterns.includes(pat);if(!alwaysValid){cxt.subschema({keyword:"patternProperties",schemaProp:pat,dataProp:key,dataPropType:util_2.Type.Str},valid)}if(it.opts.unevaluated&&props!==true){gen.assign((0,codegen_1._)`${props}[${key}]`,true)}else if(!alwaysValid&&!it.allErrors){gen.if((0,codegen_1.not)(valid),()=>gen.break())}})})}}};exports.default=def}});var require_not=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var util_1=require_util();var def={keyword:"not",schemaType:["object","boolean"],trackErrors:true,code(cxt){const{gen,schema,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema)){cxt.fail();return}const valid=gen.name("valid");cxt.subschema({keyword:"not",compositeRule:true,createErrors:false,allErrors:false},valid);cxt.failResult(valid,()=>cxt.reset(),()=>cxt.error())},error:{message:"must NOT be valid"}};exports.default=def}});var require_anyOf=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var code_1=require_code2();var def={keyword:"anyOf",schemaType:"array",trackErrors:true,code:code_1.validateUnion,error:{message:"must match a schema in anyOf"}};exports.default=def}});var require_oneOf=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var error51={message:"must match exactly one schema in oneOf",params:({params})=>(0,codegen_1._)`{passingSchemas: ${params.passing}}`};var def={keyword:"oneOf",schemaType:"array",trackErrors:true,error:error51,code(cxt){const{gen,schema,parentSchema,it}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");if(it.opts.discriminator&&parentSchema.discriminator)return;const schArr=schema;const valid=gen.let("valid",false);const passing=gen.let("passing",null);const schValid=gen.name("_valid");cxt.setParams({passing});gen.block(validateOneOf);cxt.result(valid,()=>cxt.reset(),()=>cxt.error(true));function validateOneOf(){schArr.forEach((sch,i)=>{let schCxt;if((0,util_1.alwaysValidSchema)(it,sch)){gen.var(schValid,true)}else{schCxt=cxt.subschema({keyword:"oneOf",schemaProp:i,compositeRule:true},schValid)}if(i>0){gen.if((0,codegen_1._)`${schValid} && ${valid}`).assign(valid,false).assign(passing,(0,codegen_1._)`[${passing}, ${i}]`).else()}gen.if(schValid,()=>{gen.assign(valid,true);gen.assign(passing,i);if(schCxt)cxt.mergeEvaluated(schCxt,codegen_1.Name)})})}}};exports.default=def}});var require_allOf=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var util_1=require_util();var def={keyword:"allOf",schemaType:"array",code(cxt){const{gen,schema,it}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");const valid=gen.name("valid");schema.forEach((sch,i)=>{if((0,util_1.alwaysValidSchema)(it,sch))return;const schCxt=cxt.subschema({keyword:"allOf",schemaProp:i},valid);cxt.ok(valid);cxt.mergeEvaluated(schCxt)})}};exports.default=def}});var require_if=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var error51={message:({params})=>(0,codegen_1.str)`must match "${params.ifClause}" schema`,params:({params})=>(0,codegen_1._)`{failingKeyword: ${params.ifClause}}`};var def={keyword:"if",schemaType:["object","boolean"],trackErrors:true,error:error51,code(cxt){const{gen,parentSchema,it}=cxt;if(parentSchema.then===void 0&&parentSchema.else===void 0){(0,util_1.checkStrictMode)(it,'"if" without "then" and "else" is ignored')}const hasThen=hasSchema(it,"then");const hasElse=hasSchema(it,"else");if(!hasThen&&!hasElse)return;const valid=gen.let("valid",true);const schValid=gen.name("_valid");validateIf();cxt.reset();if(hasThen&&hasElse){const ifClause=gen.let("ifClause");cxt.setParams({ifClause});gen.if(schValid,validateClause("then",ifClause),validateClause("else",ifClause))}else if(hasThen){gen.if(schValid,validateClause("then"))}else{gen.if((0,codegen_1.not)(schValid),validateClause("else"))}cxt.pass(valid,()=>cxt.error(true));function validateIf(){const schCxt=cxt.subschema({keyword:"if",compositeRule:true,createErrors:false,allErrors:false},schValid);cxt.mergeEvaluated(schCxt)}function validateClause(keyword,ifClause){return()=>{const schCxt=cxt.subschema({keyword},schValid);gen.assign(valid,schValid);cxt.mergeValidEvaluated(schCxt,valid);if(ifClause)gen.assign(ifClause,(0,codegen_1._)`${keyword}`);else cxt.setParams({ifClause:keyword})}}}};function hasSchema(it,keyword){const schema=it.schema[keyword];return schema!==void 0&&!(0,util_1.alwaysValidSchema)(it,schema)}exports.default=def}});var require_thenElse=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var util_1=require_util();var def={keyword:["then","else"],schemaType:["object","boolean"],code({keyword,parentSchema,it}){if(parentSchema.if===void 0)(0,util_1.checkStrictMode)(it,`"${keyword}" without "if" is ignored`)}};exports.default=def}});var require_applicator=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var additionalItems_1=require_additionalItems();var prefixItems_1=require_prefixItems();var items_1=require_items();var items2020_1=require_items2020();var contains_1=require_contains();var dependencies_1=require_dependencies();var propertyNames_1=require_propertyNames();var additionalProperties_1=require_additionalProperties();var properties_1=require_properties();var patternProperties_1=require_patternProperties();var not_1=require_not();var anyOf_1=require_anyOf();var oneOf_1=require_oneOf();var allOf_1=require_allOf();var if_1=require_if();var thenElse_1=require_thenElse();function getApplicator(draft2020=false){const applicator=[not_1.default,anyOf_1.default,oneOf_1.default,allOf_1.default,if_1.default,thenElse_1.default,propertyNames_1.default,additionalProperties_1.default,dependencies_1.default,properties_1.default,patternProperties_1.default];if(draft2020)applicator.push(prefixItems_1.default,items2020_1.default);else applicator.push(additionalItems_1.default,items_1.default);applicator.push(contains_1.default);return applicator}exports.default=getApplicator}});var require_format=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/format.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var error51={message:({schemaCode})=>(0,codegen_1.str)`must match format "${schemaCode}"`,params:({schemaCode})=>(0,codegen_1._)`{format: ${schemaCode}}`};var def={keyword:"format",type:["number","string"],schemaType:"string",$data:true,error:error51,code(cxt,ruleType){const{gen,data,$data,schema,schemaCode,it}=cxt;const{opts,errSchemaPath,schemaEnv,self}=it;if(!opts.validateFormats)return;if($data)validate$DataFormat();else validateFormat();function validate$DataFormat(){const fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats});const fDef=gen.const("fDef",(0,codegen_1._)`${fmts}[${schemaCode}]`);const fType=gen.let("fType");const format=gen.let("format");gen.if((0,codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`,()=>gen.assign(fType,(0,codegen_1._)`${fDef}.type || "string"`).assign(format,(0,codegen_1._)`${fDef}.validate`),()=>gen.assign(fType,(0,codegen_1._)`"string"`).assign(format,fDef));cxt.fail$data((0,codegen_1.or)(unknownFmt(),invalidFmt()));function unknownFmt(){if(opts.strictSchema===false)return codegen_1.nil;return(0,codegen_1._)`${schemaCode} && !${format}`}function invalidFmt(){const callFormat=schemaEnv.$async?(0,codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`:(0,codegen_1._)`${format}(${data})`;const validData=(0,codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;return(0,codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`}}function validateFormat(){const formatDef=self.formats[schema];if(!formatDef){unknownFormat();return}if(formatDef===true)return;const[fmtType,format,fmtRef]=getFormat(formatDef);if(fmtType===ruleType)cxt.pass(validCondition());function unknownFormat(){if(opts.strictSchema===false){self.logger.warn(unknownMsg());return}throw new Error(unknownMsg());function unknownMsg(){return`unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`}}function getFormat(fmtDef){const code=fmtDef instanceof RegExp?(0,codegen_1.regexpCode)(fmtDef):opts.code.formats?(0,codegen_1._)`${opts.code.formats}${(0,codegen_1.getProperty)(schema)}`:void 0;const fmt=gen.scopeValue("formats",{key:schema,ref:fmtDef,code});if(typeof fmtDef=="object"&&!(fmtDef instanceof RegExp)){return[fmtDef.type||"string",fmtDef.validate,(0,codegen_1._)`${fmt}.validate`]}return["string",fmtDef,fmt]}function validCondition(){if(typeof formatDef=="object"&&!(formatDef instanceof RegExp)&&formatDef.async){if(!schemaEnv.$async)throw new Error("async format in sync schema");return(0,codegen_1._)`await ${fmtRef}(${data})`}return typeof format=="function"?(0,codegen_1._)`${fmtRef}(${data})`:(0,codegen_1._)`${fmtRef}.test(${data})`}}}};exports.default=def}});var require_format2=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var format_1=require_format();var format=[format_1.default];exports.default=format}});var require_metadata=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/metadata.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.contentVocabulary=exports.metadataVocabulary=void 0;exports.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];exports.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]}});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_core2();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_types=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DiscrError=void 0;var DiscrError;(function(DiscrError2){DiscrError2["Tag"]="tag";DiscrError2["Mapping"]="mapping"})(DiscrError||(exports.DiscrError=DiscrError={}))}});var require_discriminator=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var types_1=require_types();var compile_1=require_compile();var ref_error_1=require_ref_error();var util_1=require_util();var error51={message:({params:{discrError,tagName}})=>discrError===types_1.DiscrError.Tag?`tag "${tagName}" must be string`:`value of tag "${tagName}" must be in oneOf`,params:({params:{discrError,tag,tagName}})=>(0,codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`};var def={keyword:"discriminator",type:"object",schemaType:"object",error:error51,code(cxt){const{gen,data,schema,parentSchema,it}=cxt;const{oneOf}=parentSchema;if(!it.opts.discriminator){throw new Error("discriminator: requires discriminator option")}const tagName=schema.propertyName;if(typeof tagName!="string")throw new Error("discriminator: requires propertyName");if(schema.mapping)throw new Error("discriminator: mapping is not supported");if(!oneOf)throw new Error("discriminator: requires oneOf keyword");const valid=gen.let("valid",false);const tag=gen.const("tag",(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(tagName)}`);gen.if((0,codegen_1._)`typeof ${tag} == "string"`,()=>validateMapping(),()=>cxt.error(false,{discrError:types_1.DiscrError.Tag,tag,tagName}));cxt.ok(valid);function validateMapping(){const mapping=getMapping();gen.if(false);for(const tagValue in mapping){gen.elseIf((0,codegen_1._)`${tag} === ${tagValue}`);gen.assign(valid,applyTagSchema(mapping[tagValue]))}gen.else();cxt.error(false,{discrError:types_1.DiscrError.Mapping,tag,tagName});gen.endIf()}function applyTagSchema(schemaProp){const _valid=gen.name("valid");const schCxt=cxt.subschema({keyword:"oneOf",schemaProp},_valid);cxt.mergeEvaluated(schCxt,codegen_1.Name);return _valid}function getMapping(){var _a3;const oneOfMapping={};const topRequired=hasRequired(parentSchema);let tagRequired=true;for(let i=0;i<oneOf.length;i++){let sch=oneOf[i];if((sch===null||sch===void 0?void 0:sch.$ref)&&!(0,util_1.schemaHasRulesButRef)(sch,it.self.RULES)){const ref=sch.$ref;sch=compile_1.resolveRef.call(it.self,it.schemaEnv.root,it.baseId,ref);if(sch instanceof compile_1.SchemaEnv)sch=sch.schema;if(sch===void 0)throw new ref_error_1.default(it.opts.uriResolver,it.baseId,ref)}const propSch=(_a3=sch===null||sch===void 0?void 0:sch.properties)===null||_a3===void 0?void 0:_a3[tagName];if(typeof propSch!="object"){throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`)}tagRequired=tagRequired&&(topRequired||hasRequired(sch));addMappings(propSch,i)}if(!tagRequired)throw new Error(`discriminator: "${tagName}" must be required`);return oneOfMapping;function hasRequired({required:required2}){return Array.isArray(required2)&&required2.includes(tagName)}function addMappings(sch,i){if(sch.const){addMapping(sch.const,i)}else if(sch.enum){for(const tagValue of sch.enum){addMapping(tagValue,i)}}else{throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`)}}function addMapping(tagValue,i){if(typeof tagValue!="string"||tagValue in oneOfMapping){throw new Error(`discriminator: "${tagName}" values must be unique strings`)}oneOfMapping[tagValue]=i}}}};exports.default=def}});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,module){module.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,module){"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_core();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(v2=>this.addVocabulary(v2));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;module.exports=exports=Ajv;module.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}=it;if(!opts.validateFormats)return;const fCxt=new ajv_1.KeywordCxt(it,self.RULES.all.format.definition,"format");if(fCxt.$data)validate$DataFormat();else validateFormat();function validate$DataFormat(){const fmts=gen.scopeValue("formats",{ref:self.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=self.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_dist=__commonJS({"../../node_modules/.pnpm/ajv-formats@3.0.1/node_modules/ajv-formats/dist/index.js"(exports,module){"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])}module.exports=exports=formatsPlugin;Object.defineProperty(exports,"__esModule",{value:true});exports.default=formatsPlugin}});import{spawn}from"node:child_process";import{randomUUID as randomUUID6}from"node:crypto";import{rmSync}from"node:fs";import{join as join6}from"node:path";import{fileURLToPath}from"node:url";import{mkSecretDir,loadAgentFile as loadAgentFile2,registry as registry3,writeLaunchArtifact}from"@cotal-ai/core";import{readFileSync}from"node:fs";import{userInfo}from"node:os";import{DEFAULT_SERVER,DEV_OWNER,LAUNCH_MATERIAL_ENV as LAUNCH_MATERIAL_ENV2,brokerUrlHasUserinfo,discardLaunchMaterial,assertLifecycleToken,assertValidChannel,assertValidKind,channelInAllow,credsClaims,eventChannel,idFromCreds,isConcreteChannel,loadAgentFile,parseJoinLink,parsePersonaEndpoints,resolveReadAcl}from"@cotal-ai/core";import{LAUNCH_MATERIAL_ENV,readLaunchMaterial}from"@cotal-ai/core/launch-material";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 token=readMaterial(env)?.controlToken??env.COTAL_CONTROL_TOKEN?.trim();if(path&&token)return{path,token};if(!path&&!token)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(v2){if(!v2)return[];return v2.split(",").map(s=>s.trim()).filter(Boolean)}function endpointsEnv(v2){let raw;try{raw=JSON.parse(v2)}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(v2){return v2===void 0?void 0:splitList(v2)}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_ENV2]?.trim();delete env[LAUNCH_MATERIAL_ENV2];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?userInfo().username:void 0);if(!name)throw new Error("COTAL_NAME, COTAL_AGENT_FILE or COTAL_LINK is required \u2014 a Cotal session needs an explicit identity from its launcher");const resolvedSubscribe=envList(env.COTAL_SUBSCRIBE)??def?.subscribe??link?.channels??[];let resolvedAllowSub;try{resolvedAllowSub=resolveReadAcl(resolvedSubscribe,envList(env.COTAL_ALLOW_SUBSCRIBE)??def?.allowSubscribe)}catch(e){throw new Error(`COTAL config: ${e.message}`)}const resolvedAllowPub=envList(env.COTAL_ALLOW_PUBLISH)??def?.allowPublish??[];for(const ch of[...resolvedSubscribe,...resolvedAllowSub,...resolvedAllowPub])assertValidChannel(ch);const qEnv=splitList(env.COTAL_QUIET),mEnv=splitList(env.COTAL_MUTED);const resolvedQuiet=qEnv.length?qEnv:def?.quiet??[];const resolvedMuted=mEnv.length?mEnv:def?.muted??[];const bothModes=resolvedQuiet.filter(c=>resolvedMuted.includes(c));if(bothModes.length)throw new Error(`COTAL config: channel(s) [${bothModes.join(", ")}] are in both quiet and muted`);for(const[field,chans]of[["quiet",resolvedQuiet],["muted",resolvedMuted]])for(const ch of chans){assertValidChannel(ch);if(!isConcreteChannel(ch))throw new Error(`COTAL config: ${field} channel "${ch}" must be concrete (no wildcard)`);if(!channelInAllow(resolvedAllowSub,ch))throw new Error(`COTAL config: ${field} channel "${ch}" is not within allowSubscribe [${resolvedAllowSub.join(", ")}]`)}const material=readMaterial(env);if(env.COTAL_SERVERS?.trim()&&brokerUrlHasUserinfo(env.COTAL_SERVERS))throw new Error("COTAL config: COTAL_SERVERS must not embed credentials; name the broker URL without user:password@, and pass the credential in COTAL_CREDS, COTAL_TOKEN or a COTAL_LINK");const credsPath=material?.creds??env.COTAL_CREDS?.trim();const initialCreds=credsPath?readFileSync(credsPath,"utf8"):void 0;const credsId=initialCreds?idFromCreds(initialCreds):void 0;const boundedCreds=initialCreds!==void 0&&typeof credsClaims(initialCreds).exp==="number";const declaredId=env.COTAL_ID?.trim()||void 0;if(declaredId&&credsId&&declaredId!==credsId)throw new Error(`COTAL config: COTAL_ID ${declaredId} != creds identity ${credsId} - they must be the same nkey`);const userVars=material?.userAuth?{owner:material.userAuth.owner,actor:material.userAuth.actor,sentinel:material.userAuth.sentinelCredsPath,bearerCmd:JSON.stringify(material.userAuth.bearerCmd)}:{owner:env.COTAL_OWNER?.trim(),actor:env.COTAL_ACTOR?.trim(),sentinel:env.COTAL_SENTINEL_CREDS?.trim(),bearerCmd:env.COTAL_BEARER_CMD?.trim()};const userSet=Object.values(userVars).filter(Boolean).length;if(userSet>0&&userSet<4)throw new Error("COTAL config: user-mode launch needs ALL of COTAL_OWNER, COTAL_ACTOR, COTAL_SENTINEL_CREDS, COTAL_BEARER_CMD \u2014 a partial set is a broken launcher, not a mode");if(userSet&&credsPath)throw new Error("COTAL config: COTAL_CREDS (static auth) and COTAL_OWNER/... (user-mode auth) are mutually exclusive");const lifecycleUid=env.COTAL_LIFECYCLE_UID?.trim()||void 0;const backfillFloorRaw=env.COTAL_BACKFILL_FLOOR?.trim()||void 0;let backfillFloor;if(backfillFloorRaw!==void 0){const n=Number(backfillFloorRaw);if(!Number.isInteger(n)||n<0)throw new Error(`COTAL config: COTAL_BACKFILL_FLOOR must be a non-negative integer stream sequence, got "${backfillFloorRaw}" (a broken launcher, not a mode)`);backfillFloor=n}const acceptedToken=env.COTAL_ACCEPTED_TOKEN?.trim()||void 0;const managerInstanceId=env.COTAL_MANAGER_INSTANCE?.trim()||void 0;if(managerInstanceId!==void 0)assertLifecycleToken(managerInstanceId,"COTAL_MANAGER_INSTANCE");if(acceptedToken&&!credsPath)throw new Error("COTAL config: COTAL_ACCEPTED_TOKEN names a static issuance and needs COTAL_CREDS beside it (a broken launcher, not a mode)");if((credsPath||userSet===4)&&!lifecycleUid)throw new Error("COTAL config: an authed launch (COTAL_CREDS or user-mode) requires COTAL_LIFECYCLE_UID - the launcher mints it at provision time (a broken launcher, not a mode)");let userAuth;if(userSet===4){let bearerCmd;try{bearerCmd=JSON.parse(userVars.bearerCmd)}catch{throw new Error("COTAL config: COTAL_BEARER_CMD must be a JSON argv array")}if(!Array.isArray(bearerCmd)||!bearerCmd.length||!bearerCmd.every(a=>typeof a==="string"))throw new Error("COTAL config: COTAL_BEARER_CMD must be a non-empty JSON array of strings");userAuth={owner:userVars.owner,actor:userVars.actor,sentinelCreds:readFileSync(userVars.sentinel,"utf8"),bearerCmd}}const eventsRequired=material?.eventsRequired===true||!material&&envFlag(env,"COTAL_EVENTS_REQUIRED")===true;if(eventsRequired&&!userAuth)throw new Error("COTAL config: COTAL_EVENTS_REQUIRED is valid only for a user-mode registration launch");if(eventsRequired){const principal=userSet===4?{owner:userVars.owner,actor:userVars.actor}:{owner:DEV_OWNER,actor:credsId??declaredId??""};if(!principal.actor)throw new Error("COTAL config: this space requires events, but the session has no stable principal to derive its event channel");const channel=eventChannel(principal);if(!channelInAllow(resolvedAllowPub,channel))throw new Error(`COTAL config: space "${env.COTAL_SPACE?.trim()||link?.space||"demo"}" requires events, but this session's grant does not cover its event channel "${channel}". Widen the whole user-auth actor row with \`cotal actor grant ${principal.actor} --owner ${principal.owner} --scope <current-scope> --allow-subscribe <current-read> --allow-publish '<current-post>,${channel}' --role <current-role> --label <current-label>\`; actor grant replaces the whole row, so preserve every current field.`)}return{space:env.COTAL_SPACE?.trim()||link?.space||"demo",id:credsId??declaredId,lifecycleUid,backfillFloor,acceptedToken,managerInstanceId,creds:boundedCreds?async()=>readFileSync(credsPath,"utf8"):initialCreds,userAuth,name,role:env.COTAL_ROLE||def?.role||void 0,description:def?.description,tags:def?.tags,meta:def?.meta,capabilities:splitList(env.COTAL_CAPABILITIES).length?splitList(env.COTAL_CAPABILITIES):def?.capabilities,endpoints:env.COTAL_ENDPOINTS!==void 0?endpointsEnv(env.COTAL_ENDPOINTS):def?.endpoints,model:env.COTAL_MODEL?.trim()||void 0,variant:env.COTAL_VARIANT?.trim()||void 0,servers:material?.servers||env.COTAL_SERVERS?.trim()||link?.servers||DEFAULT_SERVER,subscribe:resolvedSubscribe,allowSubscribe:resolvedAllowSub,allowPublish:resolvedAllowPub,eventsRequired,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}from"node:async_hooks";import{EventEmitter}from"node:events";import{hostname as hostname2}from"node:os";import{normalizeMentions,RUN_LAUNCH_DEADLINE_MS,subjectMatches,isConcreteChannel as isConcreteChannel2,isChannelFamily,assertValidChannel as assertValidChannel2,channelInAllow as channelInAllow2,eventChannelPrincipal,resolvePeer as resolvePeerInRoster,peerLabel as peerLabel2,shownPeerName,CotalEndpoint,acquireLocalConsumer,BASELINE_LIFECYCLE_ENDPOINT as BASELINE_LIFECYCLE_ENDPOINT2,assertLifecycleToken as assertLifecycleToken2,EpEnvelopeError as EpEnvelopeError2,isPublishPermissionDenied,unansweredRequest,undeclaredArg,undeclaredArgInstance,EP_UNANSWERED,controlReplyFrom,controlReplyFromThrown,runAgentBearer,ANYCAST_NOTICE_KEY,partsToText,assertValidRole,turnNoticeFilter,renderOnceTask}from"@cotal-ai/core";import{checkEventStartup as checkSharedEventStartup}from"@cotal-ai/core";import{createHash as createHash2,randomUUID as randomUUID2}from"node:crypto";import{open as open2,readFile as readFile2,unlink as unlink2}from"node:fs/promises";import{hostname}from"node:os";import{dirname as dirname2,join as join2}from"node:path";import{ensureDirNoSymlink,eventPrincipalLocation}from"@cotal-ai/core";import{eventPrincipalLocation as eventPrincipalLocation2}from"@cotal-ai/core";import{createHash,randomUUID}from"node:crypto";import{constants}from"node:fs";import{open,readFile,rename,unlink}from"node:fs/promises";import{dirname,join}from"node:path";import{assertIdToken}from"@cotal-ai/core";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 isSafeNonNegInt=n=>Number.isSafeInteger(n)&&n>=0;function docGeneration(path,doc){if(typeof doc.v==="number"&&doc.v<3)return 0;if(!isSafeNonNegInt(doc.gen))throw new WalCorruptError(path,"gen is a safe non-negative integer",`found gen=${String(doc.gen)} on a v${String(doc.v)} document`);return doc.gen}async function openExclusiveNoFollow(path){return open(path,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|(constants.O_NOFOLLOW??0),384)}function assertPendingVintage(path,p,f){if(p.E!==f.lastSubjectSeq)throw new WalCorruptError(path,"pending.E === frontier.lastSubjectSeq",`pending.E=${p.E} frontier.lastSubjectSeq=${f.lastSubjectSeq} \u2014 the frozen expectation is not the tip this WAL believes, so retrying it can only CAS-halt or append at the wrong position`);if(p.seq!==f.seq+1)throw new WalCorruptError(path,"pending.seq === frontier.seq + 1",`pending.seq=${p.seq} frontier.seq=${f.seq} \u2014 a pending frame must be exactly the frontier's successor`);if(p.state==="sent_unacked"){if(p.ackSeq!==void 0)throw new WalCorruptError(path,"sent_unacked has no ackSeq",`state is "sent_unacked" but ackSeq=${String(p.ackSeq)} \u2014 the document contradicts its own tag`);return}if(!isSafeNonNegInt(p.ackSeq))throw new WalCorruptError(path,"acked.ackSeq present",`state is "acked" but ackSeq is ${String(p.ackSeq)}`);if(!(p.ackSeq>f.lastSubjectSeq))throw new WalCorruptError(path,"acked.ackSeq > frontier.lastSubjectSeq",`ackSeq=${p.ackSeq} frontier.lastSubjectSeq=${f.lastSubjectSeq} \u2014 the frontier is of a later vintage than the acked frame, so its sourceCursor may already have passed events that were never published; resuming would drop them with no gap for a consumer to see`)}function parseBrackets(path,field,v2,nullable2){if(v2===null&&nullable2)return null;if(typeof v2!=="object"||v2===null)throw new WalCorruptError(path,`${field} is an object${nullable2?" or null":""}`,JSON.stringify(v2));const b2=v2;if(b2.run!==void 0&&typeof b2.run!=="string")throw new WalCorruptError(path,`${field}.run is a string or absent`,JSON.stringify(b2.run));const lists={text:b2.text,reasoning:b2.reasoning,tools:b2.tools};for(const[k,list]of Object.entries(lists)){if(!Array.isArray(list)||list.some(x2=>typeof x2!=="string"))throw new WalCorruptError(path,`${field}.${k} is an array of strings`,JSON.stringify(list))}if(b2.run===void 0&&b2.text.concat(b2.reasoning,b2.tools).length>0)throw new WalCorruptError(path,`${field} has no open run while messages or tool calls are open`,JSON.stringify(b2));return{run:b2.run,text:b2.text,reasoning:b2.reasoning,tools:b2.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(([id,allowed])=>!id||typeof allowed!=="boolean"))throw new WalCorruptError(path,"payloadCalls is a bounded boolean record","invalid call classification");return{...value}}function parseDoc(path,raw,space,threadId,principal){let d2;try{d2=JSON.parse(raw)}catch(e){throw new WalCorruptError(path,"parseable JSON",e.message)}if(typeof d2!=="object"||d2===null)throw new WalCorruptError(path,"document is an object",typeof d2);const doc=d2;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!==space)throw new WalCorruptError(path,"space matches",`WAL space=${String(doc.space)} caller=${space}`);if(doc.threadId!==threadId)throw new WalCorruptError(path,"threadId matches",`WAL threadId=${String(doc.threadId)} caller=${threadId}`);if(doc.principal!==principal)throw new WalCorruptError(path,"principal matches",`WAL principal=${String(doc.principal)} caller=${principal}`);if(typeof doc.epoch!=="string"||doc.epoch.length===0)throw new WalCorruptError(path,"epoch is a non-empty string",String(doc.epoch));const f=doc.frontier;if(!f||!isSafeNonNegInt(f.seq)||!isSafeNonNegInt(f.lastSubjectSeq))throw new WalCorruptError(path,"frontier is well-formed",JSON.stringify(doc.frontier));if(f.sourceCursor!==void 0&&typeof f.sourceCursor!=="string")throw new WalCorruptError(path,"frontier.sourceCursor is a string or absent",typeof f.sourceCursor);if(f.seq===0!==(f.lastSubjectSeq===0))throw new WalCorruptError(path,"frontier.seq and lastSubjectSeq are both zero or both nonzero",JSON.stringify(f));if((f.seq>0||f.lastSubjectSeq>0)&&typeof f.sourceCursor!=="string")throw new WalCorruptError(path,"a nonzero frontier carries its sourceCursor",JSON.stringify(f));if(doc.pending!==null&&typeof doc.pending!=="object")throw new WalCorruptError(path,"pending is present (null or an object)",doc.pending===void 0?"the key is absent, which is not the same as null":typeof doc.pending);let pending=null;if(doc.pending!==null){const p=doc.pending;if(p.state!=="sent_unacked"&&p.state!=="acked")throw new WalCorruptError(path,"pending.state is a known tag",String(p.state));if(typeof p.id!=="string"||p.id.length===0)throw new WalCorruptError(path,"pending.id is a non-empty string",String(p.id));try{assertIdToken(p.id,"event WAL pending.id")}catch(e){throw new WalCorruptError(path,"pending.id satisfies the wire id grammar",e.message)}if(!isSafeNonNegInt(p.E)||!isSafeNonNegInt(p.seq))throw new WalCorruptError(path,"pending E/seq are safe non-negative integers",JSON.stringify(p));if(typeof p.sourceCursor!=="string")throw new WalCorruptError(path,"pending.sourceCursor is a string",typeof p.sourceCursor);if(!Array.isArray(p.body)||p.body.length===0)throw new WalCorruptError(path,"pending.body is a non-empty array of parts",JSON.stringify(p.body));if(doc.v===1)throw new WalCorruptError(path,"a v1 WAL has no frame in flight",`this v1 document holds a ${String(p.state)} frame, and v2 requires the bracket state that belongs to it \u2014 which v1 never recorded and nothing here can reconstruct. Let the older build settle this frame first, then start the newer one.`);p.brackets=parseBrackets(path,"pending.brackets",p.brackets,false);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||!isSafeNonNegInt(payload.E)||payload.ackSeq!==void 0&&(!isSafeNonNegInt(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,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(space,threadId,principal){return{v:EVENT_WAL_VERSION,gen:0,space,epoch:randomUUID(),threadId,principal,frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}}}async bindSubjectFrontier(frontier){if(this.subject===frontier)return;if(this.subject)throw new Error(`event WAL ${this.path}: a DIFFERENT subject frontier is already bound`);this.subject=frontier}get expectedTip(){if(!this.subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so there is no expectation to publish. The subject is shared by every thread of this principal, so this document's own last ack is not it; bind the principal's record with bindSubjectFrontier first.`);return this.subject.tip}async beginSend(frame){return this.serialize(async()=>{if(this.doc.pending)throw new Error(`event WAL ${this.path}: a frame is already pending; one emit unit is one pending frame`);assertIdToken(frame.id,"event WAL pending id");if(frame.E!==this.expectedTip)throw new Error(`event WAL ${this.path}: E=${frame.E} is not the subject's tip ${this.expectedTip}`);if(frame.seq!==this.doc.frontier.seq+1)throw new Error(`event WAL ${this.path}: seq=${frame.seq} is not the frontier's successor ${this.doc.frontier.seq+1}`);if(!Array.isArray(frame.body)||frame.body.length===0)throw new Error(`event WAL ${this.path}: a frame body must be a non-empty array of parts`);parsePayloadCalls(this.path,frame.payloadCalls);if(frame.payload){assertIdToken(frame.payload.id,"event WAL payload id");if(!isSafeNonNegInt(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(!isSafeNonNegInt(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(!isSafeNonNegInt(ackSeq))throw new Error(`event WAL ${this.path}: ackSeq must be a safe non-negative integer, got ${String(ackSeq)}`);if(ackSeq<=this.expectedTip)throw new Error(`event WAL ${this.path}: ackSeq=${ackSeq} is not ahead of the subject's tip ${this.expectedTip}`);const subject=this.subject;if(!subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so this ack has no shared record to advance`);await this.assertNotClobbering();await subject.advance(ackSeq);await this.write({...this.doc,pending:{...p,state:"acked",ackSeq}})})}async fold(){return this.serialize(async()=>{const p=this.doc.pending;if(!p||p.state!=="acked"||p.ackSeq===void 0)throw new Error(`event WAL ${this.path}: no acked frame to fold`);await this.write({...this.doc,frontier:{seq:p.seq,lastSubjectSeq:p.ackSeq,sourceCursor:p.sourceCursor},pending:null,brackets:p.brackets,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:randomUUID(),frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}})})}async write(next){await this.assertNotClobbering();const stamped={...next,gen:this.doc.gen+1};const tmp=join(dirname(this.path),`.${createHash("sha256").update(this.path).digest("hex").slice(0,12)}.${process.pid}.${randomUUID().slice(0,8)}.wal.tmp`);const body=JSON.stringify(stamped);const fh=await openExclusiveNoFollow(tmp);try{await fh.writeFile(body,"utf8");await fh.sync()}finally{await fh.close()}try{await 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 d2;try{d2=JSON.parse(raw)}catch(e){throw new WalCorruptError(this.path,"parseable JSON",e.message)}if(typeof d2!=="object"||d2===null)throw new WalCorruptError(this.path,"document is an object",typeof d2);const onDisk=docGeneration(this.path,d2);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 createHash2("sha256").update(value).digest("hex").slice(0,16)}function eventWalLocation(opts){const principal=eventPrincipalLocation(opts);const threadDir=join2(principal.principalDir,h(opts.threadId));return{...principal,threadDir,walPath:join2(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:randomUUID2(),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 open2(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=dirname2(dir)){await fsyncDir(dir);if(dir===opts.workspaceRoot||dirname2(dir)===dir)break}const lock=await acquirePrincipalLock(loc.lockPath);return{...loc,lock}}import{EventStateConflictError}from"@cotal-ai/core";async function checkEventStartup(ep,env){await checkSharedEventStartup({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 g2=globalThis;return g2[KEY]??={handoffs:new Map}}var keyOf=(uid,goalId)=>`${uid}:${goalId}`;function onceHandoffState(uid,goalId){return proc().handoffs.get(keyOf(uid,goalId))?.state??"pending"}function claimOnceHandoff(uid,goalIds){const p=proc();if(goalIds.some(id=>onceHandoffState(uid,id)!=="pending"))return false;for(const id of goalIds){const timer=setTimeout(()=>p.timedOut?.(uid,id),ONCE_HANDOFF_MS);timer.unref?.();p.handoffs.set(keyOf(uid,id),{state:"claimed",timer})}return true}function confirmOnceHandoff(uid,goalId){const h2=proc().handoffs.get(keyOf(uid,goalId));if(h2?.state==="sealed")return false;if(h2?.timer!==void 0)clearTimeout(h2.timer);proc().handoffs.set(keyOf(uid,goalId),{state:"confirmed"});return true}function sealOnceHandoff(uid,goalId){const h2=proc().handoffs.get(keyOf(uid,goalId));if(h2?.state!=="claimed")return false;if(h2.timer!==void 0)clearTimeout(h2.timer);proc().handoffs.set(keyOf(uid,goalId),{state:"sealed"});return true}function endOnceHandoff(uid,goalId){const h2=proc().handoffs.get(keyOf(uid,goalId));if(h2?.state==="confirmed"||h2?.state==="sealed")return;if(h2?.timer!==void 0)clearTimeout(h2.timer);proc().handoffs.set(keyOf(uid,goalId),{state:"sealed"})}function stopOnceHandoffTimer(uid,goalId){const h2=proc().handoffs.get(keyOf(uid,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}import{LINE_BREAK,peerLabel}from"@cotal-ai/core/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(text){return text.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}`}import{drainAndClose}from"@cotal-ai/core";import{BASELINE_LIFECYCLE_ENDPOINT,EpEnvelopeError,dialerFor,goalFollowRefusal,invokeCommand,isPermissionDenied,issuedUserCaller,managerCallerBinding,registryListingCaller,replyRefusedBeforeEffect,resolveService,standaloneConnectOpts}from"@cotal-ai/core";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,token,exp,ask){const user=config2.userAuth;const binding=managerCallerBinding(token,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId});const railKey=binding.credentialId??token;const connectOpts=standaloneConnectOpts({bearer:token,sentinelCreds:user.sentinelCreds,tls:config2.tls});const connId=String(connectOpts.name);const nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:1e4});const issued=async()=>{try{const caller=await issuedUserCaller(nc,config2.space,connId,binding.caller);legacyRail.delete(railKey);return caller}catch(e){if(!isPermissionDenied(e))throw e;rememberLegacyRail(railKey);return void 0}};try{const skipped=onLegacyRail(railKey);const caller=skipped?void 0:await issued();const listing=caller??await registryListingCaller(nc,config2.space,binding.caller,{connId,...exp!==void 0?{exp}:{}});return await ask(nc,listing??(skipped?await issued():void 0))}finally{await drainAndClose(nc)}}async function invokeUserManager(config2,bearer,command,args,opts={}){opts.signal?.throwIfAborted();const user=config2.userAuth;const endpoint=BASELINE_LIFECYCLE_ENDPOINT;let nc;let caller;let instanceId;let service;let skippedAcceptedRead;const onAbort=()=>{void nc?.close()};const resolve=(signal=opts.signal,deadlineMs=opts.deadlineMs??1e4)=>resolveService(nc,config2.space,endpoint,caller,{instanceId,deadlineMs,signal,commands:opts.follow?[command,"goal-result"]:[command],...opts.follow&&command!=="goal-result"?{optionalCommands:["goal-result"]}:{}});const resolvePrepared=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const remaining=()=>{signal?.throwIfAborted();const left=deadline-Date.now();if(left<=0)throw new EpEnvelopeError("deadline-exceeded","the deadline passed before the manager was resolved; the manager request WAS NOT RUN",void 0,"not-executed");return left};try{return await resolve(signal,remaining())}catch(error51){if(!skippedAcceptedRead||!isPermissionDenied(error51))throw error51;const{key,connId}=skippedAcceptedRead;skippedAcceptedRead=void 0;remaining();caller=await issuedUserCaller(nc,config2.space,connId,caller);legacyRail.delete(key);return resolve(signal,remaining())}};const connect2=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const token=await bearer(signal);let credentialId;({caller,instanceId,credentialId}=managerCallerBinding(token,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId}));const connectOpts=standaloneConnectOpts({bearer:token,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??token;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 connect2(signal,deadline);service=await resolvePrepared(signal,deadline)};const invoke=async(signal=opts.signal)=>{const unfollowable=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable)return unfollowable;const invokeOpts={target:opts.target,deadlineMs:opts.deadlineMs,signal};const result=await invokeCommand(nc,config2.space,service,command,args,invokeOpts);if(result.reply.ok===false&&replyRefusedBeforeEffect(result.reply.error)){try{service=await resolve(signal);const unfollowable2=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable2)throw new Error(unfollowable2.reply.error.message)}catch(error51){return{...result,reply:{...result.reply,error:{...result.reply.error,message:`${command} WAS NOT RUN; manager instance ${instanceId} refused before effects, and re-resolution failed: ${error51 instanceof Error?error51.message:String(error51)}`}}}}return invokeCommand(nc,config2.space,service,command,args,invokeOpts)}return result};opts.signal?.addEventListener("abort",onAbort,{once:true});try{if(opts.follow)return await opts.follow(invoke,prepare);await connect2();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.6";import{createHash as createHash3,randomUUID as randomUUID3}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,b2){return a.ts!==b2.ts?a.ts>b2.ts:a.id>b2.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,b2){const[x2,y2]=[a,b2].map(v2=>v2.split(/[-+]/)[0].split(".").map(Number));for(let i=0;i<3;i++)if(x2[i]!==y2[i])return(x2[i]??0)-(y2[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(m2){return m2.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(m2){return createHash3("sha256").update(JSON.stringify(m2)).digest("base64url")}function sleep(ms){return new Promise(r=>setTimeout(r,ms))}function ingestDedupKey(id){return id===""?void 0:id}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,v2])=>`${k}: ${String(v2)}`).join(", ");const by=typeof a.deadlineAt==="number"?`, by ${new Date(a.deadlineAt).toISOString()}`:"";const refused=typeof a.refused==="string"?`
|
|
68
|
+
deps: ${deps}}`};var def={keyword:"dependencies",type:"object",schemaType:"object",error:exports.error,code(cxt){const[propDeps,schDeps]=splitDependencies(cxt);validatePropertyDeps(cxt,propDeps);validateSchemaDeps(cxt,schDeps)}};function splitDependencies({schema}){const propertyDeps={};const schemaDeps={};for(const key in schema){if(key==="__proto__")continue;const deps=Array.isArray(schema[key])?propertyDeps:schemaDeps;deps[key]=schema[key]}return[propertyDeps,schemaDeps]}function validatePropertyDeps(cxt,propertyDeps=cxt.schema){const{gen,data,it}=cxt;if(Object.keys(propertyDeps).length===0)return;const missing=gen.let("missing");for(const prop in propertyDeps){const deps=propertyDeps[prop];if(deps.length===0)continue;const hasProperty=(0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties);cxt.setParams({property:prop,depsCount:deps.length,deps:deps.join(", ")});if(it.allErrors){gen.if(hasProperty,()=>{for(const depProp of deps){(0,code_1.checkReportMissingProp)(cxt,depProp)}})}else{gen.if((0,codegen_1._)`${hasProperty} && (${(0,code_1.checkMissingProp)(cxt,deps,missing)})`);(0,code_1.reportMissingProp)(cxt,missing);gen.else()}}}exports.validatePropertyDeps=validatePropertyDeps;function validateSchemaDeps(cxt,schemaDeps=cxt.schema){const{gen,data,keyword,it}=cxt;const valid=gen.name("valid");for(const prop in schemaDeps){if((0,util_1.alwaysValidSchema)(it,schemaDeps[prop]))continue;gen.if((0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties),()=>{const schCxt=cxt.subschema({keyword,schemaProp:prop},valid);cxt.mergeValidEvaluated(schCxt,valid)},()=>gen.var(valid,true));cxt.ok(valid)}}exports.validateSchemaDeps=validateSchemaDeps;exports.default=def}});var require_propertyNames=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var error51={message:"property name must be valid",params:({params})=>(0,codegen_1._)`{propertyName: ${params.propertyName}}`};var def={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:error51,code(cxt){const{gen,schema,data,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema))return;const valid=gen.name("valid");gen.forIn("key",data,key=>{cxt.setParams({propertyName:key});cxt.subschema({keyword:"propertyNames",data:key,dataTypes:["string"],propertyName:key,compositeRule:true},valid);gen.if((0,codegen_1.not)(valid),()=>{cxt.error(true);if(!it.allErrors)gen.break()})});cxt.ok(valid)}};exports.default=def}});var require_additionalProperties=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var code_1=require_code2();var codegen_1=require_codegen();var names_1=require_names();var util_1=require_util();var error51={message:"must NOT have additional properties",params:({params})=>(0,codegen_1._)`{additionalProperty: ${params.additionalProperty}}`};var def={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:true,trackErrors:true,error:error51,code(cxt){const{gen,schema,parentSchema,data,errsCount,it}=cxt;if(!errsCount)throw new Error("ajv implementation error");const{allErrors,opts}=it;it.props=true;if(opts.removeAdditional!=="all"&&(0,util_1.alwaysValidSchema)(it,schema))return;const props=(0,code_1.allSchemaProperties)(parentSchema.properties);const patProps=(0,code_1.allSchemaProperties)(parentSchema.patternProperties);checkAdditionalProperties();cxt.ok((0,codegen_1._)`${errsCount} === ${names_1.default.errors}`);function checkAdditionalProperties(){gen.forIn("key",data,key=>{if(!props.length&&!patProps.length)additionalPropertyCode(key);else gen.if(isAdditional(key),()=>additionalPropertyCode(key))})}function isAdditional(key){let definedProp;if(props.length>8){const propsSchema=(0,util_1.schemaRefOrVal)(it,parentSchema.properties,"properties");definedProp=(0,code_1.isOwnProperty)(gen,propsSchema,key)}else if(props.length){definedProp=(0,codegen_1.or)(...props.map(p=>(0,codegen_1._)`${key} === ${p}`))}else{definedProp=codegen_1.nil}if(patProps.length){definedProp=(0,codegen_1.or)(definedProp,...patProps.map(p=>(0,codegen_1._)`${(0,code_1.usePattern)(cxt,p)}.test(${key})`))}return(0,codegen_1.not)(definedProp)}function deleteAdditional(key){gen.code((0,codegen_1._)`delete ${data}[${key}]`)}function additionalPropertyCode(key){if(opts.removeAdditional==="all"||opts.removeAdditional&&schema===false){deleteAdditional(key);return}if(schema===false){cxt.setParams({additionalProperty:key});cxt.error();if(!allErrors)gen.break();return}if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it,schema)){const valid=gen.name("valid");if(opts.removeAdditional==="failing"){applyAdditionalSchema(key,valid,false);gen.if((0,codegen_1.not)(valid),()=>{cxt.reset();deleteAdditional(key)})}else{applyAdditionalSchema(key,valid);if(!allErrors)gen.if((0,codegen_1.not)(valid),()=>gen.break())}}}function applyAdditionalSchema(key,valid,errors){const subschema={keyword:"additionalProperties",dataProp:key,dataPropType:util_1.Type.Str};if(errors===false){Object.assign(subschema,{compositeRule:true,createErrors:false,allErrors:false})}cxt.subschema(subschema,valid)}}};exports.default=def}});var require_properties=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var validate_1=require_validate();var code_1=require_code2();var util_1=require_util();var additionalProperties_1=require_additionalProperties();var def={keyword:"properties",type:"object",schemaType:"object",code(cxt){const{gen,schema,parentSchema,data,it}=cxt;if(it.opts.removeAdditional==="all"&&parentSchema.additionalProperties===void 0){additionalProperties_1.default.code(new validate_1.KeywordCxt(it,additionalProperties_1.default,"additionalProperties"))}const allProps=(0,code_1.allSchemaProperties)(schema);for(const prop of allProps){it.definedProperties.add(prop)}if(it.opts.unevaluated&&allProps.length&&it.props!==true){it.props=util_1.mergeEvaluated.props(gen,(0,util_1.toHash)(allProps),it.props)}const properties=allProps.filter(p=>!(0,util_1.alwaysValidSchema)(it,schema[p]));if(properties.length===0)return;const valid=gen.name("valid");for(const prop of properties){if(hasDefault(prop)){applyPropertySchema(prop)}else{gen.if((0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties));applyPropertySchema(prop);if(!it.allErrors)gen.else().var(valid,true);gen.endIf()}cxt.it.definedProperties.add(prop);cxt.ok(valid)}function hasDefault(prop){return it.opts.useDefaults&&!it.compositeRule&&schema[prop].default!==void 0}function applyPropertySchema(prop){cxt.subschema({keyword:"properties",schemaProp:prop,dataProp:prop},valid)}}};exports.default=def}});var require_patternProperties=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var code_1=require_code2();var codegen_1=require_codegen();var util_1=require_util();var util_2=require_util();var def={keyword:"patternProperties",type:"object",schemaType:"object",code(cxt){const{gen,schema,data,parentSchema,it}=cxt;const{opts}=it;const patterns=(0,code_1.allSchemaProperties)(schema);const alwaysValidPatterns=patterns.filter(p=>(0,util_1.alwaysValidSchema)(it,schema[p]));if(patterns.length===0||alwaysValidPatterns.length===patterns.length&&(!it.opts.unevaluated||it.props===true)){return}const checkProperties=opts.strictSchema&&!opts.allowMatchingProperties&&parentSchema.properties;const valid=gen.name("valid");if(it.props!==true&&!(it.props instanceof codegen_1.Name)){it.props=(0,util_2.evaluatedPropsToName)(gen,it.props)}const{props}=it;validatePatternProperties();function validatePatternProperties(){for(const pat of patterns){if(checkProperties)checkMatchingProperties(pat);if(it.allErrors){validateProperties(pat)}else{gen.var(valid,true);validateProperties(pat);gen.if(valid)}}}function checkMatchingProperties(pat){for(const prop in checkProperties){if(new RegExp(pat).test(prop)){(0,util_1.checkStrictMode)(it,`property ${prop} matches pattern ${pat} (use allowMatchingProperties)`)}}}function validateProperties(pat){gen.forIn("key",data,key=>{gen.if((0,codegen_1._)`${(0,code_1.usePattern)(cxt,pat)}.test(${key})`,()=>{const alwaysValid=alwaysValidPatterns.includes(pat);if(!alwaysValid){cxt.subschema({keyword:"patternProperties",schemaProp:pat,dataProp:key,dataPropType:util_2.Type.Str},valid)}if(it.opts.unevaluated&&props!==true){gen.assign((0,codegen_1._)`${props}[${key}]`,true)}else if(!alwaysValid&&!it.allErrors){gen.if((0,codegen_1.not)(valid),()=>gen.break())}})})}}};exports.default=def}});var require_not=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var util_1=require_util();var def={keyword:"not",schemaType:["object","boolean"],trackErrors:true,code(cxt){const{gen,schema,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema)){cxt.fail();return}const valid=gen.name("valid");cxt.subschema({keyword:"not",compositeRule:true,createErrors:false,allErrors:false},valid);cxt.failResult(valid,()=>cxt.reset(),()=>cxt.error())},error:{message:"must NOT be valid"}};exports.default=def}});var require_anyOf=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var code_1=require_code2();var def={keyword:"anyOf",schemaType:"array",trackErrors:true,code:code_1.validateUnion,error:{message:"must match a schema in anyOf"}};exports.default=def}});var require_oneOf=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var error51={message:"must match exactly one schema in oneOf",params:({params})=>(0,codegen_1._)`{passingSchemas: ${params.passing}}`};var def={keyword:"oneOf",schemaType:"array",trackErrors:true,error:error51,code(cxt){const{gen,schema,parentSchema,it}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");if(it.opts.discriminator&&parentSchema.discriminator)return;const schArr=schema;const valid=gen.let("valid",false);const passing=gen.let("passing",null);const schValid=gen.name("_valid");cxt.setParams({passing});gen.block(validateOneOf);cxt.result(valid,()=>cxt.reset(),()=>cxt.error(true));function validateOneOf(){schArr.forEach((sch,i)=>{let schCxt;if((0,util_1.alwaysValidSchema)(it,sch)){gen.var(schValid,true)}else{schCxt=cxt.subschema({keyword:"oneOf",schemaProp:i,compositeRule:true},schValid)}if(i>0){gen.if((0,codegen_1._)`${schValid} && ${valid}`).assign(valid,false).assign(passing,(0,codegen_1._)`[${passing}, ${i}]`).else()}gen.if(schValid,()=>{gen.assign(valid,true);gen.assign(passing,i);if(schCxt)cxt.mergeEvaluated(schCxt,codegen_1.Name)})})}}};exports.default=def}});var require_allOf=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var util_1=require_util();var def={keyword:"allOf",schemaType:"array",code(cxt){const{gen,schema,it}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");const valid=gen.name("valid");schema.forEach((sch,i)=>{if((0,util_1.alwaysValidSchema)(it,sch))return;const schCxt=cxt.subschema({keyword:"allOf",schemaProp:i},valid);cxt.ok(valid);cxt.mergeEvaluated(schCxt)})}};exports.default=def}});var require_if=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var error51={message:({params})=>(0,codegen_1.str)`must match "${params.ifClause}" schema`,params:({params})=>(0,codegen_1._)`{failingKeyword: ${params.ifClause}}`};var def={keyword:"if",schemaType:["object","boolean"],trackErrors:true,error:error51,code(cxt){const{gen,parentSchema,it}=cxt;if(parentSchema.then===void 0&&parentSchema.else===void 0){(0,util_1.checkStrictMode)(it,'"if" without "then" and "else" is ignored')}const hasThen=hasSchema(it,"then");const hasElse=hasSchema(it,"else");if(!hasThen&&!hasElse)return;const valid=gen.let("valid",true);const schValid=gen.name("_valid");validateIf();cxt.reset();if(hasThen&&hasElse){const ifClause=gen.let("ifClause");cxt.setParams({ifClause});gen.if(schValid,validateClause("then",ifClause),validateClause("else",ifClause))}else if(hasThen){gen.if(schValid,validateClause("then"))}else{gen.if((0,codegen_1.not)(schValid),validateClause("else"))}cxt.pass(valid,()=>cxt.error(true));function validateIf(){const schCxt=cxt.subschema({keyword:"if",compositeRule:true,createErrors:false,allErrors:false},schValid);cxt.mergeEvaluated(schCxt)}function validateClause(keyword,ifClause){return()=>{const schCxt=cxt.subschema({keyword},schValid);gen.assign(valid,schValid);cxt.mergeValidEvaluated(schCxt,valid);if(ifClause)gen.assign(ifClause,(0,codegen_1._)`${keyword}`);else cxt.setParams({ifClause:keyword})}}}};function hasSchema(it,keyword){const schema=it.schema[keyword];return schema!==void 0&&!(0,util_1.alwaysValidSchema)(it,schema)}exports.default=def}});var require_thenElse=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var util_1=require_util();var def={keyword:["then","else"],schemaType:["object","boolean"],code({keyword,parentSchema,it}){if(parentSchema.if===void 0)(0,util_1.checkStrictMode)(it,`"${keyword}" without "if" is ignored`)}};exports.default=def}});var require_applicator=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var additionalItems_1=require_additionalItems();var prefixItems_1=require_prefixItems();var items_1=require_items();var items2020_1=require_items2020();var contains_1=require_contains();var dependencies_1=require_dependencies();var propertyNames_1=require_propertyNames();var additionalProperties_1=require_additionalProperties();var properties_1=require_properties();var patternProperties_1=require_patternProperties();var not_1=require_not();var anyOf_1=require_anyOf();var oneOf_1=require_oneOf();var allOf_1=require_allOf();var if_1=require_if();var thenElse_1=require_thenElse();function getApplicator(draft2020=false){const applicator=[not_1.default,anyOf_1.default,oneOf_1.default,allOf_1.default,if_1.default,thenElse_1.default,propertyNames_1.default,additionalProperties_1.default,dependencies_1.default,properties_1.default,patternProperties_1.default];if(draft2020)applicator.push(prefixItems_1.default,items2020_1.default);else applicator.push(additionalItems_1.default,items_1.default);applicator.push(contains_1.default);return applicator}exports.default=getApplicator}});var require_format=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/format.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var error51={message:({schemaCode})=>(0,codegen_1.str)`must match format "${schemaCode}"`,params:({schemaCode})=>(0,codegen_1._)`{format: ${schemaCode}}`};var def={keyword:"format",type:["number","string"],schemaType:"string",$data:true,error:error51,code(cxt,ruleType){const{gen,data,$data,schema,schemaCode,it}=cxt;const{opts,errSchemaPath,schemaEnv,self}=it;if(!opts.validateFormats)return;if($data)validate$DataFormat();else validateFormat();function validate$DataFormat(){const fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats});const fDef=gen.const("fDef",(0,codegen_1._)`${fmts}[${schemaCode}]`);const fType=gen.let("fType");const format=gen.let("format");gen.if((0,codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`,()=>gen.assign(fType,(0,codegen_1._)`${fDef}.type || "string"`).assign(format,(0,codegen_1._)`${fDef}.validate`),()=>gen.assign(fType,(0,codegen_1._)`"string"`).assign(format,fDef));cxt.fail$data((0,codegen_1.or)(unknownFmt(),invalidFmt()));function unknownFmt(){if(opts.strictSchema===false)return codegen_1.nil;return(0,codegen_1._)`${schemaCode} && !${format}`}function invalidFmt(){const callFormat=schemaEnv.$async?(0,codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`:(0,codegen_1._)`${format}(${data})`;const validData=(0,codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;return(0,codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`}}function validateFormat(){const formatDef=self.formats[schema];if(!formatDef){unknownFormat();return}if(formatDef===true)return;const[fmtType,format,fmtRef]=getFormat(formatDef);if(fmtType===ruleType)cxt.pass(validCondition());function unknownFormat(){if(opts.strictSchema===false){self.logger.warn(unknownMsg());return}throw new Error(unknownMsg());function unknownMsg(){return`unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`}}function getFormat(fmtDef){const code=fmtDef instanceof RegExp?(0,codegen_1.regexpCode)(fmtDef):opts.code.formats?(0,codegen_1._)`${opts.code.formats}${(0,codegen_1.getProperty)(schema)}`:void 0;const fmt=gen.scopeValue("formats",{key:schema,ref:fmtDef,code});if(typeof fmtDef=="object"&&!(fmtDef instanceof RegExp)){return[fmtDef.type||"string",fmtDef.validate,(0,codegen_1._)`${fmt}.validate`]}return["string",fmtDef,fmt]}function validCondition(){if(typeof formatDef=="object"&&!(formatDef instanceof RegExp)&&formatDef.async){if(!schemaEnv.$async)throw new Error("async format in sync schema");return(0,codegen_1._)`await ${fmtRef}(${data})`}return typeof format=="function"?(0,codegen_1._)`${fmtRef}(${data})`:(0,codegen_1._)`${fmtRef}.test(${data})`}}}};exports.default=def}});var require_format2=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var format_1=require_format();var format=[format_1.default];exports.default=format}});var require_metadata=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/metadata.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.contentVocabulary=exports.metadataVocabulary=void 0;exports.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];exports.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]}});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_core2();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_types=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DiscrError=void 0;var DiscrError;(function(DiscrError2){DiscrError2["Tag"]="tag";DiscrError2["Mapping"]="mapping"})(DiscrError||(exports.DiscrError=DiscrError={}))}});var require_discriminator=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var types_1=require_types();var compile_1=require_compile();var ref_error_1=require_ref_error();var util_1=require_util();var error51={message:({params:{discrError,tagName}})=>discrError===types_1.DiscrError.Tag?`tag "${tagName}" must be string`:`value of tag "${tagName}" must be in oneOf`,params:({params:{discrError,tag,tagName}})=>(0,codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`};var def={keyword:"discriminator",type:"object",schemaType:"object",error:error51,code(cxt){const{gen,data,schema,parentSchema,it}=cxt;const{oneOf}=parentSchema;if(!it.opts.discriminator){throw new Error("discriminator: requires discriminator option")}const tagName=schema.propertyName;if(typeof tagName!="string")throw new Error("discriminator: requires propertyName");if(schema.mapping)throw new Error("discriminator: mapping is not supported");if(!oneOf)throw new Error("discriminator: requires oneOf keyword");const valid=gen.let("valid",false);const tag=gen.const("tag",(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(tagName)}`);gen.if((0,codegen_1._)`typeof ${tag} == "string"`,()=>validateMapping(),()=>cxt.error(false,{discrError:types_1.DiscrError.Tag,tag,tagName}));cxt.ok(valid);function validateMapping(){const mapping=getMapping();gen.if(false);for(const tagValue in mapping){gen.elseIf((0,codegen_1._)`${tag} === ${tagValue}`);gen.assign(valid,applyTagSchema(mapping[tagValue]))}gen.else();cxt.error(false,{discrError:types_1.DiscrError.Mapping,tag,tagName});gen.endIf()}function applyTagSchema(schemaProp){const _valid=gen.name("valid");const schCxt=cxt.subschema({keyword:"oneOf",schemaProp},_valid);cxt.mergeEvaluated(schCxt,codegen_1.Name);return _valid}function getMapping(){var _a3;const oneOfMapping={};const topRequired=hasRequired(parentSchema);let tagRequired=true;for(let i=0;i<oneOf.length;i++){let sch=oneOf[i];if((sch===null||sch===void 0?void 0:sch.$ref)&&!(0,util_1.schemaHasRulesButRef)(sch,it.self.RULES)){const ref=sch.$ref;sch=compile_1.resolveRef.call(it.self,it.schemaEnv.root,it.baseId,ref);if(sch instanceof compile_1.SchemaEnv)sch=sch.schema;if(sch===void 0)throw new ref_error_1.default(it.opts.uriResolver,it.baseId,ref)}const propSch=(_a3=sch===null||sch===void 0?void 0:sch.properties)===null||_a3===void 0?void 0:_a3[tagName];if(typeof propSch!="object"){throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`)}tagRequired=tagRequired&&(topRequired||hasRequired(sch));addMappings(propSch,i)}if(!tagRequired)throw new Error(`discriminator: "${tagName}" must be required`);return oneOfMapping;function hasRequired({required:required2}){return Array.isArray(required2)&&required2.includes(tagName)}function addMappings(sch,i){if(sch.const){addMapping(sch.const,i)}else if(sch.enum){for(const tagValue of sch.enum){addMapping(tagValue,i)}}else{throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`)}}function addMapping(tagValue,i){if(typeof tagValue!="string"||tagValue in oneOfMapping){throw new Error(`discriminator: "${tagName}" values must be unique strings`)}oneOfMapping[tagValue]=i}}}};exports.default=def}});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,module){module.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,module){"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_core();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(v2=>this.addVocabulary(v2));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;module.exports=exports=Ajv;module.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}=it;if(!opts.validateFormats)return;const fCxt=new ajv_1.KeywordCxt(it,self.RULES.all.format.definition,"format");if(fCxt.$data)validate$DataFormat();else validateFormat();function validate$DataFormat(){const fmts=gen.scopeValue("formats",{ref:self.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=self.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_dist=__commonJS({"../../node_modules/.pnpm/ajv-formats@3.0.1/node_modules/ajv-formats/dist/index.js"(exports,module){"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])}module.exports=exports=formatsPlugin;Object.defineProperty(exports,"__esModule",{value:true});exports.default=formatsPlugin}});import{spawn}from"node:child_process";import{randomUUID as randomUUID6}from"node:crypto";import{rmSync}from"node:fs";import{join as join6}from"node:path";import{fileURLToPath}from"node:url";import{mkSecretDir,loadAgentFile as loadAgentFile2,registry as registry3,writeLaunchArtifact}from"@cotal-ai/core";import{readFileSync}from"node:fs";import{userInfo}from"node:os";import{DEFAULT_SERVER,DEV_OWNER,LAUNCH_MATERIAL_ENV as LAUNCH_MATERIAL_ENV2,brokerUrlHasUserinfo,discardLaunchMaterial,assertLifecycleToken,assertValidChannel,assertValidKind,channelInAllow,credsClaims,eventChannel,idFromCreds,isConcreteChannel,loadAgentFile,parseJoinLink,parsePersonaEndpoints,resolveReadAcl}from"@cotal-ai/core";import{LAUNCH_MATERIAL_ENV,readLaunchMaterial}from"@cotal-ai/core/launch-material";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 token=readMaterial(env)?.controlToken??env.COTAL_CONTROL_TOKEN?.trim();if(path&&token)return{path,token};if(!path&&!token)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(v2){if(!v2)return[];return v2.split(",").map(s=>s.trim()).filter(Boolean)}function endpointsEnv(v2){let raw;try{raw=JSON.parse(v2)}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(v2){return v2===void 0?void 0:splitList(v2)}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_ENV2]?.trim();delete env[LAUNCH_MATERIAL_ENV2];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?userInfo().username:void 0);if(!name)throw new Error("COTAL_NAME, COTAL_AGENT_FILE or COTAL_LINK is required \u2014 a Cotal session needs an explicit identity from its launcher");const resolvedSubscribe=envList(env.COTAL_SUBSCRIBE)??def?.subscribe??link?.channels??[];let resolvedAllowSub;try{resolvedAllowSub=resolveReadAcl(resolvedSubscribe,envList(env.COTAL_ALLOW_SUBSCRIBE)??def?.allowSubscribe)}catch(e){throw new Error(`COTAL config: ${e.message}`)}const resolvedAllowPub=envList(env.COTAL_ALLOW_PUBLISH)??def?.allowPublish??[];for(const ch of[...resolvedSubscribe,...resolvedAllowSub,...resolvedAllowPub])assertValidChannel(ch);const qEnv=splitList(env.COTAL_QUIET),mEnv=splitList(env.COTAL_MUTED);const resolvedQuiet=qEnv.length?qEnv:def?.quiet??[];const resolvedMuted=mEnv.length?mEnv:def?.muted??[];const bothModes=resolvedQuiet.filter(c=>resolvedMuted.includes(c));if(bothModes.length)throw new Error(`COTAL config: channel(s) [${bothModes.join(", ")}] are in both quiet and muted`);for(const[field,chans]of[["quiet",resolvedQuiet],["muted",resolvedMuted]])for(const ch of chans){assertValidChannel(ch);if(!isConcreteChannel(ch))throw new Error(`COTAL config: ${field} channel "${ch}" must be concrete (no wildcard)`);if(!channelInAllow(resolvedAllowSub,ch))throw new Error(`COTAL config: ${field} channel "${ch}" is not within allowSubscribe [${resolvedAllowSub.join(", ")}]`)}const material=readMaterial(env);if(env.COTAL_SERVERS?.trim()&&brokerUrlHasUserinfo(env.COTAL_SERVERS))throw new Error("COTAL config: COTAL_SERVERS must not embed credentials; name the broker URL without user:password@, and pass the credential in COTAL_CREDS, COTAL_TOKEN or a COTAL_LINK");const credsPath=material?.creds??env.COTAL_CREDS?.trim();const initialCreds=credsPath?readFileSync(credsPath,"utf8"):void 0;const credsId=initialCreds?idFromCreds(initialCreds):void 0;const boundedCreds=initialCreds!==void 0&&typeof credsClaims(initialCreds).exp==="number";const declaredId=env.COTAL_ID?.trim()||void 0;if(declaredId&&credsId&&declaredId!==credsId)throw new Error(`COTAL config: COTAL_ID ${declaredId} != creds identity ${credsId} - they must be the same nkey`);const userVars=material?.userAuth?{owner:material.userAuth.owner,actor:material.userAuth.actor,sentinel:material.userAuth.sentinelCredsPath,bearerCmd:JSON.stringify(material.userAuth.bearerCmd)}:{owner:env.COTAL_OWNER?.trim(),actor:env.COTAL_ACTOR?.trim(),sentinel:env.COTAL_SENTINEL_CREDS?.trim(),bearerCmd:env.COTAL_BEARER_CMD?.trim()};const userSet=Object.values(userVars).filter(Boolean).length;if(userSet>0&&userSet<4)throw new Error("COTAL config: user-mode launch needs ALL of COTAL_OWNER, COTAL_ACTOR, COTAL_SENTINEL_CREDS, COTAL_BEARER_CMD \u2014 a partial set is a broken launcher, not a mode");if(userSet&&credsPath)throw new Error("COTAL config: COTAL_CREDS (static auth) and COTAL_OWNER/... (user-mode auth) are mutually exclusive");const lifecycleUid=env.COTAL_LIFECYCLE_UID?.trim()||void 0;const backfillFloorRaw=env.COTAL_BACKFILL_FLOOR?.trim()||void 0;let backfillFloor;if(backfillFloorRaw!==void 0){const n=Number(backfillFloorRaw);if(!Number.isInteger(n)||n<0)throw new Error(`COTAL config: COTAL_BACKFILL_FLOOR must be a non-negative integer stream sequence, got "${backfillFloorRaw}" (a broken launcher, not a mode)`);backfillFloor=n}const acceptedToken=env.COTAL_ACCEPTED_TOKEN?.trim()||void 0;const managerInstanceId=env.COTAL_MANAGER_INSTANCE?.trim()||void 0;if(managerInstanceId!==void 0)assertLifecycleToken(managerInstanceId,"COTAL_MANAGER_INSTANCE");if(acceptedToken&&!credsPath)throw new Error("COTAL config: COTAL_ACCEPTED_TOKEN names a static issuance and needs COTAL_CREDS beside it (a broken launcher, not a mode)");if((credsPath||userSet===4)&&!lifecycleUid)throw new Error("COTAL config: an authed launch (COTAL_CREDS or user-mode) requires COTAL_LIFECYCLE_UID - the launcher mints it at provision time (a broken launcher, not a mode)");let userAuth;if(userSet===4){let bearerCmd;try{bearerCmd=JSON.parse(userVars.bearerCmd)}catch{throw new Error("COTAL config: COTAL_BEARER_CMD must be a JSON argv array")}if(!Array.isArray(bearerCmd)||!bearerCmd.length||!bearerCmd.every(a=>typeof a==="string"))throw new Error("COTAL config: COTAL_BEARER_CMD must be a non-empty JSON array of strings");userAuth={owner:userVars.owner,actor:userVars.actor,sentinelCreds:readFileSync(userVars.sentinel,"utf8"),bearerCmd}}const eventsRequired=material?.eventsRequired===true||!material&&envFlag(env,"COTAL_EVENTS_REQUIRED")===true;if(eventsRequired&&!userAuth)throw new Error("COTAL config: COTAL_EVENTS_REQUIRED is valid only for a user-mode registration launch");if(eventsRequired){const principal=userSet===4?{owner:userVars.owner,actor:userVars.actor}:{owner:DEV_OWNER,actor:credsId??declaredId??""};if(!principal.actor)throw new Error("COTAL config: this space requires events, but the session has no stable principal to derive its event channel");const channel=eventChannel(principal);if(!channelInAllow(resolvedAllowPub,channel))throw new Error(`COTAL config: space "${env.COTAL_SPACE?.trim()||link?.space||"demo"}" requires events, but this session's grant does not cover its event channel "${channel}". Widen the whole user-auth actor row with \`cotal actor grant ${principal.actor} --owner ${principal.owner} --scope <current-scope> --allow-subscribe <current-read> --allow-publish '<current-post>,${channel}' --role <current-role> --label <current-label>\`; actor grant replaces the whole row, so preserve every current field.`)}return{space:env.COTAL_SPACE?.trim()||link?.space||"demo",id:credsId??declaredId,lifecycleUid,backfillFloor,acceptedToken,managerInstanceId,creds:boundedCreds?async()=>readFileSync(credsPath,"utf8"):initialCreds,userAuth,name,role:env.COTAL_ROLE||def?.role||void 0,description:def?.description,tags:def?.tags,meta:def?.meta,capabilities:splitList(env.COTAL_CAPABILITIES).length?splitList(env.COTAL_CAPABILITIES):def?.capabilities,endpoints:env.COTAL_ENDPOINTS!==void 0?endpointsEnv(env.COTAL_ENDPOINTS):def?.endpoints,model:env.COTAL_MODEL?.trim()||void 0,variant:env.COTAL_VARIANT?.trim()||void 0,servers:material?.servers||env.COTAL_SERVERS?.trim()||link?.servers||DEFAULT_SERVER,subscribe:resolvedSubscribe,allowSubscribe:resolvedAllowSub,allowPublish:resolvedAllowPub,eventsRequired,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}from"node:async_hooks";import{EventEmitter}from"node:events";import{hostname as hostname2}from"node:os";import{normalizeMentions,RUN_LAUNCH_DEADLINE_MS,subjectMatches,isConcreteChannel as isConcreteChannel2,isChannelFamily,assertValidChannel as assertValidChannel2,channelInAllow as channelInAllow2,eventChannelPrincipal,resolvePeer as resolvePeerInRoster,peerLabel as peerLabel2,shownPeerName,CotalEndpoint,acquireLocalConsumer,BASELINE_LIFECYCLE_ENDPOINT as BASELINE_LIFECYCLE_ENDPOINT2,assertLifecycleToken as assertLifecycleToken2,EpEnvelopeError as EpEnvelopeError2,isPublishPermissionDenied,unansweredRequest,undeclaredArg,undeclaredArgInstance,EP_UNANSWERED,controlReplyFrom,controlReplyFromThrown,runAgentBearer,ANYCAST_NOTICE_KEY,partsToText,assertValidRole,turnNoticeFilter,renderOnceTask}from"@cotal-ai/core";import{checkEventStartup as checkSharedEventStartup}from"@cotal-ai/core";import{createHash as createHash2,randomUUID as randomUUID2}from"node:crypto";import{open as open2,readFile as readFile2,unlink as unlink2}from"node:fs/promises";import{hostname}from"node:os";import{dirname as dirname2,join as join2}from"node:path";import{ensureDirNoSymlink,eventPrincipalLocation}from"@cotal-ai/core";import{eventPrincipalLocation as eventPrincipalLocation2}from"@cotal-ai/core";import{createHash,randomUUID}from"node:crypto";import{constants}from"node:fs";import{open,readFile,rename,unlink}from"node:fs/promises";import{dirname,join}from"node:path";import{assertIdToken}from"@cotal-ai/core";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 isSafeNonNegInt=n=>Number.isSafeInteger(n)&&n>=0;function docGeneration(path,doc){if(typeof doc.v==="number"&&doc.v<3)return 0;if(!isSafeNonNegInt(doc.gen))throw new WalCorruptError(path,"gen is a safe non-negative integer",`found gen=${String(doc.gen)} on a v${String(doc.v)} document`);return doc.gen}async function openExclusiveNoFollow(path){return open(path,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|(constants.O_NOFOLLOW??0),384)}function assertPendingVintage(path,p,f){if(p.E!==f.lastSubjectSeq)throw new WalCorruptError(path,"pending.E === frontier.lastSubjectSeq",`pending.E=${p.E} frontier.lastSubjectSeq=${f.lastSubjectSeq} \u2014 the frozen expectation is not the tip this WAL believes, so retrying it can only CAS-halt or append at the wrong position`);if(p.seq!==f.seq+1)throw new WalCorruptError(path,"pending.seq === frontier.seq + 1",`pending.seq=${p.seq} frontier.seq=${f.seq} \u2014 a pending frame must be exactly the frontier's successor`);if(p.state==="sent_unacked"){if(p.ackSeq!==void 0)throw new WalCorruptError(path,"sent_unacked has no ackSeq",`state is "sent_unacked" but ackSeq=${String(p.ackSeq)} \u2014 the document contradicts its own tag`);return}if(!isSafeNonNegInt(p.ackSeq))throw new WalCorruptError(path,"acked.ackSeq present",`state is "acked" but ackSeq is ${String(p.ackSeq)}`);if(!(p.ackSeq>f.lastSubjectSeq))throw new WalCorruptError(path,"acked.ackSeq > frontier.lastSubjectSeq",`ackSeq=${p.ackSeq} frontier.lastSubjectSeq=${f.lastSubjectSeq} \u2014 the frontier is of a later vintage than the acked frame, so its sourceCursor may already have passed events that were never published; resuming would drop them with no gap for a consumer to see`)}function parseBrackets(path,field,v2,nullable2){if(v2===null&&nullable2)return null;if(typeof v2!=="object"||v2===null)throw new WalCorruptError(path,`${field} is an object${nullable2?" or null":""}`,JSON.stringify(v2));const b2=v2;if(b2.run!==void 0&&typeof b2.run!=="string")throw new WalCorruptError(path,`${field}.run is a string or absent`,JSON.stringify(b2.run));const lists={text:b2.text,reasoning:b2.reasoning,tools:b2.tools};for(const[k,list]of Object.entries(lists)){if(!Array.isArray(list)||list.some(x2=>typeof x2!=="string"))throw new WalCorruptError(path,`${field}.${k} is an array of strings`,JSON.stringify(list))}if(b2.run===void 0&&b2.text.concat(b2.reasoning,b2.tools).length>0)throw new WalCorruptError(path,`${field} has no open run while messages or tool calls are open`,JSON.stringify(b2));return{run:b2.run,text:b2.text,reasoning:b2.reasoning,tools:b2.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(([id,allowed])=>!id||typeof allowed!=="boolean"))throw new WalCorruptError(path,"payloadCalls is a bounded boolean record","invalid call classification");return{...value}}function parseDoc(path,raw,space,threadId,principal){let d2;try{d2=JSON.parse(raw)}catch(e){throw new WalCorruptError(path,"parseable JSON",e.message)}if(typeof d2!=="object"||d2===null)throw new WalCorruptError(path,"document is an object",typeof d2);const doc=d2;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!==space)throw new WalCorruptError(path,"space matches",`WAL space=${String(doc.space)} caller=${space}`);if(doc.threadId!==threadId)throw new WalCorruptError(path,"threadId matches",`WAL threadId=${String(doc.threadId)} caller=${threadId}`);if(doc.principal!==principal)throw new WalCorruptError(path,"principal matches",`WAL principal=${String(doc.principal)} caller=${principal}`);if(typeof doc.epoch!=="string"||doc.epoch.length===0)throw new WalCorruptError(path,"epoch is a non-empty string",String(doc.epoch));const f=doc.frontier;if(!f||!isSafeNonNegInt(f.seq)||!isSafeNonNegInt(f.lastSubjectSeq))throw new WalCorruptError(path,"frontier is well-formed",JSON.stringify(doc.frontier));if(f.sourceCursor!==void 0&&typeof f.sourceCursor!=="string")throw new WalCorruptError(path,"frontier.sourceCursor is a string or absent",typeof f.sourceCursor);if(f.seq===0!==(f.lastSubjectSeq===0))throw new WalCorruptError(path,"frontier.seq and lastSubjectSeq are both zero or both nonzero",JSON.stringify(f));if((f.seq>0||f.lastSubjectSeq>0)&&typeof f.sourceCursor!=="string")throw new WalCorruptError(path,"a nonzero frontier carries its sourceCursor",JSON.stringify(f));if(doc.pending!==null&&typeof doc.pending!=="object")throw new WalCorruptError(path,"pending is present (null or an object)",doc.pending===void 0?"the key is absent, which is not the same as null":typeof doc.pending);let pending=null;if(doc.pending!==null){const p=doc.pending;if(p.state!=="sent_unacked"&&p.state!=="acked")throw new WalCorruptError(path,"pending.state is a known tag",String(p.state));if(typeof p.id!=="string"||p.id.length===0)throw new WalCorruptError(path,"pending.id is a non-empty string",String(p.id));try{assertIdToken(p.id,"event WAL pending.id")}catch(e){throw new WalCorruptError(path,"pending.id satisfies the wire id grammar",e.message)}if(!isSafeNonNegInt(p.E)||!isSafeNonNegInt(p.seq))throw new WalCorruptError(path,"pending E/seq are safe non-negative integers",JSON.stringify(p));if(typeof p.sourceCursor!=="string")throw new WalCorruptError(path,"pending.sourceCursor is a string",typeof p.sourceCursor);if(!Array.isArray(p.body)||p.body.length===0)throw new WalCorruptError(path,"pending.body is a non-empty array of parts",JSON.stringify(p.body));if(doc.v===1)throw new WalCorruptError(path,"a v1 WAL has no frame in flight",`this v1 document holds a ${String(p.state)} frame, and v2 requires the bracket state that belongs to it \u2014 which v1 never recorded and nothing here can reconstruct. Let the older build settle this frame first, then start the newer one.`);p.brackets=parseBrackets(path,"pending.brackets",p.brackets,false);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||!isSafeNonNegInt(payload.E)||payload.ackSeq!==void 0&&(!isSafeNonNegInt(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,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(space,threadId,principal){return{v:EVENT_WAL_VERSION,gen:0,space,epoch:randomUUID(),threadId,principal,frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}}}async bindSubjectFrontier(frontier){if(this.subject===frontier)return;if(this.subject)throw new Error(`event WAL ${this.path}: a DIFFERENT subject frontier is already bound`);this.subject=frontier}get expectedTip(){if(!this.subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so there is no expectation to publish. The subject is shared by every thread of this principal, so this document's own last ack is not it; bind the principal's record with bindSubjectFrontier first.`);return this.subject.tip}async beginSend(frame){return this.serialize(async()=>{if(this.doc.pending)throw new Error(`event WAL ${this.path}: a frame is already pending; one emit unit is one pending frame`);assertIdToken(frame.id,"event WAL pending id");if(frame.E!==this.expectedTip)throw new Error(`event WAL ${this.path}: E=${frame.E} is not the subject's tip ${this.expectedTip}`);if(frame.seq!==this.doc.frontier.seq+1)throw new Error(`event WAL ${this.path}: seq=${frame.seq} is not the frontier's successor ${this.doc.frontier.seq+1}`);if(!Array.isArray(frame.body)||frame.body.length===0)throw new Error(`event WAL ${this.path}: a frame body must be a non-empty array of parts`);parsePayloadCalls(this.path,frame.payloadCalls);if(frame.payload){assertIdToken(frame.payload.id,"event WAL payload id");if(!isSafeNonNegInt(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(!isSafeNonNegInt(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(!isSafeNonNegInt(ackSeq))throw new Error(`event WAL ${this.path}: ackSeq must be a safe non-negative integer, got ${String(ackSeq)}`);if(ackSeq<=this.expectedTip)throw new Error(`event WAL ${this.path}: ackSeq=${ackSeq} is not ahead of the subject's tip ${this.expectedTip}`);const subject=this.subject;if(!subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so this ack has no shared record to advance`);await this.assertNotClobbering();await subject.advance(ackSeq);await this.write({...this.doc,pending:{...p,state:"acked",ackSeq}})})}async fold(){return this.serialize(async()=>{const p=this.doc.pending;if(!p||p.state!=="acked"||p.ackSeq===void 0)throw new Error(`event WAL ${this.path}: no acked frame to fold`);await this.write({...this.doc,frontier:{seq:p.seq,lastSubjectSeq:p.ackSeq,sourceCursor:p.sourceCursor},pending:null,brackets:p.brackets,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:randomUUID(),frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}})})}async write(next){await this.assertNotClobbering();const stamped={...next,gen:this.doc.gen+1};const tmp=join(dirname(this.path),`.${createHash("sha256").update(this.path).digest("hex").slice(0,12)}.${process.pid}.${randomUUID().slice(0,8)}.wal.tmp`);const body=JSON.stringify(stamped);const fh=await openExclusiveNoFollow(tmp);try{await fh.writeFile(body,"utf8");await fh.sync()}finally{await fh.close()}try{await 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 d2;try{d2=JSON.parse(raw)}catch(e){throw new WalCorruptError(this.path,"parseable JSON",e.message)}if(typeof d2!=="object"||d2===null)throw new WalCorruptError(this.path,"document is an object",typeof d2);const onDisk=docGeneration(this.path,d2);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 createHash2("sha256").update(value).digest("hex").slice(0,16)}function eventWalLocation(opts){const principal=eventPrincipalLocation(opts);const threadDir=join2(principal.principalDir,h(opts.threadId));return{...principal,threadDir,walPath:join2(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:randomUUID2(),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 open2(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=dirname2(dir)){await fsyncDir(dir);if(dir===opts.workspaceRoot||dirname2(dir)===dir)break}const lock=await acquirePrincipalLock(loc.lockPath);return{...loc,lock}}import{EventStateConflictError}from"@cotal-ai/core";async function checkEventStartup(ep,env){await checkSharedEventStartup({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 g2=globalThis;return g2[KEY]??={handoffs:new Map}}var keyOf=(uid,goalId)=>`${uid}:${goalId}`;function onceHandoffState(uid,goalId){return proc().handoffs.get(keyOf(uid,goalId))?.state??"pending"}function claimOnceHandoff(uid,goalIds){const p=proc();if(goalIds.some(id=>onceHandoffState(uid,id)!=="pending"))return false;for(const id of goalIds){const timer=setTimeout(()=>p.timedOut?.(uid,id),ONCE_HANDOFF_MS);timer.unref?.();p.handoffs.set(keyOf(uid,id),{state:"claimed",timer})}return true}function confirmOnceHandoff(uid,goalId){const h2=proc().handoffs.get(keyOf(uid,goalId));if(h2?.state==="sealed")return false;if(h2?.timer!==void 0)clearTimeout(h2.timer);proc().handoffs.set(keyOf(uid,goalId),{state:"confirmed"});return true}function sealOnceHandoff(uid,goalId){const h2=proc().handoffs.get(keyOf(uid,goalId));if(h2?.state!=="claimed")return false;if(h2.timer!==void 0)clearTimeout(h2.timer);proc().handoffs.set(keyOf(uid,goalId),{state:"sealed"});return true}function endOnceHandoff(uid,goalId){const h2=proc().handoffs.get(keyOf(uid,goalId));if(h2?.state==="confirmed"||h2?.state==="sealed")return;if(h2?.timer!==void 0)clearTimeout(h2.timer);proc().handoffs.set(keyOf(uid,goalId),{state:"sealed"})}function stopOnceHandoffTimer(uid,goalId){const h2=proc().handoffs.get(keyOf(uid,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}import{LINE_BREAK,peerLabel}from"@cotal-ai/core/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(text){return text.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}`}import{drainAndClose}from"@cotal-ai/core";import{BASELINE_LIFECYCLE_ENDPOINT,EpEnvelopeError,dialerFor,goalFollowRefusal,invokeCommand,isPermissionDenied,issuedUserCaller,managerCallerBinding,registryListingCaller,replyRefusedBeforeEffect,resolveService,standaloneConnectOpts}from"@cotal-ai/core";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,token,exp,ask){const user=config2.userAuth;const binding=managerCallerBinding(token,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId});const railKey=binding.credentialId??token;const connectOpts=standaloneConnectOpts({bearer:token,sentinelCreds:user.sentinelCreds,tls:config2.tls});const connId=String(connectOpts.name);const nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:1e4});const issued=async()=>{try{const caller=await issuedUserCaller(nc,config2.space,connId,binding.caller);legacyRail.delete(railKey);return caller}catch(e){if(!isPermissionDenied(e))throw e;rememberLegacyRail(railKey);return void 0}};try{const skipped=onLegacyRail(railKey);const caller=skipped?void 0:await issued();const listing=caller??await registryListingCaller(nc,config2.space,binding.caller,{connId,...exp!==void 0?{exp}:{}});return await ask(nc,listing??(skipped?await issued():void 0))}finally{await drainAndClose(nc)}}async function invokeUserManager(config2,bearer,command,args,opts={}){opts.signal?.throwIfAborted();const user=config2.userAuth;const endpoint=BASELINE_LIFECYCLE_ENDPOINT;let nc;let caller;let instanceId;let service;let skippedAcceptedRead;const onAbort=()=>{void nc?.close()};const resolve=(signal=opts.signal,deadlineMs=opts.deadlineMs??1e4)=>resolveService(nc,config2.space,endpoint,caller,{instanceId,deadlineMs,signal,commands:opts.follow?[command,"goal-result"]:[command],...opts.follow&&command!=="goal-result"?{optionalCommands:["goal-result"]}:{}});const resolvePrepared=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const remaining=()=>{signal?.throwIfAborted();const left=deadline-Date.now();if(left<=0)throw new EpEnvelopeError("deadline-exceeded","the deadline passed before the manager was resolved; the manager request WAS NOT RUN",void 0,"not-executed");return left};try{return await resolve(signal,remaining())}catch(error51){if(!skippedAcceptedRead||!isPermissionDenied(error51))throw error51;const{key,connId}=skippedAcceptedRead;skippedAcceptedRead=void 0;remaining();caller=await issuedUserCaller(nc,config2.space,connId,caller);legacyRail.delete(key);return resolve(signal,remaining())}};const connect2=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const token=await bearer(signal);let credentialId;({caller,instanceId,credentialId}=managerCallerBinding(token,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId}));const connectOpts=standaloneConnectOpts({bearer:token,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??token;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 connect2(signal,deadline);service=await resolvePrepared(signal,deadline)};const invoke=async(signal=opts.signal)=>{const unfollowable=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable)return unfollowable;const invokeOpts={target:opts.target,deadlineMs:opts.deadlineMs,signal};const result=await invokeCommand(nc,config2.space,service,command,args,invokeOpts);if(result.reply.ok===false&&replyRefusedBeforeEffect(result.reply.error)){try{service=await resolve(signal);const unfollowable2=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable2)throw new Error(unfollowable2.reply.error.message)}catch(error51){return{...result,reply:{...result.reply,error:{...result.reply.error,message:`${command} WAS NOT RUN; manager instance ${instanceId} refused before effects, and re-resolution failed: ${error51 instanceof Error?error51.message:String(error51)}`}}}}return invokeCommand(nc,config2.space,service,command,args,invokeOpts)}return result};opts.signal?.addEventListener("abort",onAbort,{once:true});try{if(opts.follow)return await opts.follow(invoke,prepare);await connect2();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.8";import{createHash as createHash3,randomUUID as randomUUID3}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,b2){return a.ts!==b2.ts?a.ts>b2.ts:a.id>b2.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,b2){const[x2,y2]=[a,b2].map(v2=>v2.split(/[-+]/)[0].split(".").map(Number));for(let i=0;i<3;i++)if(x2[i]!==y2[i])return(x2[i]??0)-(y2[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(m2){return m2.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(m2){return createHash3("sha256").update(JSON.stringify(m2)).digest("base64url")}function sleep(ms){return new Promise(r=>setTimeout(r,ms))}function ingestDedupKey(id){return id===""?void 0:id}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,v2])=>`${k}: ${String(v2)}`).join(", ");const by=typeof a.deadlineAt==="number"?`, by ${new Date(a.deadlineAt).toISOString()}`:"";const refused=typeof a.refused==="string"?`
|
|
69
69
|
Your last answer was refused: ${a.refused}`:"";return`
|
|
70
70
|
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`
|
|
71
71
|
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}}.
|
|
@@ -78,7 +78,7 @@ ${context}${ask}`});const text=`\u{1F3AF} Cotal \u2014 a run handed you ${waitin
|
|
|
78
78
|
${blocks.join("\n")}
|
|
79
79
|
(Do the work now with your own tools. 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,goalIds:waiting.map(t=>t.goalId)}}commitSurfacedTurns(goalIds){if(this.config.turnRelay===false&&!this.nativeTurnLeaseValid())return;for(const id of goalIds){const t=this.activeTurns.get(id);if(t?.once!==void 0&&!confirmOnceHandoff(this.onceUid(),id))continue;if(t)t.surfaced=true}}claimTurns(goalIds){return claimOnceHandoff(this.onceUid(),goalIds.filter(id=>(this.activeTurns.get(id)??this.settledTurns.get(id))?.once!==void 0))}releaseTurns(goalIds){for(const id of goalIds){if(this.activeTurns.get(id)?.once===void 0)continue;if(sealOnceHandoff(this.onceUid(),id))void this.reportUnconfirmed(id)}}noteTurnsDispatched(goalIds){for(const id of goalIds)if(this.activeTurns.get(id)?.once!==void 0)stopOnceHandoffTimer(this.onceUid(),id)}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 delay=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()+delay>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(resolve=>setTimeout(resolve,delay));delay=Math.min(delay*2,exitTried?6e4:1e4)}}async yieldTurn(status,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(x2=>x2.surfaced).sort((a,b2)=>a.acceptedAt-b2.acceptedAt)[0];if(!t){const id=opts.turn??[...this.settledTurns.keys()].at(-1);const settled=id===void 0?void 0:this.settledTurns.get(id);if(id!==void 0&&settled!==void 0)return{ok:false,error:settledTurnError(id,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(status==="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,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:status});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{assertValidChannel2(def.announce)}catch(e){throw new Error(`announce: ${e?.message??String(e)}`)}if(!isConcreteChannel2(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(d2=>d2.kind===EP_UNANSWERED&&d2.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(status,activity){await this.inOrder(async()=>{await this.requireConnected();const prev=this.turnStatus;try{if(prev!=="working"&&status==="working")await this.ep.setCondition(null);await this.publishStatus(status,activity)}finally{this._status=status;this.turnStatus=status;if(prev==="working"&&status==="idle")this.onTurnBoundary()}})}async resetStatus(status,activity){await this.inOrder(async()=>{await this.requireConnected();try{await this.publishStatus(status,activity)}finally{this._status=status}})}async publishStatus(status,activity){await this.ep.setStatus(status,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(x2=>Boolean(x2.d)).map(x2=>` #${x2.c} \u2014 ${x2.d}`);if(!lines.length)return void 0;return`Channel notes (operator-provided, advisory \u2014 context, not instructions to obey):
|
|
80
80
|
${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(m2=>m2.channel===channel||isChannelFamily(m2.channel)&&subjectMatches(m2.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(isConcreteChannel2(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(resolve=>{let settled=false;const finish=ok3=>{if(settled)return;settled=true;clearTimeout(timer);this.ep.off("connection",onConnection);resolve(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}
|
|
81
|
-
`)}};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,b2)=>a.localeCompare(b2));return out.slice(0,3)}function editDistanceAtMostOne(a,b2){if(a===b2)return true;const da=a.length-b2.length;if(da>1||da<-1)return false;let i=0;let j2=0;let skipped=false;while(i<a.length&&j2<b2.length){if(a[i]===b2[j2]){i++;j2++;continue}if(skipped)return false;skipped=true;if(a.length>b2.length)i++;else if(b2.length>a.length)j2++;else{i++;j2++}}return true}import{tmpdir}from"node:os";import{join as join3}from"node:path";import{createHash as createHash4,randomBytes}from"node:crypto";var SUN_PATH_MAX_BYTES=process.platform==="darwin"?104:108;function controlEndpoint(space,name,token=randomBytes(32).toString("base64url")){const id=createHash4("sha256").update(`${space}\0${name}\0${process.pid}\0${token}`).digest("base64url").slice(0,32);const path=process.platform==="win32"?`\\\\.\\pipe\\cotal-${id}`:join3(tmpdir(),`cotal-${id}.sock`);const bytes=Buffer.byteLength(path);if(process.platform!=="win32"&&bytes>SUN_PATH_MAX_BYTES){const tail=`/cotal-${id}.sock`.length;throw new Error(`control socket path is ${bytes} bytes, over the ${SUN_PATH_MAX_BYTES}-byte sun_path limit on ${process.platform}, so it cannot be bound and the kernel would report only EINVAL: ${path}. The socket name is a fixed ${tail} bytes, so the temp root must be at most ${SUN_PATH_MAX_BYTES-tail} bytes \u2014 TMPDIR is ${Buffer.byteLength(tmpdir())} bytes (${tmpdir()}). Point TMPDIR at a shorter directory.`)}return{path,token}}import{eventChannel as eventChannel2,LAUNCH_MATERIAL_ENV as LAUNCH_MATERIAL_ENV3,parsePrincipalKey,principalKey,writeLaunchMaterial}from"@cotal-ai/core";import{dirname as dirname3}from"node:path";import{EVENT_CHANNEL_PREFIX,eventChannel as eventChannel3,eventChannelPrincipal as eventChannelPrincipal2,isEventChannel}from"@cotal-ai/core";var OS_ENV_ALLOW=["PATH","HOME","USERPROFILE","HOMEDRIVE","HOMEPATH","USER","LOGNAME","SHELL","COMSPEC","PATHEXT","TERM","COLORTERM","COLORFGBG","LANG","LC_ALL","LC_CTYPE","LC_MESSAGES","TZ","TEMP","TMPDIR","TMP","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_STATE_HOME","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","XDG_RUNTIME_DIR","DO_NOT_TRACK","CI","SystemRoot","windir","SystemDrive","PROCESSOR_ARCHITECTURE","NUMBER_OF_PROCESSORS","ALLUSERSPROFILE","ProgramData","ProgramFiles","ProgramFiles(x86)","CommonProgramFiles","PUBLIC"];var OPERATOR_ENV_KEEP=["COTAL_HOME","COTAL_FEEDBACK_KEY","COTAL_FEEDBACK_EMAIL","COTAL_FEEDBACK_URL","COTAL_DEFAULT_AGENT","COTAL_DEFAULT_PERSONA","COTAL_SKIP_CONNECTOR_SEED","COTAL_SKIP_ASSIST","COTAL_DETACH_KEY","COTAL_COMPLETE_DEBUG","COTAL_DEBUG","COTAL_SERVE_HEADLESS","COTAL_MEMBERSHIP_INTERVAL_MS","COTAL_DELIVERY_BROKER_GONE_MS","COTAL_IDP_TIMEOUT_MS","COTAL_CODEX_BIN","COTAL_OPENCODE_BIN","COTAL_ORCA_BIN","COTAL_TELEMETRY","COTAL_TELEMETRY_DISABLED","COTAL_TELEMETRY_URL"];function launchEnv(opts={}){for(const[source,keys]of[["spawn.env",opts.envAllow],["MCP environment references",opts.mcpKeys]]){for(const k of keys??[]){const name=k.toUpperCase();if(name.startsWith("COTAL_")&&!OPERATOR_ENV_KEEP.some(keep=>keep===name))throw new Error(`${source} cannot list "${k}": the launcher sets COTAL_ names for each seat, and only the machine-wide ones such as COTAL_HOME cross from the spawning process`)}}const env={};const sourceKey=new Map;for(const k of Object.keys(process.env))sourceKey.set(k.toLowerCase(),k);const copy=name=>{const src=sourceKey.get(name.toLowerCase());if(src===void 0)return;const v2=process.env[src];if(v2!==void 0)env[src]=v2};for(const k of OS_ENV_ALLOW)copy(k);for(const k of OPERATOR_ENV_KEEP)copy(k);for(const k of[...opts.providerKeys??[],...opts.mcpKeys??[],...opts.envAllow??[]])copy(k);return env}function aclEnv(opts){const env={};if(opts.subscribe)env.COTAL_SUBSCRIBE=opts.subscribe.join(",");if(opts.allowSubscribe)env.COTAL_ALLOW_SUBSCRIBE=opts.allowSubscribe.join(",");if(opts.allowPublish)env.COTAL_ALLOW_PUBLISH=opts.allowPublish.join(",");if(opts.capabilities?.length)env.COTAL_CAPABILITIES=opts.capabilities.join(",");if(opts.endpoints!==void 0)env.COTAL_ENDPOINTS=JSON.stringify(opts.endpoints);return env}var UNSAFE_LAUNCH_OPTION_KEYS=new Set(["__proto__","constructor","prototype"]);var LAUNCH_OPTION_KEY=/^[A-Za-z][A-Za-z0-9_-]*$/;function connectorLaunchOptions(connector,launchOptions){if(!launchOptions)return[];for(const k of Object.keys(launchOptions))if(UNSAFE_LAUNCH_OPTION_KEYS.has(k)||!LAUNCH_OPTION_KEY.test(k))throw new Error(`${connector} connector: launch option key ${JSON.stringify(k)} is not a valid flag name`);return Object.entries(launchOptions)}function materialEnv(opts,artifacts){if(opts.userAuth&&opts.creds)throw new Error("launch: creds (static auth) and userAuth (user-mode auth) are mutually exclusive \u2014 one launch carries one identity plane");const material={};if(opts.creds)material.creds=opts.creds;if(opts.servers)material.servers=opts.servers;if(opts.token)material.token=opts.token;if(opts.controlToken)material.controlToken=opts.controlToken;if(opts.eventsRequired)material.eventsRequired=true;if(opts.eventPayloads===false)material.eventPayloadsWithheld=true;if(opts.userAuth)material.userAuth=opts.userAuth;if(Object.keys(material).length===0)return{};const path=writeLaunchMaterial(material);artifacts.push(dirname3(path));return{[LAUNCH_MATERIAL_ENV3]:path}}function launchArmsEvents(opts){return opts.events!==false||opts.eventsRequired===true}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 eventChannel2(ep.principal)}import{AGUI_FRAME_KIND,AGUI_EVENT_TYPE,isAguiFramePart}from"@cotal-ai/core";import{AGUI_FRAME_KIND as AGUI_FRAME_KIND2,AGUI_EVENT_TYPE as AGUI_EVENT_TYPE2,isAguiFramePart as isAguiFramePart2}from"@cotal-ai/core";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 b2=new _AguiBrackets;b2.run=s.run;for(const id of s.text)b2.text.add(id);for(const id of s.reasoning)b2.reasoning.add(id);for(const id of s.tools)b2.tools.add(id);return b2}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_TYPE2.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_TYPE2.RUN_FINISHED||t===AGUI_EVENT_TYPE2.RUN_ERROR){if(t===AGUI_EVENT_TYPE2.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_TYPE2.TEXT_MESSAGE_START:return this.openId(this.text,String(e.messageId),t);case AGUI_EVENT_TYPE2.TEXT_MESSAGE_CONTENT:return this.requireOpen(this.text,String(e.messageId),t);case AGUI_EVENT_TYPE2.TEXT_MESSAGE_END:return this.closeId(this.text,String(e.messageId),t);case AGUI_EVENT_TYPE2.REASONING_MESSAGE_START:return this.openId(this.reasoning,String(e.messageId),t);case AGUI_EVENT_TYPE2.REASONING_MESSAGE_CONTENT:return this.requireOpen(this.reasoning,String(e.messageId),t);case AGUI_EVENT_TYPE2.REASONING_MESSAGE_END:return this.closeId(this.reasoning,String(e.messageId),t);case AGUI_EVENT_TYPE2.TOOL_CALL_START:return this.openId(this.tools,String(e.toolCallId),t);case AGUI_EVENT_TYPE2.TOOL_CALL_ARGS:return this.requireOpen(this.tools,String(e.toolCallId),t);case AGUI_EVENT_TYPE2.TOOL_CALL_END:return this.closeId(this.tools,String(e.toolCallId),t);case AGUI_EVENT_TYPE2.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_TYPE2.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 id=e.value.toolCallId;if(this.tools.has(id))throw new AguiVocabularyError(`${TOOL_RESULT_EVENT} for "${id}" 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(set2,id,t){if(set2.has(id))throw new AguiVocabularyError(`${t} re-opened "${id}" while already open`);set2.add(id)}requireOpen(set2,id,t){if(!set2.has(id))throw new AguiVocabularyError(`${t} for "${id}" which is not open`)}closeId(set2,id,t){if(!set2.delete(id))throw new AguiVocabularyError(`${t} for "${id}" 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_KIND2,protocol:AGUI_PROTOCOL,threadId:opts.threadId,runId:opts.runId,epoch:opts.epoch,seq:opts.seq,events:opts.events}}function parseAguiFrame(part){if(!isAguiFramePart2(part))throw new AguiVocabularyError(`not an AG-UI frame: expected kind ${JSON.stringify(AGUI_FRAME_KIND2)}, 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_TYPE2));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_TYPE2.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_TYPE2.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_TYPE2.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_TYPE2.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_TYPE2.TEXT_MESSAGE_CONTENT,messageId:o.messageId,delta:o.delta,timestamp:o.timestamp,...o.cotal?{cotal:o.cotal}:{}}}function textMessageEnd(o){return{type:AGUI_EVENT_TYPE2.TEXT_MESSAGE_END,messageId:o.messageId,timestamp:o.timestamp,...o.cotal?{cotal:o.cotal}:{}}}function toolCallStart(o){return{type:AGUI_EVENT_TYPE2.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_TYPE2.TOOL_CALL_END,toolCallId:o.toolCallId,timestamp:o.timestamp,...o.cotal?{cotal:o.cotal}:{}}}var TRUNCATABLE_FIELDS=[{type:AGUI_EVENT_TYPE2.TOOL_CALL_ARGS,field:"delta"},{type:AGUI_EVENT_TYPE2.TOOL_CALL_RESULT,field:"content"},{type:AGUI_EVENT_TYPE2.TEXT_MESSAGE_CONTENT,field:"delta"}];var EGRESS_FORBIDDEN_TYPES=new Set([AGUI_EVENT_TYPE2.TOOL_CALL_ARGS,AGUI_EVENT_TYPE2.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_TYPE2.RUN_STARTED,new Set(["type","timestamp","rawEvent","threadId","runId","parentRunId","input","cotal"])],[AGUI_EVENT_TYPE2.RUN_FINISHED,new Set(["type","timestamp","rawEvent","threadId","runId","result","outcome","cotal"])],[AGUI_EVENT_TYPE2.RUN_ERROR,new Set(["type","timestamp","rawEvent","message","code","cotal"])],[AGUI_EVENT_TYPE2.TEXT_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","name","cotal"])],[AGUI_EVENT_TYPE2.TEXT_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE2.TEXT_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE2.TOOL_CALL_START,new Set(["type","timestamp","rawEvent","toolCallId","toolCallName","parentMessageId","cotal"])],[AGUI_EVENT_TYPE2.TOOL_CALL_ARGS,new Set(["type","timestamp","rawEvent","toolCallId","delta","cotal"])],[AGUI_EVENT_TYPE2.TOOL_CALL_END,new Set(["type","timestamp","rawEvent","toolCallId","cotal"])],[AGUI_EVENT_TYPE2.TOOL_CALL_RESULT,new Set(["type","timestamp","rawEvent","messageId","toolCallId","content","role","cotal"])],[AGUI_EVENT_TYPE2.REASONING_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","cotal"])],[AGUI_EVENT_TYPE2.REASONING_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE2.REASONING_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE2.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 v2=value;if(typeof v2.toolCallId!=="string")return"value";if(typeof v2.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 v2=value;return{toolCallId:v2.toolCallId,isError:v2.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_TYPE2.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_TYPE2.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_TYPE2.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_TYPE2.RUN_ERROR?egressRunError(e):isToolResultMarker(e)?egressToolResultMarker(e):e)}function frozenBodyEgressVerdict(body){let unreadable=false;try{for(const part of body){try{if(!isAguiFramePart2(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_TYPE2.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 createHash6,randomUUID as randomUUID5}from"node:crypto";import{dirname as dirname5,join as join5}from"node:path";import{isAguiFramePart as isAguiFramePart3,isCasLoss,principalKey as principalKey2}from"@cotal-ai/core";import{execFileSync}from"node:child_process";init_external();init_external();import{isConcreteChannel as isConcreteChannel4,isChannelFamily as isChannelFamily2,assertValidChannel as assertValidChannel3,MAX_CHANNEL_LENGTH,channelInAllow as channelInAllow3,patternInAllow,AmbiguousPeerError,peerLabel as peerLabel4,sharedNameIds,assertLifecycleToken as assertLifecycleToken3,isPermissionDenied as isPermissionDenied2,renderLifecycleBlocked,EpEnvelopeError as EpEnvelopeError3,EP_UNANSWERED as EP_UNANSWERED2,REGISTRY_PAGE_LIMIT,LANG_PROBLEM_DETAIL_KIND,formatAge,parseDuration,presenceAges,presenceText,isAnycastSeq}from"@cotal-ai/core";var ok=text=>({text});var err=text=>({text,isError:true});function receipt(status,value){if(status!==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 headers={"content-type":"application/json"};const body={...input};if(options.key){headers.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,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{isConcreteChannel as isConcreteChannel3,parsePrincipalKey as parsePrincipalKey2,peerLabel as peerLabel3}from"@cotal-ai/core";import{createHash as createHash5}from"node:crypto";import{readFileSync as readFileSync2}from"node:fs";import{join as join4}from"node:path";import{gunzipSync}from"node:zlib";var DOCS_VERSION="0.164.6";function loadDocsMetadata(){return{"version":"0.164.6","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here (informative)","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here (informative)","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept (informative)","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference: the `cotal_*` tool surface every connected agent gets.","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference (informative task card)","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept (informative)","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference (the persisted form of an agent's identity + persona, read by every launcher)","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference (informative)","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide: describes the TypeScript reference implementation, not the wire contract.","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide (informative)","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI), not the wire contract.","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI and connectors), not the wire contract.","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide (informative)","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide (informative)","category":"Guide","summary":"Launch Codex on a Cotal mesh, connect your own Codex conversations, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide (informative)","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-opencode","title":"Connect OpenCode","kind":"Guide (informative)","category":"Guide","summary":"Launch OpenCode on a Cotal mesh and choose the model and options for your installed version."},{"slug":"connect-pi","title":"Connect pi (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Launch pi on a Cotal mesh or load the Cotal extension into your own pi host."},{"slug":"connector-runtime-reference","title":"Connector runtime reference","kind":"Reference","category":"Reference","summary":"Shared connection recovery, presence display, send receipts, delivery acknowledgement, reply correlation, and resume records."},{"slug":"connectors","title":"Connectors","kind":"Guide (informative)","category":"Guide","summary":"Choose an agent application and connect its sessions to a Cotal mesh."},{"slug":"console","title":"Use the console","kind":"Guide","category":"Guide","summary":"Inspect a mesh from the terminal and use authorized operator controls."},{"slug":"control-discovery","title":"Endpoint discovery","kind":"Reference","category":"Reference","summary":"Command contracts, manager instance selection, request outcomes, and service registration."},{"slug":"control-lifecycle","title":"Manager lifecycle contracts","kind":"Reference","category":"Reference","summary":"Managed identities, static slots, spawn goals, chat sessions, terminal access, and grants."},{"slug":"control-surface","title":"The control surface","kind":"Concept (informative)","category":"Concept","summary":"How clients discover commands, address service instances, and follow durable actions."},{"slug":"dashboard-api","title":"Dashboard HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Dashboard HTTP interface."},{"slug":"define-a-team","title":"Define a team","kind":"Guide (informative)","category":"Guide","summary":"Describe agents and channels in a manifest, then boot or deploy that team."},{"slug":"delivery-daemon","title":"The delivery daemon","kind":"Concept (informative)","category":"Concept","summary":"Why durable channel delivery needs a trusted service, and what happens without it."},{"slug":"delivery-service-reference","title":"Delivery service contracts","kind":"Reference","category":"Reference","summary":"Fan-out, trusted reads, leases, membership retirement, credential adoption, and daemon lifetime."},{"slug":"deploy","title":"Deploy agent teams","kind":"Guide (informative)","category":"Guide","summary":"Review the container example, its current build limitation, and the credentials it needs."},{"slug":"embedding-daemons","title":"Embedded daemon lifecycle","kind":"Reference","category":"Reference","summary":"Process runners, account-scoped hosted services, and delivery credential renewal."},{"slug":"embedding-delegated-seats","title":"Delegated seat contracts","kind":"Reference","category":"Reference","summary":"Managed lifecycle handoff, provider closure guarantees, and the limits of delegated recovery contracts."},{"slug":"embedding-endpoints","title":"CotalEndpoint reference","kind":"Reference","category":"Reference","summary":"Presence metadata, observer freshness, write diagnosis, liveness probes, and DM-only endpoint readers."},{"slug":"embedding-exports","title":"Embedding package exports","kind":"Reference","category":"Reference","summary":"Public package entry points, endpoint credentials, and Manager execution contracts."},{"slug":"embedding-manager","title":"Manager embedding authority","kind":"Reference","category":"Reference","summary":"Manager startup, signer custody, remote authority callbacks, and delegated user intent contracts."},{"slug":"embedding-provisioning","title":"Embedded space provisioning","kind":"Reference","category":"Reference","summary":"Broker trust, space credentials, durable host state, and current hosting limitations."},{"slug":"embedding-remote-clients","title":"Embedded remote clients","kind":"Reference","category":"Reference","summary":"MCP conversation routing, browser callers, remote Manager clients, and private-result prerequisites."},{"slug":"embedding-schema-inspection","title":"Space schema inspection","kind":"Reference","category":"Reference","summary":"Resource definitions, bounded read-only observations, and the limits of schema and initialization comparisons."},{"slug":"embedding-service-access","title":"Service endpoint access","kind":"Reference","category":"Reference","summary":"Authority proofs, serving credentials, verified grants, and renewal."},{"slug":"embedding-service-authority","title":"Service authority contracts","kind":"Reference","category":"Reference","summary":"Service authority contracts, platform supervisors, revocation prerequisites, and native custody limits."},{"slug":"embedding-service-callers","title":"Service endpoint callers","kind":"Reference","category":"Reference","summary":"Caller policy grants, broker payload prerequisites, revocation, and recovery limits."},{"slug":"embedding-service-custody","title":"Native service custody","kind":"Reference","category":"Reference","summary":"Immutable service reservations, bootstrap, cancellation, and bounded writer guarantees."},{"slug":"embedding-service-host","title":"Service endpoint hosting","kind":"Reference","category":"Reference","summary":"Owner approvals, native host operations, registration, and lifecycle custody."},{"slug":"embedding","title":"Embedding Cotal","kind":"Concept (informative)","category":"Concept","summary":"Choose the published packages and authority boundaries for a service built on Cotal."},{"slug":"examples","title":"Examples","kind":"Start here (informative)","category":"Start here","summary":"Choose a working example of agents collaborating through Cotal."},{"slug":"feedback-intake-api","title":"Feedback intake HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Feedback intake HTTP interface."},{"slug":"glossary","title":"Glossary","kind":"Reference (informative)","category":"Reference","summary":"Definitions of Cotal's identity, messaging, delivery, and operator terms."},{"slug":"hermes-connector-reference","title":"Hermes connector reference","kind":"Reference","category":"Reference","summary":"Hermes gateway ownership, profile state, delivery rules, presence hooks, and session forks."},{"slug":"identity-authority","title":"Credential authority","kind":"Reference","category":"Reference","summary":"Credential minting, profile grants, endpoint generations, and capability limits."},{"slug":"identity-service-auth","title":"Auth service integration","kind":"Reference","category":"Reference","summary":"Auth-service listeners, pinned IdP proofs, bridge hooks, and owner derivation."},{"slug":"identity-user-auth","title":"User-auth lifecycle","kind":"Reference","category":"Reference","summary":"Actor grants, delegation, catalogs, enrollment, sessions, views, and remote managers."},{"slug":"installation","title":"Install Cotal","kind":"Start here","category":"Start here","summary":"Install the cotal command with the shell installer or npm."},{"slug":"jcode-connector-reference","title":"Jcode connector reference","kind":"Reference","category":"Reference","summary":"Private Jcode process ownership, session forks, readiness checks, model selection, and event delivery."},{"slug":"lang-card","title":"The cotal-lang card","kind":"Reference (informative)","category":"Reference","summary":"Effect signatures, result shapes, concurrency rules, and common refusals for cotal-lang programs."},{"slug":"launch-agents","title":"Launch agents","kind":"Guide","category":"Guide","summary":"Launch an agent through a manager, attach to its terminal, and choose its persona and runtime."},{"slug":"manager-console-api","title":"Manager console HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Manager console HTTP interface."},{"slug":"manifest","title":"Mesh manifest (cotal.yaml)","kind":"Reference: every field of the mesh manifest.","category":"Reference","summary":"Manifest fields, persona overrides, channel grants, and access resolution for one team."},{"slug":"mesh-commands","title":"Mesh command catalog","kind":"Reference (informative)","category":"Reference","summary":"Built-in endpoint command declarations, capabilities, targeting modes and JSON schemas."},{"slug":"mesh-view","title":"MeshView","kind":"Reference: TypeScript observer surfaces (`MeshView`)","category":"Reference","summary":"The TypeScript observer model used by the terminal console and line stream, with dashboard feature coverage."},{"slug":"opencode-connector-reference","title":"OpenCode connector reference","kind":"Reference","category":"Reference","summary":"OpenCode version support, injected configuration, session delivery, and structured event limits."},{"slug":"overview","title":"API reference","kind":"Reference","category":"Reference","summary":"Find Cotal CLI commands, agent tools, configuration fields, and data models."},{"slug":"pi-connector-reference","title":"pi connector reference","kind":"Reference","category":"Reference","summary":"pi host lifecycle, delivery confirmation, continuation attempts, managed recovery, and event persistence."},{"slug":"presence-and-delivery","title":"Message flow","kind":"Concept (informative)","category":"Concept","summary":"How presence, routing, durable delivery, and attention determine what peers can observe and receive."},{"slug":"recover-a-mesh","title":"Recover a mesh","kind":"Guide","category":"Guide","summary":"Use status and logs to diagnose service failures, stuck presence, or a frozen registration gate."},{"slug":"register-a-mesh","title":"Register a mesh","kind":"Guide","category":"Guide","summary":"Choose the mesh a command targets and register remote brokers with verified trust."},{"slug":"release","title":"Publishing a release","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"Cotal releases with pnpm, Changesets, and one GitHub Actions workflow, changesets.yml."},{"slug":"remote-supervision","title":"Supervise a remote mesh","kind":"Guide","category":"Guide","summary":"Separate broker and manager hosts, publish an exchange, and enroll remote agents."},{"slug":"roadmap","title":"Roadmap","kind":"Project (non-normative)","category":"Project","summary":"Cotal is pre-1.0, and the v0.x wire contract can still change under the change process."},{"slug":"run-a-mesh","title":"Run a mesh","kind":"Guide (informative)","category":"Guide","summary":"Start, inspect, and stop the local stack in a prepared project."},{"slug":"security-boundaries","title":"Host boundaries","kind":"Reference","category":"Reference","summary":"Credential lifetimes, metadata exposure, launch authority, and local process risks."},{"slug":"security","title":"Security model","kind":"Concept (informative threat model)","category":"Concept","summary":"Threats, guarantees, and limits for peers sharing a trusted NATS broker."},{"slug":"setup-internals","title":"Setup internals (maintainer notes)","kind":"Project (non-normative maintainer notes)","category":"Project","summary":"How cotal setup works, and the cross-repo couplings it depends on."},{"slug":"setup","title":"Configure a space","kind":"Guide","category":"Guide","summary":"Prepare a project, choose its agent application, and save its space settings."},{"slug":"spaces","title":"Spaces","kind":"Concept (informative)","category":"Concept","summary":"How spaces isolate collaboration, and how channels, permissions, membership, and conversation ids organize work within them."},{"slug":"stability","title":"Interface stability","kind":"Project (informative)","category":"Project","summary":"Cotal's packages are pre-1.0 and publish in lockstep."},{"slug":"supervise-processes","title":"Supervise the stack","kind":"Guide","category":"Guide","summary":"Choose process ownership under systemd and monitor actual component health."},{"slug":"telemetry","title":"Telemetry","kind":"Reference","category":"Reference","summary":"CLI usage telemetry fields, levels, storage, delivery, and opt-outs."},{"slug":"transport","title":"Transport vs protocol","kind":"Concept (informative)","category":"Concept","summary":"How Cotal's wire contract uses NATS and JetStream, and what another transport binding would have to preserve."},{"slug":"upgrade-cotal","title":"Upgrade Cotal","kind":"Guide","category":"Guide","summary":"Choose an exact release, prepare the deployment, and verify the upgraded installation."},{"slug":"upgrading","title":"Upgrading a running deployment","kind":"Guide (informative)","category":"Guide","summary":"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=readFileSync2(join4(import.meta.dirname,"docs-bundle.bin"));if(packed.length!==1251988||createHash5("sha256").update(packed).digest("hex")!=="0976e4aafea8722ea0face42823fac8d64939170ea04b894c0fb9c3e4c26d4ba")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,128607],[128607,144405],[144405,162607],[162607,180456],[180456,195669],[195669,211700],[211700,235925],[235925,241655],[241655,252639],[252639,273571],[273571,278325],[278325,317242],[317242,327197],[327197,358399],[358399,376071],[376071,400555],[400555,431553],[431553,446054],[446054,448001],[448001,456986],[456986,473813],[473813,481897],[481897,485778],[485778,489159],[489159,492462],[492462,494593],[494593,497366],[497366,502887],[502887,504784],[504784,508488],[508488,520632],[520632,529652],[529652,533177],[533177,540530],[540530,545574],[545574,548578],[548578,559197],[559197,562174],[562174,570894],[570894,573884],[573884,578838],[578838,591361],[591361,604165],[604165,611601],[611601,619385],[619385,622734],[622734,625683],[625683,633240],[633240,636956],[636956,639166],[639166,642628],[642628,646045],[646045,647159],[647159,648908],[648908,652571],[652571,657301],[657301,663937],[663937,674447],[674447,687763],[687763,689636],[689636,702879],[702879,708266],[708266,712222],[712222,714731],[714731,719773],[719773,733968],[733968,740773],[740773,748158],[748158,748975],[748975,753521],[753521,759441],[759441,762819],[762819,767027],[767027,772117],[772117,777698],[777698,781120],[781120,784711],[784711,789876],[789876,793519],[793519,806977],[806977,809795],[809795,812478],[812478,815145],[815145,817636],[817636,821656],[821656,826720],[826720,830348],[830348,901443],[901443,904706],[904706,905899],[905899,912533],[912533,921278],[921278,932056],[932056,940867],[940867,946050],[946050,1207441],[1207441,1246776],[1246776,1251988]];var sourceLengths=[4844,4048,13310,89885,12190,10741,38583,17849,9941,85121,37758,11019,5079,9872,89707,42695,44478,51546,49478,43948,43919,68620,14399,29244,60576,10713,115386,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,32588,33984,19151,19100,8355,7031,19589,8312,5100,8160,9930,2248,5412,9845,11336,16082,26828,34218,4327,36039,12378,9651,8201,13306,98109,16917,18280,1638,10433,15381,7818,10170,12738,14071,7511,9014,12695,8527,35983,6519,6405,6095,6007,9711,12679,8835,209339,7380,2473,15900,22395,27911,21160,12616,757796,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=readFileSync2(join4(import.meta.dirname,"docs-index.bin"));if(packed.length!==640131||createHash5("sha256").update(packed).digest("hex")!=="bd9e046b180dd000f0f2147aae7658d91c5327bcb74cf7a17c5d539d645ba8c1")throw new Error("docs data file docs-index.bin beside this module is not the one built with it");return gunzipSync(packed)}var TOKEN=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s){const raw=s.toLowerCase().match(TOKEN);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 b2=metadata();const rows=b2.pages.map(p=>{const kind=p.kind?`: ${p.kind}`:"";return`- \`${p.slug}\`${kind}
|
|
81
|
+
`)}};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,b2)=>a.localeCompare(b2));return out.slice(0,3)}function editDistanceAtMostOne(a,b2){if(a===b2)return true;const da=a.length-b2.length;if(da>1||da<-1)return false;let i=0;let j2=0;let skipped=false;while(i<a.length&&j2<b2.length){if(a[i]===b2[j2]){i++;j2++;continue}if(skipped)return false;skipped=true;if(a.length>b2.length)i++;else if(b2.length>a.length)j2++;else{i++;j2++}}return true}import{tmpdir}from"node:os";import{join as join3}from"node:path";import{createHash as createHash4,randomBytes}from"node:crypto";var SUN_PATH_MAX_BYTES=process.platform==="darwin"?104:108;function controlEndpoint(space,name,token=randomBytes(32).toString("base64url")){const id=createHash4("sha256").update(`${space}\0${name}\0${process.pid}\0${token}`).digest("base64url").slice(0,32);const path=process.platform==="win32"?`\\\\.\\pipe\\cotal-${id}`:join3(tmpdir(),`cotal-${id}.sock`);const bytes=Buffer.byteLength(path);if(process.platform!=="win32"&&bytes>SUN_PATH_MAX_BYTES){const tail=`/cotal-${id}.sock`.length;throw new Error(`control socket path is ${bytes} bytes, over the ${SUN_PATH_MAX_BYTES}-byte sun_path limit on ${process.platform}, so it cannot be bound and the kernel would report only EINVAL: ${path}. The socket name is a fixed ${tail} bytes, so the temp root must be at most ${SUN_PATH_MAX_BYTES-tail} bytes \u2014 TMPDIR is ${Buffer.byteLength(tmpdir())} bytes (${tmpdir()}). Point TMPDIR at a shorter directory.`)}return{path,token}}import{eventChannel as eventChannel2,LAUNCH_MATERIAL_ENV as LAUNCH_MATERIAL_ENV3,parsePrincipalKey,principalKey,writeLaunchMaterial}from"@cotal-ai/core";import{dirname as dirname3}from"node:path";import{EVENT_CHANNEL_PREFIX,eventChannel as eventChannel3,eventChannelPrincipal as eventChannelPrincipal2,isEventChannel}from"@cotal-ai/core";var OS_ENV_ALLOW=["PATH","HOME","USERPROFILE","HOMEDRIVE","HOMEPATH","USER","LOGNAME","SHELL","COMSPEC","PATHEXT","TERM","COLORTERM","COLORFGBG","LANG","LC_ALL","LC_CTYPE","LC_MESSAGES","TZ","TEMP","TMPDIR","TMP","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_STATE_HOME","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","XDG_RUNTIME_DIR","DO_NOT_TRACK","CI","SystemRoot","windir","SystemDrive","PROCESSOR_ARCHITECTURE","NUMBER_OF_PROCESSORS","ALLUSERSPROFILE","ProgramData","ProgramFiles","ProgramFiles(x86)","CommonProgramFiles","PUBLIC"];var OPERATOR_ENV_KEEP=["COTAL_HOME","COTAL_FEEDBACK_KEY","COTAL_FEEDBACK_EMAIL","COTAL_FEEDBACK_URL","COTAL_DEFAULT_AGENT","COTAL_DEFAULT_PERSONA","COTAL_SKIP_CONNECTOR_SEED","COTAL_SKIP_ASSIST","COTAL_DETACH_KEY","COTAL_COMPLETE_DEBUG","COTAL_DEBUG","COTAL_SERVE_HEADLESS","COTAL_MEMBERSHIP_INTERVAL_MS","COTAL_DELIVERY_BROKER_GONE_MS","COTAL_IDP_TIMEOUT_MS","COTAL_CODEX_BIN","COTAL_OPENCODE_BIN","COTAL_ORCA_BIN","COTAL_TELEMETRY","COTAL_TELEMETRY_DISABLED","COTAL_TELEMETRY_URL"];function launchEnv(opts={}){for(const[source,keys]of[["spawn.env",opts.envAllow],["MCP environment references",opts.mcpKeys]]){for(const k of keys??[]){const name=k.toUpperCase();if(name.startsWith("COTAL_")&&!OPERATOR_ENV_KEEP.some(keep=>keep===name))throw new Error(`${source} cannot list "${k}": the launcher sets COTAL_ names for each seat, and only the machine-wide ones such as COTAL_HOME cross from the spawning process`)}}const env={};const sourceKey=new Map;for(const k of Object.keys(process.env))sourceKey.set(k.toLowerCase(),k);const copy=name=>{const src=sourceKey.get(name.toLowerCase());if(src===void 0)return;const v2=process.env[src];if(v2!==void 0)env[src]=v2};for(const k of OS_ENV_ALLOW)copy(k);for(const k of OPERATOR_ENV_KEEP)copy(k);for(const k of[...opts.providerKeys??[],...opts.mcpKeys??[],...opts.envAllow??[]])copy(k);return env}function aclEnv(opts){const env={};if(opts.subscribe)env.COTAL_SUBSCRIBE=opts.subscribe.join(",");if(opts.allowSubscribe)env.COTAL_ALLOW_SUBSCRIBE=opts.allowSubscribe.join(",");if(opts.allowPublish)env.COTAL_ALLOW_PUBLISH=opts.allowPublish.join(",");if(opts.capabilities?.length)env.COTAL_CAPABILITIES=opts.capabilities.join(",");if(opts.endpoints!==void 0)env.COTAL_ENDPOINTS=JSON.stringify(opts.endpoints);return env}var UNSAFE_LAUNCH_OPTION_KEYS=new Set(["__proto__","constructor","prototype"]);var LAUNCH_OPTION_KEY=/^[A-Za-z][A-Za-z0-9_-]*$/;function connectorLaunchOptions(connector,launchOptions){if(!launchOptions)return[];for(const k of Object.keys(launchOptions))if(UNSAFE_LAUNCH_OPTION_KEYS.has(k)||!LAUNCH_OPTION_KEY.test(k))throw new Error(`${connector} connector: launch option key ${JSON.stringify(k)} is not a valid flag name`);return Object.entries(launchOptions)}function materialEnv(opts,artifacts){if(opts.userAuth&&opts.creds)throw new Error("launch: creds (static auth) and userAuth (user-mode auth) are mutually exclusive \u2014 one launch carries one identity plane");const material={};if(opts.creds)material.creds=opts.creds;if(opts.servers)material.servers=opts.servers;if(opts.token)material.token=opts.token;if(opts.controlToken)material.controlToken=opts.controlToken;if(opts.eventsRequired)material.eventsRequired=true;if(opts.eventPayloads===false)material.eventPayloadsWithheld=true;if(opts.userAuth)material.userAuth=opts.userAuth;if(Object.keys(material).length===0)return{};const path=writeLaunchMaterial(material);artifacts.push(dirname3(path));return{[LAUNCH_MATERIAL_ENV3]:path}}function launchArmsEvents(opts){return opts.events!==false||opts.eventsRequired===true}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 eventChannel2(ep.principal)}import{AGUI_FRAME_KIND,AGUI_EVENT_TYPE,isAguiFramePart}from"@cotal-ai/core";import{AGUI_FRAME_KIND as AGUI_FRAME_KIND2,AGUI_EVENT_TYPE as AGUI_EVENT_TYPE2,isAguiFramePart as isAguiFramePart2}from"@cotal-ai/core";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 b2=new _AguiBrackets;b2.run=s.run;for(const id of s.text)b2.text.add(id);for(const id of s.reasoning)b2.reasoning.add(id);for(const id of s.tools)b2.tools.add(id);return b2}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_TYPE2.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_TYPE2.RUN_FINISHED||t===AGUI_EVENT_TYPE2.RUN_ERROR){if(t===AGUI_EVENT_TYPE2.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_TYPE2.TEXT_MESSAGE_START:return this.openId(this.text,String(e.messageId),t);case AGUI_EVENT_TYPE2.TEXT_MESSAGE_CONTENT:return this.requireOpen(this.text,String(e.messageId),t);case AGUI_EVENT_TYPE2.TEXT_MESSAGE_END:return this.closeId(this.text,String(e.messageId),t);case AGUI_EVENT_TYPE2.REASONING_MESSAGE_START:return this.openId(this.reasoning,String(e.messageId),t);case AGUI_EVENT_TYPE2.REASONING_MESSAGE_CONTENT:return this.requireOpen(this.reasoning,String(e.messageId),t);case AGUI_EVENT_TYPE2.REASONING_MESSAGE_END:return this.closeId(this.reasoning,String(e.messageId),t);case AGUI_EVENT_TYPE2.TOOL_CALL_START:return this.openId(this.tools,String(e.toolCallId),t);case AGUI_EVENT_TYPE2.TOOL_CALL_ARGS:return this.requireOpen(this.tools,String(e.toolCallId),t);case AGUI_EVENT_TYPE2.TOOL_CALL_END:return this.closeId(this.tools,String(e.toolCallId),t);case AGUI_EVENT_TYPE2.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_TYPE2.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 id=e.value.toolCallId;if(this.tools.has(id))throw new AguiVocabularyError(`${TOOL_RESULT_EVENT} for "${id}" 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(set2,id,t){if(set2.has(id))throw new AguiVocabularyError(`${t} re-opened "${id}" while already open`);set2.add(id)}requireOpen(set2,id,t){if(!set2.has(id))throw new AguiVocabularyError(`${t} for "${id}" which is not open`)}closeId(set2,id,t){if(!set2.delete(id))throw new AguiVocabularyError(`${t} for "${id}" 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_KIND2,protocol:AGUI_PROTOCOL,threadId:opts.threadId,runId:opts.runId,epoch:opts.epoch,seq:opts.seq,events:opts.events}}function parseAguiFrame(part){if(!isAguiFramePart2(part))throw new AguiVocabularyError(`not an AG-UI frame: expected kind ${JSON.stringify(AGUI_FRAME_KIND2)}, 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_TYPE2));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_TYPE2.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_TYPE2.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_TYPE2.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_TYPE2.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_TYPE2.TEXT_MESSAGE_CONTENT,messageId:o.messageId,delta:o.delta,timestamp:o.timestamp,...o.cotal?{cotal:o.cotal}:{}}}function textMessageEnd(o){return{type:AGUI_EVENT_TYPE2.TEXT_MESSAGE_END,messageId:o.messageId,timestamp:o.timestamp,...o.cotal?{cotal:o.cotal}:{}}}function toolCallStart(o){return{type:AGUI_EVENT_TYPE2.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_TYPE2.TOOL_CALL_END,toolCallId:o.toolCallId,timestamp:o.timestamp,...o.cotal?{cotal:o.cotal}:{}}}var TRUNCATABLE_FIELDS=[{type:AGUI_EVENT_TYPE2.TOOL_CALL_ARGS,field:"delta"},{type:AGUI_EVENT_TYPE2.TOOL_CALL_RESULT,field:"content"},{type:AGUI_EVENT_TYPE2.TEXT_MESSAGE_CONTENT,field:"delta"}];var EGRESS_FORBIDDEN_TYPES=new Set([AGUI_EVENT_TYPE2.TOOL_CALL_ARGS,AGUI_EVENT_TYPE2.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_TYPE2.RUN_STARTED,new Set(["type","timestamp","rawEvent","threadId","runId","parentRunId","input","cotal"])],[AGUI_EVENT_TYPE2.RUN_FINISHED,new Set(["type","timestamp","rawEvent","threadId","runId","result","outcome","cotal"])],[AGUI_EVENT_TYPE2.RUN_ERROR,new Set(["type","timestamp","rawEvent","message","code","cotal"])],[AGUI_EVENT_TYPE2.TEXT_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","name","cotal"])],[AGUI_EVENT_TYPE2.TEXT_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE2.TEXT_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE2.TOOL_CALL_START,new Set(["type","timestamp","rawEvent","toolCallId","toolCallName","parentMessageId","cotal"])],[AGUI_EVENT_TYPE2.TOOL_CALL_ARGS,new Set(["type","timestamp","rawEvent","toolCallId","delta","cotal"])],[AGUI_EVENT_TYPE2.TOOL_CALL_END,new Set(["type","timestamp","rawEvent","toolCallId","cotal"])],[AGUI_EVENT_TYPE2.TOOL_CALL_RESULT,new Set(["type","timestamp","rawEvent","messageId","toolCallId","content","role","cotal"])],[AGUI_EVENT_TYPE2.REASONING_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","cotal"])],[AGUI_EVENT_TYPE2.REASONING_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE2.REASONING_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE2.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 v2=value;if(typeof v2.toolCallId!=="string")return"value";if(typeof v2.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 v2=value;return{toolCallId:v2.toolCallId,isError:v2.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_TYPE2.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_TYPE2.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_TYPE2.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_TYPE2.RUN_ERROR?egressRunError(e):isToolResultMarker(e)?egressToolResultMarker(e):e)}function frozenBodyEgressVerdict(body){let unreadable=false;try{for(const part of body){try{if(!isAguiFramePart2(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_TYPE2.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 createHash6,randomUUID as randomUUID5}from"node:crypto";import{dirname as dirname5,join as join5}from"node:path";import{isAguiFramePart as isAguiFramePart3,isCasLoss,principalKey as principalKey2}from"@cotal-ai/core";import{execFileSync}from"node:child_process";init_external();init_external();import{isConcreteChannel as isConcreteChannel4,isChannelFamily as isChannelFamily2,assertValidChannel as assertValidChannel3,MAX_CHANNEL_LENGTH,channelInAllow as channelInAllow3,patternInAllow,AmbiguousPeerError,peerLabel as peerLabel4,sharedNameIds,assertLifecycleToken as assertLifecycleToken3,isPermissionDenied as isPermissionDenied2,renderLifecycleBlocked,EpEnvelopeError as EpEnvelopeError3,EP_UNANSWERED as EP_UNANSWERED2,REGISTRY_PAGE_LIMIT,LANG_PROBLEM_DETAIL_KIND,formatAge,parseDuration,presenceAges,presenceText,isAnycastSeq}from"@cotal-ai/core";var ok=text=>({text});var err=text=>({text,isError:true});function receipt(status,value){if(status!==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 headers={"content-type":"application/json"};const body={...input};if(options.key){headers.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,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{isConcreteChannel as isConcreteChannel3,parsePrincipalKey as parsePrincipalKey2,peerLabel as peerLabel3}from"@cotal-ai/core";import{createHash as createHash5}from"node:crypto";import{readFileSync as readFileSync2}from"node:fs";import{join as join4}from"node:path";import{gunzipSync}from"node:zlib";var DOCS_VERSION="0.164.8";function loadDocsMetadata(){return{"version":"0.164.8","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=readFileSync2(join4(import.meta.dirname,"docs-bundle.bin"));if(packed.length!==1259540||createHash5("sha256").update(packed).digest("hex")!=="09af1e922349560f6491bd4ec46869c109fe48f1113d8499cac3623d6a6abdf2")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,128607],[128607,144405],[144405,162607],[162607,180456],[180456,195669],[195669,211700],[211700,236265],[236265,241995],[241995,252979],[252979,273911],[273911,278665],[278665,317689],[317689,327644],[327644,358846],[358846,376518],[376518,401002],[401002,432e3],[432e3,446501],[446501,448448],[448448,457433],[457433,474260],[474260,482344],[482344,486225],[486225,489606],[489606,492909],[492909,495040],[495040,497813],[497813,503334],[503334,505231],[505231,508935],[508935,521079],[521079,530099],[530099,533624],[533624,540977],[540977,546021],[546021,549025],[549025,559644],[559644,562621],[562621,571341],[571341,574331],[574331,579285],[579285,591945],[591945,604749],[604749,612185],[612185,619969],[619969,623318],[623318,626267],[626267,633824],[633824,637540],[637540,639750],[639750,643212],[643212,646629],[646629,647743],[647743,649492],[649492,653155],[653155,657885],[657885,664521],[664521,675031],[675031,688347],[688347,690220],[690220,703555],[703555,708942],[708942,712898],[712898,715407],[715407,720449],[720449,734644],[734644,741449],[741449,748834],[748834,749651],[749651,754197],[754197,760117],[760117,763635],[763635,767843],[767843,773014],[773014,778595],[778595,782017],[782017,785608],[785608,790773],[790773,794416],[794416,807874],[807874,810692],[810692,813375],[813375,816042],[816042,818533],[818533,822553],[822553,827617],[827617,832319],[832319,837793],[837793,908888],[908888,912151],[912151,913344],[913344,919978],[919978,928723],[928723,939501],[939501,948312],[948312,953495],[953495,1214993],[1214993,1254328],[1254328,1259540]];var sourceLengths=[4844,4048,13310,89885,12190,10741,38583,17849,9941,85121,37758,11019,5079,9872,89707,42695,44478,51546,49478,43948,43919,69591,14399,29244,60576,10713,115718,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,32971,33984,19151,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,12076,13030,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=readFileSync2(join4(import.meta.dirname,"docs-index.bin"));if(packed.length!==643865||createHash5("sha256").update(packed).digest("hex")!=="cbc7f3f2f73e90c02d87d0c61be6b59f67ebfa81ca946d3f997218a03442ffab")throw new Error("docs data file docs-index.bin beside this module is not the one built with it");return gunzipSync(packed)}var TOKEN=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s){const raw=s.toLowerCase().match(TOKEN);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 b2=metadata();const rows=b2.pages.map(p=>{const kind=p.kind?`: ${p.kind}`:"";return`- \`${p.slug}\`${kind}
|
|
82
82
|
${p.summary}`});return[`# Cotal v${b2.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\`: ${b2.spec.title} (the wire contract; where a page disagrees, the spec wins)`,`- \`lang\`: ${b2.lang.title} (the workflow language a durable run executes; spec \xA714)`,`- \`schema\`: ${b2.schema.title} (authoritative for message shapes)`,"","## Pages",...rows].join("\n")}function renderPage(p,note){return`${note}
|
|
83
83
|
|
|
84
84
|
${p.body}`.trimStart()}var K1=1.2;var B=.75;function sources(){const b2=metadata();return[...b2.pages.map((page,source)=>pages.get(source)??page),{slug:"spec",...b2.spec},{slug:"lang",...b2.lang},{slug:"schema",...b2.schema}]}var index;function searchIndex(){if(index)return index;const lengths=loadDocsSourceLengths();for(const[source,page]of pages)lengths[source]=page.body.length;return index=decodeIndex(loadDocsIndex(),lengths,DOCS_VERSION)}function termId(terms,term){let low=0;let high=terms.length-1;while(low<=high){const mid=low+high>>>1;const candidate=terms[mid];if(candidate===term)return mid;if(candidate<term)low=mid+1;else high=mid-1}return-1}function searchDocs(query,limit=5){if(limit<=0)return[];let terms=tokenize(query).filter(t=>!STOP.has(t));if(!terms.length)terms=tokenize(query);const termSet=new Set(terms);if(!termSet.size)return[];const idx=searchIndex();const N2=idx.sections;const scores=new Float64Array(N2);for(const t of termSet){const id=termId(idx.terms,t);if(id<0)continue;const from=idx.offsets[id];const to=idx.offsets[id+1];const n=to-from;const idf=Math.log(1+(N2-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<N2;s++)if(scores[s]>0)scored.push({s,score:scores[s]});scored.sort((a,b2)=>b2.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(text,maxLines=48){const lines=text.split("\n");if(lines.length<=maxLines)return text.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}
|