@cotal-ai/connector-jcode 0.171.2 → 0.171.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/docs-bundle.bin +0 -0
- package/dist/docs-index.bin +0 -0
- package/dist/host.js +9 -9
- package/dist/index.js +1 -1
- package/dist/mcp.js +3 -3
- package/package.json +3 -3
package/dist/host.js
CHANGED
|
@@ -24,7 +24,7 @@ ${stack}`}cancel(err3);return}callback(null,msg);if(opts.strategy==="count"){max
|
|
|
24
24
|
depsCount: ${depsCount},
|
|
25
25
|
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:it2}=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,it2.opts.ownProperties);cxt.setParams({property:prop,depsCount:deps.length,deps:deps.join(", ")});if(it2.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:it2}=cxt;const valid=gen.name("valid");for(const prop in schemaDeps){if((0,util_1.alwaysValidSchema)(it2,schemaDeps[prop]))continue;gen.if((0,code_1.propertyInData)(gen,data,prop,it2.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_util3();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:it2}=cxt;if((0,util_1.alwaysValidSchema)(it2,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(!it2.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_util3();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:it2}=cxt;if(!errsCount)throw new Error("ajv implementation error");const{allErrors,opts}=it2;it2.props=true;if(opts.removeAdditional!=="all"&&(0,util_1.alwaysValidSchema)(it2,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)(it2,parentSchema.properties,"properties");definedProp=(0,code_1.isOwnProperty)(gen,propsSchema,key)}else if(props.length){definedProp=(0,codegen_1.or)(...props.map(p2=>(0,codegen_1._)`${key} === ${p2}`))}else{definedProp=codegen_1.nil}if(patProps.length){definedProp=(0,codegen_1.or)(definedProp,...patProps.map(p2=>(0,codegen_1._)`${(0,code_1.usePattern)(cxt,p2)}.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)(it2,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_util3();var additionalProperties_1=require_additionalProperties();var def={keyword:"properties",type:"object",schemaType:"object",code(cxt){const{gen,schema,parentSchema,data,it:it2}=cxt;if(it2.opts.removeAdditional==="all"&&parentSchema.additionalProperties===void 0){additionalProperties_1.default.code(new validate_1.KeywordCxt(it2,additionalProperties_1.default,"additionalProperties"))}const allProps=(0,code_1.allSchemaProperties)(schema);for(const prop of allProps){it2.definedProperties.add(prop)}if(it2.opts.unevaluated&&allProps.length&&it2.props!==true){it2.props=util_1.mergeEvaluated.props(gen,(0,util_1.toHash)(allProps),it2.props)}const properties=allProps.filter(p2=>!(0,util_1.alwaysValidSchema)(it2,schema[p2]));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,it2.opts.ownProperties));applyPropertySchema(prop);if(!it2.allErrors)gen.else().var(valid,true);gen.endIf()}cxt.it.definedProperties.add(prop);cxt.ok(valid)}function hasDefault(prop){return it2.opts.useDefaults&&!it2.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_util3();var util_2=require_util3();var def={keyword:"patternProperties",type:"object",schemaType:"object",code(cxt){const{gen,schema,data,parentSchema,it:it2}=cxt;const{opts}=it2;const patterns2=(0,code_1.allSchemaProperties)(schema);const alwaysValidPatterns=patterns2.filter(p2=>(0,util_1.alwaysValidSchema)(it2,schema[p2]));if(patterns2.length===0||alwaysValidPatterns.length===patterns2.length&&(!it2.opts.unevaluated||it2.props===true)){return}const checkProperties=opts.strictSchema&&!opts.allowMatchingProperties&&parentSchema.properties;const valid=gen.name("valid");if(it2.props!==true&&!(it2.props instanceof codegen_1.Name)){it2.props=(0,util_2.evaluatedPropsToName)(gen,it2.props)}const{props}=it2;validatePatternProperties();function validatePatternProperties(){for(const pat of patterns2){if(checkProperties)checkMatchingProperties(pat);if(it2.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)(it2,`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(it2.opts.unevaluated&&props!==true){gen.assign((0,codegen_1._)`${props}[${key}]`,true)}else if(!alwaysValid&&!it2.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_util3();var def={keyword:"not",schemaType:["object","boolean"],trackErrors:true,code(cxt){const{gen,schema,it:it2}=cxt;if((0,util_1.alwaysValidSchema)(it2,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_util3();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:it2}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");if(it2.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,i2)=>{let schCxt;if((0,util_1.alwaysValidSchema)(it2,sch)){gen.var(schValid,true)}else{schCxt=cxt.subschema({keyword:"oneOf",schemaProp:i2,compositeRule:true},schValid)}if(i2>0){gen.if((0,codegen_1._)`${schValid} && ${valid}`).assign(valid,false).assign(passing,(0,codegen_1._)`[${passing}, ${i2}]`).else()}gen.if(schValid,()=>{gen.assign(valid,true);gen.assign(passing,i2);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_util3();var def={keyword:"allOf",schemaType:"array",code(cxt){const{gen,schema,it:it2}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");const valid=gen.name("valid");schema.forEach((sch,i2)=>{if((0,util_1.alwaysValidSchema)(it2,sch))return;const schCxt=cxt.subschema({keyword:"allOf",schemaProp:i2},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_util3();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:it2}=cxt;if(parentSchema.then===void 0&&parentSchema.else===void 0){(0,util_1.checkStrictMode)(it2,'"if" without "then" and "else" is ignored')}const hasThen=hasSchema(it2,"then");const hasElse=hasSchema(it2,"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(it2,keyword){const schema=it2.schema[keyword];return schema!==void 0&&!(0,util_1.alwaysValidSchema)(it2,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_util3();var def={keyword:["then","else"],schemaType:["object","boolean"],code({keyword,parentSchema,it:it2}){if(parentSchema.if===void 0)(0,util_1.checkStrictMode)(it2,`"${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_dynamicAnchor=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.dynamicAnchor=void 0;var codegen_1=require_codegen();var names_1=require_names();var compile_1=require_compile();var ref_1=require_ref();var def={keyword:"$dynamicAnchor",schemaType:"string",code:cxt=>dynamicAnchor(cxt,cxt.schema)};function dynamicAnchor(cxt,anchor){const{gen,it:it2}=cxt;it2.schemaEnv.root.dynamicAnchors[anchor]=true;const v3=(0,codegen_1._)`${names_1.default.dynamicAnchors}${(0,codegen_1.getProperty)(anchor)}`;const validate2=it2.errSchemaPath==="#"?it2.validateName:_getValidate(cxt);gen.if((0,codegen_1._)`!${v3}`,()=>gen.assign(v3,validate2))}exports.dynamicAnchor=dynamicAnchor;function _getValidate(cxt){const{schemaEnv,schema,self:self2}=cxt.it;const{root,baseId,localRefs,meta:meta3}=schemaEnv.root;const{schemaId}=self2.opts;const sch=new compile_1.SchemaEnv({schema,schemaId,root,baseId,localRefs,meta:meta3});compile_1.compileSchema.call(self2,sch);return(0,ref_1.getValidate)(cxt,sch)}exports.default=def}});var require_dynamicRef=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.dynamicRef=void 0;var codegen_1=require_codegen();var names_1=require_names();var ref_1=require_ref();var def={keyword:"$dynamicRef",schemaType:"string",code:cxt=>dynamicRef(cxt,cxt.schema)};function dynamicRef(cxt,ref){const{gen,keyword,it:it2}=cxt;if(ref[0]!=="#")throw new Error(`"${keyword}" only supports hash fragment reference`);const anchor=ref.slice(1);if(it2.allErrors){_dynamicRef()}else{const valid=gen.let("valid",false);_dynamicRef(valid);cxt.ok(valid)}function _dynamicRef(valid){if(it2.schemaEnv.root.dynamicAnchors[anchor]){const v3=gen.let("_v",(0,codegen_1._)`${names_1.default.dynamicAnchors}${(0,codegen_1.getProperty)(anchor)}`);gen.if(v3,_callRef(v3,valid),_callRef(it2.validateName,valid))}else{_callRef(it2.validateName,valid)()}}function _callRef(validate2,valid){return valid?()=>gen.block(()=>{(0,ref_1.callRef)(cxt,validate2);gen.let(valid,true)}):()=>(0,ref_1.callRef)(cxt,validate2)}}exports.dynamicRef=dynamicRef;exports.default=def}});var require_recursiveAnchor=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var dynamicAnchor_1=require_dynamicAnchor();var util_1=require_util3();var def={keyword:"$recursiveAnchor",schemaType:"boolean",code(cxt){if(cxt.schema)(0,dynamicAnchor_1.dynamicAnchor)(cxt,"");else(0,util_1.checkStrictMode)(cxt.it,"$recursiveAnchor: false is ignored")}};exports.default=def}});var require_recursiveRef=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var dynamicRef_1=require_dynamicRef();var def={keyword:"$recursiveRef",schemaType:"string",code:cxt=>(0,dynamicRef_1.dynamicRef)(cxt,cxt.schema)};exports.default=def}});var require_dynamic=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/dynamic/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var dynamicAnchor_1=require_dynamicAnchor();var dynamicRef_1=require_dynamicRef();var recursiveAnchor_1=require_recursiveAnchor();var recursiveRef_1=require_recursiveRef();var dynamic=[dynamicAnchor_1.default,dynamicRef_1.default,recursiveAnchor_1.default,recursiveRef_1.default];exports.default=dynamic}});var require_dependentRequired=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var dependencies_1=require_dependencies();var def={keyword:"dependentRequired",type:"object",schemaType:"object",error:dependencies_1.error,code:cxt=>(0,dependencies_1.validatePropertyDeps)(cxt)};exports.default=def}});var require_dependentSchemas=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var dependencies_1=require_dependencies();var def={keyword:"dependentSchemas",type:"object",schemaType:"object",code:cxt=>(0,dependencies_1.validateSchemaDeps)(cxt)};exports.default=def}});var require_limitContains=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitContains.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var util_1=require_util3();var def={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword,parentSchema,it:it2}){if(parentSchema.contains===void 0){(0,util_1.checkStrictMode)(it2,`"${keyword}" without "contains" is ignored`)}}};exports.default=def}});var require_next=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/next.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var dependentRequired_1=require_dependentRequired();var dependentSchemas_1=require_dependentSchemas();var limitContains_1=require_limitContains();var next=[dependentRequired_1.default,dependentSchemas_1.default,limitContains_1.default];exports.default=next}});var require_unevaluatedProperties=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util3();var names_1=require_names();var error51={message:"must NOT have unevaluated properties",params:({params})=>(0,codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}`};var def={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:true,error:error51,code(cxt){const{gen,schema,data,errsCount,it:it2}=cxt;if(!errsCount)throw new Error("ajv implementation error");const{allErrors,props}=it2;if(props instanceof codegen_1.Name){gen.if((0,codegen_1._)`${props} !== true`,()=>gen.forIn("key",data,key=>gen.if(unevaluatedDynamic(props,key),()=>unevaluatedPropCode(key))))}else if(props!==true){gen.forIn("key",data,key=>props===void 0?unevaluatedPropCode(key):gen.if(unevaluatedStatic(props,key),()=>unevaluatedPropCode(key)))}it2.props=true;cxt.ok((0,codegen_1._)`${errsCount} === ${names_1.default.errors}`);function unevaluatedPropCode(key){if(schema===false){cxt.setParams({unevaluatedProperty:key});cxt.error();if(!allErrors)gen.break();return}if(!(0,util_1.alwaysValidSchema)(it2,schema)){const valid=gen.name("valid");cxt.subschema({keyword:"unevaluatedProperties",dataProp:key,dataPropType:util_1.Type.Str},valid);if(!allErrors)gen.if((0,codegen_1.not)(valid),()=>gen.break())}}function unevaluatedDynamic(evaluatedProps,key){return(0,codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`}function unevaluatedStatic(evaluatedProps,key){const ps=[];for(const p2 in evaluatedProps){if(evaluatedProps[p2]===true)ps.push((0,codegen_1._)`${key} !== ${p2}`)}return(0,codegen_1.and)(...ps)}}};exports.default=def}});var require_unevaluatedItems=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util3();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:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:error51,code(cxt){const{gen,schema,data,it:it2}=cxt;const items=it2.items||0;if(items===true)return;const len=gen.const("len",(0,codegen_1._)`${data}.length`);if(schema===false){cxt.setParams({len:items});cxt.fail((0,codegen_1._)`${len} > ${items}`)}else if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it2,schema)){const valid=gen.var("valid",(0,codegen_1._)`${len} <= ${items}`);gen.if((0,codegen_1.not)(valid),()=>validateItems(valid,items));cxt.ok(valid)}it2.items=true;function validateItems(valid,from){gen.forRange("i",from,len,i2=>{cxt.subschema({keyword:"unevaluatedItems",dataProp:i2,dataPropType:util_1.Type.Num},valid);if(!it2.allErrors)gen.if((0,codegen_1.not)(valid),()=>gen.break())})}}};exports.default=def}});var require_unevaluated=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/unevaluated/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var unevaluatedProperties_1=require_unevaluatedProperties();var unevaluatedItems_1=require_unevaluatedItems();var unevaluated=[unevaluatedProperties_1.default,unevaluatedItems_1.default];exports.default=unevaluated}});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:it2}=cxt;const{opts,errSchemaPath,schemaEnv,self:self2}=it2;if(!opts.validateFormats)return;if($data)validate$DataFormat();else validateFormat();function validate$DataFormat(){const fmts=gen.scopeValue("formats",{ref:self2.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=self2.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){self2.logger.warn(unknownMsg());return}throw new Error(unknownMsg());function unknownMsg(){return`unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`}}function getFormat(fmtDef){const code2=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:code2});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_draft2020=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/draft2020.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var core_1=require_core3();var validation_1=require_validation();var applicator_1=require_applicator();var dynamic_1=require_dynamic();var next_1=require_next();var unevaluated_1=require_unevaluated();var format_1=require_format2();var metadata_1=require_metadata();var draft2020Vocabularies=[dynamic_1.default,core_1.default,validation_1.default,(0,applicator_1.default)(true),format_1.default,metadata_1.metadataVocabulary,metadata_1.contentVocabulary,next_1.default,unevaluated_1.default];exports.default=draft2020Vocabularies}});var require_types4=__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_types4();var compile_1=require_compile();var ref_error_1=require_ref_error();var util_1=require_util3();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:it2}=cxt;const{oneOf}=parentSchema;if(!it2.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 i2=0;i2<oneOf.length;i2++){let sch=oneOf[i2];if((sch===null||sch===void 0?void 0:sch.$ref)&&!(0,util_1.schemaHasRulesButRef)(sch,it2.self.RULES)){const ref=sch.$ref;sch=compile_1.resolveRef.call(it2.self,it2.schemaEnv.root,it2.baseId,ref);if(sch instanceof compile_1.SchemaEnv)sch=sch.schema;if(sch===void 0)throw new ref_error_1.default(it2.opts.uriResolver,it2.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,i2)}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,i2){if(sch.const){addMapping(sch.const,i2)}else if(sch.enum){for(const tagValue of sch.enum){addMapping(tagValue,i2)}}else{throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`)}}function addMapping(tagValue,i2){if(typeof tagValue!="string"||tagValue in oneOfMapping){throw new Error(`discriminator: "${tagName}" values must be unique strings`)}oneOfMapping[tagValue]=i2}}}};exports.default=def}});var require_schema=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json"(exports,module2){module2.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":true,"https://json-schema.org/draft/2020-12/vocab/applicator":true,"https://json-schema.org/draft/2020-12/vocab/unevaluated":true,"https://json-schema.org/draft/2020-12/vocab/validation":true,"https://json-schema.org/draft/2020-12/vocab/meta-data":true,"https://json-schema.org/draft/2020-12/vocab/format-annotation":true,"https://json-schema.org/draft/2020-12/vocab/content":true},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:true,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:true,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:true},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:true}}}}});var require_applicator2=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json"(exports,module2){module2.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":true},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}}});var require_unevaluated2=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json"(exports,module2){module2.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":true},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}}});var require_content=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json"(exports,module2){module2.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":true},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}}});var require_core4=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json"(exports,module2){module2.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":true},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}}});var require_format_annotation=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json"(exports,module2){module2.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":true},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}}});var require_meta_data=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json"(exports,module2){module2.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":true},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:true,deprecated:{type:"boolean",default:false},readOnly:{type:"boolean",default:false},writeOnly:{type:"boolean",default:false},examples:{type:"array",items:true}}}}});var require_validation2=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json"(exports,module2){module2.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":true},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:true}]},const:true,enum:{type:"array",items:true},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}}}}});var require_json_schema_2020_12=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-2020-12/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var metaSchema=require_schema();var applicator=require_applicator2();var unevaluated=require_unevaluated2();var content=require_content();var core=require_core4();var format=require_format_annotation();var metadata2=require_meta_data();var validation=require_validation2();var META_SUPPORT_DATA=["/properties"];function addMetaSchema2020($data){;[metaSchema,applicator,unevaluated,content,core,with$data(this,format),metadata2,with$data(this,validation)].forEach(sch=>this.addMetaSchema(sch,void 0,false));return this;function with$data(ajv2,sch){return $data?ajv2.$dataMetaSchema(sch,META_SUPPORT_DATA):sch}}exports.default=addMetaSchema2020}});var require__=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/2020.js"(exports,module2){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv2020=void 0;var core_1=require_core2();var draft2020_1=require_draft2020();var discriminator_1=require_discriminator();var json_schema_2020_12_1=require_json_schema_2020_12();var META_SCHEMA_ID="https://json-schema.org/draft/2020-12/schema";var Ajv20202=class extends core_1.default{constructor(opts={}){super({...opts,dynamicRef:true,next:true,unevaluated:true})}_addVocabularies(){super._addVocabularies();draft2020_1.default.forEach(v3=>this.addVocabulary(v3));if(this.opts.discriminator)this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();const{$data,meta:meta3}=this.opts;if(!meta3)return;json_schema_2020_12_1.default.call(this,$data);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.Ajv2020=Ajv20202;module2.exports=exports=Ajv20202;module2.exports.Ajv2020=Ajv20202;Object.defineProperty(exports,"__esModule",{value:true});exports.default=Ajv20202;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 e;var init_rolldown_runtime_DN1TCW_I=__esm({"../../node_modules/.pnpm/json-schema-library@11.6.16/node_modules/json-schema-library/dist/rolldown-runtime-DN1TCW_I.mjs"(){e=(e3,t2)=>()=>(t2||(e3((t2={exports:{}}).exports,t2,t2.exports),e3=null),t2.exports)}});function getCleanClone(prototype){if(!prototype){return Object.create(null)}const Constructor=prototype.constructor;if(Constructor===Object){return prototype===Object.prototype?{}:Object.create(prototype)}if(typeof Constructor==="function"&&~toStringFunction.call(Constructor).indexOf("[native code]")){try{return new Constructor}catch(_a3){}}return Object.create(prototype)}function getTag(value){const stringTag=value[Symbol.toStringTag];if(stringTag){return stringTag}const type=toStringObject.call(value);return type.substring(8,type.length-1)}function copyOwnDescriptor(original,clone2,property,state){const ownDescriptor=Object.getOwnPropertyDescriptor(original,property)||{configurable:true,enumerable:true,value:original[property],writable:true};const descriptor=ownDescriptor.get||ownDescriptor.set?ownDescriptor:{configurable:ownDescriptor.configurable,enumerable:ownDescriptor.enumerable,value:state.copier(ownDescriptor.value,state),writable:ownDescriptor.writable};try{Object.defineProperty(clone2,property,descriptor)}catch(_a3){clone2[property]=descriptor.get?descriptor.get():descriptor.value}}function copyOwnPropertiesStrict(value,clone2,state,names,start){for(let index2=start;index2<names.length;++index2){copyOwnDescriptor(value,clone2,names[index2],state)}for(const symbol2 of Object.getOwnPropertySymbols(value)){copyOwnDescriptor(value,clone2,symbol2,state)}return clone2}function copyArray(array2,state){const clone2=new state.Constructor;state.cache.set(array2,clone2);for(let index2=0;index2<array2.length;++index2){clone2[index2]=state.copier(array2[index2],state)}return clone2}function copyArrayStrict(array2,state){const clone2=new state.Constructor;state.cache.set(array2,clone2);return copyOwnPropertiesStrict(array2,clone2,state,Object.getOwnPropertyNames(array2),0)}function copyArrayBuffer(arrayBuffer,state){if(ArrayBuffer.isView(arrayBuffer)){return sliceTypedArray.call(arrayBuffer,0)}if(arrayBuffer.resizable||arrayBuffer.growable){const maxByteLength=arrayBuffer.maxByteLength;const clone2=new state.Constructor(arrayBuffer.byteLength,{maxByteLength});new Uint8Array(clone2).set(new Uint8Array(arrayBuffer));return clone2}if(!arrayBuffer.byteLength&&getTag(arrayBuffer)==="SharedArrayBuffer"){return new state.Constructor(0)}return arrayBuffer.slice(0)}function copyArrayBufferStrict(arrayBuffer,state){const clone2=copyArrayBuffer(arrayBuffer,state);state.cache.set(arrayBuffer,clone2);const start=ArrayBuffer.isView(clone2)?clone2.length||0:0;return copyOwnPropertiesStrict(arrayBuffer,clone2,state,Object.getOwnPropertyNames(arrayBuffer),start)}function copyBlob(blob,_state){return blob.slice(0,blob.size,blob.type)}function copyDataView(dataView,state){return new state.Constructor(state.copier(dataView.buffer,state),dataView.byteOffset,dataView.byteLength)}function copyDataViewStrict(dataView,state){const{buffer}=dataView;const{cache,Constructor}=state;const bufferCopied=cache.has(buffer);const bufferClone=bufferCopied?cache.get(buffer):state.copier(buffer,state);if(!bufferCopied&&cache.has(dataView)){return cache.get(dataView)}const clone2=new Constructor(bufferClone,dataView.byteOffset,dataView.byteLength);state.cache.set(dataView,clone2);return copyOwnPropertiesStrict(dataView,clone2,state,Object.getOwnPropertyNames(dataView),0)}function copyDate(date5,state){return new state.Constructor(date5.getTime())}function copyMap(map2,state){const clone2=new state.Constructor;state.cache.set(map2,clone2);for(const[key,value]of map2){clone2.set(key,state.copier(value,state))}return clone2}function copyMapStrict(map2,state){return copyOwnPropertiesStrict(map2,copyMap(map2,state),state,Object.getOwnPropertyNames(map2),0)}function copyObject(object2,state){const clone2=getCleanClone(state.prototype);state.cache.set(object2,clone2);for(const key of Object.keys(object2)){if(key==="__proto__"){Object.defineProperty(clone2,key,{configurable:true,enumerable:true,value:state.copier(object2[key],state),writable:true})}else{clone2[key]=state.copier(object2[key],state)}}for(const symbol2 of Object.getOwnPropertySymbols(object2)){if(Object.prototype.propertyIsEnumerable.call(object2,symbol2)){clone2[symbol2]=state.copier(object2[symbol2],state)}}return clone2}function copyObjectStrict(object2,state){const clone2=getCleanClone(state.prototype);state.cache.set(object2,clone2);return copyOwnPropertiesStrict(object2,clone2,state,Object.getOwnPropertyNames(object2),0)}function copyPrimitiveWrapper(primitiveObject,state){return new state.Constructor(primitiveObject.valueOf())}function copyRegExp(regExp,state){const clone2=new state.Constructor(regExp.source,regExp.flags);clone2.lastIndex=regExp.lastIndex;return clone2}function copySelf(value,_state){return value}function copySet(set3,state){const clone2=new state.Constructor;state.cache.set(set3,clone2);for(const value of set3){clone2.add(state.copier(value,state))}return clone2}function copySetStrict(set3,state){return copyOwnPropertiesStrict(set3,copySet(set3,state),state,Object.getOwnPropertyNames(set3),0)}function createStrictHandler(handler){return(value,state)=>{const clone2=handler(value,state);state.cache.set(value,clone2);return copyOwnPropertiesStrict(value,clone2,state,Object.getOwnPropertyNames(value),0)}}function copyStringStrict(string4,state){const clone2=copyPrimitiveWrapper(string4,state);state.cache.set(string4,clone2);const{length}=string4;const names=Object.getOwnPropertyNames(string4);const start=names[length]==="length"?length+1:length;return copyOwnPropertiesStrict(string4,clone2,state,names,start)}function createDefaultCache(){return new WeakMap}function getOptions({createCache:createCacheOverride,maxDepth,methods:methodsOverride,strict}){const defaultMethods={array:strict?copyArrayStrict:copyArray,arrayBuffer:strict?copyArrayBufferStrict:copyArrayBuffer,asyncGenerator:copySelf,blob:strict?copyBlobStrict:copyBlob,dataView:strict?copyDataViewStrict:copyDataView,date:strict?copyDateStrict:copyDate,error:copySelf,generator:copySelf,map:strict?copyMapStrict:copyMap,object:strict?copyObjectStrict:copyObject,regExp:strict?copyRegExpStrict:copyRegExp,set:strict?copySetStrict:copySet};const methods=methodsOverride?Object.assign(defaultMethods,methodsOverride):defaultMethods;const copiers=getTagSpecificCopiers(methods,strict);const createCache=createCacheOverride||createDefaultCache;if(!copiers.Object||!copiers.Array){throw new Error("An object and array copier must be provided.")}return{createCache,copiers,maxDepth:maxDepth==null?DEFAULT_MAX_DEPTH:maxDepth,methods,strict:Boolean(strict)}}function getTagSpecificCopiers(methods,strict){const copyPrimitive=strict?copyPrimitiveWrapperStrict:copyPrimitiveWrapper;return Object.assign(Object.create(null),{Arguments:methods.object,Array:methods.array,ArrayBuffer:methods.arrayBuffer,AsyncGenerator:methods.asyncGenerator,BigInt64Array:methods.arrayBuffer,BigUint64Array:methods.arrayBuffer,Blob:methods.blob,Boolean:copyPrimitive,DataView:methods.dataView,Date:methods.date,Error:methods.error,Float32Array:methods.arrayBuffer,Float64Array:methods.arrayBuffer,Generator:methods.generator,Int8Array:methods.arrayBuffer,Int16Array:methods.arrayBuffer,Int32Array:methods.arrayBuffer,Map:methods.map,Number:copyPrimitive,Object:methods.object,Promise:copySelf,RegExp:methods.regExp,Set:methods.set,SharedArrayBuffer:methods.arrayBuffer,String:strict?copyStringStrict:copyPrimitiveWrapper,WeakMap:copySelf,WeakSet:copySelf,Uint8Array:methods.arrayBuffer,Uint8ClampedArray:methods.arrayBuffer,Uint16Array:methods.arrayBuffer,Uint32Array:methods.arrayBuffer})}function createCopier(options={}){const{createCache,copiers,maxDepth}=getOptions(options);const{Array:copyArray2,Object:copyObject2}=copiers;function copier(value,state){state.prototype=state.Constructor=void 0;if(!value||typeof value!=="object"){return value}if(state.cache.has(value)){return state.cache.get(value)}if(++state.depth>maxDepth){throw new MaxDepthExceededError(maxDepth)}state.prototype=Object.getPrototypeOf(value);state.Constructor=state.prototype&&state.prototype.constructor;let clone2;if(!state.Constructor||state.Constructor===Object){clone2=copyObject2(value,state)}else if(Array.isArray(value)){clone2=copyArray2(value,state)}else{const tagSpecificCopier=copiers[getTag(value)];if(tagSpecificCopier){clone2=tagSpecificCopier(value,state)}else{clone2=typeof value.then==="function"?value:copyObject2(value,state)}}--state.depth;return clone2}return function copy2(value){return copier(value,{Constructor:void 0,cache:createCache(),copier,depth:0,prototype:void 0})}}var MaxDepthExceededError,toStringFunction,toStringObject,sliceTypedArray,copyBlobStrict,copyDateStrict,copyPrimitiveWrapperStrict,copyRegExpStrict,DEFAULT_MAX_DEPTH,copyStrict,copy;var init_es=__esm({"../../node_modules/.pnpm/fast-copy@4.3.1/node_modules/fast-copy/dist/es/index.mjs"(){MaxDepthExceededError=class extends RangeError{constructor(maxDepth){super(`Maximum copy depth of ${String(maxDepth)} exceeded; the value copied is nested too deeply.`);this.maxDepth=maxDepth;this.name="MaxDepthExceededError"}};toStringFunction=Function.prototype.toString;toStringObject=Object.prototype.toString;sliceTypedArray=Object.getPrototypeOf(Int8Array.prototype).slice;copyBlobStrict=createStrictHandler(copyBlob);copyDateStrict=createStrictHandler(copyDate);copyPrimitiveWrapperStrict=createStrictHandler(copyPrimitiveWrapper);copyRegExpStrict=createStrictHandler(copyRegExp);DEFAULT_MAX_DEPTH=1e3;copyStrict=createCopier({strict:true});copy=createCopier()}});function e2(e3){return e3===`#`||e3===``||Array.isArray(e3)&&e3.length===0||false}function i(e3){return e3.replace(t,`/`).replace(n,`~`)}function a(e3){return i(decodeURIComponent(e3))}function o(t2){if(t2==null||typeof t2!=`string`||e2(t2))return Array.isArray(t2)?t2.slice():[];let n2=t2.indexOf(`#`)>=0?a:i;t2=t2.replace(r,``);let o3=t2.split(`/`);for(let e3=0,t3=o3.length;e3<t3;e3+=1)o3[e3]=n2(o3[e3]);return o3}function s(t2,n2,r2=void 0){if(n2==null||t2==null)return r2;if(e2(n2))return t2;let i2=c(t2,o(n2));return i2===void 0?r2:i2}function c(e3,t2){let n2=t2.shift();if(e3!==void 0)return n2===void 0?e3:e3==null?void 0:c(e3[n2],t2)}function y(e3,t2){if(e3.length===0)return t2?`#`:``;for(let n2=0,r2=e3.length;n2<r2;n2+=1)e3[n2]=e3[n2].replace(_,`~0`).replace(v,`~1`),t2&&(e3[n2]=encodeURIComponent(e3[n2]));return(t2?`#/`:`/`)+e3.join(`/`)}function b(e3,...t2){let n2=[];if(Array.isArray(e3))return y(e3,arguments[1]===true);let r2=arguments[arguments.length-1],i2=typeof r2==`boolean`?r2:e3&&e3[0]===`#`;for(let e4=0,t3=arguments.length;e4<t3;e4+=1)n2.push.apply(n2,o(arguments[e4]));let a3=[];for(let e4=0,t3=n2.length;e4<t3;e4+=1)if(n2[e4]===`..`){if(a3.length===0)return i2?`#`:``;a3.pop()}else a3.push(n2[e4]);return y(a3,i2)}var t,n,r,_,v;var init_dist=__esm({"../../node_modules/.pnpm/@sagold+json-pointer@7.2.1/node_modules/@sagold/json-pointer/dist/index.mjs"(){t=/~1/g;n=/~0/g;r=/(^#?\/?)/g;_=/~/g;v=/\//g}});var require_valid_url=__commonJS({"../../node_modules/.pnpm/valid-url@1.0.9/node_modules/valid-url/index.js"(exports,module2){(function(module3){"use strict";module3.exports.is_uri=is_iri;module3.exports.is_http_uri=is_http_iri;module3.exports.is_https_uri=is_https_iri;module3.exports.is_web_uri=is_web_iri;module3.exports.isUri=is_iri;module3.exports.isHttpUri=is_http_iri;module3.exports.isHttpsUri=is_https_iri;module3.exports.isWebUri=is_web_iri;var splitUri=function(uri){var splitted=uri.match(/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/);return splitted};function is_iri(value){if(!value){return}if(/[^a-z0-9\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=\.\-\_\~\%]/i.test(value))return;if(/%[^0-9a-f]/i.test(value))return;if(/%[0-9a-f](:?[^0-9a-f]|$)/i.test(value))return;var splitted=[];var scheme="";var authority="";var path4="";var query="";var fragment="";var out="";splitted=splitUri(value);scheme=splitted[1];authority=splitted[2];path4=splitted[3];query=splitted[4];fragment=splitted[5];if(!(scheme&&scheme.length&&path4.length>=0))return;if(authority&&authority.length){if(!(path4.length===0||/^\//.test(path4)))return}else{if(/^\/\//.test(path4))return}if(!/^[a-z][a-z0-9\+\-\.]*$/.test(scheme.toLowerCase()))return;out+=scheme+":";if(authority&&authority.length){out+="//"+authority}out+=path4;if(query&&query.length){out+="?"+query}if(fragment&&fragment.length){out+="#"+fragment}return out}function is_http_iri(value,allowHttps){if(!is_iri(value)){return}var splitted=[];var scheme="";var authority="";var path4="";var port="";var query="";var fragment="";var out="";splitted=splitUri(value);scheme=splitted[1];authority=splitted[2];path4=splitted[3];query=splitted[4];fragment=splitted[5];if(!scheme)return;if(allowHttps){if(scheme.toLowerCase()!="https")return}else{if(scheme.toLowerCase()!="http")return}if(!authority){return}if(/:(\d+)$/.test(authority)){port=authority.match(/:(\d+)$/)[0];authority=authority.replace(/:\d+$/,"")}out+=scheme+":";out+="//"+authority;if(port){out+=port}out+=path4;if(query&&query.length){out+="?"+query}if(fragment&&fragment.length){out+="#"+fragment}return out}function is_https_iri(value){return is_http_iri(value,true)}function is_web_iri(value){return is_http_iri(value)||is_https_iri(value)}})(module2)}});function s2(e3,t2=[]){if(!Array.isArray(e3))return e3===void 0?[]:[e3];for(let n2 of e3)Array.isArray(n2)?s2(n2,t2):(De(n2)||n2 instanceof Promise)&&t2.push(n2);return t2}function l(e3,t2){t2!=null&&Object.values(t2).forEach(t3=>d(t3,e3))}function u(e3,t2){t2?.forEach(t3=>d(t3,e3))}function d(e3,t2=[]){return F(e3)&&(t2.push(e3),l(t2,e3.$defs),e3.additionalProperties&&d(e3.additionalProperties,t2),u(t2,e3.allOf),u(t2,e3.anyOf),e3.contains&&d(e3.contains,t2),l(t2,e3.dependentSchemas),e3.if&&d(e3.if,t2),e3.else&&d(e3.else,t2),e3.then&&d(e3.then,t2),e3.items&&d(e3.items,t2),u(t2,e3.prefixItems),e3.not&&d(e3.not,t2),u(t2,e3.oneOf),e3.patternProperties&&Object.values(e3.patternProperties).forEach(({node:e4})=>d(e4,t2)),l(t2,e3.properties),e3.propertyNames&&d(e3.propertyNames,t2),e3.unevaluatedProperties&&d(e3.unevaluatedProperties,t2),e3.unevaluatedItems&&d(e3.unevaluatedItems,t2)),t2}function p(e3){let t2=f.call(e3).slice(8,-1).toLowerCase();return t2===`file`?`object`:t2}function m(e3){return p(e3)===`object`}function v2(e3,t2){return t2==null?e3?.replace(g,``)??`#`:e3==null||e3===`#`?t2?.replace(g,``):t2[0]===`#`?e3[0]===`/`?t2:`${e3.replace(_2,``)}${t2.replace(ne,``)}`:re.test(t2)?t2.replace(g,``):(0,te.resolve)(e3,t2??``)??`#`}function x(e3,t2){if(m(e3)&&b2(e3,`${t2}`)||Array.isArray(e3))return e3[t2]}function S(e3,t2,...n2){if(t2?.type===`error`)return t2;if(e3?.type===`error`||p(e3)!==p(t2))return e3;let r2=C(e3,t2);for(let e4 of n2)delete r2[e4];return r2}function C(e3,t2,n2){if(m(e3)&&m(t2)){let n3={...e3,...t2};return[...Object.keys(e3),...Object.keys(t2)].filter((e4,t3,n4)=>n4.indexOf(e4)===t3).forEach(r3=>n3[r3]=C(x(e3,r3),x(t2,r3),r3)),n3}let r2=Array.isArray(e3),i2=Array.isArray(t2);if(r2&&i2){if(n2===`required`||n2===`anyOf`)return e3.concat(t2).filter((e4,t3,n3)=>n3.indexOf(e4)===t3);if(n2===`items`||n2===`prefixItems`){let n3=[];for(let r4=0;r4<t2.length;r4+=1)m(e3[r4])&&m(t2[r4])&&e3[r4].type===t2[r4].type?n3[r4]=C(e3[r4],t2[r4]):n3.push(t2[r4]??e3[r4]);return n3}let r3=[],i3=[];for(let n3=0;n3<Math.max(e3.length,t2.length);n3+=1)m(e3[n3])&&m(t2[n3])?r3[n3]=C(e3[n3],t2[n3]):e3[n3]!==void 0&&t2[n3]!==void 0?(r3[n3]=e3[n3],i3.push(t2[n3])):e3[n3]===void 0?t2[n3]!==void 0&&i3.push(t2[n3]):r3[n3]=e3[n3];return[...r3,...i3].filter((e4,t3,n3)=>n3.indexOf(e4)===t3)}if(n2===`type`&&(r2||i2)){if(r2&&e3.includes(t2))return t2;if(i2&&t2.includes(e3))return e3;if(r2)return[...e3,t2];if(i2)return[...t2,e3]}return i2?t2:r2||t2===void 0?e3:t2}function ie(e3,t2){return(t2.order??0)-(e3.order??0)}function ae(e3,t2,n2){if(e3==null||n2.indexOf(e3)!==t2)return false;let r2=e3.toJSON?.()??e3.name;return n2.find((e4,n3)=>(e4.toJSON?.()??e4.name)===r2&&n3===t2)}function w(e3,t2){if(e3==null||t2==null)return t2||e3;let n2=Object.create(null);return[...Object.keys(e3),...Object.keys(t2)].filter((e4,t3,n3)=>n3.indexOf(e4)===t3).forEach(r2=>{let i2=D(x(e3,r2),x(t2,r2));F(i2)&&(n2[r2]=i2)}),n2}function T(e3,t2){return e3==null||t2==null?t2||e3:e3.concat(t2).filter((e4,t3,n2)=>n2.indexOf(e4)===t3)}function E(e3,t2){if(e3==null||t2==null)return e3||t2;let n2=[...e3],r2=e3.map(e4=>e4.node.evaluationPath);return t2.forEach(e4=>{r2.includes(e4.node.evaluationPath)||n2.push(e4)}),n2}function D(e3,t2,...n2){if(e3==null||t2==null)return e3||t2;let r2={};e3.items&&t2.prefixItems||e3.prefixItems&&t2.items?t2.prefixItems?r2.prefixItems=t2.prefixItems:r2.items=t2.items:(r2.prefixItems=t2.prefixItems??e3.prefixItems,r2.items=D(e3.items,t2.items));let i2={...e3,...t2,...r2,dynamicId:xe(e3.dynamicId,t2.dynamicId),oneOfIndex:e3.oneOfIndex??t2.oneOfIndex,schema:S(e3.schema,t2.schema,...n2),parent:e3.parent,resolvers:e3.resolvers.concat(t2.resolvers).filter(ae).sort(ie),reducers:e3.reducers.concat(t2.reducers).filter(ae).sort(ie),validators:e3.validators.concat(t2.validators).filter(ae).sort(ie),additionalProperties:D(e3.additionalProperties,t2.additionalProperties),contains:D(e3.contains,t2.contains),enum:T(e3.enum,t2.enum),if:D(e3.if,t2.if),then:D(e3.then,t2.then),else:D(e3.else,t2.else),not:D(e3.not,t2.not),propertyNames:D(e3.propertyNames,t2.propertyNames),unevaluatedProperties:D(e3.unevaluatedProperties,t2.unevaluatedProperties),unevaluatedItems:D(e3.unevaluatedItems,t2.unevaluatedItems),$defs:w(e3.$defs,t2.$defs),patternProperties:E(e3.patternProperties,t2.patternProperties),properties:w(e3.properties,t2.properties),required:T(e3.required,t2.required)};function a3(e4){let t3=e4.toJSON?.()??e4.name;return i2.schema?.[t3]!==void 0||(i2[t3]=void 0,false)}return n2?.forEach(e4=>i2[e4]=void 0),i2.resolvers=i2.resolvers.filter(a3),i2.reducers=i2.reducers.filter(a3),i2.validators=i2.validators.filter(a3),i2}function oe(e3,...t2){let n2={};return Object.keys(e3).forEach(r2=>{t2.includes(r2)||(n2[r2]=e3[r2])}),n2}function O(e3,...t2){if(!m(e3)||t2.length===0)return e3;let n2={};return t2.forEach(t3=>{e3[t3]!==void 0&&(n2[t3]=e3[t3])}),n2}function k(e3,t2={}){return e3.replace(/\{\{(\w+)\}\}/g,(e4,n2)=>{let r2=t2[n2];return r2==null?``:typeof r2==`object`?JSON.stringify(r2):String(r2)})}function A(e3,t2,n2,r2){return j(e3,t2,n2,r2).every(R)}function j(e3,t2,n2,r2){if(z(e3))return[e3];r2.push({pointer:n2,node:e3});let i2=e3.schema;if(i2===true)return[];if(i2===false)return[e3.createError(`invalid-data-error`,{value:t2,pointer:n2,schema:e3.schema})];let a3=[];for(let i3 of e3.validators){let o3=i3({node:e3,data:t2,pointer:n2,path:r2});Array.isArray(o3)?a3.push(...o3):o3&&a3.push(o3)}return s2(a3)}function se(e3,t2=true){let n2=b([`${e3}`]).slice(1);if(!t2)return n2;try{return encodeURIComponent(n2)}catch{return n2.replace(/%/g,`%25`)}}function M(e3){return Object.keys(e3).map(e4=>[e4,se(e4)])}function N(e3,t2){let n2=se(t2,false);return`${e3}/${e3.startsWith(`#`)?n2.replace(/%/g,`%25`):n2}`}function ce(e3,t2,n2={}){n2.path=n2.path??[],n2.withSchemaWarning=n2.withSchemaWarning??false,n2.pointer=n2.pointer??`#`;let r2=this,a3=o(e3);if(a3.length===0){let e4=r2.resolveRef(n2);return z(e4)?{node:void 0,error:e4}:{node:e4,error:void 0}}let o3=`#`,s3=r2;for(let e4=0,r3=a3.length;e4<r3;e4+=1){o3=N(o3,a3[e4]);let r4=s3.getNodeChild(a3[e4],t2,{...n2,pointer:o3});if(r4.error||r4.node==null)return r4;s3=r4.node,t2=x(t2,a3[e4])}let{node:c3,error:l2}=s3.resolveRef(n2).reduceNode(t2,{pointer:o3});return z(l2)?{node:void 0,error:l2}:F(c3)?{node:c3,error:void 0}:{error:void 0}}function le(e3,t2,n2={}){let r2=n2.pointer??N(`#`,e3),i2=n2.path??[],a3=n2.pointer??`#`,o3=this;if(o3.reducers.length){let n3=o3.reduceNode(t2,{key:e3,path:i2,pointer:a3});if(n3.error)return n3;F(n3.node)&&(o3=n3.node)}for(let n3 of o3.resolvers){let s3=n3({data:t2,key:e3,node:o3,pointer:r2});if(z(s3))return{node:void 0,error:s3};if(F(s3))return{node:s3.resolveRef({pointer:a3,path:i2}),error:void 0}}return n2.createSchema===true?{node:ve(o3).compileSchema(o3.createSchema(x(t2,e3)),`${o3.evaluationPath}/additional`,`${o3.schemaLocation}/additional`),error:void 0}:n2.withSchemaWarning===true?{node:void 0,error:o3.createError(`schema-warning`,{pointer:a3,value:t2,schema:o3.schema,key:e3})}:{node:void 0}}function de(e3){e3.formatAssertion===false&&(e3.keywords=e3.keywords.map(e4=>e4.keyword===P?{...e4,addValidate:()=>false}:e4))}function fe(e3){let t2=e3.schema[P];if(t2!=null){if(typeof t2!=`string`)return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${P}`,schema:e3.schema,value:t2,message:`Keyword '${P}' must be a string - received '${typeof t2}'`});if(e3.context.formats[t2]==null)return e3.createAnnotation(`unknown-format-warning`,{pointer:`${e3.schemaLocation}/${P}`,schema:e3.schema,value:t2,message:`Keyword '${P}' must be a string - received '${typeof t2}'`})}}function pe(e3){let{node:t2}=e3,n2=t2.context.formats[t2.schema.format];return n2?.(e3)}function F(e3){return m(e3)&&Array.isArray(e3?.reducers)&&Array.isArray(e3?.resolvers)}function ve(e3,t2=e3.context.remotes){if(e3.context.isolated===true&&t2===e3.context.remotes)return e3;let n2={...e3,context:{...e3.context,isolated:true,refs:{...e3.context.refs},anchors:{...e3.context.anchors},dynamicAnchors:{...e3.context.dynamicAnchors},remotes:{...t2}}};return Object.entries(n2.context.remotes).forEach(([t3,r2])=>{r2===e3&&(n2.context.remotes[t3]=n2)}),n2}function be(e3,t2){if(!Array.isArray(e3)||e3.length===0)throw Error(`Missing drafts in 'compileSchema({ $schema: "${t2}" })'`);return e3.length===1?e3[0]:e3.find(e4=>new RegExp(e4.$schemaRegEx,he).test(t2))??e3[e3.length-1]}function xe(e3,t2){return e3==t2?e3??``:e3==null||t2==null?(e3||t2)??``:e3.startsWith(t2)?e3:t2.startsWith(e3)?t2:`${e3}+${t2}`}function Te(e3){if(e3.schema.$ref&&we.includes(e3.context.version))return e3.context.keywords.filter(({keyword:e4})=>Ce.includes(e4)).map(t3=>Ee(t3,e3));let t2=Object.keys(e3.schema),n2=e3.context.keywords.filter(({keyword:e4})=>Ce.includes(e4)||t2.includes(e4)).map(t3=>Ee(t3,e3));return t2.filter(t3=>!t3.startsWith(`x-`)&&!_e.includes(t3)&&e3.context.keywords.find(e4=>e4.keywords?e4.keywords.includes(t3):e4.keyword===t3)==null).forEach(t3=>{n2.push(e3.createAnnotation(`unknown-keyword-warning`,{$id:e3.$id,pointer:`${e3.schemaLocation}/${t3}`,schema:e3.schema,value:t3,draft:e3.getDraftVersion()}))}),n2}function Ee(e3,t2){let n2=e3.parse?.(t2);return e3.reduce&&e3.addReduce?.(t2)&&t2.reducers.push(e3.reduce),e3.resolve&&e3.addResolve?.(t2)&&t2.resolvers.push(e3.resolve),e3.validate&&e3.addValidate?.(t2)&&t2.validators.push(e3.validate),n2}function I(e3){return m(e3)}function L(e3){return typeof e3==`boolean`}function De(e3){return m(e3)&&(e3?.type&&e3?.code&&e3?.data)!=null}function R(e3){return m(e3)&&e3.type===`annotation`}function z(e3){return m(e3)&&e3.type===`error`}function B(e3){return typeof e3==`number`}function Ae(e3){if(ke.includes(e3))return[];if(e3=e3.replace(Oe,``),e3.indexOf(`#`)===-1)return[e3.replace(/(#|\/)+$/g,``)];if(e3.indexOf(`#`)===0)return[e3.replace(Oe,``)];let t2=e3.split(`#`);return t2[0]=t2[0].replace(/(#|\/)+$/g,``),t2[1]=`#${t2[1].replace(Oe,``)}`,t2}function Me(e3,t2){e3.context.isolated!==true&&(e3.context.refs[t2]??(e3.context.refs[t2]=e3))}function Ne(e3){e3.resolveRef=Fe;let t2=v2(e3.parent?.$id,e3.schema?.$id);e3.$id=t2,e3.lastIdPointer=e3.parent?.lastIdPointer??`#`,t2!==e3.parent?.$id&&e3.evaluationPath!==`#`&&(e3.lastIdPointer=e3.evaluationPath),e3.lastIdPointer!==`#`&&e3.evaluationPath.startsWith(e3.lastIdPointer)&&Me(e3,v2(t2,`#${e3.evaluationPath.replace(e3.lastIdPointer,``)}`)),Me(e3,v2(e3.context.rootNode.$id,e3.evaluationPath));let r2=e3.schema.$anchor;if(r2){let n2=`${t2.replace(/#$/,``)}#${r2}`;e3.context.anchors[n2]??(e3.context.anchors[n2]=e3)}let i2=e3.schema.$dynamicAnchor;if(i2){let n2=`${t2.replace(/#$/,``)}#${i2}`;e3.context.dynamicAnchors[n2]??(e3.context.dynamicAnchors[n2]=e3)}if(e3.schema.$ref&&(e3.$ref=v2(t2,e3.schema.$ref),e3.$ref.startsWith(`/`)&&(e3.$ref=`#${e3.$ref}`)),e3.$ref?.startsWith(`#/$defs/`)&&s(e3.getNodeRoot().schema,e3.$ref)==null)return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/$ref`,schema:e3.schema,value:e3.schema.$ref,message:`Invalid $ref to missing target '${e3.schema.ref}'`})}function Pe({node:e3,data:t2,key:n2,pointer:r2,path:i2}){if(e3==null)return;let a3=e3.resolveRef({pointer:r2,path:i2});if(a3==null)return e3.createError(`ref-error`,{ref:e3.schema.$ref??e3.schema.$dynamicRef,pointer:r2,schema:e3.schema,value:t2});if(a3.schemaLocation===e3.schemaLocation)return a3;let{node:o3,error:s3}=D(e3,a3).reduceNode(t2,{key:n2,pointer:r2,path:i2});return o3??s3}function Fe({pointer:e3,path:t2=[]}={}){if(this.schema.$dynamicRef){let n3=Le(this,t2);return z(n3)||t2.push({pointer:e3,node:n3}),n3}if(this.$ref==null)return this;let n2=Re(this);return F(n2)&&t2.push({pointer:e3,node:n2}),n2}function Ie({node:e3,data:t2,pointer:n2=`#`,path:r2}){let i2=e3.resolveRef({pointer:n2,path:r2});return i2==null?e3.createError(`ref-error`,{ref:e3.schema.$ref??e3.schema.$dynamicRef,pointer:n2,schema:e3.schema,value:t2}):j(i2,t2,n2,r2)}function Le(e3,t2){let n2=t2,r2=v2(e3.$id,e3.schema.$dynamicRef);if(e3.context.dynamicAnchors[r2]==null&&e3.context.anchors[r2])return V(e3.context.anchors[r2],e3);for(let t3 of n2){if(t3.node.schema.$dynamicAnchor)return V(t3.node,e3);let n3=e3.schema.$dynamicRef.split(`#`).pop(),r3=v2(t3.node.$id,`#${n3}`);if(e3.context.dynamicAnchors[r3])return V(e3.context.dynamicAnchors[r3],e3)}return Re(e3,r2)}function V(e3,t2){let n2=e3.schema;m(e3.schema)&&(n2={...oe(e3.schema,`$id`),...O(t2.schema,...c2.PROPERTIES_TO_MERGE)});let{isolated:r2,remotes:i2}=t2.context;return(r2===true?ve(e3,i2):e3).compileSchema(n2,`${t2.evaluationPath}/$ref`,e3.schemaLocation)}function Re(e3,t2=e3?.$ref){if(t2==null)return e3;if(e3.context.refs[t2])return V(e3.context.refs[t2],e3);if(e3.context.anchors[t2])return V(e3.context.anchors[t2],e3);if(e3.context.dynamicAnchors[t2])return V(e3.context.dynamicAnchors[t2],e3);let r2=Ae(t2);if(r2.length===0)return e3.createError(`ref-error`,{ref:t2,pointer:e3.evaluationPath,schema:e3.schema,value:void 0});if(r2.length===1){let t3=r2[0];if(e3.context.remotes[t3])return V(e3.context.remotes[t3],e3);if(t3[0]===`#`){let r3=e3.context.rootNode.schema,i2=s(r3,t3);if(i2)return e3.compileSchema(i2,`${e3.evaluationPath}/$ref`,t3)}return e3.createError(`ref-error`,{ref:t3,pointer:e3.evaluationPath,schema:e3.schema,value:void 0})}if(r2.length===2){let n2=r2[0];if(e3.context.remotes[n2]&&e3!==e3.context.remotes[n2]){let{isolated:i2,remotes:a3}=e3.context,o3=a3[n2],s3=i2===true?ve(o3,a3):o3,c3=Re(s3,t2);if(c3||(c3=Re(s3,r2[1]),c3))return c3}if(e3.context.refs[n2]){let a3=e3.context.refs[n2],o3=o(r2[1]),s3=a3;for(let n3 of o3)if(s3=s3[n3===`definitions`?`$defs`:n3],s3==null)return e3.createError(`ref-error`,{ref:t2,pointer:e3.evaluationPath,schema:e3.schema,value:void 0,host:r2[0],local:r2[1]});return e3.context.isolated===true?V(s3,e3):s3}}return e3.createError(`ref-error`,{ref:t2,pointer:e3.evaluationPath,schema:e3.schema,value:void 0})}function H(e3,...t2){return t2.reduce((e4,t3)=>(t3.schemaValidation&&e4.push(...t3.schemaValidation),e4),e3)}function Be(e3){let t2=[];return e3.schema.$defs&&(m(e3.schema.$defs)?(e3.$defs=e3.$defs??Object.create(null),M(e3.schema.$defs).forEach(([n2,r2])=>{e3.$defs[n2]=e3.compileSchema(e3.schema.$defs[n2],`${e3.evaluationPath}/$defs/${r2}`,`${e3.schemaLocation}/$defs/${r2}`),H(t2,e3.$defs[n2])})):t2.push(e3.createError(`schema-error`,{pointer:e3.schemaLocation,schema:e3.schema,value:e3.schema.$defs,message:`$defs must be an object - received: ${typeof e3.schema.$defs}`}))),e3.schema.definitions&&(m(e3.schema.definitions)||t2.push(e3.createError(`schema-error`,{pointer:e3.schemaLocation,schema:e3.schema,value:e3.schema.$defs,message:`definitions must be an object - received: ${typeof e3.schema.definitions}`})),e3.$defs=e3.$defs??Object.create(null),M(e3.schema.definitions).forEach(([n2,r2])=>{e3.$defs[n2]=e3.compileSchema(e3.schema.definitions[n2],`${e3.evaluationPath}/definitions/${r2}`,`${e3.schemaLocation}/definitions/${r2}`),H(t2,e3.$defs[n2])})),t2}function He(e3){let t2=e3.parent?.$id;if(e3.schema?.$ref??(t2=v2(e3.parent?.$id,e3.schema?.$id)),e3.$id=t2,e3.lastIdPointer=e3.parent?.lastIdPointer??`#`,e3.resolveRef=Fe,e3.context.refs[t2]??(e3.context.refs[t2]=e3),t2!==e3.parent?.$id&&(e3.lastIdPointer=e3.evaluationPath),e3.lastIdPointer!==`#`&&e3.evaluationPath.startsWith(e3.lastIdPointer)){let n2=`#${e3.evaluationPath.replace(e3.lastIdPointer,``)}`;e3.context.refs[v2(t2,n2)]=e3}else e3.context.refs[v2(t2,e3.evaluationPath)]=e3;e3.context.refs[v2(e3.context.rootNode.$id,e3.evaluationPath)]=e3,e3.schema.$ref&&(e3.$ref=v2(t2,e3.schema.$ref))}function Ue({node:e3,data:t2,pointer:n2=`#`,path:r2}){let i2=We(e3,n2,r2);return F(i2)?j(i2,t2,n2,r2):e3.createError(`ref-error`,{ref:e3.schema.$ref,pointer:n2,schema:e3.schema,value:t2})}function We(e3,t2,n2){let r2=e3.resolveRef({pointer:t2,path:n2});return F(r2)?r2!==e3&&r2?We(r2,t2,n2):e3:e3.createError(`ref-error`,{ref:e3.schema.$ref,pointer:t2,schema:e3.schema,value:void 0})}function Ke(e3,t2){e3.context.refs[t2]??(e3.context.refs[t2]=e3)}function qe(e3){let t2=e3.parent?.$id;if(e3.schema?.$ref==null&&e3.schema?.id&&(t2=v2(e3.parent?.$id,e3.schema.id)),e3.$id=t2,e3.lastIdPointer=e3.parent?.lastIdPointer??`#`,e3.resolveRef=Je,e3.context.refs[t2]??(e3.context.refs[t2]=e3),t2!==e3.parent?.$id&&(e3.lastIdPointer=e3.evaluationPath),e3.lastIdPointer!==`#`&&e3.evaluationPath.startsWith(e3.lastIdPointer)){let n2=`#${e3.evaluationPath.replace(e3.lastIdPointer,``)}`;Ke(e3,v2(t2,n2))}else Ke(e3,v2(t2,e3.evaluationPath));Ke(e3,v2(e3.context.rootNode.$id,e3.evaluationPath)),e3.schema.$ref&&(e3.$ref=v2(t2,e3.schema.$ref))}function Je({pointer:e3,path:t2}={}){if(this.$ref==null)return this;let n2=Xe(this);return F(n2)&&t2?.push({pointer:e3,node:n2}),n2}function Ye(e3,t2){let n2=m(e3.schema)?oe(e3.schema,`id`):e3.schema,{isolated:r2,remotes:i2}=t2.context;return(r2===true?ve(e3,i2):e3).compileSchema(n2,`${t2.evaluationPath}/$ref`,n2.schemaLocation)}function Xe(e3,t2=e3?.$ref){if(t2==null)return e3;if(e3.context.refs[t2])return Ye(e3.context.refs[t2],e3);if(e3.context.anchors[t2])return Ye(e3.context.anchors[t2],e3);let n2=Ae(t2);if(n2.length===0)return e3.createError(`ref-error`,{ref:t2,pointer:e3.evaluationPath,schema:e3.schema,value:void 0});if(n2.length===1){let t3=n2[0];return e3.context.remotes[t3]?Ye(e3.context.remotes[t3],e3):e3.createError(`ref-error`,{ref:t3,pointer:e3.evaluationPath,schema:e3.schema,value:void 0})}if(n2.length===2){let r2=n2[0];if(e3.context.remotes[r2]&&e3!==e3.context.remotes[r2]){let{isolated:i3,remotes:a3}=e3.context,o3=a3[r2],s3=i3===true?ve(o3,a3):o3,c3=Xe(s3,t2);if(c3||(c3=Xe(s3,n2[1]),c3))return c3}let i2=n2[0];if(e3.context.refs[i2]){let t3=e3.context.refs[i2],r3=n2[1].split(`$defs/`).pop();if(r3&&t3?.$defs){let n3=t3.$defs[r3];return Xe(n3&&e3.context.isolated===true?Ye(n3,e3):n3)}}}else return e3.createError(`ref-error`,{ref:t2,pointer:e3.evaluationPath,schema:e3.schema,value:void 0})}function $e(e3){let{schema:t2,evaluationPath:n2,schemaLocation:r2}=e3;if(t2.additionalItems==null||t2.additionalItems===false)return;let i2=t2[Ze];if(!(m(i2)||i2===true))return e3.createError(`schema-error`,{pointer:n2,schema:t2,value:void 0,message:`Keyword '${Ze}' must be an object or a boolean - received '${typeof i2}'`});if(!Array.isArray(t2.items))return e3.createAnnotation(`schema-error`,{pointer:n2,schema:t2,value:void 0,message:`Keyword '${Ze}' is only evaluated with a given items-array`});e3.items=e3.compileSchema(t2.additionalItems,`${n2}/additionalItems`,`${r2}/additionalItems`)}function et({node:e3,key:t2,data:n2}){if(Array.isArray(n2)){let r2=x(n2,t2),{node:i2,error:a3}=e3.items.reduceNode(r2);return i2??a3}}function tt({node:e3,data:t2,pointer:n2,path:r2}){let{schema:i2}=e3;if(!Array.isArray(t2)||t2.length===0||Array.isArray(i2.items)&&i2.items.length>=t2.length)return;let a3=Array.isArray(i2.items)?i2.items.length:0,o3=[];for(let s3=a3;s3<t2.length;s3+=1){let a4=t2[s3];if(e3.items){let t3=j(e3.items,a4,`${n2}/${s3}`,r2);t3&&o3.push(...t3)}else i2.additionalItems===false&&o3.push(e3.createError(`additional-items-error`,{key:s3,pointer:`${n2}/${s3}`,value:t2,schema:i2}))}return o3}function rt(e3){let{schema:t2,evaluationPath:n2,schemaLocation:r2}=e3;if(!(t2.additionalProperties==null||L(t2.additionalProperties)))return m(t2.additionalProperties)?(e3.additionalProperties=e3.compileSchema(t2.additionalProperties,`${n2}/additionalProperties`,`${r2}/additionalProperties`),e3.additionalProperties.schemaValidation):e3.createError(`schema-error`,{pointer:e3.schemaLocation,schema:t2,value:t2.additionalProperties,message:`keyword 'additionalProperties' must be a valid JSON Schema - receoved: ${typeof t2.additionalProperties}`})}function it({node:e3,data:t2,key:n2,pointer:r2=N(`#`,n2)}){let i2=x(t2,n2);if(e3.additionalProperties){let{node:t3,error:n3}=e3.additionalProperties.reduceNode(i2,{pointer:r2});return t3??n3}if(e3.schema.additionalProperties===false)return e3.createError(`no-additional-properties-error`,{pointer:r2,schema:e3.schema,value:x(t2,n2),property:`${n2}`})}function at({node:e3,data:t2,pointer:n2=`#`,path:r2}){if(!m(t2))return;let{schema:i2}=e3,a3=[],o3=Object.keys(t2).filter(e4=>c2.propertyBlacklist.includes(e4)===false),s3=e3.patternProperties;Array.isArray(s3)&&(o3=o3.filter(e4=>{for(let t3 of s3)if(t3.pattern.test(e4))return false;return true}));let l2=e3.properties?Object.keys(e3.properties):[];return o3.filter(e4=>l2.indexOf(e4)===-1).forEach(o4=>{let s4=x(t2,o4);if(s4!==void 0){if(m(e3.additionalProperties)){let t3=j(e3.additionalProperties,s4,N(n2,o4),r2);t3&&a3.push(...t3)}else a3.push(e3.createError(`no-additional-properties-error`,{pointer:N(n2,o4),schema:i2,value:t2,property:o4,properties:l2}))}}),a3}function st(e3){let{schema:t2,evaluationPath:n2,schemaLocation:r2}=e3;if(t2[U]!=null){if(!Array.isArray(t2[U]))return e3.createError(`schema-error`,{pointer:r2,schema:t2,value:t2[U],message:`Keyword '${U}' must be an array - received '${typeof t2[U]}'`});if(t2[U].length!==0)return e3[U]=t2[U].map((t3,i2)=>e3.compileSchema(t3,`${n2}/${U}/${i2}`,`${r2}/${U}/${i2}`)),H([],...e3[U])}}function ct({node:e3,data:t2,key:n2,pointer:r2,path:i2}){if(e3[U]==null)return;let a3={},o3=``;for(let s3=0;s3<e3[U].length;s3+=1){let{node:c3}=e3[U][s3].reduceNode(t2,{key:n2,pointer:r2,path:i2});if(c3){let t3=c3.dynamicId?.replace(e3.dynamicId,``)??``,n3=t3===``?`${U}/${s3}`:t3;o3+=`${o3===``?``:`,`}${n3}`;let r3=S(e3[U][s3].schema,c3.schema);a3=S(a3,r3,U,`contains`)}}return e3.compileSchema(a3,`${e3.evaluationPath}/${o3}`,e3.schemaLocation,`${e3.schemaLocation}(${o3})`)}function lt({node:e3,data:t2,pointer:n2,path:r2}){if(!Array.isArray(e3[U])||e3[U].length===0)return;let i2=[];return e3[U].forEach(e4=>{i2.push(...j(e4,t2,n2,r2))}),i2}function dt(e3){let{schema:t2,evaluationPath:n2,schemaLocation:r2}=e3;if(t2[W]!=null){if(!Array.isArray(t2[W]))return e3.createError(`schema-error`,{pointer:r2,schema:t2,value:t2[W],message:`Keyword '${W}' must be an array - received '${typeof t2[W]}'`});if(t2[W].length!==0)return e3[W]=t2[W].map((t3,i2)=>e3.compileSchema(t3,`${n2}/${W}/${i2}`,`${r2}/${W}/${i2}`)),H([],...e3[W])}}function ft({node:e3,data:t2,pointer:n2,path:r2}){if(e3[W]==null)return;let i2={},a3=``;for(let o3=0;o3<e3[W].length;o3+=1)if(A(e3[W][o3],t2,n2,r2)){let{node:n3}=e3[W][o3].reduceNode(t2);if(n3){let t3=n3.dynamicId?.replace(e3.dynamicId,``)??``,r3=t3===``?`${W}/${o3}`:t3;a3+=`${a3===``?``:`,`}${r3}`;let s3=S(e3[W][o3].schema,n3.schema);i2=S(i2,s3,W)}}return e3.compileSchema(i2,`${e3.evaluationPath}${a3}`,e3.schemaLocation,`${e3.schemaLocation}(${a3})`)}function pt({node:e3,data:t2,pointer:n2,path:r2}){if(e3[W]!=null){for(let i2 of e3[W])if(A(i2,t2,n2,r2))return;return e3.createError(`any-of-error`,{pointer:n2,schema:e3.schema,value:t2,anyOf:e3.schema[W]})}}function ht(e3){let t2=e3.schema[G];if(t2!=null)return I(t2)||L(t2)?(e3[G]=e3.compileSchema(t2,`${e3.evaluationPath}/${G}`),e3[G].schemaValidation):e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${G}`,schema:e3.schema,value:t2,message:`Keyword '${G}' must be a valid JSON Schema - received '${typeof t2}'`})}function gt({node:e3,data:t2,pointer:n2,path:r2},i2=e3.schema.minContains??1,a3=e3.schema.maxContains??1/0){let{schema:o3}=e3;if(!Array.isArray(t2))return;let s3=0;for(let i3 of t2)A(e3.contains,i3,n2,r2)&&s3++;if(!(a3>=s3&&i2<=s3))return a3<s3?e3.createError(`contains-max-error`,{pointer:n2,schema:o3,delta:s3-a3,value:t2}):i2>s3?e3.createError(`contains-min-error`,{pointer:n2,schema:o3,delta:i2-s3,value:t2}):e3.createError(`contains-error`,{pointer:n2,schema:o3,value:t2})}function vt(e3){let t2=e3===void 0?{}:{type:p(e3)};return t2.type===`object`&&m(e3)&&(t2.properties=Object.create(null),Object.keys(e3).forEach(n2=>t2.properties[n2]=vt(e3[n2]))),t2.type===`array`&&Array.isArray(e3)&&(e3.length===1?t2.items=vt(e3[0]):(t2.items=e3.map(vt),t2.items.find(e4=>e4.type!==t2.items[0].type)??(t2.items=t2.items[0]))),t2}function yt(e3){return Array.isArray(e3)&&e3.find(e4=>typeof e4!=`string`)==null}function xt(e3){let{schema:t2}=e3;if(t2[K]==null)return;if(!m(t2[K]))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${K}`,schema:t2,value:t2[K],message:`Keyword '${K}' must be an object - received '${typeof t2[K]}'`});let n2=[];e3.dependentRequired=Object.create(null);for(let[r2,i2]of M(t2[K])){let a3=t2[K][r2];yt(a3)?e3.dependentRequired[r2]=a3:n2.push(e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${K}/${i2}`,schema:t2,value:a3,message:`Keyword '${K}[string]' must be a string[] - received '${typeof a3}'`}))}return n2}function St({node:e3,data:t2,pointer:n2=`#`}){let{dependentRequired:r2}=e3;if(r2==null||!m(t2))return;let i2=[];return Object.keys(t2).forEach(a3=>{let o3=r2[a3];if(Array.isArray(o3))for(let r3=0,a4=o3.length;r3<a4;r3+=1)b2(t2,o3[r3])||i2.push(e3.createError(`missing-dependency-error`,{missingProperty:o3[r3],pointer:n2,schema:e3.schema,value:t2}))}),i2}function wt(e3){let{dependentSchemas:t2}=e3.schema;if(t2==null)return;if(!m(t2))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${q}`,schema:e3.schema,value:t2,message:`Keyword '${q}' must be an object - received '${typeof t2}'`});if(Object.keys(t2).length===0)return;let n2=[],r2=Object.create(null);for(let[i2,a3]of M(t2)){let o3=t2[i2];m(o3)?(r2[i2]=e3.compileSchema(o3,`${e3.evaluationPath}/${q}/${a3}`,`${e3.schemaLocation}/${q}/${a3}`),H(n2,r2[i2])):L(o3)?r2[i2]=o3:n2.push(e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${q}/${a3}`,schema:e3.schema,value:o3,message:`Keyword '${q}[string]' must be a valid JSON Schema'`}))}return e3.dependentSchemas=r2,n2}function Tt({node:e3,data:t2}){let{dependentSchemas:n2}=e3;if(!m(t2)||n2==null)return e3;let r2,i2=0,a3=`${e3.schemaLocation}(`;return Object.keys(t2).forEach(e4=>{n2[e4]!=null&&(r2??={properties:Object.create(null)},F(n2[e4])?r2=S(r2,n2[e4].schema):r2.properties[e4]=n2[e4],a3+=`${i2?`,`:``}${q}/${e4}`,i2++)}),r2==null?e3:(r2=S(e3.schema,r2,q),e3.compileSchema(r2,e3.evaluationPath,e3.schemaLocation,`${a3})`))}function Et({node:e3,data:t2,pointer:n2,path:r2}){let{schema:i2,dependentSchemas:a3}=e3;if(!m(t2)||a3==null)return;let o3=[];return Object.keys(t2).forEach(c3=>{let l2=a3[c3];l2!==true&&(l2===false?o3.push(e3.createError(`missing-dependency-error`,{pointer:n2,schema:i2,value:t2})):F(l2)&&s2(j(l2,t2,n2,r2),o3))}),o3}function Ot(e3){let{dependencies:t2}=e3.schema;if(!m(t2))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${J}`,schema:e3.schema,value:t2,message:`Keyword '${J}' must be an object - received ${typeof t2}`});let n2=[];for(let[r2,i2]of M(t2)){let a3=t2[r2];I(a3)||L(a3)?(e3.dependentSchemas=e3.dependentSchemas??Object.create(null),e3.dependentSchemas[r2]=e3.compileSchema(a3,`${e3.evaluationPath}/${J}/${i2}`,`${e3.schemaLocation}/${J}/${i2}`),H(n2,e3.dependentSchemas[r2])):yt(a3)?(e3.dependentRequired=e3.dependentRequired??Object.create(null),e3.dependentRequired[r2]=a3):n2.push(e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${J}`,schema:e3.schema,value:t2,message:`Keyword '${J}[string]' must be JSON Schema or string[]`}))}return n2}function kt({node:e3,data:t2,key:n2,pointer:r2,path:i2}){if(!m(t2)||e3.dependentRequired==null&&e3.dependentSchemas==null)return e3;let a3=e3.compileSchema(e3.schema,e3.evaluationPath,e3.schemaLocation),o3=a3.schema.required??[],s3=``,c3=e3.dependentRequired;c3&&Object.keys(c3).forEach(e4=>{if(!b2(t2,e4)&&!o3.includes(e4)||c3[e4]==null)return;o3.push(...c3[e4]);let n3=`${J}/${e4}`;s3+=`${s3===``?``:`,`}${n3}`});let l2=e3.dependentSchemas;if(l2)for(let c4 of Object.keys(l2)){if(!b2(t2,c4)&&!o3.includes(c4))continue;let u2=l2[c4];if(!F(u2))continue;Array.isArray(u2.schema.required)&&o3.push(...u2.schema.required);let{node:d2,error:f2}={...u2,schema:{...u2.schema,required:o3}}.reduceNode(t2,{key:n2,pointer:N(`${r2}/${J}`,c4),path:i2});if(!d2)return f2;a3=D(a3,d2);let p2=d2.dynamicId?.replace(e3.dynamicId,``)??``,m2=p2===``?`${J}/${c4}`:p2;s3+=`${s3===``?``:`,`}${m2}`}return a3===e3?e3:o3.length===0?a3:(o3=a3.schema.required?a3.schema.required.concat(...o3):o3,o3=o3.filter((e4,t3,n3)=>n3.indexOf(e4)===t3),a3=D(a3,a3,J),a3.compileSchema({...a3.schema,required:o3},a3.evaluationPath,a3.schemaLocation,`${e3.schemaLocation}(${s3})`))}function At({node:e3,data:t2,pointer:n2,path:r2}){if(!m(t2))return;let i2=[];return e3.dependentRequired&&s2(St({node:e3,data:t2,pointer:n2,path:r2}),i2),e3.dependentSchemas&&s2(Et({node:e3,data:t2,pointer:n2,path:r2}),i2),i2}function Nt(e3){let t2=e3.schema[jt];if(t2!=null){if(typeof t2!=`boolean`)return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${jt}`,schema:e3.schema,value:t2,message:`Keyword '${jt}' must be a boolean - received '${typeof t2}'`});e3[jt]=t2}}function Pt({node:e3,data:t2,pointer:n2}){return[e3.createAnnotation(`deprecated-warning`,{pointer:n2,schema:e3.schema,value:t2},e3.schema.deprecatedMessage)]}function Ft(e3,t2){if(e3===t2)return true;if(Array.isArray(e3)||Array.isArray(t2)){if(!Array.isArray(e3)||!Array.isArray(t2)||e3.length!==t2.length)return false;for(let n2=0;n2<e3.length;n2+=1)if(!Ft(e3[n2],t2[n2]))return false;return true}if(m(e3)&&m(t2)){let n2=Object.getPrototypeOf(e3),r2=Object.getPrototypeOf(t2);if(n2!==Object.prototype&&n2!==null||r2!==Object.prototype&&r2!==null)return(0,import_fast_deep_equal.default)(e3,t2);let i2=Object.keys(e3);return i2.length===Object.keys(t2).length&&i2.every(n3=>Object.prototype.hasOwnProperty.call(t2,n3)&&Ft(e3[n3],t2[n3]))}return(0,import_fast_deep_equal.default)(e3,t2)}function Lt(e3){let{schema:t2}=e3;if(t2[Y]!=null){if(!Array.isArray(t2[Y]))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${Y}`,schema:t2,value:t2[Y],message:`Keyword '${Y}' must be an array - received '${typeof t2[Y]}'`});e3.enum=t2[Y]}}function Rt({node:e3,data:t2,pointer:n2=`#`}){if(e3.enum!=null&&!e3.enum.some(e4=>Ft(t2,e4)))return e3.createError(`enum-error`,{pointer:n2,schema:e3.schema,value:t2,values:e3.enum})}function Vt(e3){let{exclusiveMaximum:t2}=e3.schema;if(t2!=null&&typeof t2!=`number`&&typeof t2!=`boolean`)return e3.createError(`schema-error`,{pointer:e3.evaluationPath,schema:e3.schema,value:void 0,message:`Keyword 'exclusiveMaximum' must be a number - received '${typeof t2}'`})}function Ht({node:e3,data:t2,pointer:n2}){if(typeof t2==`number`&&e3.schema.exclusiveMaximum&&e3.schema.maximum===t2)return e3.createError(`maximum-error`,{maximum:e3.schema.exclusiveMaximum,length:t2,pointer:n2,schema:e3.schema,value:t2})}function Wt(e3){let{exclusiveMinimum:t2}=e3.schema;if(t2!=null&&typeof t2!=`number`&&typeof t2!=`boolean`)return e3.createError(`schema-error`,{pointer:e3.evaluationPath,schema:e3.schema,value:void 0,message:`Keyword 'exclusiveMinimum' must be a number - received '${typeof t2}'`})}function Gt({node:e3,data:t2,pointer:n2}){if(typeof t2==`number`&&e3.schema.exclusiveMinimum&&e3.schema.minimum===t2)return e3.createError(`minimum-error`,{minimum:e3.schema.exclusiveMinimum,length:t2,pointer:n2,schema:e3.schema,value:t2})}function nn(e3,t2){if(e3.oneOf)return e3.oneOf.map(e4=>e4.resolveRef());if(e3.items?.oneOf)return e3.items.oneOf.map(e4=>e4.resolveRef());if(e3.prefixItems&&e3.prefixItems.length>+t2){let{node:n3,error:r3}=e3.getNodeChild(t2);return n3?[n3]:r3}if(e3.schema.additionalItems){if(e3.schema.additionalItems===true)return[e3.compileSchema({type:`string`})];if(e3.items)return[e3.items.resolveRef()]}if(e3.prefixItems&&e3.prefixItems.length<=+t2)return[];let{node:n2,error:r2}=e3.getNodeChild(t2);return n2?[n2]:r2}function sn(e3,t2){let n2=p(t2),r2=e3.schema;if(r2===true)return n2===`bigint`?`number`:rn.some(e4=>e4===n2)?n2:void 0;if(!m(r2))return;let i2=r2.type;if(Array.isArray(i2)){if(i2.includes(n2))return n2;let e4=p(r2.default);return i2.includes(e4)?e4:i2[0]}if(i2)return i2;if(Array.isArray(r2.enum)){let e4=r2.enum.map(e5=>p(e5)).filter((e5,t4,n3)=>n3.indexOf(e5)===t4);if(e4.includes(n2))return n2;let t3=p(r2.default);return e4.includes(t3)?t3:e4[0]}let a3=Object.keys(e3.schema),o3=a3.filter(e4=>an.includes(e4)),s3=a3.filter(e4=>on.includes(e4));if(o3.length>0&&o3.length>s3.length)return`object`;if(s3.length>0&&s3.length>o3.length)return`array`;if(e3.if)return sn(e3.if.resolveRef()??e3.if,t2);if(e3.allOf)for(let n3 of e3.allOf){let e4=sn(n3.resolveRef()??n3,t2);if(e4)return e4}if(e3.oneOf)for(let n3 of e3.oneOf){let e4=sn(n3.resolveRef()??n3,t2);if(e4)return e4}if(e3.anyOf)for(let n3 of e3.anyOf){let e4=sn(n3.resolveRef()??n3,t2);if(e4)return e4}if(r2.$ref){let n3=e3.resolveRef();if(n3)return sn(n3,t2)}}function cn(e3){switch(p(e3)){case`string`:case`array`:return e3?.length===0;case`null`:case`undefined`:return true;case`object`:return Object.keys(e3).length===0;default:return false}}function fn(e3){let{schema:t2,evaluationPath:n2,schemaLocation:r2}=e3;if(t2[X]!=null){if(!Array.isArray(t2[X]))return e3.createError(`schema-error`,{pointer:r2,schema:t2,value:t2[X],message:`Keyword '${X}' must be an array - received '${typeof t2[X]}'`});if(t2[X].length!==0)return e3[X]=t2[X].map((t3,i2)=>e3.compileSchema(t3,`${n2}/${X}/${i2}`,`${r2}/${X}/${i2}`)),H([],...e3[X])}}function pn({node:e3,data:t2,pointer:n2,path:r2}){if(e3.oneOf==null)return;if(t2!=null&&e3.schema[ln])return mn({node:e3,data:t2,pointer:n2,path:r2});let i2=[],a3=[];for(let o3=0;o3<e3.oneOf.length;o3+=1){let s3=j(e3.oneOf[o3],t2,n2,r2);s3.every(R)?i2.push({index:o3,node:e3.oneOf[o3]}):a3.push(...s3)}if(i2.length===1){let{node:e4,index:a4}=i2[0],{node:o3,error:s3}=e4.reduceNode(t2,{pointer:n2,path:r2});if(o3){let t3=o3.dynamicId?.replace(e4.dynamicId,``)??``,n3=t3===``?`oneOf/${a4}`:t3;return o3.oneOfIndex=a4,o3.dynamicId=xe(o3.dynamicId,`+${e4.schemaLocation}(${n3})`),o3}return s3}return i2.length,e3.createError(`one-of-error`,{value:JSON.stringify(t2),pointer:n2,schema:e3.schema,oneOf:e3.schema.oneOf,errors:a3})}function mn({node:e3,data:t2,pointer:n2,path:r2}){if(e3.oneOf==null)return;let i2=e3.schema[ln],a3=x(t2,i2);if(t2===void 0||a3===void 0)return e3.createError(`missing-one-of-property-error`,{oneOfProperty:i2,pointer:n2,schema:e3.schema,value:t2});let o3=[];for(let c3=0;c3<e3.oneOf.length;c3+=1){let{node:l2}=e3.oneOf[c3].getNodeChild(i2,t2);if(!F(l2))return e3.createError(`missing-one-of-declarator-error`,{declarator:ln,oneOfProperty:i2,schemaLocation:e3.oneOf[c3].schemaLocation,pointer:`${n2}/oneOf/${c3}`,schema:e3.schema,value:t2});let u2=s2(j(l2,a3,N(n2,i2),r2));if(!u2.every(R))o3.push(...u2);else{let{node:i3}=e3.oneOf[c3].reduceNode(t2,{pointer:n2,path:r2});if(i3)return i3.oneOfIndex=c3,i3}}return e3.createError(`one-of-property-error`,{property:i2,value:t2,pointer:n2,schema:e3.schema,errors:o3})}function hn(e3,t2,n2,r2){if(t2==null||e3.properties==null)return-1;let i2=0,a3=Object.keys(e3.properties??{});for(let o3 of a3)t2[o3]!==void 0&&A(e3.properties[o3],t2[o3],n2,r2)&&(i2+=1);return i2}function gn({node:e3,data:t2,pointer:n2,path:r2}){if(e3.oneOf==null)return e3;let i2=pn({node:e3,data:t2,pointer:n2,path:r2});if(F(i2))return i2;if(m(t2)){let i3,a3=-1,o3=0;for(let s4=0;s4<e3.oneOf.length;s4+=1){let c4=e3.oneOf[s4],l2=hn(c4,t2,n2,r2);o3<l2&&(o3=l2,i3=c4,a3=s4)}if(i3===void 0)return e3.createError(`one-of-error`,{value:JSON.stringify(t2),pointer:n2,schema:e3.schema,oneOf:e3.schema.oneOf});let{node:s3,error:c3}=i3.reduceNode(t2,{pointer:n2,path:r2});return s3?(s3.oneOfIndex=a3,s3):c3}if(Array.isArray(t2)){let i3,a3=-1,o3=1/0;for(let n3=0;n3<e3.oneOf.length;n3+=1){let r3=e3.oneOf[n3],{errors:s4}=r3.validate(t2),c4=s4.length;c4<o3&&(o3=c4,i3=r3,a3=n3)}if(i3===void 0)return e3.createError(`one-of-error`,{value:JSON.stringify(t2),pointer:n2,schema:e3.schema,oneOf:e3.schema.oneOf});let{node:s3,error:c3}=i3.reduceNode(t2,{pointer:n2,path:r2});return s3?(s3.oneOfIndex=a3,s3):c3}return i2}function _n({node:e3,data:t2,pointer:n2=`#`,path:r2}){let{oneOf:i2,schema:a3}=e3;if(!i2)return;let o3=a3[ln],s3=x(t2,o3),c3=[],l2=[];for(let e4 of i2){let{node:t3,error:a4}=e4.getNodeChild(o3,s3);if(t3){let a5=j(t3,s3,N(n2,o3),r2);a5.every(R)?c3.push({index:i2.indexOf(e4),node:e4}):l2.push(...a5)}else console.log(`jlib oneOf error: failed getting schema for '${o3}' to resolve ${ln} in ${n2}/oneOf/${i2.indexOf(e4)}`,a4)}if(c3.length===1){let e4=c3[0];return e4.node.oneOfIndex=e4.index,j(e4.node,t2,n2,r2)}return c3.length>1?e3.createError(`multiple-one-of-error`,{value:t2,pointer:n2,schema:a3,matches:c3}):e3.createError(`one-of-error`,{value:JSON.stringify(t2),pointer:n2,schema:a3,oneOf:a3.oneOf,errors:l2})}function vn({node:e3,data:t2,pointer:n2=`#`,path:r2}){let{oneOf:i2,schema:a3}=e3;if(!i2)return;if(a3[ln])return _n({node:e3,data:t2,pointer:n2,path:r2});let o3=[],s3=[];for(let e4=0;e4<i2.length;e4+=1){let a4=j(i2[e4],t2,n2,r2);a4.every(R)?o3.push({index:e4,node:i2[e4]}):s3.push(...a4)}if(o3.length===1){let{node:e4,index:t3}=o3[0];e4.oneOfIndex=t3}else return o3.length>1?e3.createError(`multiple-one-of-error`,{value:t2,pointer:n2,schema:a3,matches:o3}):e3.createError(`one-of-error`,{value:JSON.stringify(t2),pointer:n2,schema:a3,oneOf:a3.oneOf,errors:s3})}function bn(e3,t2){if(e3.$ref==null)return;t2.cache=t2.cache??{};let{cache:n2,recursionLimit:r2=1}=t2,i2=e3.schemaLocation;if(n2[i2]=n2[i2]??{},n2[i2][e3.$ref]=n2[i2][e3.$ref]??0,n2[i2][e3.$ref]>=r2&&t2.disableRecursionLimit!==true)return false;t2.disableRecursionLimit=false,n2[i2][e3.$ref]+=1;let a3=e3.resolveRef();if(a3&&a3!==e3)return a3}function xn(e3,t2){return(t2.cache?.[e3.schemaLocation]?.[e3.$ref]??-1)<(t2.recursionLimit??1)}function Sn(e3,t2){let n2=p(t2);if(e3===void 0||t2==null||n2===e3||n2===`number`&&e3===`integer`)return t2;if(e3===`string`)return JSON.stringify(t2);if(n2!==`string`)return t2;try{let n3=JSON.parse(t2);if(p(n3)===e3)return n3}catch{}return t2}function Cn(e3,t2,n2){if(n2?.cache==null)throw Error(`Missing options`);if(e3.schema===false||e3.schema===true||yn(t2))return t2;if(e3.schema?.const!==void 0)return e3.schema?.const;let r2=e3,i2=t2;if(Array.isArray(e3.schema.enum)&&e3.schema.enum.length>0&&t2===void 0)return e3.schema.default??e3.schema.enum[0];if(e3.schema.default!==void 0&&i2===void 0&&(i2=e3.schema.default),r2.allOf?.length&&r2.allOf.forEach(e4=>{i2=e4.getData(i2,n2)??i2}),r2.anyOf&&r2.anyOf?.length>0&&(i2=r2.anyOf[0].getData(i2,n2)??i2),r2.oneOf&&r2.oneOf?.length>0){if(cn(i2))r2=D(r2,r2.oneOf[0]);else{let e4=gn({node:r2,data:i2,path:[],pointer:`#`});if(z(e4)){if(i2!=null&&n2.removeInvalidData!==true)return i2;r2=r2.oneOf[0],i2=void 0}else r2=D(r2,e4)}}let a3=bn(r2,n2);if(a3===false)return i2;F(a3)&&(i2=a3.getData(i2,n2)??i2,r2=a3);let o3=sn(r2,i2),s3=wn[o3]?.(r2,i2,n2);return s3===void 0?i2:s3}function Tn({schema:e3},t2,n2,r2){return t2===void 0?e3.const?e3.const:e3.default===void 0&&Array.isArray(e3.enum)?e3.enum[0]:e3.default===void 0&&r2!==false?n2:e3.default:Sn(e3.type,t2)}function On({node:e3,key:t2}){if(e3.prefixItems?.[t2])return e3.prefixItems[t2];if(e3.items)return e3.items}function kn(e3){let{schema:t2,evaluationPath:n2}=e3,r2=t2[En];if(r2!=null&&typeof r2!=`boolean`){if(m(r2))e3.items=e3.compileSchema(r2,`${n2}/${En}`,`${e3.schemaLocation}/${En}`);else if(Array.isArray(r2))e3.prefixItems=r2.map((t3,r3)=>e3.compileSchema(t3,`${n2}/${En}/${r3}`,`${e3.schemaLocation}/${En}/${r3}`));else return e3.createError(`schema-error`,{pointer:n2,schema:t2,value:void 0,message:`Keyword '${En}' must be an object or array - received '${typeof r2}'`})}}function An({node:e3,data:t2,pointer:n2=`#`,path:r2}){let{schema:i2}=e3;if(!Array.isArray(t2)||t2.length===0)return;if(i2.items===false)return Array.isArray(t2)&&t2.length===0?void 0:e3.createError(`invalid-data-error`,{pointer:n2,value:t2,schema:i2});let a3=[];if(e3.prefixItems){for(let i3=0;i3<Math.min(e3.prefixItems.length,t2.length);i3+=1){let o3=t2[i3],s3=e3.prefixItems[i3],c3=j(s3,o3,`${n2}/${i3}`,r2);a3.push(...c3)}return a3}if(e3.items){for(let i3=0;i3<t2.length;i3+=1){let o3=t2[i3],s3=j(e3.items,o3,`${n2}/${i3}`,r2);s3&&a3.push(...s3)}return a3}}function Nn(e3){let t2=e3.schema[jn];if(t2!=null){if(!B(t2))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${jn}`,schema:e3.schema,value:t2,message:`Keyword '${jn}' must be a number - received '${typeof t2}'`});e3[jn]=t2}}function Pn({node:e3,data:t2,pointer:n2}){if(!B(t2))return;let r2=e3[jn],{schema:i2}=e3;if(r2&&r2<t2)return e3.createError(`maximum-error`,{maximum:r2,length:t2,value:t2,pointer:n2,schema:i2});if(r2&&i2.exclusiveMaximum===true&&r2===t2)return e3.createError(`maximum-error`,{maximum:r2,length:t2,pointer:n2,schema:i2,value:t2})}function Ln(e3){let t2=e3.schema[Fn];if(t2!=null){if(!B(t2))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${Fn}`,schema:e3.schema,value:t2,message:`Keyword '${Fn}' must be a number - received '${typeof t2}'`});e3[Fn]=t2}}function Rn({node:e3,data:t2,pointer:n2}){let{schema:r2}=e3;if(Array.isArray(t2)&&r2.maxItems<t2.length)return e3.createError(`max-items-error`,{maximum:r2.maxItems,length:t2.length,schema:r2,value:t2,pointer:n2})}function zn(e3){let t2=[],n2=0,r2=e3.length;for(;n2<r2;){let i2=e3.charCodeAt(n2++);if(i2>=55296&&i2<=56319&&n2<r2){let r3=e3.charCodeAt(n2++);(r3&64512)==56320?t2.push(((i2&1023)<<10)+(r3&1023)+65536):(t2.push(i2),n2--)}else t2.push(i2)}return t2}function Hn(e3){let t2=e3.schema[Bn];if(t2!=null){if(!B(t2))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${Bn}`,schema:e3.schema,value:t2,message:`Keyword '${Bn}' must be a number - received '${typeof t2}'`});e3[Bn]=t2}}function Un({node:e3,data:t2,pointer:n2=`#`}){if(typeof t2!=`string`)return;let r2=e3[Bn],i2=zn(t2).length;if(r2<i2)return e3.createError(`max-length-error`,{maxLength:r2,length:i2,pointer:n2,schema:e3.schema,value:t2})}function Kn(e3){let t2=e3.schema[Wn];if(t2!=null){if(!B(t2))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${Wn}`,schema:e3.schema,value:t2,message:`Keyword '${Wn}' must be a number - received '${typeof t2}'`});e3[Wn]=t2}}function qn({node:e3,data:t2,pointer:n2=`#`}){if(!m(t2))return;let r2=e3[Wn],i2=Object.keys(t2).length;if(r2<i2)return e3.createError(`max-properties-error`,{maxProperties:r2,length:i2,pointer:n2,schema:e3.schema,value:t2})}function Xn(e3){let t2=e3.schema[Jn];if(t2!=null){if(!B(t2))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${Jn}`,schema:e3.schema,value:t2,message:`Keyword '${Jn}' must be a number - received '${typeof t2}'`});e3[Jn]=t2}}function Zn({node:e3,data:t2,pointer:n2}){if(!B(t2))return;let r2=e3[Jn];if(r2>t2||e3.schema.exclusiveMinimum===true&&e3.schema.minimum===t2)return e3.createError(`minimum-error`,{minimum:r2,length:t2,pointer:n2,schema:e3.schema,value:t2})}function er(e3){let t2=e3.schema[Qn];if(t2!=null){if(!B(t2))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${Qn}`,schema:e3.schema,value:t2,message:`Keyword '${Qn}' must be a number - received '${typeof t2}'`});e3[Qn]=t2}}function tr({node:e3,data:t2,pointer:n2}){if(!Array.isArray(t2))return;let r2=e3[Qn];if(r2>t2.length)return e3.createError(`min-items-error`,{minItems:r2,length:t2.length,pointer:n2,schema:e3.schema,value:t2})}function ir(e3){let t2=e3.schema[nr];if(t2!=null){if(!B(t2))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${nr}`,schema:e3.schema,value:t2,message:`Keyword '${nr}' must be a number - received '${typeof t2}'`});e3[nr]=t2}}function ar({node:e3,data:t2,pointer:n2=`#`}){if(typeof t2!=`string`)return;let r2=zn(t2).length,i2=e3[nr];if(!(i2<=r2))return e3.createError(`min-length-error`,{minLength:i2,length:r2,pointer:n2,schema:e3.schema,value:t2})}function cr(e3){let t2=e3.schema[or];if(t2!=null){if(!B(t2))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${or}`,schema:e3.schema,value:t2,message:`Keyword '${or}' must be a number - received '${typeof t2}'`});e3[or]=t2}}function lr({node:e3,data:t2,pointer:n2=`#`}){if(!m(t2))return;let r2=Object.keys(t2).length;if(e3.schema.minProperties>r2)return e3.createError(`min-properties-error`,{minProperties:e3.schema.minProperties,length:r2,pointer:n2,schema:e3.schema,value:t2})}function ur(e3){let t2=`${e3}`;if(t2.includes(`e-`))return parseInt(t2.replace(/.*e-/,``));let n2=t2.indexOf(`.`);return n2===-1?0:t2.length-(n2+1)}function pr(e3){let t2=e3.schema[dr];if(t2!=null){if(!B(t2))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${dr}`,schema:e3.schema,value:t2,message:`Keyword '${dr}' must be a number - received '${typeof t2}'`});e3[dr]=t2}}function mr({node:e3,data:t2,pointer:n2}){if(typeof t2!=`number`)return;let r2=e3[dr],i2=ur(t2),a3=ur(r2);if(i2>a3)return e3.createError(`multiple-of-error`,{multipleOf:r2,value:t2,pointer:n2,schema:e3.schema});let o3=10**a3;if(Math.round(t2*o3)%Math.round(r2*o3)/o3!==0)return e3.createError(`multiple-of-error`,{multipleOf:r2,value:t2,pointer:n2,schema:e3.schema})}function gr(e3){let{schema:t2,evaluationPath:n2,schemaLocation:r2}=e3,i2=t2.not;if(i2!=null)return!I(i2)&&!L(i2)?e3.createError(`schema-error`,{pointer:`${r2}/not`,schema:t2,value:i2,message:`Keyword 'not' must be a valid JSON Schema - received '${typeof i2}'`}):(e3.not=e3.compileSchema(t2.not,`${n2}/not`,`${r2}/not`),e3.not.schemaValidation)}function _r({node:e3,data:t2,pointer:n2,path:r2}){let{schema:i2}=e3;if(A(e3.not,t2,n2,r2))return e3.createError(`not-error`,{value:t2,not:i2.not,pointer:n2,schema:i2})}function xr(e3){let t2=e3.schema[vr];if(t2!=null){if(typeof t2!=`string`)return e3.createError(`schema-error`,{pointer:e3.schemaLocation,schema:e3.schema,value:t2,message:`Keyword 'pattern' must be a string - received '${typeof t2}'`});try{e3[vr]=new RegExp(t2,e3.schema.regexFlags??yr)}catch(n2){return e3.createError(`schema-error`,{pointer:e3.schemaLocation,schema:e3.schema,value:t2,message:n2.message})}}}function Sr({node:e3,data:t2,pointer:n2=`#`}){if(typeof t2==`string`&&e3.pattern.test(t2)===false){let{schema:r2}=e3;return e3.createError(`pattern-error`,{pattern:r2.pattern,description:r2.patternExample||r2.pattern,received:t2,schema:r2,value:t2,pointer:n2})}}function Tr(e3){let{schema:t2}=e3;if(!m(t2.patternProperties))return;let n2=M(t2.patternProperties);if(n2.length!==0)return e3.patternProperties=n2.map(([n3,r2])=>({name:n3,pattern:new RegExp(n3,t2.regexFlags??Cr),node:e3.compileSchema(t2.patternProperties[n3],`${e3.evaluationPath}/patternProperties/${r2}`,`${e3.schemaLocation}/patternProperties/${r2}`)})),H([],...e3.patternProperties.map(({node:e4})=>e4))}function Er({node:e3,key:t2}){return e3.patternProperties?.find(({pattern:e4})=>e4.test(`${t2}`))?.node}function Dr({node:e3,data:t2,key:n2}){let{patternProperties:r2}=e3;if(r2==null)return;let i2,a3=Object.keys(t2??{});n2&&a3.push(`${n2}`);let o3=`${e3.schemaLocation}(`;return a3.push(...Object.keys(e3.schema.properties??{})),a3.forEach((t3,n3,a4)=>{if(a4.indexOf(t3)!==n3)return;let s3=x(e3.schema.properties,t3)??{},c3=r2.filter(e4=>e4.pattern.test(t3));c3.forEach(e4=>s3=S(s3,e4.node.schema)),c3.length>0&&(i2??={properties:Object.create(null)},i2.properties[t3]=s3,o3+=`${c3.map(({name:e4})=>`patternProperties/${e4}`).join(`,`)}`)}),i2==null?e3:(i2=S(e3.schema,i2,`patternProperties`),e3.compileSchema(i2,e3.evaluationPath,e3.schemaLocation,`${o3})`))}function Or({node:e3,data:t2,pointer:n2,path:r2}){if(!m(t2))return;let{schema:i2,patternProperties:a3}=e3,o3=i2.properties||{},s3=Object.keys(i2.patternProperties).join(`,`),c3=[];return Object.keys(t2).forEach(l2=>{let u2=x(t2,l2),d2=a3.filter(e4=>e4.pattern.test(l2));d2.forEach(({node:e4})=>c3.push(...j(e4,u2,N(n2,l2),r2))),!b2(o3,l2)&&d2.length===0&&i2.additionalProperties===false&&c3.push(e3.createError(`no-additional-properties-error`,{key:l2,pointer:N(n2,l2),schema:i2,value:u2,patterns:s3}))}),c3}function Ar({node:e3,key:t2}){return x(e3.properties,t2)}function jr(e3){let{schema:t2,evaluationPath:n2,schemaLocation:r2}=e3;if(t2.properties==null)return;if(t2.properties&&!m(t2.properties))return e3.createError(`schema-error`,{pointer:r2,schema:t2,value:void 0,message:"keyword `properties` must be of type `object`"});let i2=[],a3=Object.create(null);return M(t2.properties).forEach(([o3,s3])=>{let c3=e3.compileSchema(t2.properties[o3],`${n2}/properties/${s3}`,`${r2}/properties/${s3}`);a3[o3]=c3,H(i2,a3[o3])}),e3.properties=a3,i2}function Mr({node:e3,data:t2,pointer:n2,path:r2}){if(!m(t2))return;let i2=[],a3=e3.properties??{};return Object.keys(t2).forEach(e4=>{let o3=x(t2,e4),s3=x(a3,e4);if(s3==null||o3===void 0)return;let c3=j(s3,o3,N(n2,e4),r2);i2.push(...c3)}),i2}function Fr(e3){let t2=e3.schema[Nr];if(t2!=null){if(!(I(t2)||L(t2)))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${Nr}`,schema:e3.schema,value:t2,message:`Keyword '${Nr}' must be a valid JSON Schema - received '${typeof t2}'`});if(!L(t2))return e3.propertyNames=e3.compileSchema(t2,`${e3.evaluationPath}/propertyNames`,`${e3.schemaLocation}/propertyNames`),e3.propertyNames.schemaValidation}}function Ir({node:e3,data:t2,pointer:n2,path:r2}){let{schema:i2}=e3;if(!m(t2))return;if(i2.propertyNames===false)return Object.keys(t2).length===0?void 0:e3.createError(`invalid-property-name-error`,{property:Object.keys(t2),pointer:n2,value:t2,schema:i2});if(i2[Nr]===true)return;let a3=e3[Nr];if(!m(a3))return;let o3=[];return Object.keys(t2).forEach(s3=>{let c3=j(a3,s3,N(n2,s3),r2);c3.every(R)||o3.push(e3.createError(`invalid-property-name-error`,{property:s3,pointer:n2,validationError:c3.find(z),value:t2[s3],schema:i2}))}),o3}function zr(e3){let t2=e3.schema[Lr];if(t2!=null){if(!yt(t2))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${Lr}`,schema:e3.schema,value:t2,message:`Keyword '${Lr}' must be a string[]`});e3.required=t2}}function Br({node:e3,data:t2,pointer:n2=`#`}){let{required:r2}=e3;if(m(t2))return r2.map(r3=>{if(!b2(t2,r3))return e3.createError(`required-property-error`,{key:r3,pointer:n2,schema:e3.schema,value:t2})})}function Vr(e3){return{...e3,keywords:[...e3.keywords.map(e4=>({...e4}))]}}function Hr(e3,t2){let{keywords:n2}=Ur(e3,...t2.keywords??[]),r2={...e3.errors,...t2.errors??{}},i2={...e3.formats,...t2.formats??{}};return Gr({...e3,...t2,formats:i2,keywords:n2,errors:r2})}function Ur(e3,...t2){let n2=Vr(e3);return t2.forEach(e4=>Wr(n2,e4)),n2}function Wr(e3,t2){let n2=e3.keywords.findIndex(e4=>e4.keyword===t2.keyword);n2===-1?e3.keywords.push(t2):e3.keywords[n2]=t2}function Gr(e3){return e3.keywords?.forEach(e4=>{let t2=()=>e4.keyword;e4.validate&&(e4.validate.toJSON=t2,e4.validate.order=e4.order??0),e4.reduce&&(e4.reduce.toJSON=t2,e4.reduce.order=e4.order??0),e4.resolve&&(e4.resolve.toJSON=t2,e4.resolve.order=e4.order??0)}),e3.keywords?.sort((e4,t2)=>(t2.order??0)-(e4.order??0)),e3}function Kr(e3,t2,n2=`#`,r2=[]){let i2=e3.resolveRef()??e3;return r2.push({node:i2,value:t2,pointer:n2}),m(t2)?Object.keys(t2).forEach(e4=>{let{node:a3}=i2.getNodeChild(e4,t2);a3&&Kr(a3,x(t2,e4),N(n2,e4),r2)}):Array.isArray(t2)&&t2.forEach((e4,a3)=>{let{node:o3}=i2.getNodeChild(a3,t2);o3&&Kr(o3,x(t2,a3),N(n2,a3),r2)}),r2}function Yr(e3){let t2=e3.schema[Z];if(t2!=null){if(typeof t2!=`string`&&!Array.isArray(t2))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${Z}`,schema:e3.schema,value:t2,message:`Keyword '${Z}' must be a string or a string[] - received ${typeof t2}`});if(typeof t2==`string`&&!qr.includes(t2))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${Z}`,schema:e3.schema,value:t2,message:`Keyword '${Z}' is not a valid JSON Schema type - received '${t2}'. Expected one of ${qr.join(`, `)}`});if(Array.isArray(t2)){let n2=t2.findIndex(e4=>!qr.includes(e4));if(n2!==-1)return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${Z}/${n2}`,schema:e3.schema,value:t2[n2],message:`Keyword '${Z}' contains an invalid JSON Schema type: '${t2[n2]}'`})}e3[Z]=t2}}function Xr({node:e3,pointer:t2,data:n2}){let r2=Zr(n2,e3.type);if(r2!==`undefined`&&Array.isArray(e3.schema.type)&&e3.schema.type.includes(r2))return e3.compileSchema({...e3.schema,pointer:t2,type:r2},e3.evaluationPath)}function Zr(e3,t2){let n2=p(e3);return n2===`number`&&(t2===`integer`||Array.isArray(t2)&&t2.includes(`integer`))?Number.isInteger(e3)||isNaN(e3)?`integer`:`number`:n2}function Qr({node:e3,data:t2,pointer:n2}){let r2=e3[Z],i2=Zr(t2,r2);if(!(t2===void 0||r2===i2||Array.isArray(r2)&&r2.includes(i2)))return e3.createError(`type-error`,{value:t2,received:i2,expected:r2,schema:e3.schema,pointer:n2})}function ti(e3){let t2=e3.schema[$r];if(t2!=null&&t2!==false){if(typeof t2!=`boolean`)return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${$r}`,schema:e3.schema,value:t2,message:`Keyword '${$r}' must be a boolean - received ${typeof t2}`});e3.uniqueItems=true}}function ni({node:e3,data:t2,pointer:n2}){if(!Array.isArray(t2))return;let{schema:r2}=e3,i2=[],a3=[];return t2.forEach((o3,s3)=>{for(let c3=s3+1;c3<t2.length;c3+=1)Ft(o3,t2[c3])&&!i2.includes(c3)&&(a3.push(e3.createError(`unique-items-error`,{pointer:`${n2}/${c3}`,duplicatePointer:`${n2}/${s3}`,arrayPointer:n2,value:JSON.stringify(o3),schema:r2})),i2.push(c3))}),a3}function ai({node:e3,data:t2,pointer:n2}){if(!Ft(t2,e3.schema.const))return[e3.createError(`const-error`,{pointer:n2,schema:e3.schema,value:t2,expected:e3.schema.const})]}function ci(e3){let t2=e3.schema[oi];if(t2!=null&&typeof t2!=`number`)return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${oi}`,schema:e3.schema,value:t2,message:`Keyword '${oi}' must be a number - received '${typeof t2}'`})}function li({node:e3,data:t2,pointer:n2}){if(typeof t2==`number`&&e3.schema.exclusiveMaximum<=t2)return e3.createError(`exclusive-maximum-error`,{maximum:e3.schema.exclusiveMaximum,length:t2,pointer:n2,schema:e3.schema,value:t2})}function fi(e3){let t2=e3.schema[ui];if(t2!=null&&typeof t2!=`number`)return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${ui}`,schema:e3.schema,value:t2,message:`Keyword '${ui}' must be a number - received '${typeof t2}'`})}function pi({node:e3,data:t2,pointer:n2}){if(typeof t2==`number`&&e3.schema.exclusiveMinimum>=t2)return e3.createError(`exclusive-minimum-error`,{minimum:e3.schema.exclusiveMinimum,length:t2,pointer:n2,schema:e3.schema,value:t2})}function gi(e3){let{schema:t2,evaluationPath:n2}=e3,r2=[];return t2.if!=null&&(I(t2.if)||L(t2.if)?(e3.if=e3.compileSchema(t2.if,`${n2}/if`),H(r2,e3.if)):r2.push(e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/if`,schema:e3.schema,value:t2.if,message:`Keyword 'if' must be valid JSON Schema - received '${typeof t2.if}'`}))),t2.then!=null&&(I(t2.then)||L(t2.then)?(e3.then=e3.compileSchema(t2.then,`${n2}/then`),H(r2,e3.then)):r2.push(e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/then`,schema:e3.schema,value:t2.then,message:`Keyword 'then' must be valid JSON Schema - received '${typeof t2.then}'`}))),t2.else!=null&&(I(t2.else)||L(t2.else)?(e3.else=e3.compileSchema(t2.else,`${n2}/else`),H(r2,e3.else)):r2.push(e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/else`,schema:e3.schema,value:t2.else,message:`Keyword 'else' must be valid JSON Schema - received '${typeof t2.else}'`}))),r2}function _i({node:e3,data:t2,pointer:n2,path:r2}){if(t2!==void 0&&e3.if!=null){if(A(e3.if,t2,n2,[...r2??[]])){if(e3.then){let{node:n3}=e3.then.reduceNode(t2);if(n3){let t3=n3.dynamicId?.replace(e3.dynamicId,``).replace(/^#/,``)??``,r3=t3===``?`(then)`:t3,i2=S(e3.then.schema,n3.schema,`if`,`then`,`else`);return e3.compileSchema(i2,e3.then.evaluationPath,e3.schemaLocation,`${e3.schemaLocation}${r3}`)}}}else if(e3.else){let{node:n3}=e3.else.reduceNode(t2);if(n3){let t3=n3.dynamicId?.replace(e3.dynamicId,``)??``,r3=t3===``?`(else)`:t3,i2=S(e3.else.schema,n3.schema,`if`,`then`,`else`);return e3.compileSchema(i2,e3.else.evaluationPath,e3.schemaLocation,`${e3.schemaLocation}${r3}`)}}}}function vi({node:e3,data:t2,pointer:n2,path:r2}){if(e3.if!=null){if(A(e3.if,t2,n2,[...r2??[]])){if(e3.then)return j(e3.then,t2,n2,r2)}else if(e3.else)return j(e3.else,t2,n2,r2)}}function xi(e3,t2){e3.context.refs[t2]??(e3.context.refs[t2]=e3)}function Si(e3){e3.resolveRef=Ci;let t2=v2(e3.parent?.$id,e3.schema?.$id);e3.$id=t2,e3.lastIdPointer=e3.parent?.lastIdPointer??`#`,t2!==e3.parent?.$id&&e3.evaluationPath!==`#`&&(e3.lastIdPointer=e3.evaluationPath),e3.lastIdPointer!==`#`&&e3.evaluationPath.startsWith(e3.lastIdPointer)&&xi(e3,v2(t2,`#${e3.evaluationPath.replace(e3.lastIdPointer,``)}`)),xi(e3,v2(e3.context.rootNode.$id,e3.evaluationPath)),e3.schema.$anchor&&(e3.context.anchors[`${t2.replace(/#$/,``)}#${e3.schema.$anchor}`]=e3),e3.schema.$ref&&(e3.$ref=v2(t2,e3.schema.$ref),e3.$ref.startsWith(`/`)&&(e3.$ref=`#${e3.$ref}`))}function Ci({pointer:e3,path:t2}={}){if(this.schema.$recursiveRef){let n3=Ti(this,t2??[]);return F(n3)&&t2?.push({pointer:e3,node:n3}),n3}if(this.$ref==null)return this;let n2=Ei(this);return F(n2)&&t2?.push({pointer:e3,node:n2}),n2}function wi({node:e3,data:t2,pointer:n2=`#`,path:r2}){let i2=e3.resolveRef({pointer:n2,path:r2});return i2==null?e3.createError(`ref-error`,{ref:e3.schema.$ref??e3.schema.$recursiveRef,pointer:n2,schema:e3.schema,value:t2}):j(i2,t2,n2,r2)}function Ti(e3,t2){let n2=t2,r2=0;for(let t3=n2.length-1;t3>=0;t3--){if(n2[t3].node.schema.$recursiveAnchor===false)return Ei(e3,v2(e3.$id,e3.schema.$recursiveRef));if(/^https?:\/\//.test(n2[t3].node.schema.$id??``)&&n2[t3].node.schema.$recursiveAnchor!==true){r2=t3;break}}let i2=n2.find((e4,t3)=>t3>=r2&&e4.node.schema.$recursiveAnchor===true);return i2?i2.node:Ei(e3,v2(e3.$id,e3.schema.$recursiveRef))}function Ei(e3,t2=e3?.$ref){if(t2==null)return e3;if(e3.context.refs[t2])return V(e3.context.refs[t2],e3);if(e3.context.anchors[t2])return V(e3.context.anchors[t2],e3);let r2=Ae(t2);if(r2.length===0)return e3.createError(`ref-error`,{ref:t2,pointer:e3.evaluationPath,schema:e3.schema,value:void 0});if(r2.length===1){let t3=r2[0];if(e3.context.remotes[t3])return V(e3.context.remotes[t3],e3);if(t3[0]===`#`){let r3=t3.match(/#[^#]*$/)?.pop(),i2=e3.context.rootNode.schema,a3=s(i2,r3);if(a3)return e3.compileSchema(a3,`${e3.evaluationPath}/$ref`,r3)}return e3.createError(`ref-error`,{ref:t3,pointer:e3.evaluationPath,schema:e3.schema,value:void 0})}if(r2.length===2){let n2=r2[0];if(e3.context.remotes[n2]&&e3!==e3.context.remotes[n2]){let{isolated:i2,remotes:a3}=e3.context,o3=a3[n2],s3=i2===true?ve(o3,a3):o3,c3=Ei(s3,t2);if(c3||(c3=Ei(s3,r2[1]),c3))return c3}if(e3.context.refs[n2]){let a3=e3.context.refs[n2],o3=o(r2[1]),s3=a3;for(let n3 of o3)if(s3=s3[n3===`definitions`?`$defs`:n3],s3==null)return e3.createError(`ref-error`,{ref:t2,pointer:e3.evaluationPath,schema:e3.schema,value:void 0,host:r2[0],local:r2[1]});return e3.context.isolated===true?V(s3,e3):s3}}return e3.createError(`ref-error`,{ref:t2,pointer:e3.evaluationPath,schema:e3.schema,value:void 0})}function ki(e3){let{unevaluatedItems:t2}=e3.schema;if(t2!=null&&typeof t2!=`boolean`){if(!m(t2))return e3.createError(`schema-error`,{pointer:e3.evaluationPath,schema:e3.schema,value:void 0,message:`Keyword '${Di}' must be an object - received '${typeof t2}'`});e3.unevaluatedItems=e3.compileSchema(e3.schema.unevaluatedItems,`${e3.evaluationPath}/${Di}`,`${e3.schemaLocation}/${Di}`)}}function Ai({node:e3,data:t2,pointer:n2,path:r2}){let{schema:i2}=e3;if(!Array.isArray(t2)||t2.length===0||i2.unevaluatedItems==null||i2.unevaluatedItems===true)return;let{node:a3}=e3.reduceNode(t2,{pointer:n2,path:r2});if(a3??=e3,a3.schema.unevaluatedItems===true||a3.schema.additionalItems===true)return;let o3=e3.if!=null&&A(e3.if,t2,n2,r2),s3=[];for(let a4=0;a4<t2.length;a4+=1){let c3=t2[a4],{node:l2}=e3.getNodeChild(a4,t2,{path:r2});if(l2&&!A(l2,c3,`${n2}/${a4}`,r2)){let o4=e3.unevaluatedItems;if(o4&&t2.forEach(e4=>{let t3=j(o4,e4,`${n2}/${a4}`,r2);if(t3!=null){if(Array.isArray(t3))return s3.push(...t3);s3.push(t3)}}),e3.schema.unevaluatedItems===false)return e3.createError(`unevaluated-items-error`,{pointer:`${n2}/${a4}`,value:JSON.stringify(c3),schema:i2})}if(l2===void 0&&!(o3&&e3.if.prefixItems&&e3.if.prefixItems.length>a4)){if(e3.unevaluatedItems){let t3=j(e3.unevaluatedItems,c3,`${n2}/${a4}`,r2);t3.length>0&&s3.push(...t3)}else s3.push(e3.createError(`unevaluated-items-error`,{pointer:`${n2}/${a4}`,value:JSON.stringify(c3),schema:i2}))}}return s3}function ji({node:e3,data:t2,key:n2,pointer:r2,path:i2}){if(Array.isArray(e3.schema.required)&&!e3.schema.required.find(e4=>b2(t2,e4)))return false;if(e3.schema.unevaluatedProperties===true||e3.schema.additionalProperties===true||e3.properties?.[n2]&&e3.properties[n2].validate(t2[n2],r2,i2).valid||e3.patternProperties&&e3.patternProperties.find(e4=>e4.pattern.test(n2)))return true;if(e3.allOf){for(let a4 of e3.allOf)if(ji({node:a4,data:t2,key:n2,pointer:r2,path:i2}))return true}if(e3.anyOf){for(let a4 of e3.anyOf)if(A(a4,t2,r2,i2)&&ji({node:a4,data:t2,key:n2,pointer:r2,path:i2}))return true}if(e3.oneOf){for(let a4 of e3.oneOf)if(A(a4,t2,r2,i2)&&ji({node:a4,data:t2,key:n2,pointer:r2,path:i2}))return true}if(e3.if){let a4=A(e3.if,t2,r2,i2);if(a4&&ji({node:e3.if,data:t2,key:n2,pointer:r2,path:i2}))return true;if(a4&&e3.then){if(ji({node:e3.then,data:t2,key:n2,pointer:r2,path:i2}))return true}else if(!a4&&e3.else&&ji({node:e3.else,data:t2,key:n2,pointer:r2,path:i2}))return true}let a3=e3.resolveRef({pointer:r2,path:i2});return!!(a3!==e3&&ji({node:a3,data:t2,key:n2,pointer:r2,path:i2}))}function Pi(e3){let t2=e3.schema[Mi];if(t2!=null){if(!(I(t2)||L(t2)))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${Mi}`,schema:e3.schema,value:t2,message:`Keyword '${Mi}' must be a valid JSON Schema - received '${typeof t2}'`});if(!L(t2))return e3.unevaluatedProperties=e3.compileSchema(e3.schema.unevaluatedProperties,`${e3.evaluationPath}/${Mi}`,`${e3.schemaLocation}/${Mi}`),e3.unevaluatedProperties.schemaValidation}}function Fi({node:e3,data:t2,pointer:n2,path:r2}){if(!m(t2))return;let i2=Object.keys(t2).filter(e4=>t2[e4]!==void 0);if(i2.length===0)return;let a3=[];for(let o3 of i2){if(e3.properties?.[o3]||ji({node:e3,data:t2,key:o3,pointer:n2,path:r2}))continue;let{node:i3}=e3.getNodeChild(o3,t2,{pointer:n2,path:r2});if(i3===void 0){if(e3.unevaluatedProperties){let i4=j(e3.unevaluatedProperties,t2[o3],N(n2,o3),r2);a3.push(...i4)}else e3.schema.unevaluatedProperties===false&&a3.push(e3.createError(`unevaluated-property-error`,{pointer:N(n2,o3),value:JSON.stringify(t2[o3]),schema:e3.schema}))}if(i3&&!A(i3,t2[o3],N(n2,o3),r2)){if(e3.unevaluatedProperties){let i4=j(e3.unevaluatedProperties,t2[o3],N(n2,o3),r2);a3.push(...i4)}else e3.schema.unevaluatedProperties===false&&a3.push(e3.createError(`unevaluated-property-error`,{pointer:N(n2,o3),value:JSON.stringify(t2[o3]),schema:e3.schema}))}}return a3}function Li(e3,t2){if(e3.items){let t3=e3.items.resolveRef();if(t3?.oneOf)return t3.oneOf.map(e4=>e4.resolveRef())}if(e3.oneOf)return e3.oneOf.map(e4=>e4.resolveRef());if(e3.prefixItems&&e3.prefixItems.length>+t2){let{node:n3,error:r3}=e3.getNodeChild(t2);return F(n3)?[n3]:r3}if(e3.schema.items===true)return[e3.compileSchema({type:`string`})];if(e3.schema.items===false)return[];if(e3.items)return[e3.items.resolveRef()];if(e3.prefixItems&&e3.prefixItems.length<=+t2)return[];let{node:n2,error:r2}=e3.getNodeChild(t2);return r2??[n2]}function Ri(e3,t2){if(e3.$ref==null)return;t2.cache=t2.cache??{};let{cache:n2,recursionLimit:r2=1}=t2,i2=e3.schemaLocation;if(n2[i2]=n2[i2]??{},n2[i2][e3.$ref]=n2[i2][e3.$ref]??0,n2[i2][e3.$ref]>=r2&&t2.disableRecursionLimit!==true)return false;t2.disableRecursionLimit=false,n2[i2][e3.$ref]+=1;let a3=e3.resolveRef();if(a3&&a3!==e3)return a3}function zi(e3,t2){return(t2.cache?.[e3.schemaLocation]?.[e3.$ref]??-1)<(t2.recursionLimit??1)}function Bi(e3,t2){let n2=p(t2);if(e3===void 0||t2==null||n2===e3||n2===`number`&&e3===`integer`)return t2;if(e3===`string`)return JSON.stringify(t2);if(n2!==`string`)return t2;try{let n3=JSON.parse(t2);if(p(n3)===e3)return n3}catch{}return t2}function Vi(e3,t2,n2){if(n2?.cache==null)throw Error(`Missing options`);if(e3.schema===false||e3.schema===true||yn(t2))return t2;if(e3.schema?.const!==void 0)return e3.schema?.const;let r2=e3,i2=t2;if(Array.isArray(e3.schema.enum)&&e3.schema.enum.length>0&&t2===void 0)return e3.schema.default??e3.schema.enum[0];if(e3.schema.default!==void 0&&i2===void 0&&(i2=e3.schema.default),r2.allOf?.length&&r2.allOf.forEach(e4=>{i2=e4.getData(i2,n2)??i2}),r2.anyOf&&r2.anyOf?.length>0&&(i2=r2.anyOf[0].getData(i2,n2)??i2),r2.oneOf&&r2.oneOf?.length>0){if(cn(i2))r2=D(r2,r2.oneOf[0]);else{let e4=gn({node:r2,data:i2,path:[],pointer:`#`});if(z(e4)){if(i2!=null&&n2.removeInvalidData!==true)return i2;r2=r2.oneOf[0],i2=void 0}else r2=D(r2,e4)}}let a3=Ri(r2,n2);if(a3===false)return i2;F(a3)&&(i2=a3.getData(i2,n2)??i2,r2=a3);let o3=sn(r2,i2),s3=Hi[o3]?.(r2,i2,n2);return s3===void 0?i2:s3}function Ui({schema:e3},t2,n2,r2){return t2===void 0?e3.const?e3.const:e3.default===void 0&&Array.isArray(e3.enum)?e3.enum[0]:e3.default===void 0&&r2!==false?n2:e3.default:Bi(e3.type,t2)}function Gi({node:e3,key:t2}){if(!(e3.prefixItems&&e3.prefixItems?.length>+t2))return e3.items}function Ki(e3){let t2=e3.schema[Q];if(t2!=null){if(!(I(t2)||L(t2)))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${Q}`,schema:e3.schema,value:t2,message:`Keyword '${Q}' must be a valid JSON Schema - received '${typeof t2}'`});if(t2!==true)return e3[Q]=e3.compileSchema(t2,`${e3.evaluationPath}/${Q}`,`${e3.schemaLocation}/${Q}`),e3[Q].schemaValidation}}function qi({node:e3,data:t2,pointer:n2=`#`,path:r2}){let{schema:i2}=e3;if(!Array.isArray(t2)||t2.length===0||Array.isArray(i2.prefixItems)&&i2.prefixItems.length>=t2.length)return;if(i2.items===false)return Array.isArray(t2)&&t2.length===0?void 0:e3.createError(`invalid-data-error`,{pointer:n2,value:t2,schema:i2});let a3=[];if(e3.items){for(let o3=i2.prefixItems?.length??0;o3<t2.length;o3+=1){let i3=t2[o3],s3=j(e3.items,i3,`${n2}/${o3}`,r2);s3&&a3.push(...s3)}return a3}}function Xi({node:e3,key:t2}){if(e3.prefixItems&&e3.prefixItems[t2])return e3.prefixItems[t2]}function Zi(e3){let{schema:t2,evaluationPath:n2}=e3;if(Array.isArray(t2.prefixItems))return e3.prefixItems=t2.prefixItems.map((t3,r2)=>e3.compileSchema(t3,`${n2}/${Ji}/${r2}`,`${e3.schemaLocation}/${Ji}/${r2}`)),H([],...e3.prefixItems)}function Qi({node:e3,data:t2,pointer:n2=`#`,path:r2}){if(!Array.isArray(t2)||t2.length===0)return;let i2=[],a3=e3[Ji];if(a3){for(let e4=0;e4<Math.min(a3.length,t2.length);e4+=1){let o3=t2[e4],s3=a3[e4],c3=j(s3,o3,`${n2}/${e4}`,r2);i2.push(...c3)}return i2}}function $i({node:e3,data:t2,key:n2,pointer:r2,path:i2}){let a3=x(t2,n2);if(e3.schema.unevaluatedItems===true||e3.schema.items===true||e3.contains&&A(e3.contains,a3,`${r2}/${n2}`,i2))return true;if(e3.allOf){for(let a4 of e3.allOf)if($i({node:a4,data:t2,key:n2,pointer:r2,path:i2}))return true}if(e3.anyOf){for(let a4 of e3.anyOf)if(A(a4,t2,r2,i2)&&$i({node:a4,data:t2,key:n2,pointer:r2,path:i2}))return true}if(e3.oneOf){for(let a4 of e3.oneOf)if(A(a4,t2,r2,i2)&&$i({node:a4,data:t2,key:n2,pointer:r2,path:i2}))return true}if(e3.if){let a4=A(e3.if,t2,r2,i2);if(a4&&$i({node:e3.if,data:t2,key:n2,pointer:r2,path:i2})||a4&&e3.if.prefixItems&&e3.if.prefixItems.length>n2)return true;if(a4&&e3.then){if($i({node:e3.then,data:t2,key:n2,pointer:r2,path:i2}))return true}else if(!a4&&e3.else&&$i({node:e3.else,data:t2,key:n2,pointer:r2,path:i2}))return true}}function na(e3){let t2=e3.schema[ea];if(t2!=null){if(!(I(t2)||L(t2)))return e3.createError(`schema-error`,{pointer:`${e3.schemaLocation}/${ea}`,schema:e3.schema,value:t2,message:`Keyword '${ea}' must be a valid JSON Schema - received '${typeof t2}'`});if(!L(t2))return e3.unevaluatedItems=e3.compileSchema(e3.schema.unevaluatedItems,`${e3.evaluationPath}/${ea}`,`${e3.schemaLocation}/${ea}`),e3.unevaluatedItems.schemaValidation}}function ra({node:e3,data:t2,pointer:n2,path:r2}){let{schema:i2}=e3;if(!Array.isArray(t2)||t2.length===0||i2.unevaluatedItems==null||i2.unevaluatedItems===true)return;let a3=[];for(let o3=0;o3<t2.length;o3+=1){if($i({node:e3,data:t2,pointer:n2,key:o3,path:r2}))continue;let s3=t2[o3],{node:c3}=e3.getNodeChild(o3,t2,{path:r2});if(c3===void 0){if(e3.unevaluatedItems){let t3=j(e3.unevaluatedItems,s3,`${n2}/${o3}`,r2);t3.length>0&&a3.push(...t3)}else a3.push(e3.createError(`unevaluated-items-error`,{pointer:`${n2}/${o3}`,value:JSON.stringify(s3),schema:i2}))}if(c3&&!A(c3,s3,`${n2}/${o3}`,r2)&&(e3.unevaluatedItems&&e3.unevaluatedItems.validate(s3,`${n2}/${o3}`,r2).valid===false||e3.schema.unevaluatedItems===false))return e3.createError(`unevaluated-items-error`,{pointer:`${n2}/${o3}`,value:JSON.stringify(s3),schema:i2})}return a3}function sa(e3,t2){return e3.find(e4=>new RegExp(e4.$schemaRegEx,aa).test(t2))??e3[e3.length-1]}function ca(e3,n2={}){let r2=n2.remote;if(Array.isArray(n2.remotes)&&n2.remotes.length>0&&!n2.remote){let e4=[...n2.remotes];e4.forEach((e5,t2)=>{if(e5.$id==null)throw Error(`required $id on remotes[${t2}] is missing`)}),r2=ca(e4.shift(),{formatAssertion:n2.formatAssertion}),e4.forEach(e5=>r2?.addRemoteSchema(e5.$id,e5))}let i2=n2.formatAssertion??true,a3=n2.drafts??oa,o3=sa(a3,I(e3)?e3.$schema??n2.draft:void 0),c3={evaluationPath:`#`,lastIdPointer:`#`,schemaLocation:`#`,dynamicId:``,reducers:[],resolvers:[],validators:[],schema:e3,context:{remotes:{},dynamicAnchors:{},...r2?.context??{},anchors:{},refs:{},...copy(O(o3,`methods`,`keywords`,`version`,`formats`,`errors`)),draft:n2.draft,getDataDefaultOptions:n2.getDataDefaultOptions,throwOnInvalidRef:n2.throwOnInvalidRef??false,drafts:a3},...Se};if(c3.context.rootNode=c3,c3.context.remotes[(I(e3)?e3.$id:void 0)??`#`]=c3,r2){let e4=Re(c3,c3.schema.$schema);if(F(e4)&&e4.schema.$vocabulary){let t2=Object.keys(e4.schema.$vocabulary).find(e5=>e5.includes(`vocab/format-assertion`));t2&&i2===`meta-schema`&&(i2=e4.schema.$vocabulary[t2]===true);let n3=Object.keys(e4.getData({},{addOptionalProps:true}));n3.length>0&&(c3.context.keywords=c3.context.keywords.filter(e5=>n3.includes(e5.keyword)))}}if(c3.context.formatAssertion=i2,de(c3.context),!I(e3)&&!L(e3))return c3.schemaErrors=[c3.createError(`schema-error`,{pointer:`#`,schema:e3,value:void 0,message:`JSON schema must be object or boolean - reveived: '${e3}'`})],c3;let l2=Te(c3).filter(e4=>e4!=null);l2=s2(l2);let u2=[],d2=[];if(l2.forEach(e4=>{z(e4)?(e4.data.schemaId=c3.context.rootNode.$id??`#`,u2.push(e4)):R(e4)&&(e4.data.schemaId=c3.context.rootNode.$id??`#`,d2.push(e4))}),Array.isArray(r2?.schemaErrors)&&u2.push(...r2.schemaErrors),Array.isArray(r2?.schemaAnnotations)&&d2.push(...r2.schemaAnnotations),n2.throwOnInvalidSchema&&u2.length>0){let e4=Error(`Invalid schema passed to compileSchema`);throw e4.data=u2,e4}return c3.schemaErrors=u2,c3.schemaAnnotations=d2,c3}var import_fast_deep_equal,import_valid_url,c2,f,h,ee,te,ne,g,re,_2,y2,b2,P,ue,me,he,ge,_e,Se,Ce,we,Oe,ke,je,ze,Ve,Ge,Ze,Qe,nt,U,ot,W,ut,G,mt,_t,K,bt,q,Ct,J,Dt,jt,Mt,Y,It,zt,Bt,Ut,Kt,qt,Jt,Yt,Xt,Zt,Qt,$t,en,tn,rn,an,on,X,ln,un,dn,yn,wn,En,Dn,jn,Mn,Fn,In,Bn,Vn,Wn,Gn,Jn,Yn,Qn,$n,nr,rr,or,sr,dr,fr,hr,vr,yr,br,Cr,wr,kr,Nr,Pr,Lr,Rr,Z,qr,Jr,$r,ei,ri,ii,oi,si,ui,di,mi,hi,yi,bi,Di,Oi,Mi,Ni,Ii,Hi,Q,Wi,Ji,Yi,ea,ta,ia,aa,oa,la;var init_dist2=__esm({"../../node_modules/.pnpm/json-schema-library@11.6.16/node_modules/json-schema-library/dist/index.mjs"(){init_rolldown_runtime_DN1TCW_I();init_es();init_dist();import_fast_deep_equal=__toESM(require_fast_deep_equal(),1);import_valid_url=__toESM(require_valid_url(),1);c2={DECLARATOR_ONEOF:`oneOfProperty`,propertyBlacklist:[`_id`],DYNAMIC_PROPERTIES:[`$ref`,`$defs`,`if`,`then`,`else`,`allOf`,`anyOf`,`oneOf`,`dependentSchemas`,`dependentRequired`,`definitions`,`dependencies`,`patternProperties`,`propertyDependencies`],REGEX_FLAGS:`u`,VALID_ANNOTATION_KEYWORDS:[`$id`,`$schema`,`title`,`description`,`default`,`oneOfProperty`],PROPERTIES_TO_MERGE:[`title`,`description`,`default`,`options`,`x-options`,`readOnly`,`writeOnly`]};f=Object.prototype.toString;h=e(((e3,t2)=>{let n2=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r2=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),i2=RegExp.prototype.test.bind(/^\d*$/u),a3=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),o3=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),s3=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),c3=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),l2=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),u2=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=]$/u),d2=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=]*$/u);function f2(e4){let t3=``,n3=0,r3=0;for(r3=0;r3<e4.length;r3++)if(n3=e4[r3].charCodeAt(0),n3!==48){if(!(n3>=48&&n3<=57||n3>=65&&n3<=70||n3>=97&&n3<=102))return``;t3+=e4[r3];break}for(r3+=1;r3<e4.length;r3++){if(n3=e4[r3].charCodeAt(0),!(n3>=48&&n3<=57||n3>=65&&n3<=70||n3>=97&&n3<=102))return``;t3+=e4[r3]}return t3}let p2=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),m2=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),h3=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),ee2=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u),te2=RegExp.prototype.test.bind(/[^\d!"$&'()*+,\-.;=_`a-z{}~]/u),ne2=RegExp.prototype.test.bind(/(?:^|\.)\d+$/u);function g2(e4){return te2(e4)||ne2(e4)}function re2(e4){if(e4.length===0)return false;for(let t3=0;t3<e4.length;t3++)if(!h3(e4[t3])){if(e4[t3]===`%`&&t3+2<e4.length&&a3(e4.slice(t3+1,t3+3)))t3+=2;else return false}return true}function _3(e4){let t3=-1,n3=0,r3=-1,i3=0;for(let a5=0;a5<e4.length;a5++)e4[a5]===`0`?(r3===-1&&(r3=a5),i3++,i3>n3&&(n3=i3,t3=r3)):(r3=-1,i3=0);if(n3<2)return e4.join(`:`);let a4=e4.slice(0,t3).join(`:`),o4=e4.slice(t3+n3).join(`:`);return a4+`::`+o4}function v3(e4){let t3=e4.indexOf(`::`);if(t3!==-1&&e4.indexOf(`::`,t3+1)!==-1)return;let n3=t3===-1?e4.split(`:`):e4.slice(0,t3).split(`:`),i3=t3===-1?[]:e4.slice(t3+2).split(`:`);t3!==-1&&(n3.length===1&&n3[0]===``&&(n3.length=0),i3.length===1&&i3[0]===``&&(i3.length=0));let a4=n3.concat(i3),o4=0;for(let e5=0;e5<a4.length;e5++){let n4=a4[e5];if(n4===``)return;if(n4.indexOf(`.`)!==-1){if(e5!==a4.length-1||t3!==-1&&i3.length===0||!r2(n4))return;o4+=2}else{if(!p2(n4))return;a4[e5]=parseInt(n4,16).toString(16),o4++}}if(t3===-1)return o4===8?_3(a4):void 0;if(o4>=8)return;let s4=a4.slice(0,n3.length);for(let e5=o4;e5<8;e5++)s4.push(`0`);for(let e5=n3.length;e5<a4.length;e5++)s4.push(a4[e5]);return _3(s4)}function y3(e4){let t3=e4[0]===`[`&&e4[e4.length-1]===`]`;if((e4[0]===`[`||e4[e4.length-1]===`]`)&&!t3)return{host:e4,isIPV6:false,error:true};let n3=t3?e4.slice(1,-1):e4;if(t3&&m2(n3))return n3=n3.toLowerCase(),{host:`[${n3}]`,escapedHost:n3,isIPV6:false,isIPVFuture:true};if(b3(n3,`:`)<2)return{host:e4,isIPV6:false,error:t3};let r3=``,i3=n3.indexOf(`%`);if(i3!==-1){let t4=n3.slice(i3,i3+3).toLowerCase()===`%25`?3:1;if(r3=n3.slice(i3+t4),!re2(r3))return{host:e4,isIPV6:false,error:true};n3=n3.slice(0,i3)}let a4=v3(n3);return a4===void 0?{host:e4,isIPV6:false,error:true}:{host:a4+(r3?`%`+r3:``),escapedHost:a4+(r3?`%25`+r3:``),isIPV6:true}}function b3(e4,t3){let n3=0;for(let r3=0;r3<e4.length;r3++)e4[r3]===t3&&n3++;return n3}function x2(e4){let t3=e4,n3=[],r3=-1,i3=0;for(;i3=t3.length;){if(i3===1){if(t3===`.`)break;if(t3===`/`){n3.push(`/`);break}n3.push(t3);break}if(i3===2){if(t3[0]===`.`){if(t3[1]===`.`)break;if(t3[1]===`/`){t3=t3.slice(2);continue}}else if(t3[0]===`/`&&t3[1]===`.`){n3.push(`/`);break}}else if(i3===3&&t3===`/..`){n3.length!==0&&n3.pop(),n3.push(`/`);break}if(t3[0]===`.`){if(t3[1]===`.`){if(t3[2]===`/`){t3=t3.slice(3);continue}}else if(t3[1]===`/`){t3=t3.slice(2);continue}}else if(t3[0]===`/`&&t3[1]===`.`){if(t3[2]===`/`){t3=t3.slice(2);continue}if(t3[2]===`.`&&t3[3]===`/`){t3=t3.slice(3),n3.length!==0&&n3.pop();continue}}if((r3=t3.indexOf(`/`,1))===-1){n3.push(t3);break}n3.push(t3.slice(0,r3)),t3=t3.slice(r3)}return n3.join(``)}let S2={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`},C2=/[@/?#]/g;function ie2(e4,t3,n3=false){return t3?(C2.lastIndex=0,e4.replace(C2,e5=>S2[e5])):d2(e4)?e4:k2(e4,u2,n3)}function ae2(e4,t3=false){if(e4.indexOf(`%`)===-1)return e4;let n3=``;for(let r3=0;r3<e4.length;r3++){if(e4[r3]===`%`&&r3+2<e4.length){let i3=e4.slice(r3+1,r3+3);if(a3(i3)){let e5=i3.toUpperCase(),a4=String.fromCharCode(parseInt(e5,16));t3&&o3(a4)?n3+=a4:n3+=`%`+e5,r3+=2;continue}}n3+=e4[r3]}return n3}let w2=Array(256);{let e4=`0123456789ABCDEF`;for(let t3=0;t3<256;t3++)w2[t3]=`%`+e4[t3>>4]+e4[t3&15]}function T2(e4){return e4>=48&&e4<=57||e4>=65&&e4<=90||e4>=97&&e4<=122||e4===42||e4===43||e4===45||e4===46||e4===47||e4===64||e4===95}function E2(e4){return e4<2048?w2[192|e4>>6]+w2[128|e4&63]:e4<65536?w2[224|e4>>12]+w2[128|e4>>6&63]+w2[128|e4&63]:w2[240|e4>>18]+w2[128|e4>>12&63]+w2[128|e4>>6&63]+w2[128|e4&63]}function D2(e4){let t3=``;for(let n3=0;n3<e4.length;n3++){let r3=e4[n3];if(r3===`%`&&n3+2<e4.length){let r4=e4.slice(n3+1,n3+3);if(a3(r4)){let e5=r4.toUpperCase(),i3=String.fromCharCode(parseInt(e5,16));i3!==`.`&&o3(i3)?t3+=i3:t3+=`%`+e5,n3+=2;continue}}if(s3(r3))t3+=r3;else{let i3=e4.charCodeAt(n3);if(i3<128)t3+=T2(i3)?r3:w2[i3];else if(i3<55296||i3>57343)t3+=E2(i3);else if(i3<=56319&&n3+1<e4.length){let r4=e4.charCodeAt(n3+1);r4>=56320&&r4<=57343?(t3+=E2(65536+(i3-55296<<10)+(r4-56320)),n3++):t3+=E2(65533)}else t3+=E2(65533)}}return t3}function oe2(e4,t3=false){let n3=``,r3=t3&&e4[0]!==`/`;for(let t4=0;t4<e4.length;t4++){let i3=e4[t4];if(i3===`%`&&t4+2<e4.length){let r4=e4.slice(t4+1,t4+3);if(a3(r4)){n3+=`%`+r4.toUpperCase(),t4+=2;continue}}if(i3===`/`&&(r3=false),s3(i3)&&(i3!==`:`||!r3))n3+=i3;else{let r4=e4.charCodeAt(t4);if(r4<128)n3+=w2[r4];else if(r4<55296||r4>57343)n3+=E2(r4);else if(r4<=56319&&t4+1<e4.length){let i4=e4.charCodeAt(t4+1);i4>=56320&&i4<=57343?(n3+=E2(65536+(r4-55296<<10)+(i4-56320)),t4++):n3+=E2(65533)}else n3+=E2(65533)}}return n3}function O2(e4){let t3=``;for(let n3=0;n3<e4.length;n3++){let r3=e4[n3];if(r3===`%`&&n3+2<e4.length){let r4=e4.slice(n3+1,n3+3);if(a3(r4)){let e5=r4.toUpperCase(),i3=String.fromCharCode(parseInt(e5,16));o3(i3)?t3+=i3:t3+=`%`+e5,n3+=2;continue}}if(c3(r3))t3+=r3;else{let i3=e4.charCodeAt(n3);if(i3<128)t3+=T2(i3)?r3:w2[i3];else if(i3<55296||i3>57343)t3+=E2(i3);else if(i3<=56319&&n3+1<e4.length){let r4=e4.charCodeAt(n3+1);r4>=56320&&r4<=57343?(t3+=E2(65536+(i3-55296<<10)+(r4-56320)),n3++):t3+=E2(65533)}else t3+=E2(65533)}}return t3}function k2(e4,t3,n3=false){let r3=``;for(let i3=0;i3<e4.length;i3++){let o4=e4[i3];if(o4===`%`&&i3+2<e4.length){let t4=e4.slice(i3+1,i3+3);if(a3(t4)){r3+=`%`+t4.toUpperCase(),i3+=2;continue}}if(t3(o4))r3+=o4;else{let t4=e4.charCodeAt(i3);if(t4<128)r3+=w2[t4];else if(t4<55296||t4>57343)r3+=n3?o4:E2(t4);else if(t4<=56319&&i3+1<e4.length){let a4=e4.charCodeAt(i3+1);a4>=56320&&a4<=57343?(r3+=n3?o4+e4[i3+1]:E2(65536+(t4-55296<<10)+(a4-56320)),i3++):r3+=n3?`\uFFFD`:E2(65533)}else r3+=n3?`\uFFFD`:E2(65533)}}return r3}function A2(e4){return k2(e4,l2)}function j2(e4){return k2(e4,c3)}function se2(e4){return k2(e4,c3)}function M2(e4){let t3=``;for(let n3=0;n3<e4.length;n3++){let r3=e4[n3];if(r3===`%`&&n3+2<e4.length){let r4=e4.slice(n3+1,n3+3);if(a3(r4)){t3+=`%`+r4.toUpperCase(),n3+=2;continue}}let i3=e4.charCodeAt(n3);if(i3<128)t3+=T2(i3)?r3:w2[i3];else if(i3<55296||i3>57343)t3+=E2(i3);else if(i3<=56319&&n3+1<e4.length){let r4=e4.charCodeAt(n3+1);r4>=56320&&r4<=57343?(t3+=E2(65536+(i3-55296<<10)+(r4-56320)),n3++):t3+=E2(65533)}else t3+=E2(65533)}return t3}function N2(e4){let t3=e4.ipv6Zone;if(t3===void 0)return;let n3=e4.host,r3=n3.indexOf(`%`);if(r3===-1)return;let i3=n3.slice(0,r3)+`%25`+t3,a4=y3(`[`+i3+`]`);if(a4.isIPV6===true&&a4.host===n3)return`[`+i3+`]`}function ce2(e4,t3=false){let n3=[];if(e4.userinfo!==void 0&&(n3.push(A2(e4.userinfo)),n3.push(`@`)),e4.host!==void 0){let i3=e4.host;if(!r2(i3)){let n4=N2(e4);if(n4!==void 0)i3=n4;else{let e5=y3(i3);e5.isIPV6!==true&&e5.isIPVFuture!==true&&(i3=ae2(i3,true),e5=y3(i3)),i3=e5.isIPV6===true||e5.isIPVFuture===true?`[${e5.escapedHost}]`:ie2(i3,false,t3)}}n3.push(i3)}if(typeof e4.port==`number`||typeof e4.port==`string`){let t4=String(e4.port);if(!i2(t4))throw TypeError(`URI port is malformed.`);n3.push(`:`),n3.push(t4)}return n3.length?n3.join(``):void 0}t2.exports={BYTE_HEX:w2,percentEncodeNonAscii:E2,nonSimpleDomain:ee2,nonSimpleMailtoDomain:g2,recomposeAuthority:ce2,encodeHost:ie2,normalizePercentEncoding:ae2,normalizePathEncoding:D2,serializePathEncoding:oe2,normalizeQueryFragmentEncoding:O2,encodeUserinfo:A2,encodeQuery:j2,encodeFragment:se2,escapePreservingEscapes:M2,removeDotSegments:x2,isIPv4:r2,isUUID:n2,normalizeIPv6:y3,stringArrayToHexStripped:f2}}));ee=e(((e3,t2)=>{let{isUUID:n2,BYTE_HEX:r2,percentEncodeNonAscii:i2,nonSimpleMailtoDomain:a3}=h(),o3=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,s3=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`,`mailto`];function c3(e4){return s3.indexOf(e4)!==-1}function l2(e4){return e4.secure===true?true:e4.secure===false?false:e4.scheme?e4.scheme.length===3&&(e4.scheme[0]===`w`||e4.scheme[0]===`W`)&&(e4.scheme[1]===`s`||e4.scheme[1]===`S`)&&(e4.scheme[2]===`s`||e4.scheme[2]===`S`):false}function u2(e4){return e4.host||(e4.error=e4.error||`HTTP URIs must have a host.`),e4}function d2(e4){let t3=String(e4.scheme).toLowerCase()===`https`;return(e4.port===(t3?443:80)||e4.port===``)&&(e4.port=void 0),e4.path||=`/`,e4}function f2(e4){return e4.secure=l2(e4),e4.resourceName=(e4.path||`/`)+(e4.query?`?`+e4.query:``),e4.path=void 0,e4.query=void 0,e4}function p2(e4){if((e4.port===(l2(e4)?443:80)||e4.port===``)&&(e4.port=void 0),typeof e4.secure==`boolean`&&(e4.scheme=e4.secure?`wss`:`ws`,e4.secure=void 0),e4.resourceName){let t3=e4.resourceName.indexOf(`?`),n3=t3===-1?e4.resourceName:e4.resourceName.slice(0,t3);e4.path=n3&&n3!==`/`?n3:void 0,e4.query=t3===-1?void 0:e4.resourceName.slice(t3+1),e4.resourceName=void 0}return e4.fragment=void 0,e4}function m2(e4,t3){if(!e4.path)return e4.error=`URN can not be parsed`,e4;let n3=e4.path.match(o3);if(n3&&n3[0]===e4.path){let r3=t3.scheme||e4.scheme||`urn`;e4.nid=n3[1].toLowerCase(),e4.nss=n3[2];let i3=P2(`${r3}:${t3.nid||e4.nid}`);e4.path=void 0,i3&&(e4=i3.parse(e4,t3))}else e4.error=e4.error||`URN can not be parsed.`;return e4}function ee2(e4,t3){if(e4.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n3=t3.scheme||e4.scheme||`urn`,r3=e4.nid.toLowerCase(),i3=P2(`${n3}:${t3.nid||r3}`);i3&&(e4=i3.serialize(e4,t3));let a4=e4,o4=e4.nss;return a4.path=`${r3||t3.nid}:${o4}`,t3.skipEscape=true,a4}function te2(e4,t3){let r3=e4;return r3.uuid=r3.nss,r3.nss=void 0,!t3.tolerant&&(!r3.uuid||!n2(r3.uuid))&&(r3.error=r3.error||`UUID is not valid.`),r3}function ne2(e4){let t3=e4;return t3.nss=(e4.uuid||``).toLowerCase(),t3}let g2={scheme:`http`,domainHost:true,parse:u2,serialize:d2},re2={scheme:`https`,domainHost:g2.domainHost,parse:u2,serialize:d2},_3={scheme:`ws`,domainHost:true,parse:f2,serialize:p2},v3={scheme:`wss`,domainHost:_3.domainHost,parse:_3.parse,serialize:_3.serialize},y3={scheme:`urn`,parse:m2,serialize:ee2,skipNormalize:true,absolutePath:true},b3={scheme:`urn:uuid`,parse:te2,serialize:ne2,skipNormalize:true},x2=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$'()*+;:`;function S2(e4,t3=false){let n3=new Uint8Array(128);for(let t4=0;t4<e4.length;t4++)n3[e4.charCodeAt(t4)]=1;let r3=e4.replace(/[\\\]^-]/gu,`\\$&`),i3=t3?`[${r3}]|[^\\0-\\x7F\\uD800-\\uDFFF]`:`[${r3}]`;return{all:RegExp(`^(?:${i3})*$`,`u`),table:n3,allowNonAscii:t3}}let C2=S2(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$'()*+=`),ie2=S2(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$'()*+,;:@`),ae2=S2(x2),w2=S2(x2,true),T2=/^[\da-f]{2}$/iu,E2=/^\[[\x21-\x5A\x5E-\x7E]*\]$/u,D2=`URI mailto has an invalid recipient domain.`,oe2=/[\uD800-\uDFFF]/u;function O2(e4){if(typeof e4!=`string`||e4.indexOf(`%`)===-1)return e4;try{return decodeURIComponent(e4)}catch{return e4}}function k2(e4){let t3=``;for(let n3=0;n3<e4.length;n3++){let r3=e4.charCodeAt(n3);if(r3>=55296&&r3<=56319&&n3+1<e4.length){let r4=e4.charCodeAt(n3+1);if(r4>=56320&&r4<=57343){t3+=e4[n3]+e4[n3+1],n3++;continue}}t3+=r3>=55296&&r3<=57343?`\uFFFD`:e4[n3]}return t3}function A2(e4,t3){if(t3.all.test(e4))return e4;let n3=t3.table,a4=``;for(let o4=0;o4<e4.length;o4++){let s4=e4.charCodeAt(o4);if(s4<128)n3[s4]===1?a4+=e4[o4]:s4===37&&o4+2<e4.length&&T2.test(e4.slice(o4+1,o4+3))?(a4+=`%`+e4.slice(o4+1,o4+3).toUpperCase(),o4+=2):a4+=r2[s4];else if(s4<55296||s4>57343)a4+=t3.allowNonAscii?e4[o4]:i2(s4);else{if(s4<=56319&&o4+1<e4.length){let n4=e4.charCodeAt(o4+1);if(n4>=56320&&n4<=57343){a4+=t3.allowNonAscii?e4[o4]+e4[o4+1]:i2(65536+(s4-55296<<10)+(n4-56320)),o4++;continue}}a4+=t3.allowNonAscii?`\uFFFD`:i2(65533)}}return a4}function j2(e4,t3,n3){let r3=String(e4).toLowerCase();if(E2.test(r3)||r3!==``&&!a3(r3))return r3;try{let e5=new URL(`http://`+r3);if(e5.username||e5.password||e5.port||e5.pathname!==`/`||e5.search||e5.hash||!e5.hostname)throw Error(D2);return t3&&t3.unicodeSupport?r3:e5.hostname}catch{return n3&&(n3.error=n3.error||D2),r3}}function se2(e4,t3){let n3=t3&&t3.unicodeSupport?w2:ae2;return e4.length>1&&e4[0]===`[`&&e4[e4.length-1]===`]`?`[`+A2(e4.slice(1,-1),n3)+`]`:A2(e4,n3)}function M2(e4,t3){let n3=e4,r3=n3.path,i3=n3.query;r3&&oe2.test(r3)&&(r3=k2(r3)),i3&&oe2.test(i3)&&(i3=k2(i3));let a4=r3?r3.indexOf(`,`)===-1?[r3]:r3.split(`,`):[];if(n3.path=void 0,i3){let e5=null,t4=0;for(;t4<=i3.length;){let r4=i3.indexOf(`&`,t4);r4===-1&&(r4=i3.length);let o4=i3.slice(t4,r4);t4=r4+1;let s4=o4.indexOf(`=`);if(s4!==o4.lastIndexOf(`=`)){n3.error=n3.error||`URI mailto has malformed header fields.`;continue}let c4=O2(s4===-1?o4:o4.slice(0,s4)),l3=c4.toLowerCase(),u3=s4===-1?``:o4.slice(s4+1);if(l3===`to`){let e6=u3.split(`,`);for(let t5=0;t5<e6.length;t5++)a4.push(e6[t5])}else l3===`subject`?n3.subject=O2(u3):l3===`body`?n3.body=O2(u3):(e5===null&&(e5=Object.create(null)),e5[c4]=O2(u3))}e5!==null&&(n3.headers=e5)}n3.query=void 0,a4.length>0&&(n3.userinfo!==void 0||n3.host!==void 0||n3.port!==void 0)&&(n3.userinfo=void 0,n3.host=void 0,n3.port=void 0,n3.error=n3.error||`URI mailto must not have an authority component.`);for(let e5=0;e5<a4.length;e5++){let r4=a4[e5],i4=r4.lastIndexOf(`@`);if(i4<0){n3.error=n3.error||D2,a4[e5]=O2(r4);continue}let o4=O2(r4.slice(0,i4)),s4=j2(O2(r4.slice(i4+1)),t3,n3);a4[e5]=o4+`@`+s4}return a4.length&&(n3.to=a4),n3}function N2(e4){return A2(e4.replace(/%/gu,`%25`),ie2)}function ce2(e4,t3){let n3=e4,r3=Array.isArray(n3.to)?n3.to.slice():[],i3=n3.headers&&typeof n3.headers==`object`?Object.assign(Object.create(null),n3.headers):Object.create(null),a4=Object.create(null);for(let e5 in i3){let t4=e5.toLowerCase();if(t4===`to`){let t5=String(i3[e5]).split(`,`);for(let e6=0;e6<t5.length;e6++)r3.push(t5[e6])}else t4===`subject`||t4===`body`?a4[t4]=i3[e5]:a4[e5]=i3[e5]}if(n3.subject!==void 0&&(a4.subject=n3.subject),n3.body!==void 0&&(a4.body=n3.body),n3.headers=a4,r3.length){n3.userinfo=void 0,n3.host=void 0,n3.port=void 0;for(let e5=0;e5<r3.length;e5++){let n4=String(r3[e5]),i4=n4.lastIndexOf(`@`),a5=i4>=0?n4.slice(0,i4):n4,o5=i4>=0?n4.slice(i4+1):``,s5=A2(a5,C2),c4=j2(O2(o5),t3);r3[e5]=s5+`@`+se2(c4,t3)}n3.path=r3.join(`,`),t3.skipEscape=true}else n3.path=void 0;let o4=``,s4=0;for(let e5 in a4)s4++!==0&&(o4+=`&`),o4+=N2(e5)+`=`+A2(String(a4[e5]),ie2);return s4===0?n3.headers=void 0:n3.query=o4,n3}let le2={http:g2,https:re2,ws:_3,wss:v3,urn:y3,"urn:uuid":b3,mailto:{scheme:`mailto`,parse:M2,serialize:ce2,domainHost:false,unicodeSupport:true,skipNormalize:true,absolutePath:true}};Object.setPrototypeOf(le2,null);function P2(e4){return e4&&(le2[e4]||le2[e4.toLowerCase()])||void 0}t2.exports={wsIsSecure:l2,SCHEMES:le2,isValidSchemeName:c3,getSchemeHandler:P2}}));te=e(((e3,t2)=>{let{normalizeIPv6:n2,removeDotSegments:r2,recomposeAuthority:i2,normalizePercentEncoding:a3,normalizePathEncoding:o3,serializePathEncoding:s3,normalizeQueryFragmentEncoding:c3,encodeQuery:l2,encodeFragment:u2,encodeHost:d2,isIPv4:f2,nonSimpleDomain:p2}=h(),{SCHEMES:m2,getSchemeHandler:te2}=ee(),ne2=/^[A-Za-z][A-Za-z0-9+.-]*$/u,g2=`URI scheme is malformed.`;function re2(e4){let t3=unescape(String(e4));if(!ne2.test(t3))throw TypeError(g2);return t3}function _3(e4,t3){return typeof e4==`string`?e4=A2(e4,t3):typeof e4==`object`&&(e4=k2(S2(e4,t3),t3)),e4}function v3(e4,t3,r3){let i3=r3?Object.assign({scheme:`null`},r3):{scheme:`null`},{parsed:a4,malformedAuthorityOrPort:o4,malformedReferenceEdge:s4,malformedPercentEncoding:c4,malformedSchemeSpecific:l3,malformedHost:u3,malformedScheme:d3}=O2(e4,i3),{parsed:p3,malformedAuthorityOrPort:m3,malformedReferenceEdge:h3,malformedPercentEncoding:ee2,malformedSchemeSpecific:ne3,malformedHost:g3,malformedScheme:re3}=O2(t3,i3);if(o4||m3||s4||h3||c4||ee2||l3||ne3||u3||g3||d3||re3)throw Error(a4.error||p3.error||`URI is malformed.`);let _4=b3(a4,p3,i3,true),v4=te2(r3&&r3.scheme||_4.scheme),y4=_4.host;if((_4.scheme===`http`||_4.scheme===`https`)&&!y4)throw Error(`HTTP URIs must have a host.`);let x3=y4!==void 0&&y4!==``&&(f2(y4)||n2(y4).isIPV6);oe2(_4,r3||{},v4,x3);let C3=y4&&y4.indexOf(`%`)!==-1&&!new RegExp("\\P{ASCII}","u").test(y4);if(_4.error&&!C3)throw Error(_4.error);return i3.skipEscape=true,v4&&v4.absolutePath&&(i3.absolutePath=true),S2(_4,i3)}function y3(e4,t3){e4.host=t3.host,t3.ipv6Zone!==void 0&&(e4.ipv6Zone=t3.ipv6Zone)}function b3(e4,t3,n3,i3){let a4={};if(i3||(e4=k2(S2(e4,n3),n3),t3=k2(S2(t3,n3),n3)),n3||={},!n3.tolerant&&t3.scheme){a4.scheme=t3.scheme,a4.userinfo=t3.userinfo,y3(a4,t3),a4.port=t3.port;let e5=te2(t3.scheme);a4.path=e5&&e5.absolutePath?t3.path||``:r2(t3.path||``),a4.query=t3.query}else t3.userinfo!==void 0||t3.host!==void 0||t3.port!==void 0?(a4.userinfo=t3.userinfo,y3(a4,t3),a4.port=t3.port,a4.path=r2(t3.path||``),a4.query=t3.query):(t3.path?(t3.path[0]===`/`?a4.path=r2(t3.path):(a4.path=(e4.userinfo!==void 0||e4.host!==void 0||e4.port!==void 0)&&!e4.path?`/`+t3.path:e4.path?e4.path.slice(0,e4.path.lastIndexOf(`/`)+1)+t3.path:t3.path,a4.path=r2(a4.path)),a4.query=t3.query):(a4.path=e4.path,a4.query=t3.query===void 0?e4.query:t3.query),a4.userinfo=e4.userinfo,y3(a4,e4),a4.port=e4.port),a4.scheme=e4.scheme;return a4.fragment=t3.fragment,a4}function x2(e4,t3,n3){let r3=se2(e4,n3),i3=se2(t3,n3);return r3!==void 0&&i3!==void 0&&r3===i3}function S2(e4,t3){let n3={host:e4.host,ipv6Zone:e4.ipv6Zone,scheme:e4.scheme,userinfo:e4.userinfo,port:e4.port,path:e4.path,query:e4.query,nid:e4.nid,nss:e4.nss,uuid:e4.uuid,fragment:e4.fragment,reference:e4.reference,resourceName:e4.resourceName,secure:e4.secure,to:e4.to,subject:e4.subject,body:e4.body,headers:e4.headers,error:``},o4=Object.assign({},t3),c4=[];n3.scheme&&=re2(n3.scheme);let d3=te2(o4.scheme||n3.scheme);d3&&d3.serialize&&d3.serialize(n3,o4);let f3=n3.userinfo!==void 0||n3.host!==void 0||n3.port!==void 0,p3=!o4.skipEscape&&n3.scheme===void 0&&!f3;n3.path!==void 0&&(n3.path=o4.skipEscape?a3(n3.path):s3(n3.path,p3)),o4.reference!==`suffix`&&n3.scheme&&(n3.scheme=re2(n3.scheme),c4.push(n3.scheme,`:`));let m3=o4.unicodeSupport===true||!!(d3&&d3.unicodeSupport),h3=i2(n3,m3);if(h3!==void 0&&(o4.reference!==`suffix`&&c4.push(`//`),c4.push(h3),n3.path&&n3.path[0]!==`/`&&c4.push(`/`)),n3.path!==void 0){let e5=n3.path;!o4.absolutePath&&(!d3||!d3.absolutePath)&&(e5=r2(e5)),p3&&(e5=s3(e5,true)),h3===void 0&&e5[0]===`/`&&e5[1]===`/`&&(e5=`/%2F`+e5.slice(2)),c4.push(e5)}return n3.query!==void 0&&c4.push(`?`,l2(n3.query)),n3.fragment!==void 0&&c4.push(`#`,u2(n3.fragment)),c4.join(``)}let C2=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,ie2=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,ae2=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function w2(e4,t3){if(t3[2]!==void 0&&e4.path&&e4.path[0]!==`/`)return`URI path must start with "/" when authority is present.`;if(typeof e4.port==`number`&&(e4.port<0||e4.port>65535))return`URI port is malformed.`}function T2(e4){if(e4===void 0)return false;let t3=e4.indexOf(`%`);for(;t3!==-1;){if(t3+2>=e4.length||!/^[\da-f]{2}$/iu.test(e4.slice(t3+1,t3+3)))return true;t3=e4.indexOf(`%`,t3+3)}return false}function E2(e4){return e4[0]===`[`&&e4[e4.length-1]===`]`}function D2(e4){let t3=e4[4];return T2(e4[3])||t3!==void 0&&!E2(t3)&&T2(t3)||T2(e4[6])||T2(e4[7])||T2(e4[8])}function oe2(e4,t3,n3,r3){let i3=e4.host&&e4.host[0]===`[`&&e4.host[e4.host.length-1]===`]`;if(!t3.unicodeSupport&&(!n3||!n3.unicodeSupport)&&e4.host&&!E2(e4.host)&&(t3.domainHost||n3&&n3.domainHost)&&r3===false&&!i3&&p2(e4.host))try{e4.host=new URL(`http://`+e4.host).hostname}catch(t4){return e4.error=e4.error||`Host's domain name can not be converted to ASCII: `+t4,true}return false}function O2(e4,t3){let r3=Object.assign({},t3),i3={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},s4=false,l3=e4.length!==0&&(e4.charCodeAt(0)<=32||e4.charCodeAt(e4.length-1)<=32),u3=false,p3=false,h3=false,ee2=false,re3=false,_4=false;r3.reference===`suffix`&&(e4=r3.scheme?r3.scheme+`:`+e4:`//`+e4);let v4=e4.match(ie2);v4!==null&&v4[1].indexOf(`\\`)!==-1&&(i3.error=`URI authority must not contain a literal backslash.`,s4=true);let y4=e4.match(ae2);if(y4!==null){let e5=y4[1],t4=e5.replace(/[\t\n\r]/g,``);t4.length>=2&&(t4.slice(0,2)===`//`?e5.length!==t4.length&&(i3.error=i3.error||`URI authority introducer must not contain whitespace.`,s4=true):(i3.error=i3.error||`URI authority must not contain a literal backslash.`,s4=true))}l3&&(i3.error=i3.error||`URI must not contain leading or trailing C0 controls or spaces.`);let b4=e4.match(C2);if(b4){if(i3.scheme=b4[1],i3.userinfo=b4[3],i3.host=b4[4],i3.port=parseInt(b4[5],10),i3.path=b4[6]||``,i3.query=b4[7],i3.fragment=b4[8],i3.scheme!==void 0){let e5=unescape(i3.scheme);ne2.test(e5)?i3.scheme=e5.toLowerCase():(i3.error=i3.error||g2,re3=true)}u3=D2(b4),u3&&(i3.error=i3.error||`URI contains malformed percent-encoding.`),isNaN(i3.port)&&(i3.port=b4[5]);let t4=w2(i3,b4);if(t4!==void 0&&(i3.error=i3.error||t4,s4=true),i3.host){if(f2(i3.host)===false){let e5=E2(i3.host),t5=i3.host.indexOf(`[`)!==-1||i3.host.indexOf(`]`)!==-1,r4=n2(i3.host);_4=r4.isIPV6||r4.isIPVFuture===true,ee2=t5&&(!e5||r4.error===true),i3.host=_4?r4.host:r4.host.toLowerCase(),_4&&r4.isIPV6===true&&i3.host.indexOf(`%`)!==-1&&(i3.ipv6Zone=i3.host.slice(i3.host.indexOf(`%`)+1)),ee2&&(i3.error=i3.error||`URI host is malformed.`,s4=true)}else _4=true}i3.reference=i3.scheme===void 0&&i3.userinfo===void 0&&i3.host===void 0&&i3.port===void 0&&i3.query===void 0&&!i3.path?`same-document`:i3.scheme===void 0?`relative`:i3.fragment===void 0?`absolute`:`uri`,r3.reference&&r3.reference!==`suffix`&&r3.reference!==i3.reference&&(i3.error=i3.error||`URI is not a `+r3.reference+` reference.`);let l4=te2(r3.scheme||i3.scheme);if(ee2||(h3=oe2(i3,r3,l4,_4)),i3.host!==void 0&&!ee2){let t5=i3.host;if(e4.indexOf(`%`)!==-1&&!_4&&(t5=a3(t5,true),t5=a3(t5.toLowerCase())),r3.scheme!==`null`){let e5=r3.unicodeSupport===true||!!(l4&&l4.unicodeSupport);i3.host=d2(t5,_4,e5)}else i3.host=t5}(!l4||l4&&!l4.skipNormalize)&&(i3.path&&=o3(i3.path),i3.query&&=c3(i3.query),i3.fragment&&=c3(i3.fragment)),l4&&l4.parse&&(l4.parse(i3,r3),l4===m2.urn&&i3.nid===void 0&&(p3=true))}else i3.error=i3.error||`URI can not be parsed.`;return{parsed:i3,malformedAuthorityOrPort:s4,malformedReferenceEdge:l3,malformedPercentEncoding:u3,malformedSchemeSpecific:p3,malformedHost:h3,malformedScheme:re3}}function k2(e4,t3){return O2(e4,t3).parsed}function A2(e4,t3){return j2(e4,t3).normalized}function j2(e4,t3){let{parsed:n3,malformedAuthorityOrPort:r3,malformedReferenceEdge:i3,malformedPercentEncoding:a4,malformedSchemeSpecific:o4,malformedHost:s4,malformedScheme:c4}=O2(e4,t3);return{normalized:r3||i3||a4||o4||s4||c4?e4:S2(n3,t3),malformedAuthorityOrPort:r3,malformedReferenceEdge:i3,malformedPercentEncoding:a4,malformedSchemeSpecific:o4,malformedHost:s4,malformedScheme:c4}}function se2(e4,t3){if(typeof e4!=`string`&&typeof e4!=`object`)return;let n3;try{n3=typeof e4==`string`?e4:S2(e4,t3)}catch{return}let{normalized:r3,malformedAuthorityOrPort:i3,malformedReferenceEdge:a4,malformedPercentEncoding:o4,malformedSchemeSpecific:s4,malformedHost:c4,malformedScheme:l3}=j2(n3,t3);return i3||a4||o4||s4||c4||l3?void 0:r3}let M2={SCHEMES:m2,normalize:_3,resolve:v3,resolveComponent:b3,equal:x2,serialize:S2,parse:k2};t2.exports=M2,t2.exports.default=M2,t2.exports.fastUri=M2}))();ne=/(#)+$/;g=/#$/;re=/^[^:]+:\/\/[^/]+\//;_2=/#.*$/;y2=Object.prototype.hasOwnProperty;b2=(e3,t2)=>!(e3[t2]===void 0||!y2.call(e3,t2));P=`format`;ue={id:P,keyword:P,parse:fe,addValidate:({schema:e3})=>e3?.format!=null,validate:pe};({DYNAMIC_PROPERTIES:me,REGEX_FLAGS:he,DECLARATOR_ONEOF:ge,VALID_ANNOTATION_KEYWORDS:_e}=c2);Se={compileSchema(e3,t2,n2,i2){let a3=this;t2??=a3.evaluationPath;let o3=t2.split(`/$ref`)[0],c3={lastIdPointer:a3.lastIdPointer,context:a3.context,parent:a3,evaluationPath:t2,dynamicId:xe(a3.dynamicId,i2),schemaLocation:n2??b(a3.schemaLocation,o3),reducers:[],resolvers:[],validators:[],schema:e3,...Se};return!I(e3)&&!L(e3)?(c3.schemaValidation=[c3.createError(`schema-error`,{pointer:n2??t2,schema:e3,value:void 0,message:`JSON schema must be object or boolean - reveived: '${e3}'`})],c3):(c3.schemaValidation=s2(Te(c3).filter(e4=>e4!=null)),c3)},createError(e3,t2,n2){let r2=this,i2=n2;if(i2===void 0){let n3=r2.schema?.errorMessages?.[e3]??r2.context.errors[e3];if(typeof n3==`function`)return n3(t2);i2=k(n3??name,t2)}return{type:`error`,code:e3,message:i2,data:t2}},createAnnotation(e3,t2,n2){let r2=this,i2=n2;if(i2===void 0){let n3=r2.schema?.errorMessages?.[e3]??r2.context.errors[e3];if(typeof n3==`function`)return n3(t2);i2=k(n3??name,t2)}return{type:`annotation`,code:e3,message:i2,data:t2}},createSchema(e3){return this.context.methods.createSchema(e3)},getChildSelection(e3){let t2=this;return t2.context.methods.getChildSelection(t2,e3)},getNode:ce,getNodeChild:le,getNodeRef(e3){return this.compileSchema({$ref:e3},`$dynamic`).resolveRef()},getNodeRoot(){return this.context.rootNode},getDraftVersion(){return this.context.version},getData(e3,t2){let n2=this,r2={recursionLimit:1,...n2.context.getDataDefaultOptions,cache:{},...t2??{}};return n2.context.methods.getData(n2,e3,r2)},reduceNode(e3,t2={}){let n2=this,{key:r2=`missing-key`,pointer:i2=n2.evaluationPath,path:a3}=t2,o3=ve(n2);if(o3.schema===false)return{node:o3,error:void 0};if(o3.schema===true){let t3=o3.compileSchema(o3.createSchema(e3),o3.evaluationPath,o3.schemaLocation);return a3?.push({pointer:i2,node:o3}),{node:t3,error:void 0}}let s3,c3=o3.compileSchema(o3.schema,o3.evaluationPath,o3.schemaLocation),l2=o3.reducers;for(let t3 of l2){let n3=t3({data:e3,key:r2,node:o3,pointer:i2,path:a3??[]});if(z(n3))return{node:void 0,error:n3};if(n3){if(n3.schema===false){s3=false;break}c3=D(c3,n3)}}return s3===false?{node:{...o3,schema:false,reducers:[]},error:void 0}:(c3!==o3&&a3?.push({pointer:i2,node:o3}),c3.schema=oe(c3.schema,ge,...me),me.forEach(e4=>c3[e4]=void 0),{node:c3,error:void 0})},validate(e3,t2=`#`,n2=[]){let r2=this,i2=j(r2,e3,t2,n2)??[],a3=[],o3=[],c3=s2(Array.isArray(i2)?i2:[i2]).filter(z),l2=[];return s2(Array.isArray(i2)?i2:[i2]).forEach(e4=>{if(z(e4)){if(r2.context.throwOnInvalidRef&&e4.code===`ref-error`){let t3=Error(`Invalid $ref: `+e4.message);throw t3.data=a3,t3}a3.push(e4)}else e4 instanceof Promise?l2.push(e4.then(s2)):R(e4)&&o3.push(e4)}),{valid:c3.length===0,errors:a3,annotations:o3,errorsAsync:l2}},addRemoteSchema(e3,n2){I(n2)&&(n2.$id=v2(n2.$id||e3));let r2=this,{context:i2}=r2,a3=I(n2)?n2.$schema??r2.context.draft:void 0,o3=be(i2.drafts,a3??i2.rootNode.schema?.$schema),c3={evaluationPath:`#`,lastIdPointer:`#`,schemaLocation:`#`,dynamicId:``,reducers:[],resolvers:[],validators:[],schema:n2,context:{...i2,isolated:false,refs:{},anchors:{},...copy(O(o3,`methods`,`keywords`,`version`,`formats`,`errors`))},...Se};c3.context.rootNode=c3,c3.context.remotes[v2(e3)]=c3,de(c3.context);let l2=Te(c3).filter(e4=>e4!=null);l2=s2(l2);let u2=[],d2=[],f2=c3.context.rootNode.$id??v2(e3);return l2.forEach(e4=>{z(e4)?(e4.data.schemaId=f2,u2.push(e4)):R(e4)&&(e4.data.schemaId=f2,d2.push(e4))}),r2.schemaErrors=(r2.schemaErrors??[]).concat(u2),r2.schemaAnnotations=(r2.schemaAnnotations??[]).concat(d2),r2},resolveRef(e3){throw Error(`method 'resolveRef' is not implemented`)},toSchemaNodes(){return d(this)},toDataNodes(e3,t2){let n2=this;return n2.context.methods.toDataNodes(n2,e3,t2)},toJSON(){let e3=this;return{...e3,context:void 0,errors:void 0,parent:e3.parent?.evaluationPath}}};Ce=[`$ref`,`if`,`$defs`];we=[`draft-04`,`draft-06`,`draft-07`];Oe=/(#)+$/g;ke=[``,null,`#`];je={id:`$ref`,keyword:`$ref`,order:10,parse:Ne,addReduce:e3=>e3.$ref!=null||e3.schema.$dynamicRef!=null,reduce:Pe,addValidate:({schema:e3})=>e3.$ref!=null||e3.$dynamicRef!=null,validate:Ie};ze={id:`$defs`,keyword:`$defs`,parse:Be};Ve={id:`$ref`,keyword:`$ref`,parse:He,addValidate:({schema:e3})=>e3.$ref!=null,validate:Ue};Ge={id:`$ref`,keyword:`$ref`,parse:qe,addValidate:({schema:e3})=>e3.$ref!=null,validate:Ve.validate};Ze=`additionalItems`;Qe={id:Ze,keyword:Ze,order:-10,parse:$e,addResolve:e3=>e3.items!=null,resolve:et,addValidate:({schema:e3})=>e3[Ze]!=null&&e3[Ze]!==true&&Array.isArray(e3.items),validate:tt};nt={id:`additionalProperties`,keyword:`additionalProperties`,order:-10,parse:rt,addResolve:({schema:e3})=>e3.additionalProperties!=null,resolve:it,addValidate:({schema:e3})=>e3.additionalProperties!==true&&e3.additionalProperties!=null&&!(e3.additionalProperties===false&&m(e3.patternProperties)),validate:at};U=`allOf`;ot={id:U,keyword:U,parse:st,addReduce:e3=>e3[U]!=null,reduce:ct,addValidate:e3=>e3[U]!=null,validate:lt};W=`anyOf`;ut={id:W,keyword:W,parse:dt,addReduce:e3=>e3[W]!=null,reduce:ft,addValidate:e3=>e3[W]!=null,validate:pt};G=`contains`;mt={id:G,keyword:G,parse:ht,addValidate:e3=>e3[G]!=null,validate:gt,addReduce:e3=>e3[G]!=null,reduce:({node:e3})=>e3.compileSchema({items:{anyOf:[e3[G].schema]}},e3.evaluationPath,e3.schemaLocation)};_t={...mt,validate:e3=>gt(e3,1,1/0)};K=`dependentRequired`;bt={id:K,keyword:K,parse:xt,addValidate:e3=>e3[K]!=null,validate:St};q=`dependentSchemas`;Ct={id:q,keyword:q,parse:wt,addReduce:e3=>e3.dependentSchemas!=null,reduce:Tt,addValidate:e3=>e3.dependentSchemas!=null,validate:Et};J=`dependencies`;Dt={id:J,keyword:J,parse:Ot,order:-9,addReduce:e3=>e3.schema[J]!=null,reduce:kt,addValidate:e3=>e3.schema[J]!=null,validate:At};jt=`deprecated`;Mt={id:jt,keyword:jt,parse:Nt,addValidate:e3=>e3[jt]===true,validate:Pt};Y=`enum`;It={id:Y,keyword:Y,parse:Lt,addValidate:e3=>e3.enum!=null,validate:Rt};zt={"additional-items-error":"Array at `{{pointer}}` may not have an additional item `{{key}}`","additional-properties-error":"Additional property `{{property}}` on `{{pointer}}` does not match schema `{{schema}}`","all-of-error":"Value `{{value}}` at `{{pointer}}` does not match schema of `{{allOf}}`","any-of-error":"Value `{{value}}` at `{{pointer}}` does not match any schema of `{{anyOf}}`","const-error":"Expected value at `{{pointer}}` to be `{{expected}}`, but value given is `{{value}}`","contains-any-error":"The array at `{{pointer}}` must contain at least one item","contains-array-error":"The property at `{{pointer}}` must not be an array","contains-error":"The array at `{{pointer}}` must contain an element that matches `{{schema}}`","contains-min-error":"The array at `{{pointer}}` contains {{delta}} too few items matching `{{schema}}`","contains-max-error":"The array at `{{pointer}}` contains {{delta}} too many items matching `{{schema}}`","enum-error":"Expected given value `{{value}}` in `{{pointer}}` to be one of `{{values}}`","exclusive-maximum-error":"Value in `{{pointer}}` is `{{length}}`, but should be at most `{{maximum}}`","exclusive-minimum-error":"Value in `{{pointer}}` is `{{length}}`, but should be at minimum `{{minimum}}`","forbidden-property-error":"Property name `{{property}}` at `{{pointer}}` is not allowed","format-date-error":"Value `{{value}}` at `{{pointer}}` is not a valid date","format-date-time-error":"Value `{{value}}` at `{{pointer}}` is not a valid date-time","format-duration-error":"Value `{{value}}` at `{{pointer}}` is not a valid duration","format-email-error":"Value `{{value}}` at `{{pointer}}` is not a valid email","format-hostname-error":"Value `{{value}}` at `{{pointer}}` is not a valid hostname","format-idn-hostname-error":"Value `{{value}}` at `{{pointer}}` is not a valid idn hostname","format-ipv4-error":"Value `{{value}}` at `{{pointer}}` is not a valid IPv4 address","format-ipv4-leading-zero-error":`IPv4 addresses starting with zero are invalid, since they are interpreted as octals`,"format-ipv6-error":"Value `{{value}}` at `{{pointer}}` is not a valid IPv6 address","format-ipv6-leading-zero-error":`IPv6 addresses starting with zero are invalid, since they are interpreted as octals`,"format-iri-error":"Value `{{value}}` at `{{pointer}}` is not a valid iri","format-iri-reference-error":"Value `{{value}}` at `{{pointer}}` is not a valid iri-reference","format-json-pointer-error":"Value `{{value}}` at `{{pointer}}` is not a valid json-pointer","format-regex-error":"Value `{{value}}` at `{{pointer}}` is not a valid regular expression","format-time-error":"Value `{{value}}` at `{{pointer}}` is not a valid time","format-uri-error":"Value `{{value}}` at `{{pointer}}` is not a valid uri","format-uri-reference-error":"Value `{{value}}` at `{{pointer}}` is not a valid uri-reference","format-uri-template-error":"Value `{{value}}` at `{{pointer}}` is not a valid uri-template","format-url-error":"Value `{{value}}` at `{{pointer}}` is not a valid url","format-uuid-error":"Value `{{value}}` at `{{pointer}}` is not a valid uuid","invalid-data-error":"No value may be specified in `{{pointer}}`","invalid-property-name-error":"Invalid property name `{{property}}` at `{{pointer}}`","maximum-error":"Value in `{{pointer}}` is `{{length}}`, but should be `{{maximum}}` at maximum","max-items-error":"Too many items in `{{pointer}}`, should be `{{maximum}}` at most, but got `{{length}}`","max-length-error":"Value `{{pointer}}` should have a maximum length of `{{maxLength}}`, but got `{{length}}`.","max-properties-error":"Too many properties in `{{pointer}}`, should be `{{maxProperties}}` at most, but got `{{length}}`","minimum-error":"Value in `{{pointer}}` is `{{length}}`, but should be `{{minimum}}` at minimum","min-items-error":"Too few items in `{{pointer}}`, should be at least `{{minItems}}`, but got `{{length}}`","min-items-one-error":"At least one item is required in `{{pointer}}`","min-length-error":"Value `{{pointer}}` should have a minimum length of `{{minLength}}`, but got `{{length}}`.","min-length-one-error":"A value is required in `{{pointer}}`","missing-one-of-declarator-error":"Missing oneOf declarator `{{declarator}}` in schema `{{schemaLocation}}`","min-properties-error":"Too few properties in `{{pointer}}`, should be at least `{{minProperties}}`, but got `{{length}}`","missing-array-item-error":`Array at '{{pointer}}' has a missing item at '{{key}}'`,"missing-dependency-error":"The required propery '{{missingProperty}}' in `{{pointer}}` is missing","missing-one-of-property-error":"Value at `{{pointer}}` must be object or array and have a property ${oneOfProperty}: ${value}","multiple-of-error":"Expected `{{value}}` in `{{pointer}}` to be multiple of `{{multipleOf}}`","multiple-one-of-error":"Value `{{value}}` should not match multiple schemas in oneOf `{{matches}}`","no-additional-properties-error":"Additional property `{{property}}` in `{{pointer}}` is not allowed","not-error":"Value `{{value}}` at pointer should not match schema `{{not}}`","one-of-error":"Value `{{value}}` in `{{pointer}}` does not match any given oneof schema","one-of-property-error":"Failed finding a matching oneOfProperty schema in `{{pointer}}` where `{{property}}` matches `{{value}}`","pattern-error":"Value in `{{pointer}}` should match `{{description}}`, but received `{{received}}`","pattern-properties-error":"Property `{{key}}` does not match any patterns in `{{pointer}}`. Valid patterns are: {{patterns}}","ref-error":`Could not resolve $ref '{{ref}}' from '{{pointer}}'`,"required-property-error":"The required property `{{key}}` is missing at `{{pointer}}`","schema-warning":`Failed retrieving a schema from '{{pointer}}' to key '{{key}}'`,"type-error":"Expected `{{value}}` ({{received}}) in `{{pointer}}` to be of type `{{expected}}`","undefined-value-error":"Value must not be undefined in `{{pointer}}`","unevaluated-property-error":"Invalid unevaluated property `{{pointer}}`","unevaluated-items-error":"Invalid unevaluated item `{{pointer}}`","unique-items-error":"Items in array must be unique. Value `{{value}}` in `{{pointer}}` is a duplicate of {{duplicatePointer}}.","unknown-property-error":"Could not find a valid schema for property `{{pointer}}` within object","value-not-empty-error":"A value for `{{property}}` is required at `{{pointer}}`","deprecated-warning":"Value at `{{pointer}}` is deprecated","schema-error":`Invalid schema found at {{pointer}}: {{message}}`,"unknown-keyword-warning":`Keyword '{{value}}' is not a valid keyword to draft '{{draft}}'`,"unknown-format-warning":`Format {{value}} is not a valid format`};Bt={id:`exclusiveMaximum`,keyword:`exclusiveMaximum`,parse:Vt,addValidate:({schema:e3})=>e3.exclusiveMaximum===true||!isNaN(e3.maximum),validate:Ht};Ut={id:`exclusiveMinimum`,keyword:`exclusiveMinimum`,parse:Wt,addValidate:({schema:e3})=>e3.exclusiveMinimum===true||!isNaN(e3.minimum),validate:Gt};({REGEX_FLAGS:Kt}=c2);qt=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/;Jt=/^((([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;Yt=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;Xt=/^(?<time>(?:([0-1]\d|2[0-3]):[0-5]\d:(?<second>[0-5]\d|60)))(?:\.\d+)?(?<offset>(?:z|[+-]([0-1]\d|2[0-3])(?::?[0-5]\d)?))$/i;Zt=[0,31,28,31,30,31,30,31,31,30,31,30,31];Qt=/^(?:\/(?:[^~/]|~0|~1)*)*$/;$t=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;en=/^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/;tn={date:({node:e3,pointer:t2,data:n2})=>{let{schema:r2}=e3;if(typeof n2!=`string`||n2===``)return;let i2=n2.match(Yt);if(!i2)return e3.createError(`format-date-error`,{value:n2,pointer:t2,schema:r2});let a3=+i2[1],o3=+i2[2],s3=+i2[3],c3=a3%4==0&&(a3%100!=0||a3%400==0);if(!(o3>=1&&o3<=12&&s3>=1&&s3<=(o3==2&&c3?29:Zt[o3])))return e3.createError(`format-date-error`,{value:n2,pointer:t2,schema:r2})},"date-time":({node:e3,pointer:t2,data:n2,path:r2})=>{let{schema:i2}=e3;if(typeof n2!=`string`||n2===``)return;let a3=n2.split(/t/i);if(a3.length===2){let n3=tn.date({node:e3,pointer:t2,data:a3[0],path:r2})===void 0,i3=tn.time({node:e3,pointer:t2,data:a3[1],path:r2})===void 0;if(n3&&i3)return}return e3.createError(`format-date-time-error`,{value:n2,pointer:t2,schema:i2})},duration:({node:e3,pointer:t2,data:n2})=>{if(p(n2)===`string`&&(!en.test(n2)||/(\d+M)(\d+W)|(\d+Y)(\d+W)/.test(n2)))return e3.createError(`format-duration-error`,{value:n2,pointer:t2,schema:e3.schema})},email:({node:e3,pointer:t2,data:n2})=>{let{schema:r2}=e3;if(typeof n2!=`string`||n2===``)return;let i2=n2.lastIndexOf(`@`),a3=n2.substr(0,i2),o3=n2.substr(i2+1);if(!a3||!o3||a3.length>64||o3.length>253)return e3.createError(`format-email-error`,{value:n2,pointer:t2,schema:r2});let s3=a3;if(/^".*"$/.test(a3)&&(s3=a3.replace(/(^")|([. @]+)|("$)/g,``)),s3[0]===`.`||s3.endsWith(`.`)||s3.includes(`..`)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(s3))return e3.createError(`format-email-error`,{value:n2,pointer:t2,schema:r2});if(/^\[.*\]$/.test(o3)){let e4=o3.substr(1,o3.length-2);if(qt.test(e4)||Jt.test(e4)||/IPv6:::[0-9a-f]{1,4}/.test(e4))return}if(!/^[a-z0-9.-]+$/i.test(o3)||!o3.split(`.`).every(e4=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e4)))return e3.createError(`format-email-error`,{value:n2,pointer:t2,schema:r2})},"json-pointer":({node:e3,pointer:t2,data:n2})=>{let{schema:r2}=e3;if(typeof n2==`string`&&n2!==``&&!Qt.test(n2))return e3.createError(`format-json-pointer-error`,{value:n2,pointer:t2,schema:r2})},"relative-json-pointer":({node:e3,pointer:t2,data:n2})=>{let{schema:r2}=e3;if(typeof n2==`string`&&!$t.test(n2))return e3.createError(`format-json-pointer-error`,{value:n2,pointer:t2,schema:r2})},regex:({node:e3,pointer:t2,data:n2})=>{let{schema:r2}=e3;if(!(typeof n2==`object`||typeof n2==`number`||Array.isArray(n2)||p(n2)===`boolean`)){if(typeof n2==`string`&&/\\Z$/.test(n2)===false){try{new RegExp(n2,r2.regexFlags??Kt);return}catch{}return e3.createError(`format-regex-error`,{value:n2,pointer:t2,schema:r2})}return e3.createError(`format-regex-error`,{value:n2,pointer:t2,schema:r2})}},time:({node:e3,pointer:t2,data:n2})=>{let{schema:r2}=e3;if(typeof n2!=`string`||n2===``)return;let i2=n2.match(Xt);if(!i2)return e3.createError(`format-date-time-error`,{value:n2,pointer:t2,schema:r2});if(i2.groups?.second===`60`){if(/23:59:60(z|\+00:00)/i.test(n2))return;let a3=i2.groups.time.match(/(\d+):(\d+):/),o3=i2.groups.offset.match(/(\d+):(\d+)/);if(a3&&o3){let e4=parseInt(a3[1]),t3=parseInt(o3[1]),n3=parseInt(a3[2]),r3=parseInt(o3[2]),s3;s3=/^-/.test(i2.groups.offset)?(e4+t3)*60+(n3+r3):(24+e4-t3)*60+(n3-r3);let c3=Math.floor(s3/60),l2=c3%24,u2=s3-c3*60;if(l2===23&&u2===59)return}return e3.createError(`format-date-time-error`,{value:n2,pointer:t2,schema:r2})}},url:({node:e3,data:t2,pointer:n2})=>{let{schema:r2}=e3;if(typeof t2==`string`&&t2!==``&&!(0,import_valid_url.isWebUri)(t2))return e3.createError(`format-url-error`,{value:t2,pointer:n2,schema:r2})},uuid:({node:e3,data:t2,pointer:n2})=>{let{schema:r2}=e3;if(typeof t2==`string`&&t2!==``&&!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t2))return e3.createError(`format-uuid-error`,{value:t2,pointer:n2,schema:r2})}};rn=[`string`,`number`,`integer`,`boolean`,`null`,`array`,`object`];an=[`additionalProperties`,`dependencies`,`dependentSchemas`,`dependentRequired`,`maxProperties`,`minProperties`,`patternProperties`,`properties`,`propertyNames`,`required`,`unevaluatedProperties`];on=[`contains`,`items`,`maxItems`,`minItems`,`unevaluatedItems`,`uniqueItems`];X=`oneOf`;({DECLARATOR_ONEOF:ln}=c2);un={id:X,keyword:X,parse:fn,addReduce:e3=>e3[X]!=null,reduce:pn,addValidate:e3=>e3[X]!=null,validate:vn};dn={id:`oneOf-fuzzy`,keyword:`oneOf`,parse:fn,addReduce:e3=>e3.oneOf!=null,reduce:gn,addValidate:e3=>e3.oneOf!=null,validate:vn};yn=()=>false;try{typeof File==`function`&&(yn=e3=>e3 instanceof File)}catch{}wn={null:(e3,t2,n2)=>Tn(e3,t2,null,n2.useTypeDefaults),string:(e3,t2,n2)=>Tn(e3,t2,``,n2.useTypeDefaults),number:(e3,t2,n2)=>Tn(e3,t2,0,n2.useTypeDefaults),integer:(e3,t2,n2)=>Tn(e3,t2,0,n2.useTypeDefaults),boolean:(e3,t2,n2)=>Tn(e3,t2,false,n2.useTypeDefaults),object:(e3,t2,n2)=>{let r2=e3.schema,i2=r2.default===void 0?{}:r2.default,a3=Object.create(null),o3=n2.extendDefaults===false&&r2.default!==void 0?[]:r2.required??[],s3=e3.properties;s3&&Object.keys(s3).forEach(e4=>{let r3=s3[e4],c4=o3.includes(e4),l3=x(t2,e4),u2=t2===void 0||l3===void 0?x(i2,e4):l3;if(u2!==void 0||c4||n2.addOptionalProps){let t3=r3.getData(u2,n2),i3=p(t3);if(n2.removeInvalidData&&i3!==`object`&&i3!==`array`&&!r3.validate(t3).valid)return;(t3!==void 0||n2.useTypeDefaults!==false)&&(a3[e4]=t3)}});let c3=e3.dependentRequired;m(c3)&&Object.keys(c3).forEach(t3=>{let r3=c3[t3];x(a3,t3)!==void 0&&r3.forEach(t4=>{let{node:r4}=e3.getNodeChild(t4,a3);r4&&(a3[t4]=r4.getData(x(a3,t4),n2))})});let l2=e3.dependentSchemas;if(l2&&Object.keys(l2).forEach(e4=>{let r3=l2[e4];if(a3[e4]!==void 0&&F(r3)){let e5=r3.getData(t2??a3,n2);Object.assign(a3,e5)}}),t2){if(n2.removeInvalidData===true&&(r2.additionalProperties===false||m(r2.additionalProperties))){let n3=e3.additionalProperties;F(n3)&&Object.keys(t2).forEach(e4=>{if(a3[e4]==null){let r3=x(t2,e4);n3.validate(r3).valid&&(a3[e4]=r3)}})}else Object.keys(t2).forEach(r3=>{let i3=p(r3);if(n2.removeInvalidData&&e3.properties&&e3.properties[r3]&&i3!==`object`&&i3!==`array`){let i4=e3.properties[r3],a4=i4.getData(x(t2,r3),n2);if(!i4.validate(a4).valid)return}a3[r3]??(a3[r3]=x(t2,r3))})}if(e3.if){let{valid:t3}=e3.if.validate(a3);if(t3&&e3.then){let t4=e3.then.getData(a3,n2);Object.assign(a3,t4)}else if(!t3&&e3.else){let t4=e3.else.getData(a3,n2);Object.assign(a3,t4)}}return{...i2,...a3}},array:(e3,n2,r2)=>{let i2=e3.schema,a3=i2.default===void 0?[]:i2.default,o3=Array.isArray(n2)?[...n2]:a3,s3=r2.extendDefaults===false&&i2.default!==void 0?0:i2.minItems??0;if(i2.items==null){if(e3.items){let t2=Math.max(s3,o3.length);for(let n3=0;n3<t2;n3+=1)o3[n3]=e3.items.getData(o3[n3],r2)}return o3||[]}if(e3.prefixItems){let t2=Array.isArray(n2)?n2:[],i3=Math.max(s3??0,e3.prefixItems.length);for(let n3=0;n3<i3;n3+=1){let i4=e3.prefixItems[n3]??e3.items;if(i4&&xn(i4,r2)||t2[n3]!==void 0){let e4=i4.getData(o3[n3]==null?a3[n3]:o3[n3],r2);e4!==void 0&&(o3[n3]=e4)}}return o3||[]}if(e3.items==null)return o3;if(e3.items&&xn(e3.items,r2)||Array.isArray(n2)&&n2?.length>0){let n3={...r2.cache};for(let i3=0,c3=Math.max(s3,o3.length);i3<c3;i3+=1){r2.cache=copy(n3);let s4={...r2,disableRecursionLimit:true},c4=e3.items.getData(o3[i3]==null?a3[i3]:o3[i3],s4);if(c4===void 0)return o3;o3[i3]=c4}}return o3}};En=`items`;Dn={id:En,keyword:En,parse:kn,addResolve:e3=>(e3.prefixItems||e3[En])!=null,resolve:On,addValidate:({schema:e3})=>e3.items!=null,validate:An};jn=`maximum`;Mn={id:jn,keyword:jn,parse:Nn,addValidate:e3=>e3.maximum!=null,validate:Pn};Fn=`maxItems`;In={id:Fn,keyword:Fn,parse:Ln,addValidate:({schema:e3})=>!isNaN(e3.maxItems),validate:Rn};Bn=`maxLength`;Vn={id:Bn,keyword:Bn,parse:Hn,addValidate:e3=>e3[Bn]!=null,validate:Un};Wn=`maxProperties`;Gn={id:Wn,keyword:Wn,parse:Kn,addValidate:e3=>e3[Wn]!=null,validate:qn};Jn=`minimum`;Yn={id:Jn,keyword:Jn,parse:Xn,addValidate:e3=>e3[Jn]!=null,validate:Zn};Qn=`minItems`;$n={id:Qn,keyword:Qn,parse:er,addValidate:e3=>e3[Qn]!=null,validate:tr};nr=`minLength`;rr={id:nr,keyword:nr,parse:ir,addValidate:e3=>e3[nr]!=null,validate:ar};or=`minProperties`;sr={id:or,keyword:or,parse:cr,addValidate:e3=>e3[or]!=null,validate:lr};dr=`multipleOf`;fr={id:dr,keyword:dr,parse:pr,addValidate:e3=>e3[dr]!=null,validate:mr};hr={id:`not`,keyword:`not`,parse:gr,addValidate:e3=>e3.not!=null,validate:_r};vr=`pattern`;({REGEX_FLAGS:yr}=c2);br={id:vr,keyword:vr,parse:xr,addValidate:e3=>e3[vr]!=null,validate:Sr};({REGEX_FLAGS:Cr}=c2);wr={id:`patternProperties`,keyword:`patternProperties`,parse:Tr,addReduce:e3=>e3.patternProperties!=null,reduce:Dr,addResolve:e3=>e3.patternProperties!=null,resolve:Er,addValidate:e3=>e3.patternProperties!=null,validate:Or};kr={id:`property`,keyword:`properties`,parse:jr,addResolve:e3=>e3.properties!=null,resolve:Ar,addValidate:e3=>e3.properties!=null,validate:Mr};Nr=`propertyNames`;Pr={id:Nr,keyword:Nr,parse:Fr,addValidate:e3=>e3.schema[Nr]!=null,validate:Ir};Lr=`required`;Rr={id:Lr,keyword:Lr,parse:zr,addValidate:e3=>e3.required!=null,validate:Br};Z=`type`;qr=[`null`,`boolean`,`number`,`integer`,`string`,`object`,`array`];Jr={id:Z,keyword:Z,parse:Yr,addReduce:e3=>Array.isArray(e3.type),reduce:Xr,addValidate:e3=>e3.type!=null,validate:Qr};$r=`uniqueItems`;ei={id:$r,keyword:$r,parse:ti,addValidate:({schema:e3})=>e3[$r]===true,validate:ni};ri=Gr({version:`draft-04`,$schemaRegEx:`draft-?0?4`,$schema:`http://json-schema.org/draft-04/schema#`,errors:zt,formats:tn,methods:{createSchema:vt,getData:Cn,getChildSelection:nn,toDataNodes:Kr},keywords:[Ge,ot,ut,_t,ze,Dt,Mt,It,Bt,Ut,ue,Dn,Mn,In,Vn,Gn,Yn,$n,rr,sr,fr,hr,wr,br,kr,Pr,Rr,Jr,ei,un,Qe,nt]});ii={id:`const`,keyword:`const`,addValidate:({schema:e3})=>e3.const!==void 0,validate:ai};oi=`exclusiveMaximum`;si={id:oi,keyword:oi,parse:ci,addValidate:({schema:e3})=>e3.exclusiveMaximum!=null&&!isNaN(parseInt(e3.exclusiveMaximum)),validate:li};ui=`exclusiveMinimum`;di={id:ui,keyword:ui,parse:fi,addValidate:({schema:e3})=>e3[ui]!=null&&!isNaN(parseInt(e3[ui])),validate:pi};mi=Gr({version:`draft-06`,$schemaRegEx:`draft-?0?6`,$schema:`http://json-schema.org/draft-06/schema#`,errors:zt,formats:tn,methods:{createSchema:vt,getData:Cn,getChildSelection:nn,toDataNodes:Kr},keywords:[Ve,ot,ut,ii,_t,ze,Dt,Mt,It,si,di,ue,Dn,Mn,In,Vn,Gn,Yn,$n,rr,sr,fr,hr,wr,br,kr,Pr,Rr,Jr,ei,un,Qe,nt]});hi={id:`if-then-else`,keyword:`if`,keywords:[`if`,`then`,`else`],parse:gi,addReduce:e3=>e3.if!=null&&(e3.then!=null||e3.else!=null),reduce:_i,addValidate:e3=>e3.if!=null,validate:vi};yi=Gr({version:`draft-07`,$schemaRegEx:`draft-?0?7`,$schema:`http://json-schema.org/draft-07/schema#`,errors:zt,formats:tn,methods:{createSchema:vt,getData:Cn,getChildSelection:nn,toDataNodes:Kr},keywords:[Ve,ot,ut,ii,_t,ze,Dt,Mt,It,si,di,ue,hi,Dn,Mn,In,Vn,Gn,Yn,$n,rr,sr,fr,hr,wr,br,kr,Pr,Rr,Jr,ei,un,Qe,nt]});bi={id:`$ref`,keyword:`$ref`,parse:Si,addValidate:({schema:e3})=>e3.$ref!=null||e3.$recursiveRef!=null,validate:wi,addReduce:({schema:e3})=>e3.$ref!=null||e3.$recursiveRef!=null,reduce:Pe};Di=`unevaluatedItems`;Oi={id:Di,keyword:Di,parse:ki,addValidate:({schema:e3})=>e3[Di]!=null,validate:Ai};Mi=`unevaluatedProperties`;Ni={id:Mi,keyword:Mi,parse:Pi,addValidate:({schema:e3})=>e3[Mi]!=null,validate:Fi};Ii=Gr({version:`draft-2019-09`,$schemaRegEx:`draft[/-]2019-?(09)?`,$schema:`https://json-schema.org/draft/2019-09/schema`,errors:zt,formats:tn,methods:{createSchema:vt,getData:Cn,getChildSelection:nn,toDataNodes:Kr},keywords:[bi,ot,ut,ii,mt,ze,Dt,bt,Ct,Mt,It,si,di,ue,hi,Dn,Mn,In,Vn,Gn,Yn,$n,rr,sr,fr,hr,wr,br,kr,Pr,Rr,Jr,Oi,Ni,ei,un,Qe,nt]});Hi={null:(e3,t2,n2)=>Ui(e3,t2,null,n2.useTypeDefaults),string:(e3,t2,n2)=>Ui(e3,t2,``,n2.useTypeDefaults),number:(e3,t2,n2)=>Ui(e3,t2,0,n2.useTypeDefaults),integer:(e3,t2,n2)=>Ui(e3,t2,0,n2.useTypeDefaults),boolean:(e3,t2,n2)=>Ui(e3,t2,false,n2.useTypeDefaults),object:(e3,t2,n2)=>{let r2=e3.schema,i2=r2.default===void 0?{}:r2.default,a3=Object.create(null),o3=n2.extendDefaults===false&&r2.default!==void 0?[]:r2.required??[],s3=e3.properties;s3&&Object.keys(s3).forEach(e4=>{let r3=s3[e4],c4=o3.includes(e4),l3=x(t2,e4),u2=t2===void 0||l3===void 0?x(i2,e4):l3;if(u2!==void 0||c4||n2.addOptionalProps){let t3=r3.getData(u2,n2),i3=p(t3);if(n2.removeInvalidData&&i3!==`object`&&i3!==`array`&&!r3.validate(t3).valid)return;(t3!==void 0||n2.useTypeDefaults!==false)&&(a3[e4]=t3)}});let c3=e3.dependentRequired;m(c3)&&Object.keys(c3).forEach(t3=>{let r3=c3[t3];x(a3,t3)!==void 0&&r3.forEach(t4=>{let{node:r4}=e3.getNodeChild(t4,a3);r4&&(a3[t4]=r4.getData(x(a3,t4),n2))})});let l2=e3.dependentSchemas;if(l2&&Object.keys(l2).forEach(e4=>{let r3=l2[e4];if(a3[e4]!==void 0&&F(r3)){let e5=r3.getData(t2??a3,n2);Object.assign(a3,e5)}}),t2&&(n2.removeInvalidData===true&&(r2.additionalProperties===false||m(r2.additionalProperties))?F(e3.additionalProperties)&&Object.keys(t2).forEach(n3=>{if(a3[n3]==null){let r3=x(t2,n3);e3.additionalProperties?.validate(r3).valid&&(a3[n3]=r3)}}):Object.keys(t2).forEach(r3=>{let i3=p(r3);if(n2.removeInvalidData&&e3.properties&&e3.properties[r3]&&i3!==`object`&&i3!==`array`){let i4=e3.properties[r3],a4=i4.getData(x(t2,r3),n2);if(!i4.validate(a4).valid)return}a3[r3]??(a3[r3]=x(t2,r3))})),e3.if){let{errors:t3}=e3.if.validate(a3);if(t3.length===0&&e3.then){let t4=e3.then.getData(a3,n2);Object.assign(a3,t4)}else if(t3.length>0&&e3.else){let t4=e3.else.getData(a3,n2);Object.assign(a3,t4)}}return{...i2,...a3}},array:(e3,n2,r2)=>{let i2=e3.schema,a3=i2.default===void 0?[]:i2.default,o3=Array.isArray(n2)?[...n2]:a3,s3=r2.extendDefaults===false&&i2.default!==void 0?0:i2.minItems??0;if(i2.prefixItems==null){if(e3.items&&(zi(e3.items,r2)||o3?.length>0)){let n3={...r2.cache},i3=Math.max(s3,o3.length);for(let s4=0;s4<i3;s4+=1){r2.cache=copy(n3);let i4={...r2,disableRecursionLimit:true};o3[s4]=e3.items.getData(o3[s4]==null?a3[s4]:o3[s4],i4)}}return o3||[]}if(e3.prefixItems){let t2=Array.isArray(n2)?n2:[],i3=Math.max(s3??0,e3.prefixItems.length);for(let n3=0;n3<i3;n3+=1){let i4=e3.prefixItems[n3]??e3.items;if(i4&&zi(i4,r2)||t2[n3]!==void 0){let e4=i4.getData(o3[n3]==null?a3[n3]:o3[n3],r2);e4!==void 0&&(o3[n3]=e4)}}return o3||[]}if(e3.items==null)return o3;if(e3.items&&zi(e3.items,r2)||n2?.length>0){let n3={...r2.cache};for(let i3=0,c3=Math.max(s3,o3.length);i3<c3;i3+=1){r2.cache=copy(n3);let s4={...r2,disableRecursionLimit:true},c4=e3.items.getData(o3[i3]==null?a3[i3]:o3[i3],s4);if(c4===void 0)return o3;o3[i3]=c4}}return o3}};Q=`items`;Wi={id:Q,keyword:Q,parse:Ki,addResolve:e3=>e3[Q]!=null,resolve:Gi,addValidate:e3=>e3[Q]!=null,validate:qi};Ji=`prefixItems`;Yi={id:Ji,keyword:Ji,parse:Zi,addResolve:e3=>e3[Ji]!=null,resolve:Xi,addValidate:e3=>e3[Ji]!=null,validate:Qi};ea=`unevaluatedItems`;ta={id:ea,keyword:ea,parse:na,addValidate:({schema:e3})=>e3.unevaluatedItems!=null,validate:ra};ia=Gr({version:`draft-2020-12`,$schemaRegEx:`draft[/-]2020-?(12)?`,$schema:`https://json-schema.org/draft/2020-12/schema`,errors:zt,formats:tn,methods:{createSchema:vt,getData:Vi,getChildSelection:Li,toDataNodes:Kr},keywords:[je,nt,ot,ut,ii,mt,ze,Dt,bt,Ct,Mt,It,si,di,ue,hi,Wi,Mn,In,Vn,Gn,Yn,$n,rr,sr,fr,hr,un,br,wr,Yi,kr,Pr,Rr,Jr,ta,Ni,ei]});({REGEX_FLAGS:aa}=c2);oa=[ri,mi,yi,Ii,ia];la=Hr(ia,{$schemaRegEx:`.`,keywords:[dn],errors:{"min-length-error":e3=>e3.minLength===1?{type:`error`,code:`min-length-one-error`,message:`An input is required`,data:e3}:{type:`error`,code:`min-length-error`,message:k("Value in `{{pointer}}` is `{{length}}`, but should be `{{minLength}}` at minimum",e3),data:e3}}})}});function prepareContractValidator(bundle){const copy2=value=>JSON.parse(JSON.stringify(value));const registry4=ca({},OPTIONS);const resources2=[];for(const[digest,member]of Object.entries(bundle.members??{})){const uri=`cotal:${digest}`;registry4.addRemoteSchema(uri,copy2(member));const resource=registry4.context.remotes[uri];const id2=resource.$id;if(id2===void 0)throw new Error("registered resource has no identity");for(const table of[resource.context.refs,resource.context.anchors,resource.context.dynamicAnchors]){for(const[ref,node]of Object.entries(table)){if(ref===id2||ref.startsWith(`${id2}#`))table[uri+ref.slice(id2.length)]=node}}resources2.push(resource)}if(registry4.schemaErrors?.length)throw new Error("schema is invalid");const root=ca(copy2(bundle.root),{...OPTIONS,remote:registry4});resources2.push(root);for(const resource of resources2){for(const node of resource.toSchemaNodes()){if(node.schema&&typeof node.schema==="object"&&(node.schema.$ref||node.schema.$dynamicRef)){const resolved=node.resolveRef({path:[]});if(z(resolved))throw new Error(resolved.message)}}}const validate2=Object.assign(value=>{const result=root.validate(value);if(result.errorsAsync.length)throw new Error("contract validation must be synchronous");validate2.errors=result.valid?null:result.errors.map(error51=>{const property=error51.code==="no-additional-properties-error"&&typeof error51.data.property==="string"?error51.data.property:void 0;const missing=error51.code==="required-property-error"&&typeof error51.data.key==="string"?error51.data.key:void 0;return{code:String(error51.code),instancePath:typeof error51.data.pointer==="string"?error51.data.pointer.slice(1):"",message:property!==void 0?"must NOT have additional properties":missing!==void 0?`must have required property '${missing}'`:`schema assertion failed (${error51.code})`,...property===void 0?{}:{additionalProperty:property}}});return result.valid},{errors:null,schema:copy2(bundle.root)});return validate2}var OPTIONS;var init_contract_validator=__esm({"../../packages/core/dist/contract-validator.js"(){"use strict";init_dist2();OPTIONS={drafts:[ia],formatAssertion:false,throwOnInvalidSchema:true,throwOnInvalidRef:true}}});function rangesOverlap(a3,b3){for(const[al,ah]of a3)for(const[bl,bh]of b3)if(al<=bh&&bl<=ah)return true;return false}function rangesCover(outer,[lo,hi2]){return outer.some(([ol,oh])=>ol<=lo&&hi2<=oh)}function intersects(a3,b3){if(!a3.neg&&!b3.neg)return rangesOverlap(a3.ranges,b3.ranges);if(a3.neg&&b3.neg)return true;const pos=a3.neg?b3:a3;const neg=a3.neg?a3:b3;return!pos.ranges.every(r2=>rangesCover(neg.ranges,r2))}function union(a3,b3){if(!a3.neg&&a3.ranges.length===0)return b3;if(!b3.neg&&b3.ranges.length===0)return a3;if(a3.neg||b3.neg)return FULL;return{neg:false,ranges:[...a3.ranges,...b3.ranges]}}function powSat(base,exp){let out=1;for(let i2=0;i2<exp&&out<CHOICE_SAT;i2++)out=mulSat(out,base);return out}function edgeRepeat(facts,pick2){const deeper=new Array(facts.length+1);deeper[facts.length]=EMPTY;for(let i2=facts.length-1;i2>=0;i2--)deeper[i2]=union(pick2(facts[i2]),deeper[i2+1]);let acc=EMPTY;for(let i2=0;i2<facts.length;i2++){acc=union(acc,pick2(facts[i2]));if(!facts[i2].nullable&&!intersects(facts[i2].set,deeper[i2+1]))break}return acc}function assertStartAnchored(node){switch(node.kind){case"anchor":if(node.at!=="start")refuse("a top-level branch must begin with a '^' start anchor (Ajv tests patterns unanchored)");return;case"seq":if(node.items.length===0)refuse("an empty top-level branch is not start-anchored");assertStartAnchored(node.items[0]);return;case"alt":for(const b3 of node.branches)assertStartAnchored(b3);return;default:refuse("a top-level branch must begin with a '^' start anchor (Ajv tests patterns unanchored)")}}function analyze(node){switch(node.kind){case"anchor":return{set:EMPTY,nullable:true,variable:false,ambiguousAlt:false,choices:1,leadRep:EMPTY,trailRep:EMPTY};case"atom":return{set:node.set,nullable:node.set.ranges.length===0&&!node.set.neg,variable:false,ambiguousAlt:false,choices:1,leadRep:EMPTY,trailRep:EMPTY};case"seq":{const facts=node.items.map(analyze);for(let i2=0;i2<facts.length;i2++){const T2=facts[i2].trailRep;if(T2.ranges.length===0&&!T2.neg)continue;for(let j2=i2+1;j2<facts.length;j2++){if(intersects(T2,facts[j2].leadRep))refuse("two overlapping variable repetitions in sequence (polynomial backtracking class)");if(!facts[j2].nullable&&!intersects(facts[j2].set,T2))break}}return{set:facts.reduce((s3,f2)=>union(s3,f2.set),EMPTY),nullable:facts.every(f2=>f2.nullable),variable:facts.some(f2=>f2.variable),ambiguousAlt:facts.some(f2=>f2.ambiguousAlt),choices:facts.reduce((n2,f2)=>mulSat(n2,f2.choices),1),leadRep:edgeRepeat(facts,f2=>f2.leadRep),trailRep:edgeRepeat([...facts].reverse(),f2=>f2.trailRep)}}case"alt":{const facts=node.branches.map(analyze);let ambiguous=facts.some(f2=>f2.ambiguousAlt);if(facts.filter(f2=>f2.nullable).length>1)ambiguous=true;for(let i2=0;i2<facts.length&&!ambiguous;i2++){for(let j2=i2+1;j2<facts.length;j2++){if(intersects(facts[i2].set,facts[j2].set)){ambiguous=true;break}}}return{set:facts.reduce((s3,f2)=>union(s3,f2.set),EMPTY),nullable:facts.some(f2=>f2.nullable),variable:facts.some(f2=>f2.variable),ambiguousAlt:ambiguous,choices:ambiguous?facts.reduce((n2,f2)=>Math.min(n2+f2.choices,CHOICE_SAT),0):facts.reduce((n2,f2)=>Math.max(n2,f2.choices),1),leadRep:facts.reduce((s3,f2)=>union(s3,f2.leadRep),EMPTY),trailRep:facts.reduce((s3,f2)=>union(s3,f2.trailRep),EMPTY)}}case"quant":{const body=analyze(node.body);const repeats=node.max>1||node.max===Infinity;if(repeats){if(body.variable)refuse("repeats a group that itself contains a quantifier (exponential backtracking class)");if(body.nullable)refuse("repeats a nullable body (unbounded ambiguity on empty matches)");if(body.ambiguousAlt)refuse("repeats an ambiguous alternation (branches overlap; exponential backtracking class)")}const nondet=node.max>node.min;return{set:body.set,nullable:body.nullable||node.min===0,variable:body.variable||nondet||repeats,ambiguousAlt:body.ambiguousAlt,choices:node.max===node.min?powSat(body.choices,node.min):node.min===0&&node.max===1?Math.min(body.choices+1,CHOICE_SAT):body.choices,leadRep:nondet?union(body.set,body.leadRep):body.leadRep,trailRep:nondet?union(body.set,body.trailRep):body.trailRep}}}}function assertSafePattern(pattern,maxChars){if(pattern.length>maxChars)throw new Error(`pattern of ${pattern.length} characters exceeds the profile complexity bound (${maxChars})`);try{const ast=new Parser(pattern).parse();assertStartAnchored(ast);const facts=analyze(ast);if(facts.choices>CHOICE_BUDGET)refuse(`aggregate alternation ambiguity of ${facts.choices>=CHOICE_SAT?"at least ":""}${facts.choices} paths exceeds the ${CHOICE_BUDGET}-path budget (the fixed-alternation exponential class)`)}catch(e3){if(e3 instanceof PatternRefused)throw new Error(`pattern ${JSON.stringify(pattern)} is outside the profile's safe subset: ${e3.message}`);throw new Error(`pattern ${JSON.stringify(pattern)} did not parse under the profile's safe subset: ${e3.message}`)}}var FULL,EMPTY,set,single,PatternRefused,refuse,Parser,CHOICE_BUDGET,CHOICE_SAT,mulSat;var init_safe_pattern=__esm({"../../packages/core/dist/safe-pattern.js"(){"use strict";FULL={neg:true,ranges:[]};EMPTY={neg:false,ranges:[]};set=(...ranges)=>({neg:false,ranges});single=c3=>set([c3,c3]);PatternRefused=class extends Error{};refuse=reason=>{throw new PatternRefused(reason)};Parser=class{src;i=0;constructor(src){this.src=src}peek(){return this.src[this.i]}next(){return this.src[this.i++]}eof(){return this.i>=this.src.length}parse(){const node=this.alternation();if(!this.eof())refuse(`unexpected "${this.peek()}" at ${this.i}`);return node}alternation(){const branches=[this.sequence()];while(this.peek()==="|"){this.next();branches.push(this.sequence())}return branches.length===1?branches[0]:{kind:"alt",branches}}sequence(){const items=[];while(!this.eof()&&this.peek()!=="|"&&this.peek()!==")")items.push(this.quantified());return{kind:"seq",items}}quantified(){let node=this.atom();for(;;){const c3=this.peek();let min,max;if(c3==="*"){min=0;max=Infinity}else if(c3==="+"){min=1;max=Infinity}else if(c3==="?"){min=0;max=1}else if(c3==="{"){const m2=/^\{(\d+)(?:,(\d*))?\}/.exec(this.src.slice(this.i));if(!m2)break;min=parseInt(m2[1],10);max=m2[2]===void 0?min:m2[2]===""?Infinity:parseInt(m2[2],10);if(max<min)refuse(`quantifier {${min},${max}} is inverted`);this.i+=m2[0].length-1}else break;this.next();if(this.peek()==="?")this.next();node={kind:"quant",body:node,min,max}}return node}atom(){const c3=this.next();if(c3==="("){if(this.peek()==="?"){const ahead=this.src.slice(this.i,this.i+3);if(/^\?(:|<[a-zA-Z_])/.test(ahead)){this.next();if(this.peek()==="<"){while(this.next()!==">"){if(this.eof())refuse("unterminated group name")}}else this.next()}else{refuse("lookarounds and special groups are outside the profile's safe subset")}}const body=this.alternation();if(this.next()!==")")refuse("unterminated group");return body}if(c3==="[")return{kind:"atom",set:this.charClass()};if(c3===".")return{kind:"atom",set:FULL};if(c3==="^")return{kind:"anchor",at:"start"};if(c3==="$")return{kind:"anchor",at:"end"};if(c3==="\\")return{kind:"atom",set:this.escape(false)};if(c3===")"||c3===void 0)refuse("unbalanced group");return{kind:"atom",set:single(this.codePoint())}}codePoint(){const cp=this.src.codePointAt(this.i-1);if(cp>65535)this.i++;return cp}charClass(){let neg=false;if(this.peek()==="^"){this.next();neg=true}const ranges=[];let approx=false;while(this.peek()!=="]"){if(this.eof())refuse("unterminated character class");let lo;const c3=this.next();if(c3==="\\"){if(this.peek()==="b"){this.next();lo=8}else{const s3=this.escape(true);if(s3.neg||s3.ranges.length!==1||s3.ranges[0][0]!==s3.ranges[0][1]){approx=true;for(const r2 of s3.neg?[[0,1114111]]:s3.ranges)ranges.push(r2)}else lo=s3.ranges[0][0]}}else lo=this.codePoint();if(lo!==void 0){if(this.peek()==="-"&&this.src[this.i+1]!=="]"&&this.src[this.i+1]!==void 0){this.next();const hiC=this.next();const hi2=hiC==="\\"?(()=>{const s3=this.escape(true);if(s3.neg||s3.ranges.length!==1){approx=true;return 1114111}return s3.ranges[0][0]})():this.codePoint();ranges.push([lo,hi2])}else ranges.push([lo,lo])}}this.next();if(neg&&approx)return FULL;return{neg,ranges}}escape(inClass){const c3=this.next();if(c3===void 0)refuse("dangling escape");if(!inClass&&c3>="1"&&c3<="9")refuse(`backreference \\${c3} is outside the profile's safe subset`);if(c3==="k")refuse("named backreferences are outside the profile's safe subset");if(c3==="b"||c3==="B")return EMPTY;switch(c3){case"d":return set([48,57]);case"D":return{neg:true,ranges:[[48,57]]};case"w":return set([48,57],[65,90],[95,95],[97,122]);case"W":return{neg:true,ranges:[[48,57],[65,90],[95,95],[97,122]]};case"s":return set([9,13],[32,32],[160,160],[8232,8233]);case"S":return{neg:true,ranges:[[9,13],[32,32],[160,160],[8232,8233]]};case"n":return single(10);case"r":return single(13);case"t":return single(9);case"f":return single(12);case"v":return single(11);case"0":return single(0);case"x":{const m2=/^[0-9a-fA-F]{2}/.exec(this.src.slice(this.i));if(!m2)refuse("malformed \\x escape");this.i+=2;return single(parseInt(m2[0],16))}case"u":{const braced=/^\{([0-9a-fA-F]{1,6})\}/.exec(this.src.slice(this.i));if(braced){this.i+=braced[0].length;const cp2=parseInt(braced[1],16);if(cp2>=55296&&cp2<=57343)refuse("surrogate code point escapes are outside the safe subset");return single(cp2)}const m2=/^[0-9a-fA-F]{4}/.exec(this.src.slice(this.i));if(!m2)refuse("malformed \\u escape");this.i+=4;const cp=parseInt(m2[0],16);if(cp>=55296&&cp<=57343)refuse("surrogate escapes are outside the safe subset (write the character or \\u{\u2026})");return single(cp)}case"p":case"P":{const m2=/^\{[^}]*\}/.exec(this.src.slice(this.i));if(!m2)refuse("malformed \\p escape");this.i+=m2[0].length;return FULL}default:if(/[A-Za-z0-9]/.test(c3))refuse(`escape \\${c3} is outside the profile's safe subset`);return single(c3.codePointAt(0))}}};CHOICE_BUDGET=64;CHOICE_SAT=1<<20;mulSat=(a3,b3)=>Math.min(a3*b3,CHOICE_SAT)}});function singleDocumentClosure(root){const manifest=buildContractClosureManifest(contractDigest(root),[]);return{manifest,closureDigest:contractDigest(manifest)}}function canonicalOrInvalid(v3,label){try{return canonicalJson(v3)}catch(e3){throw new ContractInvalidError(`${label}: ${e3.message}`)}}function digestOrInvalid(v3,label){try{return contractDigest(v3)}catch(e3){throw new ContractInvalidError(`${label}: ${e3.message}`)}}function structuralDepth(v3,depth=0){if(depth>SCHEMA_PROFILE.maxDepth)return depth;if(v3===null||typeof v3!=="object")return depth;let max=depth;const children=Array.isArray(v3)?v3:Object.values(v3);for(const c3 of children){const d2=structuralDepth(c3,depth+1);if(d2>max)max=d2;if(max>SCHEMA_PROFILE.maxDepth)return max}return max}function assertBoundedPattern(p2,label,where){try{assertSafePattern(p2,SCHEMA_PROFILE.maxPatternChars)}catch(e3){throw new ContractInvalidError(`${label}: ${where} refused: ${e3.message}`)}}function collectRefs(v3,label,out=[]){if(v3===null||typeof v3!=="object")return out;if(Array.isArray(v3)){for(const c3 of v3)collectRefs(c3,label,out);return out}for(const[k2,c3]of Object.entries(v3)){if((k2==="$ref"||k2==="$dynamicRef")&&typeof c3==="string")out.push(c3);if(k2==="pattern"&&typeof c3==="string")assertBoundedPattern(c3,label,"a pattern");if(k2==="patternProperties"&&c3!==null&&typeof c3==="object"&&!Array.isArray(c3)){for(const p2 of Object.keys(c3))assertBoundedPattern(p2,label,"a patternProperties key")}collectRefs(c3,label,out)}return out}function assertAdmittedVocabulary(doc,label){const atSchema=(d2,path4)=>{if(typeof d2==="boolean")return;if(d2===null||typeof d2!=="object"||Array.isArray(d2))return;for(const[k2,v3]of Object.entries(d2)){if(!ADMITTED.has(k2))throw new ContractInvalidError(`${label}: keyword ${JSON.stringify(k2)} at ${path4||"/"} is not in the profile's admitted vocabulary; an unrecognised keyword is REFUSED rather than ignored, because this profile cannot count what it does not recognise`);const here=`${path4}/${k2}`;if(SCHEMA_VALUED_KEYS.includes(k2))atSchema(v3,here);else if(SCHEMA_VALUED_MAP_KEYS.includes(k2)&&v3&&typeof v3==="object"&&!Array.isArray(v3))for(const[name2,sub]of Object.entries(v3))atSchema(sub,`${here}/${name2}`);else if(SCHEMA_VALUED_LIST_KEYS.includes(k2)&&Array.isArray(v3))v3.forEach((sub,i2)=>atSchema(sub,`${here}/${i2}`))}};atSchema(doc,"")}function assertDocumentProfile(doc,label){const canonical=canonicalOrInvalid(doc,label);const bytes=Buffer.byteLength(canonical,"utf8");if(bytes>SCHEMA_PROFILE.maxDocumentBytes)throw new ContractInvalidError(`${label}: document is ${bytes} bytes (profile max ${SCHEMA_PROFILE.maxDocumentBytes})`);if(structuralDepth(doc)>SCHEMA_PROFILE.maxDepth)throw new ContractInvalidError(`${label}: nesting exceeds profile depth ${SCHEMA_PROFILE.maxDepth}`);assertAdmittedVocabulary(doc,label);const storeRefs=[];for(const ref of collectRefs(doc,label)){if(ref.startsWith("#"))continue;const m2=STORE_REF.exec(ref);if(!m2)throw new ContractInvalidError(`${label}: external $ref ${JSON.stringify(ref)}; only local '#\u2026' or digest-pinned 'cotal:sha256:<hex>' references are permitted (no ambient resolution)`);storeRefs.push(m2[1])}return storeRefs}function makeCompiled(validate2,closureDigest){const compiled=Object.freeze({validate:validate2,closureDigest});COMPILED.add(compiled);return compiled}function isCompiledContract(c3){return typeof c3==="object"&&c3!==null&&COMPILED.has(c3)}function assertCompiledContract(c3,what2){if(!isCompiledContract(c3))throw new ContractInvalidError(`${what2} is not a profile-compiled contract (schema-profile compileContract); a structural {validate, closureDigest} pair carries no compile provenance and is refused (SPEC 13.7)`);return c3}function assertClosureProfile(bundle){const members=bundle.members??{};for(const d2 of Object.keys(members)){if(!isContractDigest(d2))throw new ContractInvalidError(`bundle member key ${JSON.stringify(d2)} is not a sha256 digest`)}const seen=new Set;let closureBytes=0;let frontier=assertDocumentProfile(bundle.root,"root schema");closureBytes+=Buffer.byteLength(canonicalOrInvalid(bundle.root,"root schema"),"utf8");for(let chain=0;frontier.length>0;chain++){if(chain>=SCHEMA_PROFILE.maxRefChain)throw new ContractInvalidError(`reference chain exceeds profile depth ${SCHEMA_PROFILE.maxRefChain}`);const next=[];for(const digest of frontier){if(seen.has(digest))continue;seen.add(digest);const member=members[digest];if(member===void 0)throw new ContractInvalidError(`unresolved digest reference ${digest}: not present in the bundle (schemas are closed; nothing is fetched)`);if(digestOrInvalid(member,`member ${digest}`)!==digest)throw new ContractInvalidError(`bundle member under ${digest} does not hash to its key (content is ${digestOrInvalid(member,`member ${digest}`)})`);closureBytes+=Buffer.byteLength(canonicalOrInvalid(member,`member ${digest}`),"utf8");if(closureBytes>SCHEMA_PROFILE.maxClosureBytes)throw new ContractInvalidError(`closure is ${closureBytes} bytes (profile max ${SCHEMA_PROFILE.maxClosureBytes})`);next.push(...assertDocumentProfile(member,`member ${digest}`))}frontier=next}const extras=Object.keys(members).filter(d2=>!seen.has(d2));if(extras.length>0)throw new ContractInvalidError(`bundle carries ${extras.length} member(s) unreachable from the root (${extras.slice(0,3).join(", ")}${extras.length>3?", \u2026":""})`);return contractDigest(buildContractClosureManifest(digestOrInvalid(bundle.root,"root schema"),[...seen]))}function compileWithinBudget(bundle){try{const meta3=new ProfileAjv(AJV_PROFILE_OPTIONS);for(const[digest,member]of Object.entries(bundle.members??{}))meta3.addSchema(member,`cotal:${digest}`);meta3.addSchema(bundle.root);return prepareContractValidator(bundle)}catch(error51){throw new ContractInvalidError(`schema does not compile under the 2020-12 profile: ${error51.message}`)}}function compileContract(bundle){const closureDigest=assertClosureProfile(bundle);return makeCompiled(compileWithinBudget(bundle),closureDigest)}function compileContractSchema(bundle){return compileContract(bundle).validate}function serviceContractTable(rows){const contracts=Object.create(null);for(const row of rows){let pair2;Object.defineProperty(contracts,row.name,{enumerable:true,get:()=>{if(!pair2){pair2=Object.freeze({input:compileContract({root:row.input}),output:compileContract({root:row.output})})}return pair2}})}return{contracts:Object.freeze(contracts),artifactValues:()=>{const values=[];const seen=new Set;for(const r2 of rows){for(const source of[r2.input,r2.output]){const{manifest}=singleDocumentClosure(source);if(seen.has(manifest.root))continue;seen.add(manifest.root);values.push(source,manifest)}}return values}}}var import__,AJV_PROFILE_OPTIONS,sharedMeta,ProfileAjv,VOID_SCHEMA,VOID_SCHEMA_ARTIFACT_DIGEST,VOID_SCHEMA_DIGEST,STORE_REF,ContractInvalidError,SCHEMA_VALUED_KEYS,SCHEMA_VALUED_MAP_KEYS,SCHEMA_VALUED_LIST_KEYS,SCALAR_KEYS,ADMITTED,COMPILED;var init_schema_profile=__esm({"../../packages/core/dist/schema-profile.js"(){"use strict";import__=__toESM(require__(),1);init_contract_validator();init_schema_bounds();init_canonical();init_safe_pattern();init_contract_manifest();AJV_PROFILE_OPTIONS=Object.freeze({strict:false,allErrors:true,ownProperties:true,validateFormats:false,loadSchema:void 0,validateSchema:true,meta:true,unicodeRegExp:true,inlineRefs:false});ProfileAjv=class extends import__.Ajv2020{validateSchema(schema,throwOrLogError){if(schema===null||typeof schema!=="object")return super.validateSchema(schema,throwOrLogError);if(!sharedMeta){const ajv2=new import__.Ajv2020(AJV_PROFILE_OPTIONS);sharedMeta={ajv:ajv2,keys:new Set([...Object.keys(ajv2.schemas),...Object.keys(ajv2.refs)])}}if(schema.$schema!==void 0&&!sharedMeta.keys.has(schema.$schema))return super.validateSchema(schema,throwOrLogError);try{return sharedMeta.ajv.validateSchema(schema,throwOrLogError)}finally{this.errors=sharedMeta.ajv.errors}}};VOID_SCHEMA=Object.freeze({type:"null"});VOID_SCHEMA_ARTIFACT_DIGEST=contractDigest(VOID_SCHEMA);VOID_SCHEMA_DIGEST=singleDocumentClosure(VOID_SCHEMA).closureDigest;STORE_REF=/^cotal:(sha256:[0-9a-f]{64})(#.*)?$/;ContractInvalidError=class extends Error{code="contract-invalid";constructor(message){super(message);this.name="ContractInvalidError"}};SCHEMA_VALUED_KEYS=["not","if","then","else","items","contains","additionalProperties","propertyNames","unevaluatedItems","unevaluatedProperties","contentSchema","additionalItems"];SCHEMA_VALUED_MAP_KEYS=["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"];SCHEMA_VALUED_LIST_KEYS=["allOf","anyOf","oneOf","prefixItems"];SCALAR_KEYS=["type","enum","const","multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","maxItems","minItems","uniqueItems","maxContains","minContains","maxProperties","minProperties","required","dependentRequired","format","contentEncoding","contentMediaType","title","description","default","deprecated","readOnly","writeOnly","examples","$comment","$id","$schema","$ref","$anchor","$dynamicRef","$dynamicAnchor","$vocabulary"];ADMITTED=new Set([...SCHEMA_VALUED_KEYS,...SCHEMA_VALUED_MAP_KEYS,...SCHEMA_VALUED_LIST_KEYS,...SCALAR_KEYS]);COMPILED=new WeakSet}});function invalid(what2){throw new ContractInvalidError(`cluster document does not validate: ${what2}`)}function buildClusterDocument(urn,revision,rows){return{urn,revision,attributes:[],events:[],commands:rows.map(r2=>({name:r2.name,class:"ephemeral",targeted:r2.targeted,...r2.modes?{modes:[...r2.modes]}:{},...r2.authorities?{authorities:[...r2.authorities]}:{},capability:r2.capability,inputDigest:singleDocumentClosure(r2.input).closureDigest,outputDigest:singleDocumentClosure(r2.output).closureDigest}))}}function parseClusterDocument(raw){const o3=isRec(raw)?raw:invalid("not an object");if(typeof o3.urn!=="string"||!URN.test(o3.urn))invalid(`urn ${JSON.stringify(o3.urn)} is not a reverse-DNS cluster type URN`);if(typeof o3.revision!=="number"||!Number.isSafeInteger(o3.revision)||o3.revision<0)invalid("revision is not an unsigned integer");if(!Array.isArray(o3.attributes))invalid("attributes is not an array");if(!Array.isArray(o3.events))invalid("events is not an array");if(!Array.isArray(o3.commands)||o3.commands.length===0)invalid("commands must be a non-empty array");const seen=new Set;const commands=o3.commands.map((c3,i2)=>{const cmd=isRec(c3)?c3:invalid(`commands[${i2}] is not an object`);const name2=typeof cmd.name==="string"?cmd.name:invalid(`commands[${i2}].name is not a string`);try{assertCommandToken(name2)}catch(e3){invalid(`commands[${i2}].name: ${e3.message}`)}if(name2==="describe")invalid(`commands[${i2}] declares "describe": reserved, served by the machinery, never a cluster command (SPEC 13.7)`);if(seen.has(name2))invalid(`command "${name2}" is declared twice`);seen.add(name2);if(cmd.class!=="ephemeral"&&cmd.class!=="journal")invalid(`command "${name2}" class ${JSON.stringify(cmd.class)} is not "ephemeral" | "journal"`);if(typeof cmd.targeted!=="boolean")invalid(`command "${name2}" must declare targeted as a boolean (SPEC 13.7)`);let authorities;if(cmd.authorities!==void 0){if(cmd.targeted!==false)invalid(`command "${name2}" declares authorities and targeted: true; a principal-route command is untargeted, its subject head is the target (SPEC 13.21)`);if(cmd.modes!==void 0)invalid(`command "${name2}" declares authorities beside authorization modes; the two belong to different routes (SPEC 13.21)`);if(!Array.isArray(cmd.authorities)||cmd.authorities.length===0)invalid(`command "${name2}" authorities must be a non-empty array of authority words (SPEC 13.21)`);const uniq=new Set;for(const w2 of cmd.authorities){if(typeof w2!=="string"||!isPrincipalAuthority(w2))invalid(`command "${name2}" admits unknown authority ${JSON.stringify(w2)}`);if(uniq.has(w2))invalid(`command "${name2}" admits authority "${w2}" twice`);uniq.add(w2)}authorities=[...cmd.authorities]}let modes;if(cmd.targeted){if(!Array.isArray(cmd.modes)||cmd.modes.length===0)invalid(`targeted command "${name2}" must declare its admitted authorization modes (SPEC 13.7)`);const uniq=new Set;for(const m2 of cmd.modes){if(typeof m2!=="string"||!isEpAuthzMode(m2))invalid(`command "${name2}" admits unknown mode ${JSON.stringify(m2)}`);if(uniq.has(m2))invalid(`command "${name2}" admits mode "${m2}" twice`);uniq.add(m2)}modes=[...cmd.modes]}else if(cmd.modes!==void 0){invalid(`untargeted command "${name2}" must not declare authorization modes`)}if(typeof cmd.capability!=="string"||!CAPABILITY.test(cmd.capability))invalid(`command "${name2}" capability is not a bounded capability token`);if(!isContractDigest(cmd.inputDigest))invalid(`command "${name2}" inputDigest is not a sha256 closure digest`);if(!isContractDigest(cmd.outputDigest))invalid(`command "${name2}" outputDigest is not a sha256 closure digest`);let traits;if(cmd.traits!==void 0){if(!Array.isArray(cmd.traits))invalid(`command "${name2}" traits is not an array`);const tSeen=new Set;for(const t2 of cmd.traits){if(typeof t2!=="string"||!URN.test(t2))invalid(`command "${name2}" trait ${JSON.stringify(t2)} is not a reverse-DNS trait URN (SPEC 13.7)`);if(tSeen.has(t2))invalid(`command "${name2}" declares trait "${t2}" twice`);tSeen.add(t2)}traits=[...cmd.traits]}let action;if(cmd.action!==void 0){if(cmd.action!==true)invalid(`command "${name2}" action ${JSON.stringify(cmd.action)} is not true (the action composite is present or absent; "false" is a second way to say absent)`);if(cmd.class!=="journal")invalid(`command "${name2}" declares the action composite but class "${cmd.class}": an action command's submissions are journal-class (SPEC 13.7)`);action=true}let admissionCeiling;if(cmd.class==="journal"){const ceil=isRec(cmd.admissionCeiling)?cmd.admissionCeiling:invalid(`journal-class command "${name2}" must declare admissionCeiling {maxBytes, maxDepth, maxItems}: the canonicalizer reads its ceilings from the digest-verified surface, never from a constant`);const nums={};for(const f2 of["maxBytes","maxDepth","maxItems"]){const v3=ceil[f2];if(typeof v3!=="number"||!Number.isSafeInteger(v3)||v3<=0)invalid(`command "${name2}" admissionCeiling.${f2} ${JSON.stringify(v3)} is not a positive safe integer`);nums[f2]=v3}admissionCeiling={maxBytes:nums.maxBytes,maxDepth:nums.maxDepth,maxItems:nums.maxItems}}else if(cmd.admissionCeiling!==void 0){invalid(`ephemeral command "${name2}" declares admissionCeiling: an ephemeral command receives no journal submissions, so a ceiling on it is unreadable by anything`)}let readinessDeadlineMs;if(cmd.readinessDeadlineMs!==void 0){if(!action)invalid(`command "${name2}" declares readinessDeadlineMs without the action composite: readiness is goal state and only an action command has a goal`);if(typeof cmd.readinessDeadlineMs!=="number"||!Number.isSafeInteger(cmd.readinessDeadlineMs)||cmd.readinessDeadlineMs<0)invalid(`command "${name2}" readinessDeadlineMs ${JSON.stringify(cmd.readinessDeadlineMs)} is not a non-negative safe integer (SPEC 13.11)`);readinessDeadlineMs=cmd.readinessDeadlineMs}return{name:name2,class:cmd.class,targeted:cmd.targeted,...modes?{modes}:{},...authorities?{authorities}:{},capability:cmd.capability,inputDigest:cmd.inputDigest,outputDigest:cmd.outputDigest,...traits?{traits}:{},...action?{action}:{},...admissionCeiling?{admissionCeiling}:{},...readinessDeadlineMs!==void 0?{readinessDeadlineMs}:{}}});return{urn:o3.urn,revision:o3.revision,attributes:[...o3.attributes],commands,events:[...o3.events]}}var isRec,URN,TRAIT_GUARDED,TRAIT_PRICED,GOVERNED_TRAIT_URNS,CAPABILITY;var init_endpoint_cluster=__esm({"../../packages/core/dist/endpoint-cluster.js"(){"use strict";init_canonical();init_contract_manifest();init_schema_profile();init_endpoint_subjects();isRec=v3=>v3!==null&&typeof v3==="object"&&!Array.isArray(v3);URN=/^[a-z0-9][a-z0-9-]{0,62}(\.[a-z0-9][a-z0-9-]{0,62}){1,15}$/;TRAIT_GUARDED="ai.cotal.guarded";TRAIT_PRICED="ai.cotal.priced";GOVERNED_TRAIT_URNS=Object.freeze([TRAIT_GUARDED,TRAIT_PRICED]);CAPABILITY=/^[a-z][a-z0-9._-]{0,63}$/}});function isAgentCommandName(name2){return typeof name2==="string"&&COMMAND_NAME_RE.test(name2)}function agentPromptDigest(content){return contractDigest(content)}function deepFreeze(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))deepFreeze(child);Object.freeze(value)}return value}var AGENT_ENDPOINT,AGENT_CLUSTER_URN,AGENT_CLUSTER_REVISION,AGENT_CMD_PROMPTS,AGENT_CMD_PROMPT,AGENT_CMD_PROMPT_ANSWER,AGENT_CMD_COMMANDS,AGENT_CMD_COMMAND,AGENT_CMD_COMMAND_CANCEL,AGENT_CMD_COMMAND_STATE,AGENT_PROMPT_CONTENT_MAX_BYTES,AGENT_PROMPT_LIST_MAX,AGENT_PROMPT_OPTIONS_MAX,AGENT_COMMAND_LIST_MAX,AGENT_COMMAND_DESCRIPTION_MAX,AGENT_COMMAND_INPUT_HINT_MAX,AGENT_COMMAND_MESSAGE_MAX,AGENT_PROMPT_STATE_DETAIL,AGENT_PROMPT_DIGEST_DETAIL,AGENT_PROMPT_SIZE_DETAIL,AGENT_COMMAND_STATE_DETAIL,COMMAND_NAME_PATTERN,COMMAND_NAME_RE,closed2,text,anyString,uint,TIMESTAMP,PROMPT_ID,DIGEST,OPTION_ID,REVERSE_DNS,EFFECT,KIND,TITLE,ANSWERER,ANSWER_REF,SEEN,OUTCOME,OPEN_STATE,SENT_STATE,CLOSED_STATE,LIVE_STATE,STATE,SOURCE,ANNOTATIONS,CHOICE,STRINGS,FORM_PROPERTY,FORM_SCHEMA,INPUT,SUBJECT,OPTION,CONTENT,summary,PROMPT,VALUES,AGENT_PROMPTS_INPUT_SCHEMA,AGENT_PROMPTS_OUTPUT_SCHEMA,AGENT_PROMPT_INPUT_SCHEMA,AGENT_PROMPT_OUTPUT_SCHEMA,AGENT_PROMPT_ANSWER_INPUT_SCHEMA,AGENT_PROMPT_ANSWER_OUTPUT_SCHEMA,COMMAND_NAME,TARGET,ENTRY,AGENT_COMMANDS_INPUT_SCHEMA,AGENT_COMMANDS_OUTPUT_SCHEMA,COMMAND_ID,COMMAND_MESSAGE,COMMAND_STATE,AGENT_COMMAND_INPUT_SCHEMA,AGENT_COMMAND_OUTPUT_SCHEMA,AGENT_COMMAND_CANCEL_INPUT_SCHEMA,AGENT_COMMAND_CANCEL_OUTPUT_SCHEMA,AGENT_COMMAND_STATE_INPUT_SCHEMA,AGENT_COMMAND_STATE_OUTPUT_SCHEMA,AGENT_COMMANDS,TABLE,AGENT_CONTRACTS,AGENT_CLUSTER;var init_agent_endpoint=__esm({"../../packages/core/dist/agent-endpoint.js"(){"use strict";init_canonical();init_endpoint_cluster();init_schema_profile();AGENT_ENDPOINT="agent";AGENT_CLUSTER_URN="ai.cotal.agent";AGENT_CLUSTER_REVISION=2;AGENT_CMD_PROMPTS="prompts";AGENT_CMD_PROMPT="prompt";AGENT_CMD_PROMPT_ANSWER="prompt-answer";AGENT_CMD_COMMANDS="commands";AGENT_CMD_COMMAND="command";AGENT_CMD_COMMAND_CANCEL="command-cancel";AGENT_CMD_COMMAND_STATE="command-state";AGENT_PROMPT_CONTENT_MAX_BYTES=262144;AGENT_PROMPT_LIST_MAX=32;AGENT_PROMPT_OPTIONS_MAX=16;AGENT_COMMAND_LIST_MAX=512;AGENT_COMMAND_DESCRIPTION_MAX=1024;AGENT_COMMAND_INPUT_HINT_MAX=256;AGENT_COMMAND_MESSAGE_MAX=2048;AGENT_PROMPT_STATE_DETAIL="ai.cotal.agent.prompt-state";AGENT_PROMPT_DIGEST_DETAIL="ai.cotal.agent.prompt-digest";AGENT_PROMPT_SIZE_DETAIL="ai.cotal.agent.prompt-size";AGENT_COMMAND_STATE_DETAIL="ai.cotal.agent.command-state";COMMAND_NAME_PATTERN="^[^\\s\\p{C}]{1,128}$";COMMAND_NAME_RE=new RegExp(COMMAND_NAME_PATTERN,"u");closed2=(required2,properties)=>({type:"object",additionalProperties:false,...required2.length?{required:required2}:{},properties});text=max=>({type:"string",minLength:1,maxLength:max});anyString={type:"string"};uint={type:"integer",minimum:0,maximum:Number.MAX_SAFE_INTEGER};TIMESTAMP={type:"string",pattern:"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$"};PROMPT_ID={type:"string",pattern:"^[a-z2-7]{26}$"};DIGEST={type:"string",pattern:"^sha256:[0-9a-f]{64}$"};OPTION_ID={type:"string",pattern:"^[a-z0-9-]{1,32}$"};REVERSE_DNS={type:"string",maxLength:64,pattern:"^[a-z0-9-]{1,63}\\.[a-z0-9.-]{1,63}$"};EFFECT={enum:["proceed","refuse","cancel"]};KIND={anyOf:[{enum:["permission","question","plan","form"]},REVERSE_DNS]};TITLE={type:"string",minLength:1,maxLength:200,pattern:"^[^\\r\\n]*$"};ANSWERER=closed2(["id","uid","authority"],{id:{type:"string",pattern:"^[A-Za-z0-9_]{1,64}\\.[A-Za-z0-9_]{1,64}$"},uid:{type:"string",pattern:"^[a-z0-9]{26,32}$"},authority:{enum:["owner","grant"]}});ANSWER_REF=closed2(["by","option","effect","at"],{by:ANSWERER,option:OPTION_ID,effect:EFFECT,at:TIMESTAMP});SEEN={oneOf:[closed2(["tie","effect"],{tie:{const:"prompt"},effect:EFFECT}),closed2(["tie","effect"],{tie:{const:"subject"},effect:EFFECT}),closed2(["tie"],{tie:{const:"none"}})]};OUTCOME={oneOf:[closed2(["kind","answer"],{kind:{const:"answered"},answer:ANSWER_REF}),closed2(["kind","answer","seen"],{kind:{const:"unconfirmed"},answer:ANSWER_REF,seen:SEEN}),closed2(["kind","answer"],{kind:{const:"undelivered"},answer:ANSWER_REF}),closed2(["kind","seen"],{kind:{const:"local"},seen:SEEN,late:ANSWER_REF}),closed2(["kind","seen"],{kind:{const:"withdrawn"},seen:SEEN}),closed2(["kind"],{kind:{const:"expired"}})]};OPEN_STATE=closed2(["kind"],{kind:{const:"open"}});SENT_STATE=closed2(["kind","answer","delivery"],{kind:{const:"sent"},answer:ANSWER_REF,delivery:{enum:["unconfirmed","delivered"]}});CLOSED_STATE=closed2(["kind","at","outcome"],{kind:{const:"closed"},at:TIMESTAMP,outcome:OUTCOME});LIVE_STATE={oneOf:[OPEN_STATE,SENT_STATE]};STATE={oneOf:[OPEN_STATE,SENT_STATE,CLOSED_STATE]};SOURCE=closed2(["harness"],{harness:text(128),scope:text(128),toolCallId:text(128)});ANNOTATIONS={title:anyString,description:anyString};CHOICE=closed2(["const","title"],{const:anyString,title:anyString,description:anyString});STRINGS={type:"array",minItems:1,items:anyString};FORM_PROPERTY={anyOf:[closed2(["type"],{type:{const:"string"},...ANNOTATIONS,minLength:uint,maxLength:uint,format:{enum:["email","uri","date","date-time"]},default:anyString}),closed2(["type"],{type:{enum:["number","integer"]},...ANNOTATIONS,minimum:{type:"number"},maximum:{type:"number"},default:{type:"number"}}),closed2(["type"],{type:{const:"boolean"},...ANNOTATIONS,default:{type:"boolean"}}),closed2(["type","enum"],{type:{const:"string"},...ANNOTATIONS,enum:STRINGS,default:anyString}),closed2(["type","oneOf"],{type:{const:"string"},...ANNOTATIONS,oneOf:{type:"array",minItems:1,items:CHOICE},default:anyString}),closed2(["type","items"],{type:{const:"array"},...ANNOTATIONS,minItems:uint,maxItems:uint,items:{oneOf:[closed2(["type","enum"],{type:{const:"string"},enum:STRINGS}),closed2(["anyOf"],{anyOf:{type:"array",minItems:1,items:CHOICE}})]},default:{type:"array",items:anyString}})]};FORM_SCHEMA=closed2(["type","properties"],{type:{const:"object"},properties:{type:"object",additionalProperties:FORM_PROPERTY},required:{type:"array",items:anyString}});INPUT={oneOf:[closed2(["kind","value"],{kind:{const:"shown"},value:{}}),closed2(["kind","bytes"],{kind:{const:"omitted"},bytes:uint})]};SUBJECT={oneOf:[closed2(["type","name","input"],{type:{const:"tool"},name:{type:"string",minLength:1},input:INPUT,cwd:anyString,server:anyString}),closed2(["type","url"],{type:{const:"url"},url:{type:"string",minLength:1}}),closed2(["type","data"],{type:REVERSE_DNS,data:{}})]};OPTION=closed2(["id","label","effect"],{id:OPTION_ID,label:text(80),effect:EFFECT,description:text(500),persists:text(500),note:{enum:["optional","required"]},form:{const:"required"}});CONTENT=closed2(["kind","title","options"],{kind:KIND,title:TITLE,body:closed2(["format","text"],{format:{enum:["text","markdown"]},text:anyString}),subject:SUBJECT,options:{type:"array",minItems:1,maxItems:AGENT_PROMPT_OPTIONS_MAX,items:OPTION},form:closed2(["schema"],{schema:FORM_SCHEMA}),source:SOURCE});summary=state=>closed2(["id","digest","openedAt","expiresAt","state","kind","title","contentBytes"],{id:PROMPT_ID,digest:DIGEST,openedAt:TIMESTAMP,expiresAt:TIMESTAMP,state,kind:KIND,title:TITLE,contentBytes:{type:"integer",minimum:0,maximum:AGENT_PROMPT_CONTENT_MAX_BYTES},source:SOURCE});PROMPT=closed2(["id","digest","openedAt","expiresAt","state","content"],{id:PROMPT_ID,digest:DIGEST,openedAt:TIMESTAMP,expiresAt:TIMESTAMP,state:LIVE_STATE,content:CONTENT});VALUES={type:"object",additionalProperties:{anyOf:[anyString,{type:"number"},{type:"boolean"},{type:"array",items:anyString}]}};AGENT_PROMPTS_INPUT_SCHEMA=deepFreeze(closed2([],{}));AGENT_PROMPTS_OUTPUT_SCHEMA=deepFreeze(closed2(["runtime","seq","open","closed"],{runtime:closed2(["id","startedAt"],{id:{type:"string",pattern:"^[A-Za-z0-9_-]{1,64}$"},startedAt:uint}),seq:uint,open:{type:"array",maxItems:AGENT_PROMPT_LIST_MAX,items:summary(LIVE_STATE)},closed:{type:"array",maxItems:AGENT_PROMPT_LIST_MAX,items:summary(CLOSED_STATE)}}));AGENT_PROMPT_INPUT_SCHEMA=deepFreeze(closed2(["id"],{id:PROMPT_ID}));AGENT_PROMPT_OUTPUT_SCHEMA=deepFreeze(closed2(["prompt"],{prompt:PROMPT}));AGENT_PROMPT_ANSWER_INPUT_SCHEMA=deepFreeze(closed2(["id","digest","option"],{id:PROMPT_ID,digest:DIGEST,option:OPTION_ID,note:{type:"string",maxLength:2e3},values:VALUES}));AGENT_PROMPT_ANSWER_OUTPUT_SCHEMA=deepFreeze(closed2(["state"],{state:STATE}));COMMAND_NAME={type:"string",pattern:COMMAND_NAME_PATTERN};TARGET={enum:["command","skill"]};ENTRY=closed2(["name","target"],{name:COMMAND_NAME,target:TARGET,description:text(AGENT_COMMAND_DESCRIPTION_MAX),inputHint:text(AGENT_COMMAND_INPUT_HINT_MAX)});AGENT_COMMANDS_INPUT_SCHEMA=deepFreeze(closed2([],{}));AGENT_COMMANDS_OUTPUT_SCHEMA=deepFreeze({oneOf:[closed2(["supported"],{supported:{const:false}}),closed2(["supported","commands"],{supported:{const:true},commands:{type:"array",maxItems:AGENT_COMMAND_LIST_MAX,items:ENTRY}})]});COMMAND_ID={type:"string",pattern:"^[a-z2-7]{26}$"};COMMAND_MESSAGE={type:"string",maxLength:AGENT_COMMAND_MESSAGE_MAX};COMMAND_STATE={oneOf:[closed2(["kind"],{kind:{const:"queued"}}),closed2(["kind"],{kind:{const:"taken"}}),closed2(["kind"],{kind:{const:"started"}}),closed2(["kind"],{kind:{const:"cancelled"}}),closed2(["kind","code","message"],{kind:{const:"refused"},code:{enum:["not-found","failed-precondition","unavailable"]},message:COMMAND_MESSAGE}),closed2(["kind","code","message"],{kind:{const:"unknown"},code:{const:"internal"},message:COMMAND_MESSAGE})]};AGENT_COMMAND_INPUT_SCHEMA=deepFreeze(closed2(["target","name"],{target:TARGET,name:COMMAND_NAME,args:anyString}));AGENT_COMMAND_OUTPUT_SCHEMA=deepFreeze(closed2(["id"],{id:COMMAND_ID}));AGENT_COMMAND_CANCEL_INPUT_SCHEMA=deepFreeze(closed2(["id"],{id:COMMAND_ID}));AGENT_COMMAND_CANCEL_OUTPUT_SCHEMA=deepFreeze(closed2(["state"],{state:COMMAND_STATE}));AGENT_COMMAND_STATE_INPUT_SCHEMA=deepFreeze(closed2(["id"],{id:COMMAND_ID}));AGENT_COMMAND_STATE_OUTPUT_SCHEMA=deepFreeze(closed2(["state"],{state:COMMAND_STATE}));AGENT_COMMANDS=deepFreeze([{name:AGENT_CMD_PROMPTS,capability:"agent.prompts.read",authorities:["owner","grant"],input:AGENT_PROMPTS_INPUT_SCHEMA,output:AGENT_PROMPTS_OUTPUT_SCHEMA},{name:AGENT_CMD_PROMPT,capability:"agent.prompts.read",authorities:["owner","grant"],input:AGENT_PROMPT_INPUT_SCHEMA,output:AGENT_PROMPT_OUTPUT_SCHEMA},{name:AGENT_CMD_PROMPT_ANSWER,capability:"agent.prompts.answer",authorities:["owner","grant"],input:AGENT_PROMPT_ANSWER_INPUT_SCHEMA,output:AGENT_PROMPT_ANSWER_OUTPUT_SCHEMA},{name:AGENT_CMD_COMMANDS,capability:"agent.commands.read",authorities:["owner"],input:AGENT_COMMANDS_INPUT_SCHEMA,output:AGENT_COMMANDS_OUTPUT_SCHEMA},{name:AGENT_CMD_COMMAND,capability:"agent.commands.run",authorities:["owner"],input:AGENT_COMMAND_INPUT_SCHEMA,output:AGENT_COMMAND_OUTPUT_SCHEMA},{name:AGENT_CMD_COMMAND_CANCEL,capability:"agent.commands.run",authorities:["owner"],input:AGENT_COMMAND_CANCEL_INPUT_SCHEMA,output:AGENT_COMMAND_CANCEL_OUTPUT_SCHEMA},{name:AGENT_CMD_COMMAND_STATE,capability:"agent.commands.read",authorities:["owner"],input:AGENT_COMMAND_STATE_INPUT_SCHEMA,output:AGENT_COMMAND_STATE_OUTPUT_SCHEMA}].map(row=>({...row,targeted:false,authorities:row.authorities})));TABLE=serviceContractTable(AGENT_COMMANDS);AGENT_CONTRACTS=TABLE.contracts;AGENT_CLUSTER=deepFreeze(buildClusterDocument(AGENT_CLUSTER_URN,AGENT_CLUSTER_REVISION,AGENT_COMMANDS))}});function isRepeatSafeCommand(endpoint,command){if(command===REPEAT_SAFE_ANY_ENDPOINT)return true;return REPEAT_SAFE_SNAP.get(endpoint)?.has(command)===true}var BASELINE_DELIVERY_ENDPOINT,BASELINE_DELIVERY_COMMANDS,BASELINE_LIFECYCLE_ENDPOINT,BASELINE_SELF_LIFECYCLE_COMMANDS,SPAWN_CREATE_COMMANDS,SPAWN_OWNER_LIFECYCLE_COMMANDS,OPERATOR_SEAT_COMMANDS,SPAWN_SERVICE_COMMANDS,RUN_WRITE_COMMANDS,RUN_READ_COMMANDS,CHAT_SESSION_COMMANDS,MANAGER_READ_COMMANDS,MANAGER_ADMIN_COMMANDS,GOAL_BEARING_COMMANDS,GOAL_BEARING_SET,REPEAT_SAFE_COMMANDS,REPEAT_SAFE_ANY_ENDPOINT,REPEAT_SAFE_SNAP,DELIVERY_COMMANDS_SNAP,SELF_LIFECYCLE_SNAP,SPAWN_CREATE_SNAP,SPAWN_OWNER_SNAP,OPERATOR_SEAT_SNAP,SPAWN_SERVICE_SNAP,RUN_WRITE_SNAP,RUN_READ_SNAP,CHAT_SESSION_SNAP,MANAGER_READ_SNAP,MANAGER_ADMIN_SNAP,PRINCIPAL_COMMANDS;var init_endpoint_grants=__esm({"../../packages/core/dist/endpoint-grants.js"(){"use strict";init_subjects();init_endpoint_binding();init_endpoint_subjects();init_agent_endpoint();BASELINE_DELIVERY_ENDPOINT="delivery";BASELINE_DELIVERY_COMMANDS=Object.freeze(["join","leave","list"]);BASELINE_LIFECYCLE_ENDPOINT="manager";BASELINE_SELF_LIFECYCLE_COMMANDS=Object.freeze(["stop","turn-participate","turn-pending","turn-yield","turn-unconfirmed","run-answer"]);SPAWN_CREATE_COMMANDS=Object.freeze(["spawn","resolve-agent"]);SPAWN_OWNER_LIFECYCLE_COMMANDS=Object.freeze(["despawn","attach"]);OPERATOR_SEAT_COMMANDS=Object.freeze(["input","turn"]);SPAWN_SERVICE_COMMANDS=Object.freeze(["define-persona","remove-persona","inspect","list-personas","show-persona","goal-result"]);RUN_WRITE_COMMANDS=Object.freeze(["run-start","run-resume","run-start-keyed","run-submission-status","run-cancel"]);RUN_READ_COMMANDS=Object.freeze(["run-status","run-ps"]);CHAT_SESSION_COMMANDS=Object.freeze(["chat-session-open","chat-session-retire"]);MANAGER_READ_COMMANDS=Object.freeze(["status","ps","slots","inspect","models","list-personas","show-persona","goal-result"]);MANAGER_ADMIN_COMMANDS=Object.freeze(["purge","launch","resume-preserved","commit-resume","finalize-resume","prepare-preservation","commit-preservation","abort-preservation","transcript-receive"]);GOAL_BEARING_COMMANDS=Object.freeze(["spawn","launch"]);GOAL_BEARING_SET=new Set(GOAL_BEARING_COMMANDS);REPEAT_SAFE_COMMANDS=Object.freeze({[BASELINE_LIFECYCLE_ENDPOINT]:Object.freeze(["status","ps","slots","inspect","list-personas","show-persona","run-status","run-ps","goal-result"]),[BASELINE_DELIVERY_ENDPOINT]:Object.freeze(["list"])});REPEAT_SAFE_ANY_ENDPOINT="describe";REPEAT_SAFE_SNAP=new Map(Object.entries(REPEAT_SAFE_COMMANDS).map(([endpoint,commands])=>[endpoint,new Set(commands)]));DELIVERY_COMMANDS_SNAP=Object.freeze([...BASELINE_DELIVERY_COMMANDS]);SELF_LIFECYCLE_SNAP=Object.freeze([...BASELINE_SELF_LIFECYCLE_COMMANDS]);SPAWN_CREATE_SNAP=Object.freeze([...SPAWN_CREATE_COMMANDS]);SPAWN_OWNER_SNAP=Object.freeze([...SPAWN_OWNER_LIFECYCLE_COMMANDS]);OPERATOR_SEAT_SNAP=Object.freeze([...OPERATOR_SEAT_COMMANDS]);SPAWN_SERVICE_SNAP=Object.freeze([...SPAWN_SERVICE_COMMANDS]);RUN_WRITE_SNAP=Object.freeze([...RUN_WRITE_COMMANDS]);RUN_READ_SNAP=Object.freeze([...RUN_READ_COMMANDS]);CHAT_SESSION_SNAP=Object.freeze([...CHAT_SESSION_COMMANDS]);MANAGER_READ_SNAP=Object.freeze([...MANAGER_READ_COMMANDS]);MANAGER_ADMIN_SNAP=Object.freeze([...MANAGER_ADMIN_COMMANDS]);PRINCIPAL_COMMANDS=new Map(["owner","grant"].map(word=>[word,Object.freeze(["describe",...AGENT_CLUSTER.commands.filter(c3=>c3.authorities?.includes(word)).map(c3=>c3.name)])]))}});var REGISTRY_ENDPOINT,REGISTRY_ENDPOINTS_COMMAND,REGISTRY_ENDPOINTS_CAPABILITY,REGISTRY_PAGE_LIMIT,REGISTRY_ENDPOINTS_GRANT,NAME,TOKEN,ENDPOINTS_INPUT,FORM,ENDPOINTS_OUTPUT,ROWS,TABLE2,REGISTRY_CONTRACTS,registryContractArtifactValues;var init_registry_contract=__esm({"../../packages/core/dist/registry-contract.js"(){"use strict";init_endpoint_cluster();init_schema_profile();REGISTRY_ENDPOINT="registry";REGISTRY_ENDPOINTS_COMMAND="endpoints";REGISTRY_ENDPOINTS_CAPABILITY="registry.endpoints";REGISTRY_PAGE_LIMIT=100;REGISTRY_ENDPOINTS_GRANT=Object.freeze({endpoint:REGISTRY_ENDPOINT,command:REGISTRY_ENDPOINTS_COMMAND});NAME={type:"string",minLength:1,maxLength:128};TOKEN={type:"string",minLength:1,maxLength:64};ENDPOINTS_INPUT={type:"object",additionalProperties:false,properties:{limit:{type:"integer",minimum:1,maximum:REGISTRY_PAGE_LIMIT},after:NAME}};FORM={type:"object",additionalProperties:false,required:["rail","literals","covered"],properties:{rail:{enum:["ep","ep.v1","epj"]},route:{enum:["one","all","inst"]},mode:TOKEN,literals:{type:"object",additionalProperties:{type:"array",items:TOKEN}},covered:{type:"array",items:{type:"object",additionalProperties:{type:["string","null"],maxLength:64}}}}};ENDPOINTS_OUTPUT={type:"object",additionalProperties:false,required:["rows","source"],properties:{rows:{type:"array",maxItems:REGISTRY_PAGE_LIMIT,items:{type:"object",additionalProperties:false,required:["endpoint","instances","commands"],properties:{endpoint:NAME,instances:{type:"array",items:{type:"object",additionalProperties:false,required:["instanceId","state","artifacts"],properties:{instanceId:TOKEN,state:{type:["string","null"],maxLength:64},artifacts:{enum:["verified","missing","invalid"]}}}},commands:{type:"array",items:{type:"object",additionalProperties:false,required:["name","class","forms"],properties:{name:TOKEN,class:{enum:["ephemeral","journal"]},forms:{type:"array",items:FORM},instances:{type:"array",items:TOKEN}}}},unprojected:{type:"array",items:TOKEN}}}},next:NAME,source:{enum:["recorded-ceiling","no-permission-system"]}}};ROWS=[{name:REGISTRY_ENDPOINTS_COMMAND,capability:REGISTRY_ENDPOINTS_CAPABILITY,input:ENDPOINTS_INPUT,output:ENDPOINTS_OUTPUT,targeted:false}];TABLE2=serviceContractTable(ROWS);REGISTRY_CONTRACTS=TABLE2.contracts;registryContractArtifactValues=TABLE2.artifactValues}});function assertClosedKeys(o3,allowed,what2){for(const k2 of Object.keys(o3))if(!allowed.includes(k2))throw new EpEnvelopeError("internal",`${what2} carries unknown field ${JSON.stringify(k2)}; a closed schema admits no extras - garbled state never authorizes (SPEC 13.4)`)}function assertGoalResultFactShape(raw,subject,ref){if(raw===null||typeof raw!=="object"||Array.isArray(raw))throw new EpEnvelopeError("internal",`goal result fact on ${subject} is not an object; garbled state never authorizes (SPEC 13.6)`);const o3=raw;assertClosedKeys(o3,["v","goalId","fingerprint","state","outcomeDigest","data","committer","ts"],`goal result fact on ${subject}`);if(o3.committer!==void 0){const cm=o3.committer;if(cm===null||typeof cm!=="object"||Array.isArray(cm))throw new EpEnvelopeError("internal",`goal result fact on ${subject} committer is not an object; garbled state never authorizes (SPEC 13.6)`);assertClosedKeys(cm,["instanceId","epoch"],`goal result fact on ${subject} committer`);if(typeof cm.instanceId!=="string"||cm.instanceId.length===0||typeof cm.epoch!=="number"||!Number.isSafeInteger(cm.epoch)||cm.epoch<0)throw new EpEnvelopeError("internal",`goal result fact on ${subject} carries a malformed committer; garbled state never authorizes (SPEC 13.6)`)}if(o3.v!==1||typeof o3.goalId!=="string"||typeof o3.fingerprint!=="string"||o3.fingerprint.length===0||typeof o3.state!=="string"||!GOAL_TERMINAL_STATES.includes(o3.state)||typeof o3.outcomeDigest!=="string"||o3.outcomeDigest.length===0||typeof o3.ts!=="number"||!Number.isSafeInteger(o3.ts)||o3.ts<0)throw new EpEnvelopeError("internal",`goal result fact on ${subject} is malformed; garbled state never authorizes (SPEC 13.6)`);if(o3.goalId!==ref.goalId)throw new EpEnvelopeError("internal",`goal result fact on ${subject} names goalId ${JSON.stringify(o3.goalId)}, not its subject's ${ref.goalId}; a mis-subjected fact never authorizes (SPEC 13.4)`);return o3}function goalOutcomeDigestMismatch(subject){return new EpEnvelopeError("internal",`goal result fact on ${subject} carries an outcomeDigest that does not match its payload; a digest-inconsistent fact never authorizes (SPEC 13.6)`)}var GOAL_TERMINAL_STATES;var init_goal_result_fact=__esm({"../../packages/core/dist/goal-result-fact.js"(){"use strict";init_endpoint_error();GOAL_TERMINAL_STATES=Object.freeze(["succeeded","failed","cancelled","expired","uncertain"])}});async function withDeadline(p2,ms,onTimeout){let timer2;const timeout=new Promise((_3,rej)=>{timer2=setTimeout(()=>rej(onTimeout()),Math.max(1,ms))});try{return await Promise.race([p2,timeout])}finally{clearTimeout(timer2)}}var init_deadline=__esm({"../../packages/core/dist/deadline.js"(){"use strict"}});var import_jetstream4,import_transport_node3,MAX_SCHEDULE_MS;var init_endpoint_checkpoint=__esm({"../../packages/core/dist/endpoint-checkpoint.js"(){"use strict";import_jetstream4=__toESM(require_mod4(),1);import_transport_node3=__toESM(require_transport_node(),1);init_endpoint_envelope();init_deadline();init_canonical();init_endpoint_subjects();init_endpoint_records();init_endpoint_journal();init_endpoint_binding();MAX_SCHEDULE_MS=Date.UTC(9999,11,31,23,59,59,999)}});var import_nkeys3,ANCHOR_ROLES;var init_endpoint_signing=__esm({"../../packages/core/dist/endpoint-signing.js"(){"use strict";import_nkeys3=__toESM(require_mod(),1);init_canonical();init_endpoint_envelope();ANCHOR_ROLES=Object.freeze(["handles","traits","receipts","resume","sessions","authz-slots","obligations","payments","consents"])}});var import_jetstream5,import_transport_node4;var init_endpoint_receipt=__esm({"../../packages/core/dist/endpoint-receipt.js"(){"use strict";import_jetstream5=__toESM(require_mod4(),1);import_transport_node4=__toESM(require_transport_node(),1);init_canonical();init_endpoint_envelope();init_deadline();init_endpoint_records();init_endpoint_subjects();init_endpoint_journal();init_endpoint_signing()}});function assertCtx(ctx){if(!BRANDED_CONTEXTS.has(ctx))throw new EpEnvelopeError("failed-precondition",`the action context was not constructed by actionContext(); a hand-assembled resource bundle never authorizes - the space bond is constructed, not asserted (SPEC 13.4)`)}function claimGuardClearanceMint(){if(clearanceMintClaimed)throw new EpEnvelopeError("permission-denied","the guard-clearance mint is already claimed by THE gate; a guarded goal's edge into running opens only through it (SPEC 13.6)");clearanceMintClaimed=true;return(ctx,goalId)=>{assertCtx(ctx);const clearance=Object.freeze({goalId:assertIdToken(goalId,"goalId")});GUARD_CLEARANCES.set(clearance,ctx);return clearance}}function parseGoalResultFact(raw,subject,ref){const o3=assertGoalResultFactShape(raw,subject,ref);if(contractDigest(o3.data===void 0?null:o3.data)!==o3.outcomeDigest)throw goalOutcomeDigestMismatch(subject);return o3}var import_jetstream6,import_transport_node5,BRANDED_CONTEXTS,GUARD_CLEARANCES,clearanceMintClaimed,GOAL_STATES;var init_endpoint_action=__esm({"../../packages/core/dist/endpoint-action.js"(){"use strict";import_jetstream6=__toESM(require_mod4(),1);import_transport_node5=__toESM(require_transport_node(),1);init_canonical();init_endpoint_envelope();init_goal_result_fact();init_deadline();init_endpoint_subjects();init_endpoint_records();init_endpoint_journal();init_endpoint_checkpoint();init_endpoint_receipt();BRANDED_CONTEXTS=new WeakSet;GUARD_CLEARANCES=new WeakMap;clearanceMintClaimed=false;GOAL_STATES=Object.freeze(["accepted","running","waiting","cancelling","succeeded","failed","cancelled","expired","uncertain"])}});function base64url(bytes){let binary="";for(const b3 of bytes)binary+=String.fromCharCode(b3);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function fromBase64url(text3){const b64=text3.replace(/-/g,"+").replace(/_/g,"/");const binary=atob(b64+"=".repeat((4-b64.length%4)%4));return Uint8Array.from(binary,ch=>ch.charCodeAt(0))}var init_base64url=__esm({"../../packages/core/dist/base64url.js"(){"use strict"}});function openPublishDenialWatch(nc,subject,refusal,what2){const statusStream=nc.status();if(typeof statusStream?.stop!=="function")throw new EpEnvelopeError("unavailable",`the NATS connection's status() stream does not expose stop(); the ${what2} permission watch cannot be released and would leak a listener per call`);const statusIter=statusStream[Symbol.asyncIterator]();let onClose;const closed4=new Promise((_3,reject)=>{onClose=reject});closed4.catch(()=>{});const denied=new Promise((_3,reject)=>{void(async()=>{for(;;){const{value:s3,done}=await statusIter.next();if(done===true||s3===void 0)return;if(s3.type==="close"){onClose(new Error(`connection closed before the ${what2} was answered`));return}if(s3.type!=="error")continue;if(s3.error instanceof import_nats_core.PermissionViolationError&&s3.error.subject===subject){reject(refusal(s3.error));return}}})().catch(()=>{})});return{denied,closed:closed4,release(){statusStream.stop();void statusIter.return?.(void 0)}}}var import_nats_core,BROKER_REFUSAL_CAUSE;var init_endpoint_publish_denial=__esm({"../../packages/core/dist/endpoint-publish-denial.js"(){"use strict";import_nats_core=__toESM(require_mod3(),1);init_endpoint_envelope();BROKER_REFUSAL_CAUSE="either no grant covers it, or it was granted after this connection authenticated, which still has its earlier permissions: reconnect and retry (SPEC 13.2)"}});function carriesStoredProvenance(msg){return hasHeader(msg,/^Nats-(Stream|Subject|Sequence|Time-Stamp)$/i)}function carriesStoredReplyProvenance(msg){return hasHeader(msg,/^Nats-(Stream|Sequence|Time-Stamp)$/i)}function hasHeader(msg,name2){for(const[key]of msg.headers??[])if(name2.test(key))return true;return false}var init_endpoint_provenance=__esm({"../../packages/core/dist/endpoint-provenance.js"(){"use strict"}});function subjectTarget(t2){if(t2.mode==="self")return{mode:"self"};if(t2.mode==="handle"||t2.mode==="exact")return{mode:t2.mode,tOwner:t2.owner,tActor:t2.actor,tUid:t2.lifecycleUid};return{mode:t2.mode,tOwner:t2.owner}}function bodyTarget(t2){if(t2.mode==="self")return void 0;return{owner:assertBoundedOwner(t2.owner,"target owner"),actor:t2.actor,lifecycleUid:assertLifecycleToken(t2.lifecycleUid,"target lifecycleUid"),...t2.mappingRevision!==void 0?{mappingRevision:t2.mappingRevision}:{}}}function validatedArgs(op){let args;try{args=op.args===void 0?void 0:JSON.parse(JSON.stringify(op.args))}catch(e3){throw new EpEnvelopeError("bad-request",`args cannot be sent as JSON: ${e3 instanceof Error?e3.message:String(e3)}`,void 0,"not-executed")}try{assertArgsValid(op.contract.input.validate,args)}catch(e3){if(!(e3 instanceof EpEnvelopeError))throw e3;const property=op.contract.input.validate.errors?.[0]?.additionalProperty;throw new EpEnvelopeError(e3.code,e3.message,typeof property==="string"?[{kind:EP_UNDECLARED_ARG,property,...op.bind!==void 0?{instanceId:op.bind.instanceId}:{}}]:void 0,"not-executed")}return args}function requestEnvelope(op,verb,args,pin=true){const requestId=op.id!==void 0?assertIdToken(op.id,"pinned envelope id"):nonce();const env={v:1,id:requestId,op:{endpoint:op.endpoint,command:op.command,...pin?{inputDigest:op.contract.input.closureDigest,outputDigest:op.contract.output.closureDigest}:{}},class:"ephemeral",replyExpected:verb.replyExpected,...op.goalId!==void 0?{goalId:op.goalId}:{},...op.target&&op.target.mode!=="self"?{target:bodyTarget(op.target)}:{},...op.bind!==void 0?{bind:{instanceId:assertLifecycleToken(op.bind.instanceId,"bind instanceId"),epoch:op.bind.epoch}}:{},...args!==void 0?{args}:{},from:{id:`${op.caller.owner}.${op.caller.actor}`,name:op.name??op.caller.actor},...verb.deadlineMs!==void 0?{deadlineMs:verb.deadlineMs}:{},...op.correlation!==void 0?{correlation:op.correlation}:{},...op.auth!==void 0?{auth:op.auth}:{}};return{requestId,body:new TextEncoder().encode(JSON.stringify(env))}}function buildRequest(space2,route,op,verb){const args=validatedArgs(op);if(op.bind!==void 0){if(op.command==="describe")throw new EpEnvelopeError("bad-request","describe carries no bind: it is the bootstrap that produces one (SPEC 13.3)");if(route.mode==="all")throw new EpEnvelopeError("bad-request","a scatter addresses every incarnation; a bind would make every member but one refuse (SPEC 13.5)");if(route.mode==="inst"&&op.bind.instanceId!==route.instanceId)throw new EpEnvelopeError("bad-request",`bind.instanceId "${op.bind.instanceId}" contradicts the inst-rail route's instance "${route.instanceId}" (SPEC 13.2)`)}const n2=nonce();const subject=epRequestSubject(space2,{route,endpoint:op.endpoint,command:op.command,...op.target?{target:subjectTarget(op.target)}:{},caller:op.caller,nonce:n2});return{subject,n:n2,...requestEnvelope(op,verb,args)}}function assertDeadline(deadlineMs,what2="deadlineMs"){if(!Number.isSafeInteger(deadlineMs)||deadlineMs<=0||deadlineMs>MAX_TIMER_MS)throw new EpEnvelopeError("bad-request",`${what2} ${deadlineMs} must be a positive budget within the timer bound ${MAX_TIMER_MS}ms (SPEC 13.3: bounded, never unbounded; a larger setTimeout clamps to 1ms)`);return deadlineMs}function isNoRespondersMsg(msg){const h3=msg.headers;return h3!=null&&(h3.code===503||h3.status==="503")}async function raceBounded(read,ms,what2,details){let t2;try{return await Promise.race([(async()=>read())(),new Promise((_3,reject)=>{t2=setTimeout(()=>reject(new EpEnvelopeError("deadline-exceeded",`${what2} did not settle within the ${ms}ms budget (SPEC 13.5)`,details)),ms)})])}finally{if(t2!==void 0)clearTimeout(t2)}}function replySubjectFor(space2,caller,n2){return`${spacePrefix(space2)}.${epPlaneTokens(caller).join(".")}.reply.*.*.*.${callerRailTokens(caller).join(".")}.${n2}`}function noRespondersReplyTo(space2,caller,n2){return`${spacePrefix(space2)}.${epPlaneTokens(caller).join(".")}.reply._nr._nr._nr.${callerRailTokens(caller).join(".")}.${n2}`}function staleEpochRefusal(op,responder,held2,reference,rail){const who=`the ${op.endpoint} instance ${responder.instanceId}`;const ahead=responder.epoch>held2;const situation=reference==="bind"?ahead?`${who} answered at epoch ${responder.epoch}, but this handle resolved against it at epoch ${held2}: a SUCCESSOR of the bound incarnation answered (a restart or supersession), so the handle is the stale side; re-resolve to adopt it`:`${who} answered at epoch ${responder.epoch}, but this handle resolved against it at epoch ${held2}: a SUPERSEDED incarnation still connected answered, and its reply is rejected`:ahead?`${who} answered at epoch ${responder.epoch}, but a currency read of its registered epoch returned ${held2}: the responder is ahead of the registry read (the read lags a restart), so its reply is rejected until the read catches up; nothing of this caller's is stale`:`${who} answered at epoch ${responder.epoch}, but a currency read of its registered epoch returned ${held2}: a SUPERSEDED incarnation still connected answered, and its reply is rejected`;const detail={kind:EP_UNBOUND_RESPONDER,endpoint:op.endpoint,command:op.command,answeredBy:responder.instanceId,...reference==="bind"?{boundTo:responder.instanceId}:{},answeredEpoch:responder.epoch,heldEpoch:held2,reference,pinned:rail==="inst"};return new EpEnvelopeError("expired",`${situation}. THIS SAYS NOTHING ABOUT WHETHER THE COMMAND RAN: ${responder.instanceId} received the request and answered it, so if "${op.command}" mutates, that effect may already have landed; verify the outcome ('ps'/'inspect'/roster) before re-issuing (SPEC 13.2, the stale-reply rejection rule)`,[detail])}function parseAttributedReply(space2,subject,data,requestId,op,expect){const parsed=parseEpSubject(subject);if(!parsed||parsed.plane!=="reply")throw new EpEnvelopeError("internal",`a message on the caller's reply rail does not parse as a reply subject: ${subject}`);if(parsed.endpoint!==op.endpoint)throw new EpEnvelopeError("internal",`reply endpoint "${parsed.endpoint}" is not the invoked endpoint "${op.endpoint}" (SPEC 13.2: the caller binds a reply to the requested identity, never trusts the subject alone)`);if(expect?.instanceId!==void 0&&parsed.instanceId!==expect.instanceId)throw new EpEnvelopeError("internal",`reply instance "${parsed.instanceId}" is not the addressed instance "${expect.instanceId}" (SPEC 13.2)`);if(expect?.epoch!==void 0&&parsed.epoch!==expect.epoch)throw staleEpochRefusal(op,{instanceId:parsed.instanceId,epoch:parsed.epoch},expect.epoch,"bind","inst");let rawBody;try{rawBody=JSON.parse(new TextDecoder().decode(data))}catch(e3){throw new EpEnvelopeError("internal",`the reply body on the caller's rail is not JSON (${e3 instanceof Error?e3.message:String(e3)}); an unparseable reply is a responder bug surfaced as the caller boundary's structured refusal (SPEC 13.3)`)}const reply=parseEndpointReply(rawBody);if(reply.id!==requestId)throw new EpEnvelopeError("internal",`reply id "${reply.id}" does not echo the request id "${requestId}" on its nonce-scoped rail (SPEC 13.3)`);if(reply.ok)assertOutputValid(op.contract.output.validate,reply.data);return{reply,responder:{endpoint:parsed.endpoint,instanceId:parsed.instanceId,epoch:parsed.epoch}}}async function epCall(nc,space2,route,op,opts){opts.signal?.throwIfAborted();const deadlineMs=assertDeadline(opts.deadlineMs);if(route.mode==="one"&&opts.currentEpoch===void 0)throw new EpEnvelopeError("bad-request","epCall on the `one` rail requires opts.currentEpoch: the queue winner is not implicitly current, and a superseded-but-connected member's reply must be rejected (SPEC 13.2, the stale-reply rejection rule)");const req=buildRequest(space2,route,op,{replyExpected:true,deadlineMs});const expect=route.mode==="inst"?{instanceId:route.instanceId,epoch:route.epoch}:void 0;const started=Date.now();const msg=await exchange(nc,{subject:req.subject,body:req.body,requestId:req.requestId,deadlineMs,signal:opts.signal,replyFilter:replySubjectFor(space2,op.caller,req.n),sentinel:noRespondersReplyTo(space2,op.caller,req.n),what:`${op.endpoint}.${op.command}`,unanswered:unansweredDetail(op),refusal:()=>new EpEnvelopeError("permission-denied",`the call for ${op.endpoint}.${op.command} was REFUSED BY THE BROKER, not unanswered: this caller's credential does not authorize publishing to "${req.subject}"${route.mode==="inst"?` (the instance rail for ${route.instanceId})`:""}. The responder may be perfectly healthy. The current credential did not authorize this route, command or target, and the broker does not say which; ${BROKER_REFUSAL_CAUSE}`,void 0,"not-executed")});const attributed=parseAttributedReply(space2,msg.subject,msg.data,req.requestId,op,expect);if(attributed.reply.ok===false&&bindRefusalMarked(attributed.reply.error)){if(op.bind===void 0)throw new EpEnvelopeError("internal",`${op.endpoint}.${op.command} replied with a bind refusal to a request that carried no bind`);const r2=attributed.responder;if(r2.instanceId===op.bind.instanceId&&r2.epoch===op.bind.epoch)throw new EpEnvelopeError("internal",`${op.endpoint} instance ${r2.instanceId} refused ${op.command} as the wrong incarnation, but the reply subject attributes it to exactly the bound one (${op.bind.instanceId} epoch ${op.bind.epoch}); the body does not get to contradict its own attribution (SPEC 13.3)`);const refusal=(attributed.reply.error?.details??[]).find(d2=>d2.kind===EP_BIND_REFUSED);if(refusal===void 0)throw new EpEnvelopeError("internal",`${op.endpoint}.${op.command} came back marked ${EP_BIND_REFUSED} with no such detail to derive it from (SPEC 13.3)`);if(refusal.boundTo.instanceId!==op.bind.instanceId||refusal.boundTo.epoch!==op.bind.epoch)throw new EpEnvelopeError("internal",`${op.endpoint} refused ${op.command} against bind ${refusal.boundTo.instanceId} epoch ${refusal.boundTo.epoch}, but this request carried ${op.bind.instanceId} epoch ${op.bind.epoch}; a refusal computed from another request proves nothing about this one (SPEC 13.3)`);if(refusal.servedBy.instanceId!==r2.instanceId||refusal.servedBy.epoch!==r2.epoch)throw new EpEnvelopeError("internal",`${op.endpoint} refused ${op.command} claiming to be served by ${refusal.servedBy.instanceId} epoch ${refusal.servedBy.epoch}, but the reply subject attributes it to ${r2.instanceId} epoch ${r2.epoch}; the body does not get to contradict its own attribution (SPEC 13.3)`);return attributed}if(route.mode==="one"){const remaining=deadlineMs-(Date.now()-started);if(remaining<=0)throw new EpEnvelopeError("deadline-exceeded",`no budget left to verify the \`one\` responder's currency within ${deadlineMs}ms (SPEC 13.5)`);let cur;try{cur=await raceBounded(()=>opts.currentEpoch(attributed.responder.instanceId),remaining,`the \`one\` currency read for ${op.endpoint}.${op.command}`)}catch(e3){if(e3 instanceof EpEnvelopeError)throw e3;throw new EpEnvelopeError("internal",`the \`one\` currency read threw (${e3 instanceof Error?e3.message:String(e3)}); the documented error catalog holds at this boundary (SPEC 13.3)`)}if(!Number.isSafeInteger(cur)||cur<0)throw new EpEnvelopeError("failed-precondition",`the \`one\` currency read returned a non-integer/negative epoch ${String(cur)}; a garbled currency read is refused as the read's own failure, never reported as responder staleness (SPEC 13.2)`);if(attributed.responder.epoch!==cur)throw staleEpochRefusal(op,attributed.responder,cur,opts.currencyReference??"registry","one")}return attributed}async function exchange(nc,x2){let sub;let timer2;let denialWatch;let onAbort;let published=false;let readRefusal;const cancelled=new Promise((_3,reject)=>{onAbort=()=>reject(new EpEnvelopeError("unavailable",`${x2.what} observation cancelled; the request may have executed`,published?[{...x2.unanswered,requestId:x2.requestId}]:void 0,"unknown"));x2.signal?.addEventListener("abort",onAbort,{once:true})});try{denialWatch=openPublishDenialWatch(nc,x2.subject,x2.refusal,"call");const outcome=new Promise((resolve6,reject)=>{sub=nc.subscribe(x2.replyFilter,{callback:(err3,msg)=>{if(err3){if(x2.readRefused==="permission"&&err3 instanceof import_nats_core2.PermissionViolationError){const refusal=readRefusal=new EpEnvelopeError("permission-denied",`the broker refused this caller's reply read "${x2.replyFilter}" for ${x2.what}: the request was published and may have run, and its reply cannot be read here; ${BROKER_REFUSAL_CAUSE}`,[{...x2.unanswered,requestId:x2.requestId}],"unknown");void nc.flush().catch(()=>void 0).then(()=>new Promise(resolve7=>setImmediate(resolve7))).then(()=>reject(refusal));return}reject(new EpEnvelopeError("unavailable",`the caller's reply subscription failed: ${err3.message}`));return}if(carriesStoredReplyProvenance(msg))return;if(msg.subject===x2.sentinel){if(isNoRespondersMsg(msg)){reject(new EpEnvelopeError("unavailable",`no responder for ${x2.what} (SPEC 13.5)`,[x2.unanswered],"not-executed"));return}return}if(x2.accepts&&!x2.accepts(msg.subject))return;resolve6({subject:msg.subject,data:msg.data})}});x2.signal?.throwIfAborted();nc.publish(x2.subject,x2.body,{reply:x2.sentinel});published=true});const timeout=new Promise((_3,reject)=>{timer2=setTimeout(()=>reject(readRefusal??new EpEnvelopeError("deadline-exceeded",`no reply to ${x2.what} within the ${x2.deadlineMs}ms budget (SPEC 13.5)`,[{...x2.unanswered,requestId:x2.requestId}],"unknown")),x2.deadlineMs)});return await Promise.race([outcome,timeout,denialWatch.denied,cancelled])}finally{sub?.unsubscribe();if(timer2!==void 0)clearTimeout(timer2);denialWatch?.release();if(onAbort)x2.signal?.removeEventListener("abort",onAbort)}}function buildPrincipalRequest(space2,to,op,verb){if(op.target!==void 0)throw new EpEnvelopeError("bad-request","a principal-route request carries no target: the subject head is the target (SPEC 13.21)",void 0,"not-executed");if(op.bind!==void 0)throw new EpEnvelopeError("bad-request","a principal-route request carries no bind: the runtime id in the subject pins the process (SPEC 13.21)",void 0,"not-executed");if(isIssuedCaller(op.caller))throw new EpEnvelopeError("bad-request","the principal route has no versioned form; it carries the caller triple only (SPEC 13.21)",void 0,"not-executed");if(verb.deadlineMs>EP_PRINCIPAL_MAX_DEADLINE_MS)throw new EpEnvelopeError("bad-request",`deadlineMs ${verb.deadlineMs} exceeds the principal route's ${EP_PRINCIPAL_MAX_DEADLINE_MS}ms maximum (SPEC 13.21)`,void 0,"not-executed");const args=validatedArgs(op);const n2=nonce();const subject=epPrincipalRequestSubject(space2,{endpoint:op.endpoint,principal:to.principal,command:op.command,authority:to.authority,caller:op.caller,nonce:n2});return{subject,n:n2,...requestEnvelope(op,{replyExpected:true,deadlineMs:verb.deadlineMs},args,op.command!=="describe")}}async function epPrincipalCall(nc,space2,to,op,opts){opts.signal?.throwIfAborted();const deadlineMs=assertDeadline(opts.deadlineMs);const req=buildPrincipalRequest(space2,to,op,{deadlineMs});const expected=epPrincipalReplySubject(space2,{endpoint:op.endpoint,principal:to.principal,caller:op.caller,nonce:req.n});const msg=await exchange(nc,{subject:req.subject,body:req.body,requestId:req.requestId,deadlineMs,signal:opts.signal,replyFilter:epPrincipalCallerReplyFilter(space2,op.caller,req.n),sentinel:epPrincipalNoRespondersSubject(space2,op.caller,req.n),what:`${op.endpoint}.${op.command}`,unanswered:{kind:EP_UNANSWERED,endpoint:op.endpoint,command:op.command,rail:PRINCIPAL_RAIL},accepts:subject=>subject===expected,readRefused:"permission",refusal:()=>new EpEnvelopeError("permission-denied",`the call for ${op.endpoint}.${op.command} was REFUSED BY THE BROKER, not unanswered: this caller's credential does not authorize publishing to "${req.subject}", the "${to.authority}" form for ${to.principal.owner}.${to.principal.actor}. The agent may be serving; ${BROKER_REFUSAL_CAUSE}`,void 0,"not-executed")});let raw;try{raw=JSON.parse(new TextDecoder().decode(msg.data))}catch(e3){throw new EpEnvelopeError("internal",`the reply body is not JSON (${e3 instanceof Error?e3.message:String(e3)}); an unparseable reply is a responder bug (SPEC 13.3)`)}const reply=parseEndpointReply(raw);if(reply.id!==req.requestId)throw new EpEnvelopeError("internal",`reply id "${reply.id}" does not echo the request id "${req.requestId}" (SPEC 13.3)`);if(reply.ok)assertOutputValid(op.contract.output.validate,reply.data);return reply}var import_nats_core2,nonce,MAX_TIMER_MS,unansweredDetail,PRINCIPAL_RAIL;var init_endpoint_call=__esm({"../../packages/core/dist/endpoint-call.js"(){"use strict";init_base64url();import_nats_core2=__toESM(require_mod3(),1);init_endpoint_publish_denial();init_endpoint_provenance();init_subjects();init_endpoint_subjects();init_endpoint_envelope();nonce=()=>base64url(globalThis.crypto.getRandomValues(new Uint8Array(24)));MAX_TIMER_MS=2147483647;unansweredDetail=op=>({kind:EP_UNANSWERED,endpoint:op.endpoint,command:op.command,rail:epPlaneTokens(op.caller).join(".")});PRINCIPAL_RAIL="ep.prin"}});function caughtText(e3,fallback){try{return e3 instanceof Error?e3.message:String(e3)}catch{return fallback}}async function describeEndpoint(nc,space2,endpoint,caller,opts={}){opts.signal?.throwIfAborted();if(opts.classInstanceId!==void 0){assertLifecycleToken(opts.classInstanceId,"classInstanceId");if(opts.instanceId!==void 0)throw new EpEnvelopeError("bad-request","a describe cannot select both an instance route and a class responder")}const deadlineMs=opts.deadlineMs??1e4;const n2=nonce2();const requestId=nonce2();const route=opts.instanceId!==void 0?{mode:"inst",instanceId:opts.instanceId}:{mode:"one"};const subject=epRequestSubject(space2,{route,endpoint,command:"describe",caller,nonce:n2});const rail=epPlaneTokens(caller).join(".");const env={v:1,id:requestId,op:{endpoint,command:"describe"},class:"ephemeral",replyExpected:true,deadlineMs,from:{id:`${caller.owner}.${caller.actor}`,name:caller.actor}};let sub;let timer2;let retryTimer;let denialWatch;let onAbort;const startedAt2=performance.now();const unanswered=ms=>new EpEnvelopeError("deadline-exceeded",`no describe reply from ${endpoint}${opts.instanceId!==void 0?` instance ${opts.instanceId}`:opts.classInstanceId!==void 0?` class responder ${opts.classInstanceId}`:""} within ${ms}ms on the ${rail} rail`,[{kind:EP_UNANSWERED,endpoint,command:"describe",rail}]);const cancelled=new Promise((_3,reject)=>{onAbort=()=>reject(opts.signal?.reason?.name==="TimeoutError"?unanswered(Math.round(performance.now()-startedAt2)):opts.signal?.reason);opts.signal?.addEventListener("abort",onAbort,{once:true})});try{denialWatch=openPublishDenialWatch(nc,subject,()=>new EpEnvelopeError("permission-denied",`the describe for ${endpoint} was REFUSED BY THE BROKER, not unanswered: this caller's credential does not authorize publishing to "${subject}"${opts.instanceId!==void 0?` (the instance rail for ${opts.instanceId}: an instance-addressed call needs a credential minted with that instance, not a class-rail one)`:""}. The responder may be perfectly healthy; ${BROKER_REFUSAL_CAUSE}`,void 0,"not-executed"),"describe");const got=new Promise((resolve6,reject)=>{sub=nc.subscribe(epCallerReplyFilter(space2,caller),{callback:(err3,msg)=>{if(err3){reject(new EpEnvelopeError("unavailable",`describe reply subscription failed: ${err3.message}`));return}const parsed=parseEpSubject(msg.subject);if(!parsed||parsed.plane!=="reply"||parsed.endpoint!==endpoint||parsed.nonce!==n2)return;let reply2;try{reply2=parseEndpointReply(JSON.parse(dec3.decode(msg.data)))}catch{return}if(reply2.id!==requestId)return;if(opts.classInstanceId!==void 0&&parsed.instanceId!==opts.classInstanceId)return;resolve6({body:reply2,responder:{instanceId:parsed.instanceId,epoch:parsed.epoch}})}});const request=enc3.encode(JSON.stringify(env));nc.publish(subject,request);retryTimer=setInterval(()=>{try{nc.publish(subject,request)}catch(e3){reject(new EpEnvelopeError("unavailable",`the describe retry for ${endpoint} could not publish: ${caughtText(e3,"unknown publish failure")}`))}},DESCRIBE_RETRY_MS)});const timeout=new Promise((_3,reject)=>{timer2=setTimeout(()=>reject(unanswered(deadlineMs)),deadlineMs)});const{body:reply,responder}=await Promise.race([got,timeout,denialWatch.denied,cancelled]);if(reply.ok!==true){const e3=reply.error;throw new EpEnvelopeError(e3?.code??"unavailable",`describe(${endpoint}) failed: ${e3?.message??"unknown"}`)}return{answer:reply.data,responder}}finally{sub?.unsubscribe();if(timer2!==void 0)clearTimeout(timer2);if(retryTimer!==void 0)clearInterval(retryTimer);if(onAbort)opts.signal?.removeEventListener("abort",onAbort);denialWatch?.release()}}async function invokeCommand(nc,space2,service,command,args,opts){const resolved=service.commands.get(command);if(resolved===void 0)throw new EpEnvelopeError("not-found",`command "${command}" is not in ${service.endpoint}'s visible surface; describe lists ${[...service.commands.keys()].sort().join(", ")||"(none)"}`);if(resolved.targeted&&opts.target===void 0)throw new EpEnvelopeError("bad-request",`command "${command}" is targeted (modes: ${resolved.modes.join(", ")}); an invoke needs its target`);if(!resolved.targeted&&opts.target!==void 0)throw new EpEnvelopeError("bad-request",`command "${command}" is untargeted; an invoke must not carry a target`);const caller=opts.caller??service.caller;if(caller.owner!==service.caller.owner||caller.actor!==service.caller.actor||caller.uid!==service.caller.uid)throw new EpEnvelopeError("bad-request","a call's caller must name the triple its describe ran as");let sendArgs=args;if(sendArgs===void 0&&!resolved.contract.input.validate(null)&&resolved.contract.input.validate({}))sendArgs={};const describeBound=instanceId=>{if(instanceId!==service.responder.instanceId){throw new EpEnvelopeError("failed-precondition",service.pinnedInstanceId!==void 0?`the ${service.endpoint} instance ${instanceId} answered but this handle is PINNED to ${service.pinnedInstanceId}; a pinned call names its instance and never accepts another. ${instanceId} did receive and answer the request, so if "${command}" mutates, that effect may already have landed - verify before re-issuing (SPEC 13.2)`:`the ${service.endpoint} instance ${instanceId} won the class queue but this UNPINNED handle resolved against ${service.responder.instanceId}; the describe and the invoke are separate trips through the same queue, so in a multi-instance space this is an ordinary split and not necessarily a supersession - the handle cannot currently adopt a different winner. THIS SAYS NOTHING ABOUT WHETHER THE COMMAND RAN: ${instanceId} received the request and answered it, possibly after this error was raised. For a read that is harmless and re-issuing is safe; if "${command}" mutates, verify the outcome ('ps'/'inspect'/roster) before re-issuing, because a retry that assumes failure duplicates the effect. A call that addresses one instance does not split (SPEC 13.2)`,[{kind:EP_UNBOUND_RESPONDER,endpoint:service.endpoint,command,answeredBy:instanceId,boundTo:service.responder.instanceId,pinned:service.pinnedInstanceId!==void 0}])}return service.responder.epoch};const bind=opts.currentEpoch===void 0?{instanceId:service.pinnedInstanceId??service.responder.instanceId,epoch:service.responder.epoch}:void 0;const deadline=Date.now()+(opts.deadlineMs??1e4);const call=route=>epCall(nc,space2,route,{endpoint:service.endpoint,command,contract:resolved.contract,caller,...sendArgs!==void 0?{args:sendArgs}:{},...opts.target?{target:opts.target}:{},...bind!==void 0?{bind}:{},...opts.id!==void 0?{id:opts.id}:{}},{deadlineMs:deadline-Date.now(),signal:opts.signal,currentEpoch:opts.currentEpoch??describeBound,currencyReference:opts.currentEpoch?"registry":"bind"});if(service.pinnedInstanceId!==void 0)return call({mode:"inst",instanceId:service.pinnedInstanceId,epoch:service.responder.epoch});try{return await call({mode:"one"})}catch(e3){if(!(e3 instanceof EpEnvelopeError)||e3.code!=="permission-denied"||e3.outcome!=="not-executed"||deadline<=Date.now())throw e3;return call({mode:"inst",instanceId:service.responder.instanceId,epoch:service.responder.epoch})}}function goalFollowRefusal(service){if(service.commands.has("goal-result"))return void 0;return{reply:{v:1,id:globalThis.crypto.randomUUID(),ok:false,error:{code:"failed-precondition",outcome:"not-executed",message:`endpoint "${service.endpoint}" does not support "goal-result"; upgrade manager to enable durable goal following (SPEC 13.6)`}},responder:{endpoint:service.endpoint,instanceId:service.responder.instanceId,epoch:service.responder.epoch}}}var dec3,enc3,nonce2,DESCRIBE_RETRY_MS,GOAL_FOLLOW_MARGIN_MS,BIND_SPLIT_REISSUES;var init_endpoint_caller=__esm({"../../packages/core/dist/endpoint-caller.js"(){"use strict";init_base64url();init_endpoint_publish_denial();init_endpoint_envelope();init_endpoint_call();init_endpoint_subjects();dec3=new TextDecoder;enc3=new TextEncoder;nonce2=()=>base64url(globalThis.crypto.getRandomValues(new Uint8Array(24)));DESCRIBE_RETRY_MS=250;GOAL_FOLLOW_MARGIN_MS=1e4;BIND_SPLIT_REISSUES=16}});function goalProgressOrigin(space2,endpoint,caller,subject){const head=`${spacePrefix(space2)}.epe.${endpointToken(endpoint)}.`;if(!subject.startsWith(head))return void 0;const[instanceId,epoch,...tail]=subject.slice(head.length).split(".");const triple=callerTokens(caller);if(tail.length!==6||tail[0]!=="goal"||tail[1]!==triple[0]||tail[2]!==triple[1]||tail[3]!==triple[2]||tail[5]!=="progress")return void 0;if(!instanceId||!epoch||!tail[4])return void 0;return{instanceId,epoch,goalId:tail[4]}}async function submitAndFollowGoalWith(verifyFact,nc,space2,endpoint,caller,deadlineMs,submit,opts){if(!Number.isSafeInteger(deadlineMs)||deadlineMs<=0)throw new EpEnvelopeError("bad-request","goal following requires a positive integer deadline",void 0,"not-executed");const acceptingCaller={...caller};const terminals=new Map;const terminalKey=(goalId,instanceId,epoch)=>`${goalId}\0${instanceId}\0${epoch}`;let terminalPromptedRead=false;const progressSubject=epGoalProgressGrantRow(space2,endpoint,acceptingCaller);const work=new AbortController;const timers=new Set;let activeNc=nc;let activeSub;let generation=0;let unbindReconnect;let completed=false;let stopped=opts?.signal?.aborted===true;let submitted=false;let subError;let observationError;let wake;let abortPhase;let needsReconcile=false;let reading=false;let readRetryAt;let unansweredRead;let progressReady=false;const aborted2=new Promise(resolve6=>{abortPhase=resolve6});const onAbort=()=>{stopped=true;work.abort();abortPhase?.();wake?.()};const phaseError=code2=>new EpEnvelopeError(code2,submitted?"the goal submission was interrupted while in flight; its outcome is unknown. It may have been accepted or executed; do NOT retry without inspecting 'ps'/'inspect' first (SPEC 13.6)":"goal observation stopped or exceeded its deadline before submission; the manager request WAS NOT RUN",void 0,submitted?"unknown":"not-executed");let deadline=Date.now()+deadlineMs;const bounded=async(operation,until)=>{if(stopped||completed)throw phaseError("unavailable");const remaining=until-Date.now();if(remaining<=0)throw phaseError("deadline-exceeded");let timer2;try{return await Promise.race([operation(),aborted2.then(()=>{throw phaseError("unavailable")}),new Promise((_3,reject)=>{timer2=setTimeout(()=>reject(phaseError("deadline-exceeded")),Math.min(remaining,2147483647));timers.add(timer2)})])}finally{if(timer2!==void 0){clearTimeout(timer2);timers.delete(timer2)}}};const subscribe=next=>{if(completed||stopped)return;const mine=++generation;activeSub?.unsubscribe();activeNc=next;progressReady=false;subError=void 0;activeSub=next.subscribe(progressSubject,{callback:(err3,msg)=>{if(completed||stopped||mine!==generation)return;if(err3){subError??=err3;wake?.();return}const origin=goalProgressOrigin(space2,endpoint,acceptingCaller,msg.subject);if(!origin)return;let ev;try{ev=JSON.parse(dec3.decode(msg.data))}catch{return}if(ev?.phase==="terminal"&&ev.goalId===origin.goalId){terminals.set(terminalKey(origin.goalId,origin.instanceId,origin.epoch),{state:String(ev.state),data:ev.data});if(!terminalPromptedRead){terminalPromptedRead=true;needsReconcile=true}wake?.()}}})};const replaceConnection=next=>{if(completed||stopped)return;try{subscribe(next)}catch(err3){subError=err3 instanceof Error?err3:new Error(String(err3));wake?.();return}const mine=generation;void bounded(()=>next.flush(),deadline).then(()=>{if(completed||stopped||mine!==generation)return;progressReady=true;needsReconcile=true;wake?.()},err3=>{if(completed||stopped||mine!==generation)return;subError=err3 instanceof Error?err3:new Error(String(err3));wake?.()})};try{opts?.signal?.addEventListener("abort",onAbort,{once:true});if(stopped)throw phaseError("unavailable");if(opts?.prepare){let timer2;try{await Promise.race([opts.prepare(work.signal,deadline),aborted2,new Promise(resolve6=>{timer2=setTimeout(()=>{work.abort(new DOMException("the goal follow's deadline passed","TimeoutError"));setTimeout(resolve6,0)},Math.min(deadline-Date.now(),2147483647))})]);work.signal.throwIfAborted()}catch(err3){throw stopped?phaseError("unavailable"):work.signal.aborted&&!unansweredRequest(err3)?phaseError("deadline-exceeded"):err3}finally{clearTimeout(timer2)}}subscribe(opts?.currentNc?.()??nc);unbindReconnect=opts?.onReconnect?.(replaceConnection);for(;;){const preparing=activeNc;try{await bounded(()=>preparing.flush(),deadline)}catch(err3){if(!stopped&&preparing!==activeNc)continue;throw err3}if(stopped)throw phaseError("unavailable");const current2=opts?.currentNc?.();if(current2&¤t2!==activeNc)subscribe(current2);if(preparing===activeNc){progressReady=true;break}}if(stopped)throw phaseError("unavailable");submitted=true;let attributed;let submission;try{attributed=await bounded(()=>submission=submit(work.signal),deadline)}catch(err3){work.abort();let turn;const cause=submission?await Promise.race([submission.then(()=>err3,failure2=>failure2),new Promise(resolve6=>{turn=setTimeout(()=>resolve6(err3),0)})]).finally(()=>clearTimeout(turn)):err3;if(cause instanceof EpEnvelopeError&&cause.outcome==="not-executed")throw cause;const failure=stopped?phaseError("unavailable"):err3;const message2=failure instanceof Error?failure.message:String(failure);throw new EpEnvelopeError(failure instanceof EpEnvelopeError?failure.code:"unavailable",failure instanceof EpEnvelopeError&&failure.outcome==="unknown"&&message2.includes("do NOT retry")?message2:`${message2}; the submission outcome is unknown. It may have been accepted or executed; do NOT retry without inspecting 'ps'/'inspect' first (SPEC 13.6)`,cause instanceof EpEnvelopeError?cause.details:void 0,"unknown")}if(attributed.reply.ok!==true)return attributed;const acceptance=attributed.reply.data;const goalId=acceptance?.goalId;if(typeof goalId!=="string")return attributed;const acceptedFingerprint=typeof acceptance?.fingerprint==="string"?acceptance.fingerprint:void 0;const acceptedBy=attributed.responder;const acceptedKey2=terminalKey(goalId,acceptedBy.instanceId,acceptedBy.epoch);const readinessDeadlineMs=acceptance?.readinessDeadlineMs;const followDeadlineMs=typeof readinessDeadlineMs==="number"&&Number.isSafeInteger(readinessDeadlineMs)&&readinessDeadlineMs>=0?Math.max(deadlineMs,readinessDeadlineMs+GOAL_FOLLOW_MARGIN_MS):deadlineMs;deadline=Date.now()+followDeadlineMs;const reconcileAt=deadline-Math.min(deadlineMs,followDeadlineMs/2);let finalReadRequested=false;const reconcile=async()=>{if(!opts?.reconcile||completed||stopped||reading||!progressReady)return;reading=true;needsReconcile=false;try{const result=await opts.reconcile(goalId,attributed,{caller:{...acceptingCaller},signal:work.signal,deadlineMs:Math.max(1,deadline-Date.now())});if(completed||stopped||Date.now()>=deadline)return;unansweredRead=void 0;if(!result||typeof result!=="object"||result.goalId!==goalId)throw new EpEnvelopeError("internal","goal-result reply is malformed or names a different goal; it cannot authorize this outcome (SPEC 13.6)");if(result.result!==void 0){const ref={endpoint,caller:acceptingCaller,goalId};const fact=await verifyFact(result.result,"goal-result reply",ref);if(acceptedFingerprint!==void 0&&fact.fingerprint!==acceptedFingerprint)throw new EpEnvelopeError("internal","goal result fingerprint does not match the accepted goal (SPEC 13.6)");if(fact.committer!==void 0&&fact.committer.instanceId!==acceptedBy.instanceId)throw new EpEnvelopeError("internal",`goal result fact was committed by instance ${fact.committer.instanceId}, not ${acceptedBy.instanceId}, which accepted the goal; it cannot authorize this outcome (SPEC 13.6)`);terminals.set(acceptedKey2,{state:fact.state,data:fact.data})}}catch(err3){if(!completed&&!stopped&&Date.now()<deadline){if(err3 instanceof EpEnvelopeError&&err3.outcome==="not-executed"&&unansweredRequest(err3)){unansweredRead=err3;readRetryAt=Date.now()+UNANSWERED_READ_RETRY_MS}else observationError=err3 instanceof Error?err3:new Error(String(err3))}}finally{reading=false;if(!completed&&!stopped)wake?.()}};const current=opts?.currentNc?.();if(current&¤t!==activeNc&&!stopped)replaceConnection(current);needsReconcile=true;while(!terminals.has(acceptedKey2)&&!stopped&&!observationError&&!subError&&Date.now()<deadline){if(!finalReadRequested&&Date.now()>=reconcileAt){finalReadRequested=true;needsReconcile=true}if(readRetryAt!==void 0&&Date.now()>=readRetryAt){readRetryAt=void 0;needsReconcile=true}if(needsReconcile&&!reading)void reconcile();if(terminals.has(acceptedKey2)||stopped||observationError||subError)break;await new Promise(resolve6=>{const until=Math.min(finalReadRequested?deadline:reconcileAt,readRetryAt??Infinity);const timer2=setTimeout(()=>{timers.delete(timer2);wake=void 0;resolve6()},Math.max(0,Math.min(until-Date.now(),2147483647)));timers.add(timer2);wake=()=>{clearTimeout(timer2);timers.delete(timer2);wake=void 0;resolve6()}})}const terminal=terminals.get(acceptedKey2);const observationFailure=(code2,reason)=>({...attributed,reply:{...attributed.reply,ok:false,error:{code:code2,outcome:"unknown",message:`the goal "${goalId}" was accepted, but ${reason}. THE GOAL IS UNAFFECTED - it may already have succeeded; this is not evidence the goal failed. Do NOT retry: another submission could duplicate the effect. Inspect 'ps'/'inspect' first (SPEC 13.6)`}}});if(stopped)return observationFailure("unavailable","the endpoint was stopped while awaiting its outcome");if(observationError)return observationFailure("unavailable",`following its outcome failed: ${observationError.message}`);if(!terminal&&subError)return subError instanceof import_nats_core3.PermissionViolationError?observationFailure("permission-denied",`this caller is NOT PERMITTED to hear its outcome: the broker refused the per-goal progress subscription "${progressSubject}" (${subError.message}); grant this caller the per-goal progress read row`):observationFailure("unavailable",`the per-goal progress subscription "${progressSubject}" FAILED (${subError.name}: ${subError.message}); this is NOT a grant refusal, so changing ACLs is the wrong remedy`);if(!terminal)return observationFailure("deadline-exceeded",`no terminal arrived within ${followDeadlineMs}ms; this is a timeout on the WAIT${unansweredRead?`, and the last result read was not answered (${unansweredRead.message})`:""}`);if(terminal.state==="succeeded")return{...attributed,reply:{...attributed.reply,ok:true,data:terminal.data,error:void 0}};const d2=terminal.data??{};const raw=typeof d2.error==="string"?d2.error:typeof d2.reason==="string"?d2.reason:`the goal settled ${terminal.state}`;const details=Array.isArray(d2.details)?d2.details:void 0;const message=renderLifecycleBlocked(raw,details?{details}:void 0);const fromAccept=lifecycleBlockedFrom(attributed.reply.error);const merged=details??(fromAccept?[fromAccept]:void 0);return{...attributed,reply:{...attributed.reply,ok:false,error:{code:terminal.state,message,...merged?{details:merged}:{}}}}}finally{completed=true;opts?.signal?.removeEventListener("abort",onAbort);unbindReconnect?.();activeSub?.unsubscribe();for(const timer2 of timers)clearTimeout(timer2);timers.clear();wake=void 0;work.abort();abortPhase?.()}}var import_nats_core3,UNANSWERED_READ_RETRY_MS;var init_endpoint_goal_follow=__esm({"../../packages/core/dist/endpoint-goal-follow.js"(){"use strict";import_nats_core3=__toESM(require_mod3(),1);init_endpoint_envelope();init_endpoint_subjects();init_subjects();init_endpoint_caller();UNANSWERED_READ_RETRY_MS=250}});import{createHash as createHash4}from"node:crypto";async function contractStoreContext(nc,space2){if(nc===null||typeof nc!=="object"||typeof nc.close!=="function")throw new EpEnvelopeError("failed-precondition","a contract-store context is constructed from ONE binding-layer connection; separate resources are never accepted (SPEC 13.4)");if(typeof space2!=="string"||space2.length===0)throw new EpEnvelopeError("failed-precondition","a contract-store context needs a space");const js=(0,import_jetstream7.jetstream)(nc);const jsm=await(0,import_jetstream7.jetstreamManager)(nc,{checkAPI:false});const ctx=Object.freeze({space:space2});STORE_RESOURCES.set(ctx,{js,jsm});return ctx}function resources(ctx){const r2=ctx===null||typeof ctx!=="object"?void 0:STORE_RESOURCES.get(ctx);if(r2===void 0)throw new EpEnvelopeError("failed-precondition",`the contract-store context was not constructed by contractStoreContext(); a hand-assembled resource bundle never authorizes - the space bond is constructed, not asserted (SPEC 13.4)`);return r2}function contractArtifactDigestHex(bytes){return createHash4("sha256").update(bytes).digest("hex")}function assertCanonicalArtifactBytes(bytes,what2){let text3;try{text3=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new EpEnvelopeError("contract-invalid",`${what2} is not valid UTF-8; only strict canonical JSON is a contract artifact (SPEC 13.7)`)}let value;try{value=JSON.parse(text3)}catch(e3){throw new EpEnvelopeError("contract-invalid",`${what2} does not parse as JSON (${e3.message}); only strict canonical JSON is a contract artifact (SPEC 13.7)`)}let canonical;try{canonical=canonicalJson(value)}catch(e3){throw new EpEnvelopeError("contract-invalid",`${what2} is not interchangeable I-JSON (${e3.message}); only strict canonical JSON is a contract artifact (SPEC 13.7)`)}if(canonical!==text3)throw new EpEnvelopeError("contract-invalid",`${what2} is not its own RFC 8785 canonical serialization; a noncanonical encoding never gets its own content identity (SPEC 13.7)`);return value}function verifyStored(data,digestHex,subject){if(data.length>CONTRACT_ARTIFACT_MAX_BYTES)return void 0;if(contractArtifactDigestHex(data)!==digestHex)return void 0;try{assertCanonicalArtifactBytes(data,`the artifact at ${subject}`)}catch{return void 0}return data}async function fetchContractArtifact(ctx,digestHex,opts={}){const{jsm}=resources(ctx);const stream=epcStreamName(ctx.space);const subject=epcSubject(ctx.space,digestHex);const read=async req=>{try{const stored=await jsm.direct.getMessage(stream,req);return stored===null?"absent":stored.data}catch(e3){if(e3?.code===10037)return"absent";throw new EpEnvelopeError("unavailable",`the contract-store read for ${digestHex} failed (a failed observation is never absence, SPEC 13.7): ${e3?.message??String(e3)}`)}};const last=await read({last_by_subj:subject});if(last==="absent")return void 0;const okLast=verifyStored(last,digestHex,subject);if(okLast!==void 0)return okLast;if(opts.lastOnly)throw new ContractStoreCorruptError(`the message at ${subject} does not recompute its digest as strict canonical JSON (SPEC 13.7)`);const first=await read({seq:0,next_by_subj:subject});if(first==="absent")return void 0;const okFirst=verifyStored(first,digestHex,subject);if(okFirst!==void 0)return okFirst;throw new ContractStoreCorruptError(`no message at ${subject} recomputes its digest as strict canonical JSON (checked both the last and the create-only winner); verify-on-read is the tamper boundary and a store with no verifying artifact never serves (SPEC 13.7)`)}async function fetchContractClosure(ctx,closureDigestRef,extractRefs,opts={}){resources(ctx);const max=opts.maxArtifacts??CONTRACT_CLOSURE_MAX_ARTIFACTS;if(!Number.isSafeInteger(max)||max<=0||max>CONTRACT_CLOSURE_MAX_ARTIFACTS)throw new EpEnvelopeError("failed-precondition",`maxArtifacts must be a positive integer at or below the frozen ${CONTRACT_CLOSURE_MAX_ARTIFACTS}-artifact ceiling (a caller narrows, never widens); got ${JSON.stringify(opts.maxArtifacts)} (SPEC 13.7)`);const budgetMs=opts.walkBudgetMs??3e4;if(!Number.isSafeInteger(budgetMs)||budgetMs<=0)throw new EpEnvelopeError("failed-precondition",`walkBudgetMs must be a positive integer; got ${JSON.stringify(opts.walkBudgetMs)}`);if(typeof extractRefs!=="function")throw new EpEnvelopeError("failed-precondition","a closure fetch requires the reference-resolution seam (extractRefs); the store never guesses a document's reference shape (SPEC 13.7)");const startedAt2=performance.now();const overBudget=()=>performance.now()-startedAt2>budgetMs;const raceBudget=async(p2,what2)=>{opts.signal?.throwIfAborted();const rem=budgetMs-(performance.now()-startedAt2);if(rem<=0)throw new EpEnvelopeError("deadline-exceeded",`the closure walk exhausted its ${budgetMs}ms budget before ${what2} (SPEC 13.7/13.8)`);let timer2;let onAbort;const bound=new Promise((_3,reject)=>{timer2=setTimeout(()=>reject(new EpEnvelopeError("deadline-exceeded",`the closure walk exceeded its ${budgetMs}ms budget during ${what2}; a closure fetch is bounded and fails loud, never hangs (SPEC 13.7/13.8)`)),rem);onAbort=()=>reject(opts.signal?.reason);opts.signal?.addEventListener("abort",onAbort,{once:true})});try{return await Promise.race([p2,bound])}finally{clearTimeout(timer2);if(onAbort)opts.signal?.removeEventListener("abort",onAbort)}};const getArtifact=hex3=>{const memo=opts.artifactMemo;if(!memo)return fetchContractArtifact(ctx,hex3);const hit=memo.get(hex3);if(hit)return hit;const p2=fetchContractArtifact(ctx,hex3);p2.catch(()=>{});memo.set(hex3,p2);return p2};const closureHex=contractRefToHex(closureDigestRef);const manifestBytes=await raceBudget(getArtifact(closureHex),`the manifest fetch for ${closureHex}`);if(manifestBytes===void 0)throw new EpEnvelopeError("failed-precondition",`the closure manifest ${closureHex} is not published; a closure digest names its manifest artifact (SPEC 13.7)`);const manifest=parseClosureManifest(assertCanonicalArtifactBytes(manifestBytes,`the manifest ${closureHex}`),`the manifest ${closureHex}`);const rootHex=contractRefToHex(manifest.root);const out=new Map;let totalBytes=0;let rootReReached=false;const queue=[{hex:rootHex,depth:0}];while(queue.length>0){if(overBudget())throw new EpEnvelopeError("deadline-exceeded",`the closure walk for ${closureHex} exceeded its ${budgetMs}ms budget; a closure fetch is bounded and fails loud, never hangs (SPEC 13.7/13.8)`);const{hex:hex3,depth}=queue.shift();if(depth>CONTRACT_CLOSURE_MAX_REF_DEPTH)throw new EpEnvelopeError("contract-invalid",`the closure walk for ${closureHex} exceeds the ${CONTRACT_CLOSURE_MAX_REF_DEPTH}-deep reference chain bound (SPEC 13.7)`);if(out.has(hex3))continue;if(out.size>=max)throw new EpEnvelopeError("failed-precondition",`the contract closure exceeds the ${max}-artifact bound; a truncated closure never verifies as complete (SPEC 13.7)`);const bytes=await raceBudget(getArtifact(hex3),`the fetch of ${hex3}`);if(bytes===void 0)throw new EpEnvelopeError("failed-precondition",`the closure references artifact ${hex3} but it is not published; a closure is fetched all-or-nothing (SPEC 13.7)`);totalBytes+=bytes.length;if(totalBytes>CONTRACT_CLOSURE_MAX_BYTES)throw new EpEnvelopeError("contract-invalid",`the closure for ${closureHex} exceeds the ${CONTRACT_CLOSURE_MAX_BYTES}-byte bound (SPEC 13.7)`);out.set(hex3,bytes);const refs=extractRefs(new Uint8Array(bytes),hex3);if(!Array.isArray(refs)||!refs.every(r2=>typeof r2==="string"))throw new EpEnvelopeError("internal",`the reference-resolution seam returned a non-string-array for ${hex3}; a garbled resolution never extends a closure (SPEC 13.7)`);if(refs.length>CONTRACT_CLOSURE_MAX_ARTIFACTS)throw new EpEnvelopeError("contract-invalid",`artifact ${hex3} names ${refs.length} references, above the ${CONTRACT_CLOSURE_MAX_ARTIFACTS}-reference cap; an unbounded reference list never extends a closure (SPEC 13.7)`);if(overBudget())throw new EpEnvelopeError("deadline-exceeded",`the closure walk for ${closureHex} exceeded its ${budgetMs}ms budget resolving references for ${hex3} (SPEC 13.7/13.8)`);for(const r2 of refs){const rHex=contractRefToHex(r2);if(rHex===rootHex)rootReReached=true;queue.push({hex:rHex,depth:depth+1})}}const walked=new Set;for(const hex3 of out.keys())if(hex3!==rootHex||rootReReached)walked.add(sha256Ref(hex3));const memberSet=new Set(manifest.members);for(const m2 of walked)if(!memberSet.has(m2))throw new EpEnvelopeError("contract-invalid",`the closure walk reached ${m2} but the manifest ${closureHex} does not name it; an under-naming manifest never verifies (SPEC 13.7)`);for(const m2 of memberSet)if(!walked.has(m2))throw new EpEnvelopeError("contract-invalid",`the manifest ${closureHex} names ${m2} but the walk never reached it; an over-naming manifest never verifies (SPEC 13.7)`);return{manifest,artifacts:out}}var import_jetstream7,import_transport_node6,CONTRACT_ARTIFACT_MAX_BYTES,CONTRACT_CLOSURE_MAX_BYTES,CONTRACT_CLOSURE_MAX_REF_DEPTH,STORE_RESOURCES,ContractStoreCorruptError;var init_endpoint_contract_store=__esm({"../../packages/core/dist/endpoint-contract-store.js"(){"use strict";import_jetstream7=__toESM(require_mod4(),1);import_transport_node6=__toESM(require_transport_node(),1);init_canonical();init_endpoint_envelope();init_endpoint_records();init_endpoint_subjects();init_endpoint_binding();init_contract_manifest();init_contract_manifest();CONTRACT_ARTIFACT_MAX_BYTES=256*1024;CONTRACT_CLOSURE_MAX_BYTES=1024*1024;CONTRACT_CLOSURE_MAX_REF_DEPTH=32;STORE_RESOURCES=new WeakMap;ContractStoreCorruptError=class extends EpEnvelopeError{constructor(message){super("internal",message)}}}});var SERVICE_RENEWAL_TTL_SECONDS,SERVICE_AUTHORITY_MAX_BYTES,SERVICE_CALLER_PAYLOAD_OVERHEAD,SERVICE_CALLER_PAYLOAD_FLOOR,MANAGER_START_PAYLOAD_FLOOR;var init_service_authority_limits=__esm({"../../packages/core/dist/service-authority-limits.js"(){"use strict";init_endpoint_contract_store();SERVICE_RENEWAL_TTL_SECONDS=24*60*60;SERVICE_AUTHORITY_MAX_BYTES=2*1024*1024;SERVICE_CALLER_PAYLOAD_OVERHEAD=1024;SERVICE_CALLER_PAYLOAD_FLOOR=SERVICE_AUTHORITY_MAX_BYTES+SERVICE_CALLER_PAYLOAD_OVERHEAD;MANAGER_START_PAYLOAD_FLOOR=CONTRACT_ARTIFACT_MAX_BYTES+SERVICE_CALLER_PAYLOAD_OVERHEAD}});var init_endpoint_capability_policy=__esm({"../../packages/core/dist/endpoint-capability-policy.js"(){"use strict";init_canonical();init_endpoint_error();init_endpoint_grants();init_endpoint_subjects();init_subjects()}});var import_nkeys4;var init_service_gate=__esm({"../../packages/core/dist/service-gate.js"(){"use strict";import_nkeys4=__toESM(require_mod(),1);init_canonical();init_endpoint_error();init_endpoint_capability_policy();init_endpoint_subjects()}});function setEd25519Helper(lib){helper=lib}var Types,nacl,denoHelper,helper,crc16tab,NKeysErrorCode2,Prefix2,Algorithms;var init_jwt=__esm({"../../node_modules/.pnpm/@nats-io+jwt@0.0.10-5/node_modules/@nats-io/jwt/esm/jwt.js"(){(function(Types2){Types2["Operator"]="operator";Types2["Account"]="account";Types2["User"]="user";Types2["Activation"]="activation";Types2["AuthorizationResponse"]="authorization_response"})(Types||(Types={}));(function(nacl2){"use strict";var u64=function(h3,l2){this.hi=h3|0>>>0;this.lo=l2|0>>>0};var gf=function(init){var i2,r2=new Float64Array(16);if(init)for(i2=0;i2<init.length;i2++)r2[i2]=init[i2];return r2};var randombytes=function(){throw new Error("no PRNG")};var _0=new Uint8Array(16);var _9=new Uint8Array(32);_9[0]=9;var gf0=gf(),gf1=gf([1]),_121665=gf([56129,1]),D2=gf([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),D22=gf([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),X2=gf([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),Y2=gf([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),I2=gf([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function L32(x2,c3){return x2<<c3|x2>>>32-c3}function ld32(x2,i2){var u2=x2[i2+3]&255;u2=u2<<8|x2[i2+2]&255;u2=u2<<8|x2[i2+1]&255;return u2<<8|x2[i2+0]&255}function dl64(x2,i2){var h3=x2[i2]<<24|x2[i2+1]<<16|x2[i2+2]<<8|x2[i2+3];var l2=x2[i2+4]<<24|x2[i2+5]<<16|x2[i2+6]<<8|x2[i2+7];return new u64(h3,l2)}function st32(x2,j2,u2){var i2;for(i2=0;i2<4;i2++){x2[j2+i2]=u2&255;u2>>>=8}}function ts64(x2,i2,u2){x2[i2]=u2.hi>>24&255;x2[i2+1]=u2.hi>>16&255;x2[i2+2]=u2.hi>>8&255;x2[i2+3]=u2.hi&255;x2[i2+4]=u2.lo>>24&255;x2[i2+5]=u2.lo>>16&255;x2[i2+6]=u2.lo>>8&255;x2[i2+7]=u2.lo&255}function vn2(x2,xi2,y3,yi2,n2){var i2,d2=0;for(i2=0;i2<n2;i2++)d2|=x2[xi2+i2]^y3[yi2+i2];return(1&d2-1>>>8)-1}function crypto_verify_16(x2,xi2,y3,yi2){return vn2(x2,xi2,y3,yi2,16)}function crypto_verify_32(x2,xi2,y3,yi2){return vn2(x2,xi2,y3,yi2,32)}function core(out,inp,k2,c3,h3){var w2=new Uint32Array(16),x2=new Uint32Array(16),y3=new Uint32Array(16),t2=new Uint32Array(4);var i2,j2,m2;for(i2=0;i2<4;i2++){x2[5*i2]=ld32(c3,4*i2);x2[1+i2]=ld32(k2,4*i2);x2[6+i2]=ld32(inp,4*i2);x2[11+i2]=ld32(k2,16+4*i2)}for(i2=0;i2<16;i2++)y3[i2]=x2[i2];for(i2=0;i2<20;i2++){for(j2=0;j2<4;j2++){for(m2=0;m2<4;m2++)t2[m2]=x2[(5*j2+4*m2)%16];t2[1]^=L32(t2[0]+t2[3]|0,7);t2[2]^=L32(t2[1]+t2[0]|0,9);t2[3]^=L32(t2[2]+t2[1]|0,13);t2[0]^=L32(t2[3]+t2[2]|0,18);for(m2=0;m2<4;m2++)w2[4*j2+(j2+m2)%4]=t2[m2]}for(m2=0;m2<16;m2++)x2[m2]=w2[m2]}if(h3){for(i2=0;i2<16;i2++)x2[i2]=x2[i2]+y3[i2]|0;for(i2=0;i2<4;i2++){x2[5*i2]=x2[5*i2]-ld32(c3,4*i2)|0;x2[6+i2]=x2[6+i2]-ld32(inp,4*i2)|0}for(i2=0;i2<4;i2++){st32(out,4*i2,x2[5*i2]);st32(out,16+4*i2,x2[6+i2])}}else{for(i2=0;i2<16;i2++)st32(out,4*i2,x2[i2]+y3[i2]|0)}}function crypto_core_salsa20(out,inp,k2,c3){core(out,inp,k2,c3,false);return 0}function crypto_core_hsalsa20(out,inp,k2,c3){core(out,inp,k2,c3,true);return 0}var sigma=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function crypto_stream_salsa20_xor(c3,cpos,m2,mpos,b3,n2,k2){var z3=new Uint8Array(16),x2=new Uint8Array(64);var u2,i2;if(!b3)return 0;for(i2=0;i2<16;i2++)z3[i2]=0;for(i2=0;i2<8;i2++)z3[i2]=n2[i2];while(b3>=64){crypto_core_salsa20(x2,z3,k2,sigma);for(i2=0;i2<64;i2++)c3[cpos+i2]=(m2?m2[mpos+i2]:0)^x2[i2];u2=1;for(i2=8;i2<16;i2++){u2=u2+(z3[i2]&255)|0;z3[i2]=u2&255;u2>>>=8}b3-=64;cpos+=64;if(m2)mpos+=64}if(b3>0){crypto_core_salsa20(x2,z3,k2,sigma);for(i2=0;i2<b3;i2++)c3[cpos+i2]=(m2?m2[mpos+i2]:0)^x2[i2]}return 0}function crypto_stream_salsa20(c3,cpos,d2,n2,k2){return crypto_stream_salsa20_xor(c3,cpos,null,0,d2,n2,k2)}function crypto_stream(c3,cpos,d2,n2,k2){var s3=new Uint8Array(32);crypto_core_hsalsa20(s3,n2,k2,sigma);return crypto_stream_salsa20(c3,cpos,d2,n2.subarray(16),s3)}function crypto_stream_xor(c3,cpos,m2,mpos,d2,n2,k2){var s3=new Uint8Array(32);crypto_core_hsalsa20(s3,n2,k2,sigma);return crypto_stream_salsa20_xor(c3,cpos,m2,mpos,d2,n2.subarray(16),s3)}function add1305(h3,c3){var j2,u2=0;for(j2=0;j2<17;j2++){u2=u2+(h3[j2]+c3[j2]|0)|0;h3[j2]=u2&255;u2>>>=8}}var minusp=new Uint32Array([5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252]);function crypto_onetimeauth(out,outpos,m2,mpos,n2,k2){var s3,i2,j2,u2;var x2=new Uint32Array(17),r2=new Uint32Array(17),h3=new Uint32Array(17),c3=new Uint32Array(17),g2=new Uint32Array(17);for(j2=0;j2<17;j2++)r2[j2]=h3[j2]=0;for(j2=0;j2<16;j2++)r2[j2]=k2[j2];r2[3]&=15;r2[4]&=252;r2[7]&=15;r2[8]&=252;r2[11]&=15;r2[12]&=252;r2[15]&=15;while(n2>0){for(j2=0;j2<17;j2++)c3[j2]=0;for(j2=0;j2<16&&j2<n2;++j2)c3[j2]=m2[mpos+j2];c3[j2]=1;mpos+=j2;n2-=j2;add1305(h3,c3);for(i2=0;i2<17;i2++){x2[i2]=0;for(j2=0;j2<17;j2++)x2[i2]=x2[i2]+h3[j2]*(j2<=i2?r2[i2-j2]:320*r2[i2+17-j2]|0)|0|0}for(i2=0;i2<17;i2++)h3[i2]=x2[i2];u2=0;for(j2=0;j2<16;j2++){u2=u2+h3[j2]|0;h3[j2]=u2&255;u2>>>=8}u2=u2+h3[16]|0;h3[16]=u2&3;u2=5*(u2>>>2)|0;for(j2=0;j2<16;j2++){u2=u2+h3[j2]|0;h3[j2]=u2&255;u2>>>=8}u2=u2+h3[16]|0;h3[16]=u2}for(j2=0;j2<17;j2++)g2[j2]=h3[j2];add1305(h3,minusp);s3=-(h3[16]>>>7)|0;for(j2=0;j2<17;j2++)h3[j2]^=s3&(g2[j2]^h3[j2]);for(j2=0;j2<16;j2++)c3[j2]=k2[j2+16];c3[16]=0;add1305(h3,c3);for(j2=0;j2<16;j2++)out[outpos+j2]=h3[j2];return 0}function crypto_onetimeauth_verify(h3,hpos,m2,mpos,n2,k2){var x2=new Uint8Array(16);crypto_onetimeauth(x2,0,m2,mpos,n2,k2);return crypto_verify_16(h3,hpos,x2,0)}function crypto_secretbox(c3,m2,d2,n2,k2){var i2;if(d2<32)return-1;crypto_stream_xor(c3,0,m2,0,d2,n2,k2);crypto_onetimeauth(c3,16,c3,32,d2-32,c3);for(i2=0;i2<16;i2++)c3[i2]=0;return 0}function crypto_secretbox_open(m2,c3,d2,n2,k2){var i2;var x2=new Uint8Array(32);if(d2<32)return-1;crypto_stream(x2,0,32,n2,k2);if(crypto_onetimeauth_verify(c3,16,c3,32,d2-32,x2)!==0)return-1;crypto_stream_xor(m2,0,c3,0,d2,n2,k2);for(i2=0;i2<32;i2++)m2[i2]=0;return 0}function set25519(r2,a3){var i2;for(i2=0;i2<16;i2++)r2[i2]=a3[i2]|0}function car25519(o3){var c3;var i2;for(i2=0;i2<16;i2++){o3[i2]+=65536;c3=Math.floor(o3[i2]/65536);o3[(i2+1)*(i2<15?1:0)]+=c3-1+37*(c3-1)*(i2===15?1:0);o3[i2]-=c3*65536}}function sel25519(p2,q2,b3){var t2,c3=~(b3-1);for(var i2=0;i2<16;i2++){t2=c3&(p2[i2]^q2[i2]);p2[i2]^=t2;q2[i2]^=t2}}function pack25519(o3,n2){var i2,j2,b3;var m2=gf(),t2=gf();for(i2=0;i2<16;i2++)t2[i2]=n2[i2];car25519(t2);car25519(t2);car25519(t2);for(j2=0;j2<2;j2++){m2[0]=t2[0]-65517;for(i2=1;i2<15;i2++){m2[i2]=t2[i2]-65535-(m2[i2-1]>>16&1);m2[i2-1]&=65535}m2[15]=t2[15]-32767-(m2[14]>>16&1);b3=m2[15]>>16&1;m2[14]&=65535;sel25519(t2,m2,1-b3)}for(i2=0;i2<16;i2++){o3[2*i2]=t2[i2]&255;o3[2*i2+1]=t2[i2]>>8}}function neq25519(a3,b3){var c3=new Uint8Array(32),d2=new Uint8Array(32);pack25519(c3,a3);pack25519(d2,b3);return crypto_verify_32(c3,0,d2,0)}function par25519(a3){var d2=new Uint8Array(32);pack25519(d2,a3);return d2[0]&1}function unpack25519(o3,n2){var i2;for(i2=0;i2<16;i2++)o3[i2]=n2[2*i2]+(n2[2*i2+1]<<8);o3[15]&=32767}function A2(o3,a3,b3){var i2;for(i2=0;i2<16;i2++)o3[i2]=a3[i2]+b3[i2]|0}function Z2(o3,a3,b3){var i2;for(i2=0;i2<16;i2++)o3[i2]=a3[i2]-b3[i2]|0}function M2(o3,a3,b3){var i2,j2,t2=new Float64Array(31);for(i2=0;i2<31;i2++)t2[i2]=0;for(i2=0;i2<16;i2++){for(j2=0;j2<16;j2++){t2[i2+j2]+=a3[i2]*b3[j2]}}for(i2=0;i2<15;i2++){t2[i2]+=38*t2[i2+16]}for(i2=0;i2<16;i2++)o3[i2]=t2[i2];car25519(o3);car25519(o3)}function S2(o3,a3){M2(o3,a3,a3)}function inv25519(o3,i2){var c3=gf();var a3;for(a3=0;a3<16;a3++)c3[a3]=i2[a3];for(a3=253;a3>=0;a3--){S2(c3,c3);if(a3!==2&&a3!==4)M2(c3,c3,i2)}for(a3=0;a3<16;a3++)o3[a3]=c3[a3]}function pow2523(o3,i2){var c3=gf();var a3;for(a3=0;a3<16;a3++)c3[a3]=i2[a3];for(a3=250;a3>=0;a3--){S2(c3,c3);if(a3!==1)M2(c3,c3,i2)}for(a3=0;a3<16;a3++)o3[a3]=c3[a3]}function crypto_scalarmult(q2,n2,p2){var z3=new Uint8Array(32);var x2=new Float64Array(80),r2,i2;var a3=gf(),b3=gf(),c3=gf(),d2=gf(),e3=gf(),f2=gf();for(i2=0;i2<31;i2++)z3[i2]=n2[i2];z3[31]=n2[31]&127|64;z3[0]&=248;unpack25519(x2,p2);for(i2=0;i2<16;i2++){b3[i2]=x2[i2];d2[i2]=a3[i2]=c3[i2]=0}a3[0]=d2[0]=1;for(i2=254;i2>=0;--i2){r2=z3[i2>>>3]>>>(i2&7)&1;sel25519(a3,b3,r2);sel25519(c3,d2,r2);A2(e3,a3,c3);Z2(a3,a3,c3);A2(c3,b3,d2);Z2(b3,b3,d2);S2(d2,e3);S2(f2,a3);M2(a3,c3,a3);M2(c3,b3,e3);A2(e3,a3,c3);Z2(a3,a3,c3);S2(b3,a3);Z2(c3,d2,f2);M2(a3,c3,_121665);A2(a3,a3,d2);M2(c3,c3,a3);M2(a3,d2,f2);M2(d2,b3,x2);S2(b3,e3);sel25519(a3,b3,r2);sel25519(c3,d2,r2)}for(i2=0;i2<16;i2++){x2[i2+16]=a3[i2];x2[i2+32]=c3[i2];x2[i2+48]=b3[i2];x2[i2+64]=d2[i2]}var x32=x2.subarray(32);var x16=x2.subarray(16);inv25519(x32,x32);M2(x16,x16,x32);pack25519(q2,x16);return 0}function crypto_scalarmult_base(q2,n2){return crypto_scalarmult(q2,n2,_9)}function crypto_box_keypair(y3,x2){randombytes(x2,32);return crypto_scalarmult_base(y3,x2)}function crypto_box_beforenm(k2,y3,x2){var s3=new Uint8Array(32);crypto_scalarmult(s3,x2,y3);return crypto_core_hsalsa20(k2,_0,s3,sigma)}var crypto_box_afternm=crypto_secretbox;var crypto_box_open_afternm=crypto_secretbox_open;function crypto_box(c3,m2,d2,n2,y3,x2){var k2=new Uint8Array(32);crypto_box_beforenm(k2,y3,x2);return crypto_box_afternm(c3,m2,d2,n2,k2)}function crypto_box_open(m2,c3,d2,n2,y3,x2){var k2=new Uint8Array(32);crypto_box_beforenm(k2,y3,x2);return crypto_box_open_afternm(m2,c3,d2,n2,k2)}function add64(){var a3=0,b3=0,c3=0,d2=0,m16=65535,l2,h3,i2;for(i2=0;i2<arguments.length;i2++){l2=arguments[i2].lo;h3=arguments[i2].hi;a3+=l2&m16;b3+=l2>>>16;c3+=h3&m16;d2+=h3>>>16}b3+=a3>>>16;c3+=b3>>>16;d2+=c3>>>16;return new u64(c3&m16|d2<<16,a3&m16|b3<<16)}function shr64(x2,c3){return new u64(x2.hi>>>c3,x2.lo>>>c3|x2.hi<<32-c3)}function xor64(){var l2=0,h3=0,i2;for(i2=0;i2<arguments.length;i2++){l2^=arguments[i2].lo;h3^=arguments[i2].hi}return new u64(h3,l2)}function R2(x2,c3){var h3,l2,c1=32-c3;if(c3<32){h3=x2.hi>>>c3|x2.lo<<c1;l2=x2.lo>>>c3|x2.hi<<c1}else if(c3<64){h3=x2.lo>>>c3|x2.hi<<c1;l2=x2.hi>>>c3|x2.lo<<c1}return new u64(h3,l2)}function Ch(x2,y3,z3){var h3=x2.hi&y3.hi^~x2.hi&z3.hi,l2=x2.lo&y3.lo^~x2.lo&z3.lo;return new u64(h3,l2)}function Maj(x2,y3,z3){var h3=x2.hi&y3.hi^x2.hi&z3.hi^y3.hi&z3.hi,l2=x2.lo&y3.lo^x2.lo&z3.lo^y3.lo&z3.lo;return new u64(h3,l2)}function Sigma0(x2){return xor64(R2(x2,28),R2(x2,34),R2(x2,39))}function Sigma1(x2){return xor64(R2(x2,14),R2(x2,18),R2(x2,41))}function sigma0(x2){return xor64(R2(x2,1),R2(x2,8),shr64(x2,7))}function sigma1(x2){return xor64(R2(x2,19),R2(x2,61),shr64(x2,6))}var K2=[new u64(1116352408,3609767458),new u64(1899447441,602891725),new u64(3049323471,3964484399),new u64(3921009573,2173295548),new u64(961987163,4081628472),new u64(1508970993,3053834265),new u64(2453635748,2937671579),new u64(2870763221,3664609560),new u64(3624381080,2734883394),new u64(310598401,1164996542),new u64(607225278,1323610764),new u64(1426881987,3590304994),new u64(1925078388,4068182383),new u64(2162078206,991336113),new u64(2614888103,633803317),new u64(3248222580,3479774868),new u64(3835390401,2666613458),new u64(4022224774,944711139),new u64(264347078,2341262773),new u64(604807628,2007800933),new u64(770255983,1495990901),new u64(1249150122,1856431235),new u64(1555081692,3175218132),new u64(1996064986,2198950837),new u64(2554220882,3999719339),new u64(2821834349,766784016),new u64(2952996808,2566594879),new u64(3210313671,3203337956),new u64(3336571891,1034457026),new u64(3584528711,2466948901),new u64(113926993,3758326383),new u64(338241895,168717936),new u64(666307205,1188179964),new u64(773529912,1546045734),new u64(1294757372,1522805485),new u64(1396182291,2643833823),new u64(1695183700,2343527390),new u64(1986661051,1014477480),new u64(2177026350,1206759142),new u64(2456956037,344077627),new u64(2730485921,1290863460),new u64(2820302411,3158454273),new u64(3259730800,3505952657),new u64(3345764771,106217008),new u64(3516065817,3606008344),new u64(3600352804,1432725776),new u64(4094571909,1467031594),new u64(275423344,851169720),new u64(430227734,3100823752),new u64(506948616,1363258195),new u64(659060556,3750685593),new u64(883997877,3785050280),new u64(958139571,3318307427),new u64(1322822218,3812723403),new u64(1537002063,2003034995),new u64(1747873779,3602036899),new u64(1955562222,1575990012),new u64(2024104815,1125592928),new u64(2227730452,2716904306),new u64(2361852424,442776044),new u64(2428436474,593698344),new u64(2756734187,3733110249),new u64(3204031479,2999351573),new u64(3329325298,3815920427),new u64(3391569614,3928383900),new u64(3515267271,566280711),new u64(3940187606,3454069534),new u64(4118630271,4000239992),new u64(116418474,1914138554),new u64(174292421,2731055270),new u64(289380356,3203993006),new u64(460393269,320620315),new u64(685471733,587496836),new u64(852142971,1086792851),new u64(1017036298,365543100),new u64(1126000580,2618297676),new u64(1288033470,3409855158),new u64(1501505948,4234509866),new u64(1607167915,987167468),new u64(1816402316,1246189591)];function crypto_hashblocks(x2,m2,n2){var z3=[],b3=[],a3=[],w2=[],t2,i2,j2;for(i2=0;i2<8;i2++)z3[i2]=a3[i2]=dl64(x2,8*i2);var pos=0;while(n2>=128){for(i2=0;i2<16;i2++)w2[i2]=dl64(m2,8*i2+pos);for(i2=0;i2<80;i2++){for(j2=0;j2<8;j2++)b3[j2]=a3[j2];t2=add64(a3[7],Sigma1(a3[4]),Ch(a3[4],a3[5],a3[6]),K2[i2],w2[i2%16]);b3[7]=add64(t2,Sigma0(a3[0]),Maj(a3[0],a3[1],a3[2]));b3[3]=add64(b3[3],t2);for(j2=0;j2<8;j2++)a3[(j2+1)%8]=b3[j2];if(i2%16===15){for(j2=0;j2<16;j2++){w2[j2]=add64(w2[j2],w2[(j2+9)%16],sigma0(w2[(j2+1)%16]),sigma1(w2[(j2+14)%16]))}}}for(i2=0;i2<8;i2++){a3[i2]=add64(a3[i2],z3[i2]);z3[i2]=a3[i2]}pos+=128;n2-=128}for(i2=0;i2<8;i2++)ts64(x2,8*i2,z3[i2]);return n2}var iv=new Uint8Array([106,9,230,103,243,188,201,8,187,103,174,133,132,202,167,59,60,110,243,114,254,148,248,43,165,79,245,58,95,29,54,241,81,14,82,127,173,230,130,209,155,5,104,140,43,62,108,31,31,131,217,171,251,65,189,107,91,224,205,25,19,126,33,121]);function crypto_hash(out,m2,n2){var h3=new Uint8Array(64),x2=new Uint8Array(256);var i2,b3=n2;for(i2=0;i2<64;i2++)h3[i2]=iv[i2];crypto_hashblocks(h3,m2,n2);n2%=128;for(i2=0;i2<256;i2++)x2[i2]=0;for(i2=0;i2<n2;i2++)x2[i2]=m2[b3-n2+i2];x2[n2]=128;n2=256-128*(n2<112?1:0);x2[n2-9]=0;ts64(x2,n2-8,new u64(b3/536870912|0,b3<<3));crypto_hashblocks(h3,x2,n2);for(i2=0;i2<64;i2++)out[i2]=h3[i2];return 0}function add(p2,q2){var a3=gf(),b3=gf(),c3=gf(),d2=gf(),e3=gf(),f2=gf(),g2=gf(),h3=gf(),t2=gf();Z2(a3,p2[1],p2[0]);Z2(t2,q2[1],q2[0]);M2(a3,a3,t2);A2(b3,p2[0],p2[1]);A2(t2,q2[0],q2[1]);M2(b3,b3,t2);M2(c3,p2[3],q2[3]);M2(c3,c3,D22);M2(d2,p2[2],q2[2]);A2(d2,d2,d2);Z2(e3,b3,a3);Z2(f2,d2,c3);A2(g2,d2,c3);A2(h3,b3,a3);M2(p2[0],e3,f2);M2(p2[1],h3,g2);M2(p2[2],g2,f2);M2(p2[3],e3,h3)}function cswap(p2,q2,b3){var i2;for(i2=0;i2<4;i2++){sel25519(p2[i2],q2[i2],b3)}}function pack(r2,p2){var tx=gf(),ty=gf(),zi2=gf();inv25519(zi2,p2[2]);M2(tx,p2[0],zi2);M2(ty,p2[1],zi2);pack25519(r2,ty);r2[31]^=par25519(tx)<<7}function scalarmult(p2,q2,s3){var b3,i2;set25519(p2[0],gf0);set25519(p2[1],gf1);set25519(p2[2],gf1);set25519(p2[3],gf0);for(i2=255;i2>=0;--i2){b3=s3[i2/8|0]>>(i2&7)&1;cswap(p2,q2,b3);add(q2,p2);add(p2,p2);cswap(p2,q2,b3)}}function scalarbase(p2,s3){var q2=[gf(),gf(),gf(),gf()];set25519(q2[0],X2);set25519(q2[1],Y2);set25519(q2[2],gf1);M2(q2[3],X2,Y2);scalarmult(p2,q2,s3)}function crypto_sign_keypair(pk,sk,seeded){var d2=new Uint8Array(64);var p2=[gf(),gf(),gf(),gf()];var i2;if(!seeded)randombytes(sk,32);crypto_hash(d2,sk,32);d2[0]&=248;d2[31]&=127;d2[31]|=64;scalarbase(p2,d2);pack(pk,p2);for(i2=0;i2<32;i2++)sk[i2+32]=pk[i2];return 0}var L2=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function modL(r2,x2){var carry,i2,j2,k2;for(i2=63;i2>=32;--i2){carry=0;for(j2=i2-32,k2=i2-12;j2<k2;++j2){x2[j2]+=carry-16*x2[i2]*L2[j2-(i2-32)];carry=Math.floor((x2[j2]+128)/256);x2[j2]-=carry*256}x2[j2]+=carry;x2[i2]=0}carry=0;for(j2=0;j2<32;j2++){x2[j2]+=carry-(x2[31]>>4)*L2[j2];carry=x2[j2]>>8;x2[j2]&=255}for(j2=0;j2<32;j2++)x2[j2]-=carry*L2[j2];for(i2=0;i2<32;i2++){x2[i2+1]+=x2[i2]>>8;r2[i2]=x2[i2]&255}}function reduce(r2){var x2=new Float64Array(64),i2;for(i2=0;i2<64;i2++)x2[i2]=r2[i2];for(i2=0;i2<64;i2++)r2[i2]=0;modL(r2,x2)}function crypto_sign(sm,m2,n2,sk){var d2=new Uint8Array(64),h3=new Uint8Array(64),r2=new Uint8Array(64);var i2,j2,x2=new Float64Array(64);var p2=[gf(),gf(),gf(),gf()];crypto_hash(d2,sk,32);d2[0]&=248;d2[31]&=127;d2[31]|=64;var smlen=n2+64;for(i2=0;i2<n2;i2++)sm[64+i2]=m2[i2];for(i2=0;i2<32;i2++)sm[32+i2]=d2[32+i2];crypto_hash(r2,sm.subarray(32),n2+32);reduce(r2);scalarbase(p2,r2);pack(sm,p2);for(i2=32;i2<64;i2++)sm[i2]=sk[i2];crypto_hash(h3,sm,n2+64);reduce(h3);for(i2=0;i2<64;i2++)x2[i2]=0;for(i2=0;i2<32;i2++)x2[i2]=r2[i2];for(i2=0;i2<32;i2++){for(j2=0;j2<32;j2++){x2[i2+j2]+=h3[i2]*d2[j2]}}modL(sm.subarray(32),x2);return smlen}function unpackneg(r2,p2){var t2=gf(),chk=gf(),num=gf(),den=gf(),den2=gf(),den4=gf(),den6=gf();set25519(r2[2],gf1);unpack25519(r2[1],p2);S2(num,r2[1]);M2(den,num,D2);Z2(num,num,r2[2]);A2(den,r2[2],den);S2(den2,den);S2(den4,den2);M2(den6,den4,den2);M2(t2,den6,num);M2(t2,t2,den);pow2523(t2,t2);M2(t2,t2,num);M2(t2,t2,den);M2(t2,t2,den);M2(r2[0],t2,den);S2(chk,r2[0]);M2(chk,chk,den);if(neq25519(chk,num))M2(r2[0],r2[0],I2);S2(chk,r2[0]);M2(chk,chk,den);if(neq25519(chk,num))return-1;if(par25519(r2[0])===p2[31]>>7)Z2(r2[0],gf0,r2[0]);M2(r2[3],r2[0],r2[1]);return 0}function crypto_sign_open(m2,sm,n2,pk){var i2;var t2=new Uint8Array(32),h3=new Uint8Array(64);var p2=[gf(),gf(),gf(),gf()],q2=[gf(),gf(),gf(),gf()];if(n2<64)return-1;if(unpackneg(q2,pk))return-1;for(i2=0;i2<n2;i2++)m2[i2]=sm[i2];for(i2=0;i2<32;i2++)m2[i2+32]=pk[i2];crypto_hash(h3,m2,n2);reduce(h3);scalarmult(p2,q2,h3);scalarbase(q2,sm.subarray(32));add(p2,q2);pack(t2,p2);n2-=64;if(crypto_verify_32(sm,0,t2,0)){for(i2=0;i2<n2;i2++)m2[i2]=0;return-1}for(i2=0;i2<n2;i2++)m2[i2]=sm[i2+64];return n2}var crypto_secretbox_KEYBYTES=32,crypto_secretbox_NONCEBYTES=24,crypto_secretbox_ZEROBYTES=32,crypto_secretbox_BOXZEROBYTES=16,crypto_scalarmult_BYTES=32,crypto_scalarmult_SCALARBYTES=32,crypto_box_PUBLICKEYBYTES=32,crypto_box_SECRETKEYBYTES=32,crypto_box_BEFORENMBYTES=32,crypto_box_NONCEBYTES=crypto_secretbox_NONCEBYTES,crypto_box_ZEROBYTES=crypto_secretbox_ZEROBYTES,crypto_box_BOXZEROBYTES=crypto_secretbox_BOXZEROBYTES,crypto_sign_BYTES=64,crypto_sign_PUBLICKEYBYTES=32,crypto_sign_SECRETKEYBYTES=64,crypto_sign_SEEDBYTES=32,crypto_hash_BYTES=64;nacl2.lowlevel={crypto_core_hsalsa20,crypto_stream_xor,crypto_stream,crypto_stream_salsa20_xor,crypto_stream_salsa20,crypto_onetimeauth,crypto_onetimeauth_verify,crypto_verify_16,crypto_verify_32,crypto_secretbox,crypto_secretbox_open,crypto_scalarmult,crypto_scalarmult_base,crypto_box_beforenm,crypto_box_afternm,crypto_box,crypto_box_open,crypto_box_keypair,crypto_hash,crypto_sign,crypto_sign_keypair,crypto_sign_open,crypto_secretbox_KEYBYTES,crypto_secretbox_NONCEBYTES,crypto_secretbox_ZEROBYTES,crypto_secretbox_BOXZEROBYTES,crypto_scalarmult_BYTES,crypto_scalarmult_SCALARBYTES,crypto_box_PUBLICKEYBYTES,crypto_box_SECRETKEYBYTES,crypto_box_BEFORENMBYTES,crypto_box_NONCEBYTES,crypto_box_ZEROBYTES,crypto_box_BOXZEROBYTES,crypto_sign_BYTES,crypto_sign_PUBLICKEYBYTES,crypto_sign_SECRETKEYBYTES,crypto_sign_SEEDBYTES,crypto_hash_BYTES,gf,D:D2,L:L2,pack25519,unpack25519,M:M2,A:A2,S:S2,Z:Z2,pow2523,add,set25519,modL,scalarmult,scalarbase};function checkLengths(k2,n2){if(k2.length!==crypto_secretbox_KEYBYTES)throw new Error("bad key size");if(n2.length!==crypto_secretbox_NONCEBYTES)throw new Error("bad nonce size")}function checkBoxLengths(pk,sk){if(pk.length!==crypto_box_PUBLICKEYBYTES)throw new Error("bad public key size");if(sk.length!==crypto_box_SECRETKEYBYTES)throw new Error("bad secret key size")}function checkArrayTypes(){for(var i2=0;i2<arguments.length;i2++){if(!(arguments[i2]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}}function cleanup(arr){for(var i2=0;i2<arr.length;i2++)arr[i2]=0}nacl2.randomBytes=function(n2){var b3=new Uint8Array(n2);randombytes(b3,n2);return b3};nacl2.secretbox=function(msg,nonce4,key){checkArrayTypes(msg,nonce4,key);checkLengths(key,nonce4);var m2=new Uint8Array(crypto_secretbox_ZEROBYTES+msg.length);var c3=new Uint8Array(m2.length);for(var i2=0;i2<msg.length;i2++)m2[i2+crypto_secretbox_ZEROBYTES]=msg[i2];crypto_secretbox(c3,m2,m2.length,nonce4,key);return c3.subarray(crypto_secretbox_BOXZEROBYTES)};nacl2.secretbox.open=function(box,nonce4,key){checkArrayTypes(box,nonce4,key);checkLengths(key,nonce4);var c3=new Uint8Array(crypto_secretbox_BOXZEROBYTES+box.length);var m2=new Uint8Array(c3.length);for(var i2=0;i2<box.length;i2++)c3[i2+crypto_secretbox_BOXZEROBYTES]=box[i2];if(c3.length<32)return null;if(crypto_secretbox_open(m2,c3,c3.length,nonce4,key)!==0)return null;return m2.subarray(crypto_secretbox_ZEROBYTES)};nacl2.secretbox.keyLength=crypto_secretbox_KEYBYTES;nacl2.secretbox.nonceLength=crypto_secretbox_NONCEBYTES;nacl2.secretbox.overheadLength=crypto_secretbox_BOXZEROBYTES;nacl2.scalarMult=function(n2,p2){checkArrayTypes(n2,p2);if(n2.length!==crypto_scalarmult_SCALARBYTES)throw new Error("bad n size");if(p2.length!==crypto_scalarmult_BYTES)throw new Error("bad p size");var q2=new Uint8Array(crypto_scalarmult_BYTES);crypto_scalarmult(q2,n2,p2);return q2};nacl2.scalarMult.base=function(n2){checkArrayTypes(n2);if(n2.length!==crypto_scalarmult_SCALARBYTES)throw new Error("bad n size");var q2=new Uint8Array(crypto_scalarmult_BYTES);crypto_scalarmult_base(q2,n2);return q2};nacl2.scalarMult.scalarLength=crypto_scalarmult_SCALARBYTES;nacl2.scalarMult.groupElementLength=crypto_scalarmult_BYTES;nacl2.box=function(msg,nonce4,publicKey,secretKey){var k2=nacl2.box.before(publicKey,secretKey);return nacl2.secretbox(msg,nonce4,k2)};nacl2.box.before=function(publicKey,secretKey){checkArrayTypes(publicKey,secretKey);checkBoxLengths(publicKey,secretKey);var k2=new Uint8Array(crypto_box_BEFORENMBYTES);crypto_box_beforenm(k2,publicKey,secretKey);return k2};nacl2.box.after=nacl2.secretbox;nacl2.box.open=function(msg,nonce4,publicKey,secretKey){var k2=nacl2.box.before(publicKey,secretKey);return nacl2.secretbox.open(msg,nonce4,k2)};nacl2.box.open.after=nacl2.secretbox.open;nacl2.box.keyPair=function(){var pk=new Uint8Array(crypto_box_PUBLICKEYBYTES);var sk=new Uint8Array(crypto_box_SECRETKEYBYTES);crypto_box_keypair(pk,sk);return{publicKey:pk,secretKey:sk}};nacl2.box.keyPair.fromSecretKey=function(secretKey){checkArrayTypes(secretKey);if(secretKey.length!==crypto_box_SECRETKEYBYTES)throw new Error("bad secret key size");var pk=new Uint8Array(crypto_box_PUBLICKEYBYTES);crypto_scalarmult_base(pk,secretKey);return{publicKey:pk,secretKey:new Uint8Array(secretKey)}};nacl2.box.publicKeyLength=crypto_box_PUBLICKEYBYTES;nacl2.box.secretKeyLength=crypto_box_SECRETKEYBYTES;nacl2.box.sharedKeyLength=crypto_box_BEFORENMBYTES;nacl2.box.nonceLength=crypto_box_NONCEBYTES;nacl2.box.overheadLength=nacl2.secretbox.overheadLength;nacl2.sign=function(msg,secretKey){checkArrayTypes(msg,secretKey);if(secretKey.length!==crypto_sign_SECRETKEYBYTES)throw new Error("bad secret key size");var signedMsg=new Uint8Array(crypto_sign_BYTES+msg.length);crypto_sign(signedMsg,msg,msg.length,secretKey);return signedMsg};nacl2.sign.open=function(signedMsg,publicKey){checkArrayTypes(signedMsg,publicKey);if(publicKey.length!==crypto_sign_PUBLICKEYBYTES)throw new Error("bad public key size");var tmp=new Uint8Array(signedMsg.length);var mlen=crypto_sign_open(tmp,signedMsg,signedMsg.length,publicKey);if(mlen<0)return null;var m2=new Uint8Array(mlen);for(var i2=0;i2<m2.length;i2++)m2[i2]=tmp[i2];return m2};nacl2.sign.detached=function(msg,secretKey){var signedMsg=nacl2.sign(msg,secretKey);var sig=new Uint8Array(crypto_sign_BYTES);for(var i2=0;i2<sig.length;i2++)sig[i2]=signedMsg[i2];return sig};nacl2.sign.detached.verify=function(msg,sig,publicKey){checkArrayTypes(msg,sig,publicKey);if(sig.length!==crypto_sign_BYTES)throw new Error("bad signature size");if(publicKey.length!==crypto_sign_PUBLICKEYBYTES)throw new Error("bad public key size");var sm=new Uint8Array(crypto_sign_BYTES+msg.length);var m2=new Uint8Array(crypto_sign_BYTES+msg.length);var i2;for(i2=0;i2<crypto_sign_BYTES;i2++)sm[i2]=sig[i2];for(i2=0;i2<msg.length;i2++)sm[i2+crypto_sign_BYTES]=msg[i2];return crypto_sign_open(m2,sm,sm.length,publicKey)>=0};nacl2.sign.keyPair=function(){var pk=new Uint8Array(crypto_sign_PUBLICKEYBYTES);var sk=new Uint8Array(crypto_sign_SECRETKEYBYTES);crypto_sign_keypair(pk,sk);return{publicKey:pk,secretKey:sk}};nacl2.sign.keyPair.fromSecretKey=function(secretKey){checkArrayTypes(secretKey);if(secretKey.length!==crypto_sign_SECRETKEYBYTES)throw new Error("bad secret key size");var pk=new Uint8Array(crypto_sign_PUBLICKEYBYTES);for(var i2=0;i2<pk.length;i2++)pk[i2]=secretKey[32+i2];return{publicKey:pk,secretKey:new Uint8Array(secretKey)}};nacl2.sign.keyPair.fromSeed=function(seed){checkArrayTypes(seed);if(seed.length!==crypto_sign_SEEDBYTES)throw new Error("bad seed size");var pk=new Uint8Array(crypto_sign_PUBLICKEYBYTES);var sk=new Uint8Array(crypto_sign_SECRETKEYBYTES);for(var i2=0;i2<32;i2++)sk[i2]=seed[i2];crypto_sign_keypair(pk,sk,true);return{publicKey:pk,secretKey:sk}};nacl2.sign.publicKeyLength=crypto_sign_PUBLICKEYBYTES;nacl2.sign.secretKeyLength=crypto_sign_SECRETKEYBYTES;nacl2.sign.seedLength=crypto_sign_SEEDBYTES;nacl2.sign.signatureLength=crypto_sign_BYTES;nacl2.hash=function(msg){checkArrayTypes(msg);var h3=new Uint8Array(crypto_hash_BYTES);crypto_hash(h3,msg,msg.length);return h3};nacl2.hash.hashLength=crypto_hash_BYTES;nacl2.verify=function(x2,y3){checkArrayTypes(x2,y3);if(x2.length===0||y3.length===0)return false;if(x2.length!==y3.length)return false;return vn2(x2,0,y3,0,x2.length)===0?true:false};nacl2.setPRNG=function(fn2){randombytes=fn2};(function(){var crypto2=typeof globalThis!=="undefined"?globalThis.crypto||globalThis.msCrypto:null;if(crypto2&&crypto2.getRandomValues){var QUOTA=65536;nacl2.setPRNG(function(x2,n2){var i2,v3=new Uint8Array(n2);for(i2=0;i2<n2;i2+=QUOTA){crypto2.getRandomValues(v3.subarray(i2,i2+Math.min(n2-i2,QUOTA)))}for(i2=0;i2<n2;i2++)x2[i2]=v3[i2];cleanup(v3)})}else if(typeof __require!=="undefined"){crypto2=__require("crypto");if(crypto2&&crypto2.randomBytes){nacl2.setPRNG(function(x2,n2){var i2,v3=crypto2.randomBytes(n2);for(i2=0;i2<n2;i2++)x2[i2]=v3[i2];cleanup(v3)})}}})()})(typeof module!=="undefined"&&module.exports?module.exports:globalThis.nacl=globalThis.nacl||{});nacl=typeof module!=="undefined"&&module.exports?module.exports:globalThis.nacl;denoHelper={fromSeed:nacl.sign.keyPair.fromSeed,sign:nacl.sign.detached,verify:nacl.sign.detached.verify,randomBytes:nacl.randomBytes,scalarBaseMultiply:nacl.scalarMult.base,seal:nacl.box,open:nacl.box.open};crc16tab=new Uint16Array([0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920]);(function(NKeysErrorCode3){NKeysErrorCode3["InvalidPrefixByte"]="nkeys: invalid prefix byte";NKeysErrorCode3["InvalidKey"]="nkeys: invalid key";NKeysErrorCode3["InvalidPublicKey"]="nkeys: invalid public key";NKeysErrorCode3["InvalidSeedLen"]="nkeys: invalid seed length";NKeysErrorCode3["InvalidSeed"]="nkeys: invalid seed";NKeysErrorCode3["InvalidCurveSeed"]="nkeys: invalid curve seed";NKeysErrorCode3["InvalidCurveKey"]="nkeys: not a valid curve key";NKeysErrorCode3["InvalidCurveOperation"]="nkeys: curve key is not valid for sign/verify";NKeysErrorCode3["InvalidNKeyOperation"]="keys: only curve key can seal/open";NKeysErrorCode3["InvalidEncoding"]="nkeys: invalid encoded key";NKeysErrorCode3["InvalidRecipient"]="nkeys: not a valid recipient public curve key";NKeysErrorCode3["InvalidEncrypted"]="nkeys: encrypted input is not valid";NKeysErrorCode3["CannotSign"]="nkeys: cannot sign, no private key available";NKeysErrorCode3["PublicKeyOnly"]="nkeys: no seed or private key available";NKeysErrorCode3["InvalidChecksum"]="nkeys: invalid checksum";NKeysErrorCode3["SerializationError"]="nkeys: serialization error";NKeysErrorCode3["ApiError"]="nkeys: api error";NKeysErrorCode3["ClearedPair"]="nkeys: pair is cleared"})(NKeysErrorCode2||(NKeysErrorCode2={}));(function(Prefix3){Prefix3[Prefix3["Unknown"]=-1]="Unknown";Prefix3[Prefix3["Seed"]=144]="Seed";Prefix3[Prefix3["Private"]=120]="Private";Prefix3[Prefix3["Operator"]=112]="Operator";Prefix3[Prefix3["Server"]=104]="Server";Prefix3[Prefix3["Cluster"]=16]="Cluster";Prefix3[Prefix3["Account"]=0]="Account";Prefix3[Prefix3["User"]=160]="User";Prefix3[Prefix3["Curve"]=184]="Curve"})(Prefix2||(Prefix2={}));setEd25519Helper(denoHelper);(function(Algorithms2){Algorithms2["v1"]="ed25519";Algorithms2["v2"]="ed25519-nkey"})(Algorithms||(Algorithms={}))}});import{createHash as createHash5}from"node:crypto";function idFromCreds(creds){return identityFromCreds(creds).id}function jwtFromCreds(creds){return creds.match(/BEGIN NATS USER JWT-----\s*([\s\S]*?)\s*------END NATS USER JWT/)?.[1].trim()}function credsFingerprint(creds){const jwt2=jwtFromCreds(creds);if(!jwt2)throw new Error("creds: no NATS user JWT block found - cannot fingerprint");return createHash5("sha256").update(jwt2).digest("hex")}function credsClaims(creds){const payload=jwtFromCreds(creds)?.split(".")[1];if(!payload)throw new Error("creds: no NATS user JWT block found");try{return JSON.parse(Buffer.from(payload,"base64url").toString("utf8"))}catch{throw new Error("creds: undecodable user JWT payload")}}function credsRenewalDelayMs(creds){const claims2=credsClaims(creds);if(typeof claims2.exp!=="number")throw new Error("creds source returned a cred without a numeric exp - a standing-renewal endpoint requires bounded creds (mint with a lifetime, or pass a static string instead of a source)");const iatMs=(typeof claims2.iat==="number"?claims2.iat:Date.now()/1e3)*1e3;const expMs=claims2.exp*1e3;return iatMs+.75*(expMs-iatMs)-Date.now()}function identityFromCreds(creds){const seedM=creds.match(/BEGIN USER NKEY SEED-----\s*([\s\S]*?)\s*------END USER NKEY SEED/);if(!seedM)throw new Error("creds: no user nkey seed block found");const seed=seedM[1].trim();const signer=nativeNkeySigner(new TextEncoder().encode(seed));const id2=signer.getPublicKey();signer.clear();const payload=jwtFromCreds(creds)?.split(".")[1];const sub=payload?JSON.parse(Buffer.from(payload,"base64url").toString("utf8")).sub:void 0;if(sub&&sub!==id2)throw new Error(`creds: seed identity ${id2} != JWT subject ${sub}`);return{id:id2,seed}}var import_nats_core4,import_nkeys5;var init_identity=__esm({"../../packages/core/dist/identity.js"(){"use strict";init_jwt();import_nats_core4=__toESM(require_mod3(),1);import_nkeys5=__toESM(require_mod(),1);init_nkey_signer()}});var ED25519_P;var init_remote_service_authority=__esm({"../../packages/core/dist/remote-service-authority.js"(){"use strict";init_canonical();init_contract_manifest();init_endpoint_contract_store();init_endpoint_error();init_endpoint_subjects();init_endpoint_service();init_identity();init_subjects();init_service_authority_limits();init_service_authority_limits();ED25519_P=(1n<<255n)-19n}});var init_endpoint_supervisor=__esm({"../../packages/core/dist/endpoint-supervisor.js"(){"use strict"}});async function drainAndClose(nc,graceMs=1e3){let timer2;try{if(!nc.isClosed()){await Promise.race([nc.drain().catch(()=>{}),nc.closed(),new Promise(resolve6=>{timer2=setTimeout(resolve6,graceMs)})])}}finally{clearTimeout(timer2);await nc.close()}}var init_connection_cleanup=__esm({"../../packages/core/dist/connection-cleanup.js"(){"use strict"}});function isPermissionDenied(e3){if(e3 instanceof import_nats_core5.PermissionViolationError)return true;if(e3?.cause instanceof import_nats_core5.PermissionViolationError)return true;return/permissions?\s+violation/i.test(String(e3?.message??""))}var import_nats_core5;var init_permission_denied=__esm({"../../packages/core/dist/permission-denied.js"(){"use strict";import_nats_core5=__toESM(require_mod3(),1)}});import{randomUUID}from"node:crypto";import{setTimeout as delay}from"node:timers/promises";function subjectLabel(subjects){return subjects.length===1?subjects[0]:`${subjects.length} filtered subjects`}function abortReason(signal){return signal?.reason instanceof Error?signal.reason:new DOMException("This operation was aborted","AbortError")}var import_transport_node7,import_jetstream8,HISTORY_READER_INACTIVE_MS,MULTI_FILTER_BATCH,MULTI_FILTER_READ_CONCURRENCY,EndpointHistory;var init_endpoint_history=__esm({"../../packages/core/dist/endpoint-history.js"(){"use strict";import_transport_node7=__toESM(require_transport_node(),1);import_jetstream8=__toESM(require_mod4(),1);init_subjects();init_jetstream_missing();init_permission_denied();HISTORY_READER_INACTIVE_MS=5*6e4;MULTI_FILTER_BATCH=1e3;MULTI_FILTER_READ_CONCURRENCY=4;EndpointHistory=class{deps;histLock=Promise.resolve();historyReaderSlots=new Map;constructor(deps){this.deps=deps}get nc(){return this.deps.connection()}get js(){return this.deps.jetstream()}get jsm(){return this.deps.manager()}set jsm(manager){this.deps.setManager(manager)}get space(){return this.deps.space()}get owner(){return this.deps.owner()}get actor(){return this.deps.actor()}get userMode(){return this.deps.userMode()}get connId(){return this.deps.connectionId()}get card(){return this.deps.card()}async channelHistory(channel,opts){const from=opts?.publisher;const subject=from===void 0?chatSubject(this.space,"*","*",channel):chatSubject(this.space,assertValidOwnerToken(from.owner),assertValidOwnerToken(from.actor),channel);return(await this.streamHistory(chatStream(this.space),[subject],opts?.limit??100,void 0,opts?.signal)).map(r2=>r2.msg)}async channelHistoryPage(channel,opts){assertValidChannel(channel);if(!isConcreteChannel(channel))throw new Error("channelHistoryPage requires one concrete channel");const limit=opts?.limit??50;if(!Number.isSafeInteger(limit)||limit<1)throw new Error("channelHistoryPage limit must be a positive safe integer");if(!this.nc||!this.js)throw new Error(this.deps.notLiveMsg());const jsm=this.jsm??=await(0,import_jetstream8.jetstreamManager)(this.nc);const signal=AbortSignal.any([AbortSignal.timeout(1e4),...opts?.signal?[opts.signal]:[]]);signal.throwIfAborted();const stream=chatStream(this.space);const name2=chatHistDurable(this.owner,this.actor,this.deps.requireLifecycleUid("channelHistoryPage"));const subject=chatSubject(this.space,"*","*",channel);const marker=randomUUID();let created;for(;;){signal.throwIfAborted();try{created=await jsm.consumers.add(stream,{name:name2,description:marker,filter_subject:subject,ack_policy:import_jetstream8.AckPolicy.None,deliver_policy:import_jetstream8.DeliverPolicy.All,mem_storage:true,inactive_threshold:(0,import_transport_node7.nanos)(250)});break}catch(e3){if(!(e3 instanceof import_jetstream8.JetStreamApiError)||e3.code!==10148)throw e3;await delay(50,void 0,{signal})}}signal.throwIfAborted();const owns=info=>info.created===created.created&&info.config.description===marker&&info.config.filter_subject===subject;if(!owns(created))throw new Error("channelHistoryPage: consumer ownership was not established");const consumer=await this.js.consumers.get(stream,name2);const pending=created.num_pending;const out=[];let delivered=0;if(pending>0){const iter=await consumer.consume({max_messages:Math.min(pending,32)});const stop=()=>iter.stop(abortReason(signal));signal.addEventListener("abort",stop,{once:true});try{signal.throwIfAborted();for await(const m2 of iter){signal.throwIfAborted();if(!subjectMatches(subject,m2.subject))throw new Error("channelHistoryPage: consumer delivered another channel; ownership was lost");delivered++;const msg=this.deps.decodeHistory(m2);if(msg){out.push(msg);if(out.length>limit+1)out.shift()}if(delivered>=pending)break}}finally{signal.removeEventListener("abort",stop);iter.stop()}signal.throwIfAborted();if(delivered!==pending)throw new Error(`channelHistoryPage: read ${delivered} of ${pending} messages before the window was cut short`)}signal.throwIfAborted();if(!owns(await consumer.info()))throw new Error("channelHistoryPage: consumer ownership was lost");signal.throwIfAborted();return{items:out.slice(-limit),complete:out.length<=limit}}async multiChannelHistory(channels,opts){const subjects=[...new Set(channels.map(channel=>{if(!isConcreteChannel(channel)&&!(channels.length===1&&isChannelFamily(channel)))throw new Error(`multiChannelHistory: "${channel}" is a wildcard channel - name one channel family alone or concrete channels without wildcards`);assertValidChannel(channel);return chatSubject(this.space,"*","*",channel)}))];if(subjects.length===0)return[];const limit=opts?.limit??100;const size=Math.max(1,Math.trunc(opts?.batch??MULTI_FILTER_BATCH));const batches=[];for(let i2=0;i2<subjects.length;i2+=size)batches.push(subjects.slice(i2,i2+size));const pages2=new Array(batches.length);let next=0;const readBatch=async()=>{for(;;){const i2=next++;if(i2>=batches.length)return;pages2[i2]=await this.streamHistory(chatStream(this.space),batches[i2],limit,void 0,opts?.signal)}};await Promise.all(Array.from({length:Math.min(MULTI_FILTER_READ_CONCURRENCY,batches.length)},readBatch));const rows=pages2.flat().sort((a3,b3)=>a3.seq-b3.seq).slice(-limit);return rows.map(({seq,subject,msg})=>{const p2=parseSubject(subject);if(p2?.kind!=="chat")throw new Error(`multiChannelHistory: the broker delivered ${subject}, which is not a chat subject on this space`);return{channel:p2.rest,seq,msg}})}async readHistory(channel,opts){const reply=await this.deps.requestDelivery("readHistory",{channel,limit:opts?.limit});if(!reply.ok)throw new Error(reply.error??"readHistory failed");const data=reply.data;if(!Array.isArray(data?.items)||typeof data?.complete!=="boolean")throw new Error("readHistory: the delivery daemon returned a malformed page (expected { items, complete })");return{items:data.items,complete:data.complete}}async dmHistory(opts){try{return(await this.streamHistory(dmStream(this.space),[`${spacePrefix(this.space)}.inst.>`],opts?.limit??100,void 0,opts?.signal)).map(r2=>r2.msg)}catch(e3){if(isPermissionDenied(e3))return[];throw e3}}async streamHistory(stream,subjects,limit,before,signal){if(!this.nc)throw new Error(this.deps.notLiveMsg());signal?.throwIfAborted();if(!Number.isSafeInteger(limit))throw new Error(`history limit must be a whole number of messages this server can count exactly, received ${limit}`);if(limit<=0)return[];const nc=this.nc;let reader;try{reader=await this.acquireHistoryReader(nc,this.jsm??(this.jsm=await(0,import_jetstream8.jetstreamManager)(nc)),stream,signal);const ceiling=before!==void 0?before-1:await this.lastMatchingSeq(reader,subjects,signal);if(ceiling<1)return[];let span=Math.max(limit,64);let floor=1;let floorKnown=false;for(;;){signal?.throwIfAborted();const start=Math.max(floor,ceiling-span+1);const page=await this.drainWindow(reader,subjects,start,ceiling,limit,signal);if(page.length>=limit)return page.slice(-limit);if(!floorKnown){floor=Math.max(1,await this.firstMatchingSeq(reader,subjects,signal));floorKnown=true}if(start<=floor)return page.slice(-limit);span*=4}}catch(e3){const msg=String(e3?.message??"");if(/stream not found/i.test(msg)||e3?.code===404)return[];throw e3}finally{if(reader)this.releaseHistoryReader(reader)}}historyReaderId(nc){if(!this.userMode)return this.connId;const info=nc.info;if(!info)throw new Error("history: the server has not sent its INFO, so this connection has no history reader id yet");return calloutReaderId(info.server_id,info.client_id)}async acquireHistoryReader(nc,jsm,stream,signal){for(;;){signal?.throwIfAborted();const readerId=this.historyReaderId(nc);let pool=this.historyReaderSlots.get(stream);if(pool?.readerId!==readerId){pool={readerId,free:Array.from({length:HISTORY_READERS},(_3,i2)=>HISTORY_READERS-1-i2),held:0,waiting:[],refusedUntil:0};this.historyReaderSlots.set(stream,pool)}if(pool.refusedUntil>Date.now())throw this.readerDeleteRefused(stream);const slot=pool.free.pop();if(slot!==void 0){pool.held++;return{nc,js:(0,import_jetstream8.jetstream)(nc),jsm,stream,pool,slot,name:historyReaderConsumer(readerId,slot),held:true,left:false}}if(pool.held===0)throw new Error(`history: every history reader name this connection has on ${stream} is set aside, held by a consumer it did not create (another process using the same credential, or one that stopped mid-read) or by a reader it could not confirm deleted; they expire ${HISTORY_READER_INACTIVE_MS/6e4} minutes after their last use`);const waitOn=pool;await new Promise((resolve6,reject)=>{const wake=()=>{signal?.removeEventListener("abort",stop);resolve6()};const stop=()=>{waitOn.waiting.splice(waitOn.waiting.indexOf(wake),1);reject(abortReason(signal))};waitOn.waiting.push(wake);signal?.addEventListener("abort",stop,{once:true})})}}releaseHistoryReader(reader){if(!reader.held)return;reader.held=false;const pool=reader.pool;pool.held--;if(!reader.left){pool.free.push(reader.slot);pool.waiting.shift()?.();return}this.setAsideHistoryReader(pool,reader.slot);if(pool.held===0)for(const wake of pool.waiting.splice(0))wake()}setAsideHistoryReader(pool,slot){setTimeout(()=>{pool.free.push(slot);pool.waiting.shift()?.()},HISTORY_READER_INACTIVE_MS).unref()}async openHistoryReader(reader,config2){if(config2.filter_subjects?.length===1){const{filter_subjects,...rest}=config2;config2={...rest,filter_subject:filter_subjects[0]}}const pool=reader.pool;for(;;){if(this.historyReaderId(reader.nc)!==pool.readerId)throw new Error(`history: the connection was re-established during the read on ${reader.stream}, so its history reader names changed; the read is not served`);const description=`cotal history read ${randomUUID()}`;let info;try{info=await reader.jsm.consumers.add(reader.stream,{...config2,name:reader.name,description,ack_policy:import_jetstream8.AckPolicy.None,max_deliver:1,mem_storage:true,num_replicas:1,inactive_threshold:(0,import_transport_node7.nanos)(HISTORY_READER_INACTIVE_MS)})}catch(e3){if(!isConsumerAlreadyExists(e3))throw e3}if(info?.config.description===description)return reader.js.consumers.getConsumerFromInfo(info);this.setAsideHistoryReader(pool,reader.slot);const next=pool.free.pop();if(next===void 0){reader.held=false;pool.held--;for(const wake of pool.waiting.splice(0))wake();throw new Error(`history: reader ${reader.name} on ${reader.stream} is held by a consumer this read did not create, and no other reader name is free`)}reader.slot=next;reader.name=historyReaderConsumer(pool.readerId,next)}}async closeHistoryReader(reader){try{await reader.jsm.consumers.delete(reader.stream,reader.name)}catch(e3){if(isConsumerNotFound(e3))return;reader.left=true;if(this.deps.isPublishPermissionDenied(e3)){if(this.historyReaderId(reader.nc)!==reader.pool.readerId)throw new Error(`history: the connection was re-established during the read on ${reader.stream}, so it may no longer delete its reader ${reader.name}, which expires on its own; the read is not served`);reader.pool.refusedUntil=Date.now()+HISTORY_READER_INACTIVE_MS;throw this.readerDeleteRefused(reader.stream)}throw e3}}readerDeleteRefused(stream){return new Error(`history: this credential may not delete its own history readers on ${stream}; it predates the observer and admin reader-delete grant, so remint it`)}async lastMatchingSeq(reader,subjects,signal){signal?.throwIfAborted();const consumer=await this.openHistoryReader(reader,{filter_subjects:subjects,deliver_policy:import_jetstream8.DeliverPolicy.Last});try{if((await consumer.info(true)).num_pending===0)return 0;signal?.throwIfAborted();const iter=await consumer.fetch({max_messages:1});const stop=()=>iter.stop(abortReason(signal));signal?.addEventListener("abort",stop,{once:true});try{signal?.throwIfAborted();for await(const m2 of iter)return m2.seq}finally{signal?.removeEventListener("abort",stop);iter.stop()}throw new Error(`history: the broker reported messages on ${subjectLabel(subjects)} but delivered none - the read was cut short, not empty`)}finally{await this.closeHistoryReader(reader)}}async firstMatchingSeq(reader,subjects,signal){signal?.throwIfAborted();const consumer=await this.openHistoryReader(reader,{filter_subjects:subjects,deliver_policy:import_jetstream8.DeliverPolicy.All});try{if((await consumer.info(true)).num_pending===0)return 0;signal?.throwIfAborted();const iter=await consumer.fetch({max_messages:1});const stop=()=>iter.stop(abortReason(signal));signal?.addEventListener("abort",stop,{once:true});try{signal?.throwIfAborted();for await(const m2 of iter)return m2.seq}finally{signal?.removeEventListener("abort",stop);iter.stop()}throw new Error(`history: the broker reported messages on ${subjectLabel(subjects)} but delivered none - the read was cut short, not empty`)}finally{await this.closeHistoryReader(reader)}}async drainWindow(reader,subjects,start,ceiling,limit,signal){signal?.throwIfAborted();const out=[];const consumer=await this.openHistoryReader(reader,{filter_subjects:subjects,deliver_policy:import_jetstream8.DeliverPolicy.StartSequence,opt_start_seq:start});try{const pending=(await consumer.info(true)).num_pending;if(pending===0)return out;signal?.throwIfAborted();const iter=await consumer.consume({max_messages:Math.min(pending,32)});const stop=()=>iter.stop(abortReason(signal));signal?.addEventListener("abort",stop,{once:true});let delivered=0;let complete=false;try{signal?.throwIfAborted();for await(const m2 of iter){delivered++;if(m2.info.deliverySequence!==delivered)throw new Error(`history: delivery ${m2.info.deliverySequence} arrived where ${delivered} was due on ${subjectLabel(subjects)} - the window has a gap, so the page is not served`);if(m2.seq>=ceiling){if(m2.seq===ceiling){const msg2=this.deps.decodeHistory(m2);if(msg2)out.push({seq:m2.seq,subject:m2.subject,msg:msg2})}complete=true;break}const msg=this.deps.decodeHistory(m2);if(msg){out.push({seq:m2.seq,subject:m2.subject,msg});if(out.length>limit)out.shift()}if(delivered>=pending){complete=true;break}}}finally{signal?.removeEventListener("abort",stop);iter.stop()}if(!complete)throw new Error(`history: read ${delivered} of ${pending} messages on ${subjectLabel(subjects)} before the stream ended early - the window was cut short, not empty`);return out}finally{await this.closeHistoryReader(reader)}}async collectHistory(subject,start,opts={}){const run=this.histLock.then(()=>this.collectHistoryInner(subject,start,opts));this.histLock=run.catch(()=>{});return run}async collectHistoryInner(subject,start,opts={}){if(!this.jsm||!this.js)throw new Error(this.deps.notLiveMsg());const stream=chatStream(this.space);const name2=chatHistDurable(this.owner,this.actor,this.deps.requireLifecycleUid("chat history reads"));const out=[];await this.deps.deleteConsumerIfPresent(stream,name2);await this.jsm.consumers.add(stream,{name:name2,filter_subject:subject,ack_policy:import_jetstream8.AckPolicy.None,mem_storage:true,inactive_threshold:(0,import_transport_node7.nanos)(3e4),..."time"in start?{deliver_policy:import_jetstream8.DeliverPolicy.StartTime,opt_start_time:start.time.toISOString()}:{deliver_policy:import_jetstream8.DeliverPolicy.StartSequence,opt_start_seq:start.seq}});try{const consumer=await this.js.consumers.get(stream,name2);let pending=(await consumer.info()).num_pending;while(pending>0){const want=Math.min(pending,256);const iter=await consumer.fetch({max_messages:want,expires:5e3});let got=0;for await(const m2 of iter){got++;if(opts.untilSeq!==void 0&&m2.seq>opts.untilSeq)return out;if(!subjectMatches(subject,m2.subject))continue;out.push(m2);if(opts.limit!==void 0&&out.length>=opts.limit)return out}if(got<want)break;pending-=got}}finally{await this.deps.deleteConsumerIfPresent(stream,name2)}return out}async backfillChannel(channel,upToSeq,sinceMs,floorSeq){if(floorSeq!==void 0&&floorSeq>=upToSeq)return 0;const subject=chatSubject(this.space,"*","*",channel);const since=sinceMs===void 0?void 0:Date.now()-sinceMs;const start=floorSeq!==void 0?{seq:floorSeq+1}:since===void 0||!(since>0)?{seq:1}:{time:new Date(since)};let msgs;try{msgs=await this.collectHistory(subject,start,{untilSeq:upToSeq})}catch(e3){this.deps.emit("error",e3);if(isPermissionDenied(e3))throw e3;return 0}const noop={ack:()=>{},nak:()=>{},durable:false};let n2=0;for(const sm of msgs){let msg;try{msg=sm.json()}catch{continue}if(!this.deps.isRecord(msg)||!this.deps.isUsableMessageId(msg.id))continue;const parsed=parseSubject(sm.subject);if(!parsed||!this.deps.isFromSubjectSender(msg,parsed)||msg.from.id===this.card.id)continue;this.deps.emit("message",this.deps.authenticatedMessage(msg,parsed),noop,{historical:true,kind:"channel"});n2++}return n2}async recallChannel(channel,sinceSeq){if(!this.jsm)throw new Error(this.deps.notLiveMsg());if(!isConcreteChannel(channel))return{messages:[],seqs:[],dropped:false,unanswered:true};const policy=await this.deps.joinPolicyFresh(channel);if(!policy.replay)return{messages:[],seqs:[],dropped:true,unanswered:true};const subject=chatSubject(this.space,"*","*",channel);let raw;try{raw=await this.collectHistory(subject,{seq:sinceSeq+1})}catch(e3){this.deps.emit("error",e3);if(isPermissionDenied(e3))throw e3;return{messages:[],seqs:[],dropped:true,unanswered:true}}const collected=[];const seqs=[];for(const sm of raw){let msg;try{msg=sm.json()}catch{continue}if(!this.deps.isRecord(msg)||!this.deps.isUsableMessageId(msg.id))continue;const parsed=parseSubject(sm.subject);if(!parsed||!this.deps.isFromSubjectSender(msg,parsed)||msg.from.id===this.card.id)continue;collected.push(this.deps.authenticatedMessage(msg,parsed));seqs.push(sm.seq)}let dropped;try{dropped=await this.deps.chatMayHaveLost(subject,sinceSeq)}catch(e3){this.deps.emit("error",e3);if(isPermissionDenied(e3))throw e3;return{messages:[],seqs:[],dropped:true,unanswered:true}}return{messages:collected,seqs,dropped,unanswered:false}}}}});function nativeConnectionBinding(nc,what2){const serverId=nc.info?.server_id,cid=nc.info?.client_id;if(nc.isClosed()||typeof serverId!=="string"||!/^N[A-Z2-7]{55}$/.test(serverId)||!Number.isSafeInteger(cid)||cid<=0)throw new Error(`${what2} has no settled native binding`);return{serverId,cid}}function nativeBindingAfter(type){if(type==="reconnect")return true;if(type==="disconnect"||type==="forceReconnect"||type==="staleConnection"||type==="close")return false;return void 0}var init_native_connection=__esm({"../../packages/core/dist/native-connection.js"(){"use strict"}});function isLivenessPlane(plane){return LIVENESS_PLANES.includes(plane)}function responderFromLease(lease,expectedHolder){if(lease===void 0)return"unbound";if(lease.ready!==true)return"unbound";if(expectedHolder!==void 0&&lease.holder!==expectedHolder)return"stale";return"bound"}function responderFromProbe(outcome,answered){if(outcome==="replied")return answered??"unknown";if(outcome==="noResponders")return"unbound";return"unknown"}function parseLivenessAnswer(body,expectPlane){if(typeof body!=="object"||body===null)return void 0;const{plane,responder,instance}=body;if(typeof plane!=="string"||!isLivenessPlane(plane)||plane!==expectPlane)return void 0;if(responder!=="bound"&&responder!=="unbound"&&responder!=="stale"&&responder!=="unknown")return void 0;if(instance!==void 0&&(typeof instance!=="string"||instance===""))return void 0;return instance===void 0?{plane,responder}:{plane,responder,instance}}var LIVENESS_PLANES;var init_liveness=__esm({"../../packages/core/dist/liveness.js"(){"use strict";LIVENESS_PLANES=Object.freeze(["manager","delivery"])}});import{randomUUID as randomUUID2}from"node:crypto";function processRuntime(lifecycleUid){let own=scopes.get(lifecycleUid);if(!own){own=Object.freeze({id:randomUUID2(),startedAt,source:"endpoint-process"});scopes.set(lifecycleUid,own)}return own}var startedAt,scopes;var init_process_runtime=__esm({"../../packages/core/dist/process-runtime.js"(){"use strict";startedAt=Math.floor(performance.timeOrigin);scopes=new Map}});async function liveKvEntries(kv,filterOrOptions,options){let filter;let opts;if(typeof filterOrOptions==="string"||Array.isArray(filterOrOptions)){filter=filterOrOptions;opts=options}else if(filterOrOptions&&typeof filterOrOptions==="object"){if(options!==void 0){throw new TypeError("liveKvEntries does not accept a third argument when the second argument is options")}opts=filterOrOptions}else{opts=options}if(opts?.signal?.aborted){throw opts.signal.reason??new Error("scan aborted")}if(!(kv instanceof import_internal.Bucket))throw new Error(`liveKvEntries needs the @nats-io/kv Bucket implementation to bind its own consumer (got ${kv?.constructor?.name??typeof kv}). Refusing to fall back to history(), whose hidden bind-time pending count is exactly the ambiguity this exists to remove.`);const bucket=kv;const cc=bucket._buildCC(filter??">",import_internal.KvWatchInclude.AllHistory,{headers_only:false});cc.mem_storage=true;const oc=await bucket.js.consumers.getPushConsumer(bucket.stream,cc);const own=oc;const api=own.api;const owned=[{name:own.name,answered:Promise.resolve(true)}];own.api=Object.assign(Object.create(api),{add:(...args)=>{const created=api.add(...args);owned.push({name:args[1].name,answered:created.then(()=>true,e3=>e3 instanceof import_jetstream9.JetStreamApiError)});return created}});const latest=new Map;let received=0;let sawTerminal=false;let bucketName=bucket.bucket;let expected=0;let complete=false;try{const initialInfo=await oc.info(true);opts?.onConsumer?.(initialInfo);expected=initialInfo.num_pending;if(opts?.signal?.aborted){throw opts.signal.reason??new Error("scan aborted")}if(expected!==0){const iter=await oc.consume();const onAbort=()=>{iter.stop(opts?.signal?.reason??new Error("scan aborted"))};opts?.signal?.addEventListener("abort",onAbort,{once:true});try{for await(const m2 of iter){if(opts?.signal?.aborted)break;const e3=bucket.jmToWatchEntry(m2,false);received++;bucketName=e3.bucket;const prior=latest.get(e3.key);if(prior===void 0||e3.revision>=prior.revision)latest.set(e3.key,e3);if(m2.info.pending===0){sawTerminal=true;break}}}finally{opts?.signal?.removeEventListener("abort",onAbort);await iter.close()}}complete=expected===0||sawTerminal}finally{try{const answered=await Promise.all(owned.map(c3=>c3.answered));if(owned.at(-1).name!==own.name)throw new Error(`scan consumer ${own.name} was not created through the scan's consumer API - the pinned nats.js changed shape`);const deleteOwn=opts?.deleteOwnConsumer??((_stream,_name,del)=>del());let unanswered;for(let i2=owned.length-1;i2>=0;i2--){const target2=owned[i2].name;try{await deleteOwn(bucket.stream,target2,()=>bucket.jsm.consumers.delete(bucket.stream,target2))}catch(e3){if(isPublishPermissionDenied(e3))break;if(!isConsumerNotFound(e3))throw e3;if(!answered[i2])unanswered??=target2}}if(unanswered)throw new Error(`the broker never answered the create of scan consumer ${unanswered}, so it can land after its delete and live until its inactive_threshold`)}catch(e3){if(complete&&!opts?.signal?.aborted)throw e3}}if(opts?.signal?.aborted){throw opts.signal.reason??new Error("scan aborted")}if(expected===0)return[];if(!sawTerminal)throw new IncompleteKvScan(bucketName,received,expected);const out=[];for(const e3 of latest.values())if(e3.operation!=="DEL"&&e3.operation!=="PURGE")out.push(e3);return out}async function lastKvEntries(kv){if(!(kv instanceof import_internal.Bucket))throw new Error(`lastKvEntries needs the @nats-io/kv Bucket implementation to address its backing stream (got ${kv?.constructor?.name??typeof kv})`);const bucket=kv;const nc=bucket.jsm.getConnection?.();if(nc===void 0)throw new Error("lastKvEntries needs the bucket's JetStream manager to expose its connection, to tell a denied Direct Get from a slow one");const watch=openPublishDenialWatch(nc,`${bucket.jsm.getOptions().apiPrefix||"$JS.API"}.DIRECT.GET.${bucket.stream}`,err3=>err3,"Direct Get");let page;try{const read=(async()=>{const latest=new Map;for(let seq=1;;){let last=0,pending=-1;try{await new Promise((resolve6,reject)=>{bucket.jsm.direct.getBatch(bucket.stream,{seq,batch:DIRECT_BATCH,next_by_subj:`${bucket.prefix}.>`,callback:(done,sm)=>{if(done){done.err?reject(done.err):resolve6();return}try{const e3=bucket.smToEntry(sm);const prior=latest.get(e3.key);if(prior===void 0||e3.revision>=prior.revision)latest.set(e3.key,e3);last=sm.seq;pending=sm.pending}catch(e3){page?.stop(e3);reject(e3)}}}).then(iter=>{page=iter},reject)})}catch(e3){if(last===0&&e3?.code===404)break;throw e3}if(pending===0)break;if(last===0)throw new IncompleteKvScan(bucket.bucket,latest.size,latest.size+Math.max(pending,1));seq=last+1}return[...latest.values()]})();read.catch(()=>{});const end=err3=>{page?.stop(err3);throw err3};return await Promise.race([read,watch.denied.catch(end),watch.closed.catch(end)])}finally{watch.release()}}var import_internal,import_jetstream9,IncompleteKvScan,DIRECT_BATCH;var init_kv_scan=__esm({"../../packages/core/dist/kv-scan.js"(){"use strict";import_internal=__toESM(require_internal_mod3(),1);import_jetstream9=__toESM(require_mod4(),1);init_endpoint();init_endpoint_publish_denial();init_jetstream_missing();IncompleteKvScan=class extends Error{bucket;received;expected;constructor(bucket,received,expected){super(`reading ${bucket} ended after ${received} of ~${expected} entries without reaching the end of the bucket - the connection or consumer died mid-pass. Refusing to return a partial view (a short or empty result here is indistinguishable from a real answer). Retry; if it persists, the link to the broker is dropping.`);this.bucket=bucket;this.received=received;this.expected=expected;this.name="IncompleteKvScan"}};DIRECT_BATCH=1024}});function eventChannel(principal){return`${EVENT_CHANNEL_PREFIX}${principalKey(principal.owner,principal.actor).key}`}function eventChannelPrincipal(channel){if(typeof channel!=="string"||!channel.startsWith(EVENT_CHANNEL_PREFIX))return null;const principal=parsePrincipalKey(channel.slice(EVENT_CHANNEL_PREFIX.length));if(principal===null)return null;return eventChannel(principal)===channel?principal:null}var EVENT_CHANNEL_PREFIX;var init_event_channel=__esm({"../../packages/core/dist/event-channel.js"(){"use strict";init_subjects();EVENT_CHANNEL_PREFIX="events."}});function eventPayloadSubject(space2,owner2,actor2){return`${spacePrefix(space2)}.evp.${assertValidOwnerToken(owner2)}.${actor2==="*"?actor2:assertValidOwnerToken(actor2)}`}function eventPayloadStream(space2){return`EVP_${spacePrefix(space2).slice("cotal.".length)}`}var init_event_payloads=__esm({"../../packages/core/dist/event-payloads.js"(){"use strict";init_subjects();init_event_channel()}});var require_types5=__commonJS({"../../node_modules/.pnpm/@nats-io+obj@3.4.0/node_modules/@nats-io/obj/lib/types.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StorageType=void 0;var jetstream_1=require_mod4();Object.defineProperty(exports,"StorageType",{enumerable:true,get:function(){return jetstream_1.StorageType}})}});var require_base64=__commonJS({"../../node_modules/.pnpm/@nats-io+obj@3.4.0/node_modules/@nats-io/obj/lib/base64.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Base64UrlPaddedCodec=exports.Base64UrlCodec=exports.Base64Codec=void 0;var Base64Codec=class{static encode(bytes){if(typeof bytes==="string"){return btoa(bytes)}const a3=Array.from(bytes);return btoa(String.fromCharCode(...a3))}static decode(s3,binary=false){const bin=atob(s3);if(!binary){return bin}return Uint8Array.from(bin,c3=>c3.charCodeAt(0))}};exports.Base64Codec=Base64Codec;var Base64UrlCodec=class _Base64UrlCodec{static encode(bytes){return _Base64UrlCodec.toB64URLEncoding(Base64Codec.encode(bytes))}static decode(s3,binary=false){return Base64Codec.decode(_Base64UrlCodec.fromB64URLEncoding(s3),binary)}static toB64URLEncoding(b64str){return b64str.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}static fromB64URLEncoding(b64str){return b64str.replace(/_/g,"/").replace(/-/g,"+")}};exports.Base64UrlCodec=Base64UrlCodec;var Base64UrlPaddedCodec=class _Base64UrlPaddedCodec{static encode(bytes){return _Base64UrlPaddedCodec.toB64URLEncoding(Base64Codec.encode(bytes))}static decode(s3,binary=false){return Base64UrlCodec.decode(_Base64UrlPaddedCodec.fromB64URLEncoding(s3),binary)}static toB64URLEncoding(b64str){return b64str.replace(/\+/g,"-").replace(/\//g,"_")}static fromB64URLEncoding(b64str){return b64str.replace(/_/g,"/").replace(/-/g,"+")}};exports.Base64UrlPaddedCodec=Base64UrlPaddedCodec}});var require_sha256=__commonJS({"../../node_modules/.pnpm/js-sha256@0.11.1/node_modules/js-sha256/src/sha256.js"(exports,module2){(function(){"use strict";var ERROR="input is invalid type";var WINDOW=typeof window==="object";var root=WINDOW?window:{};if(root.JS_SHA256_NO_WINDOW){WINDOW=false}var WEB_WORKER=!WINDOW&&typeof self==="object";var NODE_JS=!root.JS_SHA256_NO_NODE_JS&&typeof process==="object"&&process.versions&&process.versions.node&&process.type!="renderer";if(NODE_JS){root=global}else if(WEB_WORKER){root=self}var COMMON_JS=!root.JS_SHA256_NO_COMMON_JS&&typeof module2==="object"&&module2.exports;var AMD=typeof define==="function"&&define.amd;var ARRAY_BUFFER=!root.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer!=="undefined";var HEX_CHARS="0123456789abcdef".split("");var EXTRA=[-2147483648,8388608,32768,128];var SHIFT=[24,16,8,0];var K2=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];var OUTPUT_TYPES=["hex","array","digest","arrayBuffer"];var blocks=[];if(root.JS_SHA256_NO_NODE_JS||!Array.isArray){Array.isArray=function(obj){return Object.prototype.toString.call(obj)==="[object Array]"}}if(ARRAY_BUFFER&&(root.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)){ArrayBuffer.isView=function(obj){return typeof obj==="object"&&obj.buffer&&obj.buffer.constructor===ArrayBuffer}}var createOutputMethod=function(outputType,is224){return function(message){return new Sha256(is224,true).update(message)[outputType]()}};var createMethod=function(is224){var method=createOutputMethod("hex",is224);if(NODE_JS){method=nodeWrap(method,is224)}method.create=function(){return new Sha256(is224)};method.update=function(message){return method.create().update(message)};for(var i2=0;i2<OUTPUT_TYPES.length;++i2){var type=OUTPUT_TYPES[i2];method[type]=createOutputMethod(type,is224)}return method};var nodeWrap=function(method,is224){var crypto2=__require("crypto");var Buffer2=__require("buffer").Buffer;var algorithm=is224?"sha224":"sha256";var bufferFrom;if(Buffer2.from&&!root.JS_SHA256_NO_BUFFER_FROM){bufferFrom=Buffer2.from}else{bufferFrom=function(message){return new Buffer2(message)}}var nodeMethod=function(message){if(typeof message==="string"){return crypto2.createHash(algorithm).update(message,"utf8").digest("hex")}else{if(message===null||message===void 0){throw new Error(ERROR)}else if(message.constructor===ArrayBuffer){message=new Uint8Array(message)}}if(Array.isArray(message)||ArrayBuffer.isView(message)||message.constructor===Buffer2){return crypto2.createHash(algorithm).update(bufferFrom(message)).digest("hex")}else{return method(message)}};return nodeMethod};var createHmacOutputMethod=function(outputType,is224){return function(key,message){return new HmacSha256(key,is224,true).update(message)[outputType]()}};var createHmacMethod=function(is224){var method=createHmacOutputMethod("hex",is224);method.create=function(key){return new HmacSha256(key,is224)};method.update=function(key,message){return method.create(key).update(message)};for(var i2=0;i2<OUTPUT_TYPES.length;++i2){var type=OUTPUT_TYPES[i2];method[type]=createHmacOutputMethod(type,is224)}return method};function Sha256(is224,sharedMemory){if(sharedMemory){blocks[0]=blocks[16]=blocks[1]=blocks[2]=blocks[3]=blocks[4]=blocks[5]=blocks[6]=blocks[7]=blocks[8]=blocks[9]=blocks[10]=blocks[11]=blocks[12]=blocks[13]=blocks[14]=blocks[15]=0;this.blocks=blocks}else{this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}if(is224){this.h0=3238371032;this.h1=914150663;this.h2=812702999;this.h3=4144912697;this.h4=4290775857;this.h5=1750603025;this.h6=1694076839;this.h7=3204075428}else{this.h0=1779033703;this.h1=3144134277;this.h2=1013904242;this.h3=2773480762;this.h4=1359893119;this.h5=2600822924;this.h6=528734635;this.h7=1541459225}this.block=this.start=this.bytes=this.hBytes=0;this.finalized=this.hashed=false;this.first=true;this.is224=is224}Sha256.prototype.update=function(message){if(this.finalized){return}var notString,type=typeof message;if(type!=="string"){if(type==="object"){if(message===null){throw new Error(ERROR)}else if(ARRAY_BUFFER&&message.constructor===ArrayBuffer){message=new Uint8Array(message)}else if(!Array.isArray(message)){if(!ARRAY_BUFFER||!ArrayBuffer.isView(message)){throw new Error(ERROR)}}}else{throw new Error(ERROR)}notString=true}var code2,index2=0,i2,length=message.length,blocks2=this.blocks;while(index2<length){if(this.hashed){this.hashed=false;blocks2[0]=this.block;this.block=blocks2[16]=blocks2[1]=blocks2[2]=blocks2[3]=blocks2[4]=blocks2[5]=blocks2[6]=blocks2[7]=blocks2[8]=blocks2[9]=blocks2[10]=blocks2[11]=blocks2[12]=blocks2[13]=blocks2[14]=blocks2[15]=0}if(notString){for(i2=this.start;index2<length&&i2<64;++index2){blocks2[i2>>>2]|=message[index2]<<SHIFT[i2++&3]}}else{for(i2=this.start;index2<length&&i2<64;++index2){code2=message.charCodeAt(index2);if(code2<128){blocks2[i2>>>2]|=code2<<SHIFT[i2++&3]}else if(code2<2048){blocks2[i2>>>2]|=(192|code2>>>6)<<SHIFT[i2++&3];blocks2[i2>>>2]|=(128|code2&63)<<SHIFT[i2++&3]}else if(code2<55296||code2>=57344){blocks2[i2>>>2]|=(224|code2>>>12)<<SHIFT[i2++&3];blocks2[i2>>>2]|=(128|code2>>>6&63)<<SHIFT[i2++&3];blocks2[i2>>>2]|=(128|code2&63)<<SHIFT[i2++&3]}else{code2=65536+((code2&1023)<<10|message.charCodeAt(++index2)&1023);blocks2[i2>>>2]|=(240|code2>>>18)<<SHIFT[i2++&3];blocks2[i2>>>2]|=(128|code2>>>12&63)<<SHIFT[i2++&3];blocks2[i2>>>2]|=(128|code2>>>6&63)<<SHIFT[i2++&3];blocks2[i2>>>2]|=(128|code2&63)<<SHIFT[i2++&3]}}}this.lastByteIndex=i2;this.bytes+=i2-this.start;if(i2>=64){this.block=blocks2[16];this.start=i2-64;this.hash();this.hashed=true}else{this.start=i2}}if(this.bytes>4294967295){this.hBytes+=this.bytes/4294967296<<0;this.bytes=this.bytes%4294967296}return this};Sha256.prototype.finalize=function(){if(this.finalized){return}this.finalized=true;var blocks2=this.blocks,i2=this.lastByteIndex;blocks2[16]=this.block;blocks2[i2>>>2]|=EXTRA[i2&3];this.block=blocks2[16];if(i2>=56){if(!this.hashed){this.hash()}blocks2[0]=this.block;blocks2[16]=blocks2[1]=blocks2[2]=blocks2[3]=blocks2[4]=blocks2[5]=blocks2[6]=blocks2[7]=blocks2[8]=blocks2[9]=blocks2[10]=blocks2[11]=blocks2[12]=blocks2[13]=blocks2[14]=blocks2[15]=0}blocks2[14]=this.hBytes<<3|this.bytes>>>29;blocks2[15]=this.bytes<<3;this.hash()};Sha256.prototype.hash=function(){var a3=this.h0,b3=this.h1,c3=this.h2,d2=this.h3,e3=this.h4,f2=this.h5,g2=this.h6,h3=this.h7,blocks2=this.blocks,j2,s0,s1,maj,t1,t2,ch,ab,da,cd,bc;for(j2=16;j2<64;++j2){t1=blocks2[j2-15];s0=(t1>>>7|t1<<25)^(t1>>>18|t1<<14)^t1>>>3;t1=blocks2[j2-2];s1=(t1>>>17|t1<<15)^(t1>>>19|t1<<13)^t1>>>10;blocks2[j2]=blocks2[j2-16]+s0+blocks2[j2-7]+s1<<0}bc=b3&c3;for(j2=0;j2<64;j2+=4){if(this.first){if(this.is224){ab=300032;t1=blocks2[0]-1413257819;h3=t1-150054599<<0;d2=t1+24177077<<0}else{ab=704751109;t1=blocks2[0]-210244248;h3=t1-1521486534<<0;d2=t1+143694565<<0}this.first=false}else{s0=(a3>>>2|a3<<30)^(a3>>>13|a3<<19)^(a3>>>22|a3<<10);s1=(e3>>>6|e3<<26)^(e3>>>11|e3<<21)^(e3>>>25|e3<<7);ab=a3&b3;maj=ab^a3&c3^bc;ch=e3&f2^~e3&g2;t1=h3+s1+ch+K2[j2]+blocks2[j2];t2=s0+maj;h3=d2+t1<<0;d2=t1+t2<<0}s0=(d2>>>2|d2<<30)^(d2>>>13|d2<<19)^(d2>>>22|d2<<10);s1=(h3>>>6|h3<<26)^(h3>>>11|h3<<21)^(h3>>>25|h3<<7);da=d2&a3;maj=da^d2&b3^ab;ch=h3&e3^~h3&f2;t1=g2+s1+ch+K2[j2+1]+blocks2[j2+1];t2=s0+maj;g2=c3+t1<<0;c3=t1+t2<<0;s0=(c3>>>2|c3<<30)^(c3>>>13|c3<<19)^(c3>>>22|c3<<10);s1=(g2>>>6|g2<<26)^(g2>>>11|g2<<21)^(g2>>>25|g2<<7);cd=c3&d2;maj=cd^c3&a3^da;ch=g2&h3^~g2&e3;t1=f2+s1+ch+K2[j2+2]+blocks2[j2+2];t2=s0+maj;f2=b3+t1<<0;b3=t1+t2<<0;s0=(b3>>>2|b3<<30)^(b3>>>13|b3<<19)^(b3>>>22|b3<<10);s1=(f2>>>6|f2<<26)^(f2>>>11|f2<<21)^(f2>>>25|f2<<7);bc=b3&c3;maj=bc^b3&d2^cd;ch=f2&g2^~f2&h3;t1=e3+s1+ch+K2[j2+3]+blocks2[j2+3];t2=s0+maj;e3=a3+t1<<0;a3=t1+t2<<0;this.chromeBugWorkAround=true}this.h0=this.h0+a3<<0;this.h1=this.h1+b3<<0;this.h2=this.h2+c3<<0;this.h3=this.h3+d2<<0;this.h4=this.h4+e3<<0;this.h5=this.h5+f2<<0;this.h6=this.h6+g2<<0;this.h7=this.h7+h3<<0};Sha256.prototype.hex=function(){this.finalize();var h0=this.h0,h1=this.h1,h22=this.h2,h3=this.h3,h4=this.h4,h5=this.h5,h6=this.h6,h7=this.h7;var hex3=HEX_CHARS[h0>>>28&15]+HEX_CHARS[h0>>>24&15]+HEX_CHARS[h0>>>20&15]+HEX_CHARS[h0>>>16&15]+HEX_CHARS[h0>>>12&15]+HEX_CHARS[h0>>>8&15]+HEX_CHARS[h0>>>4&15]+HEX_CHARS[h0&15]+HEX_CHARS[h1>>>28&15]+HEX_CHARS[h1>>>24&15]+HEX_CHARS[h1>>>20&15]+HEX_CHARS[h1>>>16&15]+HEX_CHARS[h1>>>12&15]+HEX_CHARS[h1>>>8&15]+HEX_CHARS[h1>>>4&15]+HEX_CHARS[h1&15]+HEX_CHARS[h22>>>28&15]+HEX_CHARS[h22>>>24&15]+HEX_CHARS[h22>>>20&15]+HEX_CHARS[h22>>>16&15]+HEX_CHARS[h22>>>12&15]+HEX_CHARS[h22>>>8&15]+HEX_CHARS[h22>>>4&15]+HEX_CHARS[h22&15]+HEX_CHARS[h3>>>28&15]+HEX_CHARS[h3>>>24&15]+HEX_CHARS[h3>>>20&15]+HEX_CHARS[h3>>>16&15]+HEX_CHARS[h3>>>12&15]+HEX_CHARS[h3>>>8&15]+HEX_CHARS[h3>>>4&15]+HEX_CHARS[h3&15]+HEX_CHARS[h4>>>28&15]+HEX_CHARS[h4>>>24&15]+HEX_CHARS[h4>>>20&15]+HEX_CHARS[h4>>>16&15]+HEX_CHARS[h4>>>12&15]+HEX_CHARS[h4>>>8&15]+HEX_CHARS[h4>>>4&15]+HEX_CHARS[h4&15]+HEX_CHARS[h5>>>28&15]+HEX_CHARS[h5>>>24&15]+HEX_CHARS[h5>>>20&15]+HEX_CHARS[h5>>>16&15]+HEX_CHARS[h5>>>12&15]+HEX_CHARS[h5>>>8&15]+HEX_CHARS[h5>>>4&15]+HEX_CHARS[h5&15]+HEX_CHARS[h6>>>28&15]+HEX_CHARS[h6>>>24&15]+HEX_CHARS[h6>>>20&15]+HEX_CHARS[h6>>>16&15]+HEX_CHARS[h6>>>12&15]+HEX_CHARS[h6>>>8&15]+HEX_CHARS[h6>>>4&15]+HEX_CHARS[h6&15];if(!this.is224){hex3+=HEX_CHARS[h7>>>28&15]+HEX_CHARS[h7>>>24&15]+HEX_CHARS[h7>>>20&15]+HEX_CHARS[h7>>>16&15]+HEX_CHARS[h7>>>12&15]+HEX_CHARS[h7>>>8&15]+HEX_CHARS[h7>>>4&15]+HEX_CHARS[h7&15]}return hex3};Sha256.prototype.toString=Sha256.prototype.hex;Sha256.prototype.digest=function(){this.finalize();var h0=this.h0,h1=this.h1,h22=this.h2,h3=this.h3,h4=this.h4,h5=this.h5,h6=this.h6,h7=this.h7;var arr=[h0>>>24&255,h0>>>16&255,h0>>>8&255,h0&255,h1>>>24&255,h1>>>16&255,h1>>>8&255,h1&255,h22>>>24&255,h22>>>16&255,h22>>>8&255,h22&255,h3>>>24&255,h3>>>16&255,h3>>>8&255,h3&255,h4>>>24&255,h4>>>16&255,h4>>>8&255,h4&255,h5>>>24&255,h5>>>16&255,h5>>>8&255,h5&255,h6>>>24&255,h6>>>16&255,h6>>>8&255,h6&255];if(!this.is224){arr.push(h7>>>24&255,h7>>>16&255,h7>>>8&255,h7&255)}return arr};Sha256.prototype.array=Sha256.prototype.digest;Sha256.prototype.arrayBuffer=function(){this.finalize();var buffer=new ArrayBuffer(this.is224?28:32);var dataView=new DataView(buffer);dataView.setUint32(0,this.h0);dataView.setUint32(4,this.h1);dataView.setUint32(8,this.h2);dataView.setUint32(12,this.h3);dataView.setUint32(16,this.h4);dataView.setUint32(20,this.h5);dataView.setUint32(24,this.h6);if(!this.is224){dataView.setUint32(28,this.h7)}return buffer};function HmacSha256(key,is224,sharedMemory){var i2,type=typeof key;if(type==="string"){var bytes=[],length=key.length,index2=0,code2;for(i2=0;i2<length;++i2){code2=key.charCodeAt(i2);if(code2<128){bytes[index2++]=code2}else if(code2<2048){bytes[index2++]=192|code2>>>6;bytes[index2++]=128|code2&63}else if(code2<55296||code2>=57344){bytes[index2++]=224|code2>>>12;bytes[index2++]=128|code2>>>6&63;bytes[index2++]=128|code2&63}else{code2=65536+((code2&1023)<<10|key.charCodeAt(++i2)&1023);bytes[index2++]=240|code2>>>18;bytes[index2++]=128|code2>>>12&63;bytes[index2++]=128|code2>>>6&63;bytes[index2++]=128|code2&63}}key=bytes}else{if(type==="object"){if(key===null){throw new Error(ERROR)}else if(ARRAY_BUFFER&&key.constructor===ArrayBuffer){key=new Uint8Array(key)}else if(!Array.isArray(key)){if(!ARRAY_BUFFER||!ArrayBuffer.isView(key)){throw new Error(ERROR)}}}else{throw new Error(ERROR)}}if(key.length>64){key=new Sha256(is224,true).update(key).array()}var oKeyPad=[],iKeyPad=[];for(i2=0;i2<64;++i2){var b3=key[i2]||0;oKeyPad[i2]=92^b3;iKeyPad[i2]=54^b3}Sha256.call(this,is224,sharedMemory);this.update(iKeyPad);this.oKeyPad=oKeyPad;this.inner=true;this.sharedMemory=sharedMemory}HmacSha256.prototype=new Sha256;HmacSha256.prototype.finalize=function(){Sha256.prototype.finalize.call(this);if(this.inner){this.inner=false;var innerHash=this.array();Sha256.call(this,this.is224,this.sharedMemory);this.update(this.oKeyPad);this.update(innerHash);Sha256.prototype.finalize.call(this)}};var exports2=createMethod();exports2.sha256=exports2;exports2.sha224=createMethod(true);exports2.sha256.hmac=createHmacMethod();exports2.sha224.hmac=createHmacMethod(true);if(COMMON_JS){module2.exports=exports2}else{root.sha256=exports2.sha256;root.sha224=exports2.sha224;if(AMD){define(function(){return exports2})}}})()}});var require_sha2562=__commonJS({"../../node_modules/.pnpm/@nats-io+obj@3.4.0/node_modules/@nats-io/obj/lib/sha256.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.setSha256Backend=setSha256Backend;exports.getSha256Backend=getSha256Backend;exports.createSha256=createSha256;var js_sha256_1=require_sha256();var backend="js";var factory=null;var initPromise=null;function setSha256Backend(b3){if(b3!=="js"&&b3!=="native"){throw new Error(`unknown sha256 backend: ${b3}`)}if(b3===backend)return;backend=b3;factory=null;initPromise=null}function getSha256Backend(){return backend}function jsFactory(){const s3=js_sha256_1.sha256.create();return{update(data){s3.update(data)},digest(){return Uint8Array.from(s3.digest())}}}async function init(){if(factory)return;if(backend==="native"){const m2=await import("node:crypto");if(typeof m2?.createHash!=="function"){throw new Error("sha256 backend 'native' selected but `node:crypto` is not available in this runtime")}const create=m2.createHash;factory=()=>{const h3=create("sha256");return{update(data){h3.update(data)},digest(){return new Uint8Array(h3.digest())}}};return}factory=jsFactory}async function createSha256(){if(!factory){initPromise=initPromise??init();await initPromise}const f2=factory;if(!f2){throw new Error("sha256 backend reset during init")}return f2()}}});var require_sha_digest_parser=__commonJS({"../../node_modules/.pnpm/@nats-io+obj@3.4.0/node_modules/@nats-io/obj/lib/sha_digest.parser.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.parseSha256=parseSha256;exports.checkSha256=checkSha256;function parseSha256(s3){return toByteArray(s3)}function isHex(s3){const hexRegex=/^[0-9A-Fa-f]+$/;if(!hexRegex.test(s3)){return false}const isAllUpperCase=/^[0-9A-F]+$/.test(s3);const isAllLowerCase=/^[0-9a-f]+$/.test(s3);if(!(isAllUpperCase||isAllLowerCase)){return false}return s3.length%2===0}function isBase64(s3){return/^[A-Za-z0-9\-_]*(={0,2})?$/.test(s3)||/^[A-Za-z0-9+/]*(={0,2})?$/.test(s3)}function detectEncoding(input){if(isHex(input)){return"hex"}else if(isBase64(input)){return"b64"}return""}function hexToByteArray(s3){if(s3.length%2!==0){throw new Error("hex string must have an even length")}const a3=new Uint8Array(s3.length/2);for(let i2=0;i2<s3.length;i2+=2){a3[i2/2]=parseInt(s3.substring(i2,i2+2),16)}return a3}function base64ToByteArray(s3){s3=s3.replace(/-/g,"+");s3=s3.replace(/_/g,"/");const sbin=atob(s3);return Uint8Array.from(sbin,c3=>c3.charCodeAt(0))}function toByteArray(input){const encoding=detectEncoding(input);switch(encoding){case"hex":return hexToByteArray(input);case"b64":return base64ToByteArray(input)}return null}function checkSha256(a3,b3){const aBytes=typeof a3==="string"?parseSha256(a3):a3;const bBytes=typeof b3==="string"?parseSha256(b3):b3;if(aBytes===null||bBytes===null){return false}if(aBytes.length!==bBytes.length){return false}for(let i2=0;i2<aBytes.length;i2++){if(aBytes[i2]!==bBytes[i2]){return false}}return true}}});var require_objectstore=__commonJS({"../../node_modules/.pnpm/@nats-io+obj@3.4.0/node_modules/@nats-io/obj/lib/objectstore.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ObjectStoreImpl=exports.ObjectStoreStatusImpl=exports.Objm=exports.digestType=exports.osPrefix=void 0;exports.objectStoreStreamName=objectStoreStreamName;exports.objectStoreBucketName=objectStoreBucketName;exports.validateBucket=validateBucket;var internal_1=require_internal_mod();var internal_2=require_internal_mod2();var base64_1=require_base64();var sha256_1=require_sha2562();var sha_digest_parser_1=require_sha_digest_parser();exports.osPrefix="OBJ_";exports.digestType="SHA-256=";function objectStoreStreamName(bucket){validateBucket(bucket);return`${exports.osPrefix}${bucket}`}function objectStoreBucketName(stream){if(stream.startsWith(exports.osPrefix)){return stream.substring(4)}return stream}var Objm3=class{js;constructor(nc){this.js=(0,internal_2.toJetStreamClient)(nc)}create(name2,opts={}){return this.#maybeCreate(name2,opts)}async open(name2,check2=true){let doInfo=true;let allowBatched=false;if(typeof check2==="boolean"){doInfo=check2}else{const o3=check2;doInfo=o3.check===true;allowBatched=o3.allowBatched===true}const apiLvl=this.js.nc.info?.api_lvl??0;if(allowBatched&&apiLvl<4){return Promise.reject(new Error("server does not support batched publishes"))}const jsm=await this.js.jetstreamManager();const os3=new ObjectStoreImpl(name2,jsm,this.js);os3.stream=objectStoreStreamName(name2);if(doInfo){const info=await os3._si();if(info===null){return Promise.reject(new Error("object store not found"))}if(allowBatched&&info.config.allow_batched!==true){return Promise.reject(new Error("existing bucket does not support batched publishes"))}}os3.allowBatched=allowBatched;return os3}#maybeCreate(name2,opts={}){if(typeof crypto?.subtle?.digest!=="function"){return Promise.reject(new Error("objectstore: unable to calculate hashes - crypto.subtle.digest with sha256 support is required"))}const{ok:ok3,min}=this.js.nc.features.get(internal_1.Feature.JS_OBJECTSTORE);if(!ok3){return Promise.reject(new Error(`objectstore is only supported on servers ${min} or better`))}return ObjectStoreImpl.create(this.js,name2,opts)}list(){const filter=v3=>{const slr=v3;const streams=slr.streams.filter(v4=>{return v4.config.name.startsWith(exports.osPrefix)});streams.forEach(si2=>{si2.config.sealed=si2.config.sealed||false;si2.config.deny_delete=si2.config.deny_delete||false;si2.config.deny_purge=si2.config.deny_purge||false;si2.config.allow_rollup_hdrs=si2.config.allow_rollup_hdrs||false});return streams.map(si2=>{return new ObjectStoreStatusImpl(si2)})};const subj=`${this.js.prefix}.STREAM.LIST`;return new internal_2.ListerImpl(subj,filter,this.js)}};exports.Objm=Objm3;var ObjectStoreStatusImpl=class{si;backingStore;constructor(si2){this.si=si2;this.backingStore="JetStream"}get bucket(){return objectStoreBucketName(this.si.config.name)}get description(){return this.si.config.description??""}get ttl(){return this.si.config.max_age}get storage(){return this.si.config.storage}get replicas(){return this.si.config.num_replicas}get sealed(){return this.si.config.sealed}get size(){return this.si.state.bytes}get streamInfo(){return this.si}get metadata(){return this.si.config.metadata}get compression(){if(this.si.config.compression){return this.si.config.compression!==internal_2.StoreCompression.None}return false}};exports.ObjectStoreStatusImpl=ObjectStoreStatusImpl;function validateBucket(name2){const validBucketRe=/^[-\w]+$/;if(!validBucketRe.test(name2)){throw new Error(`invalid bucket name: ${name2}`)}}var ObjectInfoImpl=class{info;hdrs;constructor(oi2){this.info=oi2}get name(){return this.info.name}get description(){return this.info.description??""}get headers(){if(!this.hdrs){this.hdrs=internal_1.MsgHdrsImpl.fromRecord(this.info.headers||{})}return this.hdrs}get options(){return this.info.options}get bucket(){return this.info.bucket}get chunks(){return this.info.chunks}get deleted(){return this.info.deleted??false}get digest(){return this.info.digest}get mtime(){return this.info.mtime}get nuid(){return this.info.nuid}get size(){return this.info.size}get revision(){return this.info.revision}get metadata(){return this.info.metadata||{}}isLink(){return this.info.options?.link!==void 0&&this.info.options?.link!==null}};function toServerObjectStoreMeta(meta3){const v3={name:meta3.name,description:meta3.description??"",options:meta3.options,metadata:meta3.metadata};if(meta3.headers){const mhi=meta3.headers;v3.headers=mhi.toRecord()}return v3}function emptyReadableStream(){return new ReadableStream({pull(c3){c3.enqueue(new Uint8Array(0));c3.close()}})}var ObjectStoreImpl=class _ObjectStoreImpl{jsm;js;stream;name;allowBatched=false;constructor(name2,jsm,js){this.name=name2;this.jsm=jsm;this.js=js}_checkNotEmpty(name2){if(!name2||name2.length===0){return{name:name2,error:new Error("name cannot be empty")}}return{name:name2}}async info(name2){const info=await this.rawInfo(name2);return info?new ObjectInfoImpl(info):null}async list(){const buf=[];const iter=await this.watch({ignoreDeletes:true,includeHistory:true,historyOnly:true});for await(const info of iter){buf.push(info)}return Promise.resolve(buf)}async rawInfo(name2){const{name:obj,error:error51}=this._checkNotEmpty(name2);if(error51){return Promise.reject(error51)}const meta3=this._metaSubject(obj);try{const m2=await this.jsm.streams.getMessage(this.stream,{last_by_subj:meta3});if(m2===null){return null}const soi=m2.json();soi.revision=m2.seq;return soi}catch(err3){return Promise.reject(err3)}}async _si(opts){try{return await this.jsm.streams.info(this.stream,opts)}catch(err3){if(err3 instanceof internal_2.JetStreamApiError&&err3.code===internal_2.JetStreamApiCodes.StreamNotFound){return null}return Promise.reject(err3)}}async seal(){let info=await this._si();if(info===null){return Promise.reject(new Error("object store not found"))}info.config.sealed=true;info=await this.jsm.streams.update(this.stream,info.config);return Promise.resolve(new ObjectStoreStatusImpl(info))}async status(opts){const info=await this._si(opts);if(info===null){return Promise.reject(new Error("object store not found"))}return Promise.resolve(new ObjectStoreStatusImpl(info))}destroy(){return this.jsm.streams.delete(this.stream)}async _put(meta3,rs,opts){const jsopts=this.js.getOptions();opts=opts||{timeout:jsopts.timeout};opts.timeout=opts.timeout||jsopts.timeout;opts.previousRevision=opts.previousRevision??void 0;const{timeout,previousRevision}=opts;const maxPayload=this.js.nc.info?.max_payload||1024;meta3=meta3||{};meta3.options=meta3.options||{};let maxChunk=meta3.options?.max_chunk_size||128*1024;maxChunk=maxChunk>maxPayload?maxPayload:maxChunk;meta3.options.max_chunk_size=maxChunk;const old=await this.info(meta3.name);const{name:n2,error:error51}=this._checkNotEmpty(meta3.name);if(error51){return Promise.reject(error51)}const id2=internal_1.nuid.next();const chunkSubj=this._chunkSubject(id2);const metaSubj=this._metaSubject(n2);const info=Object.assign({bucket:this.name,nuid:id2,size:0,chunks:0},toServerObjectStoreMeta(meta3));const d2=(0,internal_1.deferred)();const db=new internal_1.DataBuffer;let fi2=null;const publishChunk=async payload=>{if(this.allowBatched){if(!fi2){fi2=await(0,internal_2.startFastIngest)(this.js.nc,chunkSubj,payload,{allowGaps:false,timeout})}else{await fi2.add(chunkSubj,payload,{timeout})}return}await this.js.publish(chunkSubj,payload,{timeout})};try{const reader=rs?rs.getReader():null;const sha=await(0,sha256_1.createSha256)();while(true){const{done,value}=reader?await reader.read():{done:true,value:void 0};if(done){if(db.size()>0){const payload=db.drain();sha.update(payload);info.chunks++;info.size+=payload.length;await publishChunk(payload)}info.mtime=new Date().toISOString();const digest=base64_1.Base64UrlPaddedCodec.encode(sha.digest());info.digest=`${exports.digestType}${digest}`;info.deleted=false;const h3=(0,internal_1.headers)();if(typeof previousRevision==="number"){h3.set(internal_2.PubHeaders.ExpectedLastSubjectSequenceHdr,`${previousRevision}`)}h3.set(internal_2.JsHeaders.RollupHdr,internal_2.JsHeaders.RollupValueSubject);const ack=fi2?await fi2.last(metaSubj,JSON.stringify(info),{headers:h3,timeout}):await this.js.publish(metaSubj,JSON.stringify(info),{headers:h3,timeout});info.revision=ack.seq;if(old){try{await this.jsm.streams.purge(this.stream,{filter:`$O.${this.name}.C.${old.nuid}`})}catch(_err){}}d2.resolve(new ObjectInfoImpl(info));break}if(value){db.fill(value);while(db.size()>maxChunk){info.chunks++;info.size+=maxChunk;const payload=db.drain(meta3.options.max_chunk_size);sha.update(payload);await publishChunk(payload)}}}}catch(err3){if(fi2){try{await fi2.end()}catch(_e2){}}await this.jsm.streams.purge(this.stream,{filter:chunkSubj});d2.reject(err3)}return d2}putBlob(meta3,data,opts){function readableStreamFrom(data2){return new ReadableStream({pull(controller){controller.enqueue(data2);controller.close()}})}if(data===null){data=new Uint8Array(0)}return this.put(meta3,readableStreamFrom(data),opts)}put(meta3,rs,opts){if(meta3?.options?.link){return Promise.reject(new Error("link cannot be set when putting the object in bucket"))}return this._put(meta3,rs,opts)}async getBlob(name2){async function fromReadableStream(rs){const buf=new internal_1.DataBuffer;const reader=rs.getReader();while(true){const{done,value}=await reader.read();if(done){return buf.drain()}if(value&&value.length){buf.fill(value)}}}const r2=await this.get(name2);if(r2===null){return Promise.resolve(null)}const vs=await Promise.all([r2.error,fromReadableStream(r2.data)]);if(vs[0]){return Promise.reject(vs[0])}else{return Promise.resolve(vs[1])}}async get(name2){const info=await this.rawInfo(name2);if(info===null){return Promise.resolve(null)}if(info.deleted){return Promise.resolve(null)}if(info.options&&info.options.link){const ln2=info.options.link.name||"";if(ln2===""){throw new Error("link is a bucket")}const os3=info.options.link.bucket!==this.name?await _ObjectStoreImpl.create(this.js,info.options.link.bucket):this;return os3.get(ln2)}if(!info.digest.startsWith(exports.digestType)){return Promise.reject(new Error(`unknown digest type: ${info.digest}`))}const digest=(0,sha_digest_parser_1.parseSha256)(info.digest.substring(8));if(digest===null){return Promise.reject(new Error(`unable to parse digest: ${info.digest}`))}const d2=(0,internal_1.deferred)();const r2={info:new ObjectInfoImpl(info),error:d2};if(info.size===0){r2.data=emptyReadableStream();d2.resolve(null);return Promise.resolve(r2)}const sha=await(0,sha256_1.createSha256)();let controller;const cc={};cc.filter_subject=`$O.${this.name}.C.${info.nuid}`;cc.idle_heartbeat=(0,internal_1.nanos)(3e4);cc.flow_control=true;const oc=await this.js.consumers.getPushConsumer(this.stream,cc);const iter=await oc.consume();(async()=>{for await(const jm of iter){if(jm.data.length>0){sha.update(jm.data);controller.enqueue(jm.data)}if(jm.info.pending===0){const computedDigest=sha.digest();if(!(0,sha_digest_parser_1.checkSha256)(digest,computedDigest)){const hex3=Array.from(computedDigest).map(b3=>b3.toString(16).padStart(2,"0")).join("");controller.error(new Error(`received a corrupt object, digests do not match
|
|
26
26
|
expected: ${info.digest}
|
|
27
|
-
computed: SHA-256 ${hex3}`))}else{controller.close()}break}}})().then(()=>{d2.resolve()}).catch(err3=>{controller.error(err3);d2.reject(err3)});r2.data=new ReadableStream({start(c3){controller=c3},cancel(){iter.stop()}});return r2}linkStore(name2,bucket){if(!(bucket instanceof _ObjectStoreImpl)){return Promise.reject("bucket required")}const osi=bucket;const{name:n2,error:error51}=this._checkNotEmpty(name2);if(error51){return Promise.reject(error51)}const meta3={name:n2,options:{link:{bucket:osi.name}}};return this._put(meta3,null)}async link(name2,info){const{name:n2,error:error51}=this._checkNotEmpty(name2);if(error51){return Promise.reject(error51)}if(info.deleted){return Promise.reject(new Error("src object is deleted"))}if(info.isLink()){return Promise.reject(new Error("src object is a link"))}const dest=await this.rawInfo(name2);if(dest!==null&&!dest.deleted){return Promise.reject(new Error("an object already exists with that name"))}const link={bucket:info.bucket,name:info.name};const mm={name:n2,bucket:info.bucket,options:{link}};await this.js.publish(this._metaSubject(name2),JSON.stringify(mm));const i2=await this.info(name2);return Promise.resolve(i2)}async delete(name2){const info=await this.rawInfo(name2);if(info===null){return Promise.resolve({purged:0,success:false})}info.deleted=true;info.size=0;info.chunks=0;info.digest="";const h3=(0,internal_1.headers)();h3.set(internal_2.JsHeaders.RollupHdr,internal_2.JsHeaders.RollupValueSubject);await this.js.publish(this._metaSubject(info.name),JSON.stringify(info),{headers:h3});return this.jsm.streams.purge(this.stream,{filter:this._chunkSubject(info.nuid)})}async update(name2,meta3={}){const info=await this.rawInfo(name2);if(info===null){return Promise.reject(new Error("object not found"))}if(info.deleted){return Promise.reject(new Error("cannot update meta for a deleted object"))}meta3.name=meta3.name??info.name;const{name:n2,error:error51}=this._checkNotEmpty(meta3.name);if(error51){return Promise.reject(error51)}if(name2!==meta3.name){const i2=await this.info(meta3.name);if(i2&&!i2.deleted){return Promise.reject(new Error("an object already exists with that name"))}}meta3.name=n2;const ii2=Object.assign({},info,toServerObjectStoreMeta(meta3));const ack=await this.js.publish(this._metaSubject(ii2.name),JSON.stringify(ii2));if(name2!==meta3.name){await this.jsm.streams.purge(this.stream,{filter:this._metaSubject(name2)})}return Promise.resolve(ack)}async watch(opts={}){opts.includeHistory=opts.includeHistory??false;opts.ignoreDeletes=opts.ignoreDeletes??false;const historyOnly=opts.historyOnly??false;const qi2=new internal_1.QueuedIteratorImpl;const subj=this._metaSubjectAll();try{await this.jsm.streams.getMessage(this.stream,{last_by_subj:subj})}catch(err3){if(!(0,internal_2.isMessageNotFound)(err3)){qi2.stop(err3)}}const cc={};cc.name=`OBJ_WATCHER_${internal_1.nuid.next()}`;cc.filter_subject=subj;if(opts.includeHistory){cc.deliver_policy=internal_2.DeliverPolicy.LastPerSubject}else{cc.deliver_policy=internal_2.DeliverPolicy.New}const oc=await this.js.consumers.getPushConsumer(this.stream,cc);const info=await oc.info(true);const count=info.num_pending;let isUpdate=cc.deliver_policy===internal_2.DeliverPolicy.New||count===0;qi2._data=oc;let i2=0;const iter=await oc.consume({callback:jm=>{if(!isUpdate){i2++;isUpdate=i2>=count}const oi2=jm.json();oi2.isUpdate=isUpdate;if(oi2.deleted&&opts.ignoreDeletes===true){}else{qi2.push(oi2)}if(historyOnly&&i2===count){iter.stop()}}});(async()=>{for await(const s3 of iter.status()){switch(s3.type){case"heartbeat":if(historyOnly){qi2.push(()=>{qi2.stop()})}}}})().then();if(historyOnly&&count===0){iter.stop()}iter.closed().then(()=>{qi2.push(()=>{qi2.stop()})});qi2.iterClosed.then(()=>{iter.stop()});return qi2}_chunkSubject(id2){return`$O.${this.name}.C.${id2}`}_metaSubject(n2){return`$O.${this.name}.M.${base64_1.Base64UrlPaddedCodec.encode(n2)}`}_metaSubjectAll(){return`$O.${this.name}.M.>`}async init(opts={}){try{this.stream=objectStoreStreamName(this.name)}catch(err3){return Promise.reject(err3)}const max_age=opts?.ttl||0;delete opts.ttl;const{replicas}=opts;delete opts.replicas;const o3=opts;this.allowBatched=o3.allowBatched===true;delete o3.allowBatched;const sc=Object.assign({max_age},opts);sc.name=this.stream;sc.allow_direct=true;sc.allow_rollup_hdrs=true;sc.num_replicas=replicas||1;sc.discard=internal_2.DiscardPolicy.New;sc.subjects=[`$O.${this.name}.C.>`,`$O.${this.name}.M.>`];const apiLvl=this.js.nc.info?.api_lvl??0;if(this.allowBatched){if(apiLvl<4){return Promise.reject(new Error("server does not support batched publishes"))}sc.allow_batched=true}if(opts.placement){sc.placement=opts.placement}if(opts.metadata){sc.metadata=opts.metadata}if(typeof opts.compression==="boolean"){sc.compression=opts.compression?internal_2.StoreCompression.S2:internal_2.StoreCompression.None}let si2;try{si2=await this.jsm.streams.info(sc.name)}catch(err3){if(err3.message==="stream not found"){si2=await this.jsm.streams.add(sc)}else{throw err3}}if(this.allowBatched&&si2.config.allow_batched!==true){return Promise.reject(new Error("existing bucket does not support batched publishes"))}return si2}static async create(js,name2,opts={}){const jsm=await js.jetstreamManager();const os3=new _ObjectStoreImpl(name2,jsm,js);await os3.init(opts);return os3}};exports.ObjectStoreImpl=ObjectStoreImpl}});var require_internal_mod4=__commonJS({"../../node_modules/.pnpm/@nats-io+obj@3.4.0/node_modules/@nats-io/obj/lib/internal_mod.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.setSha256Backend=exports.getSha256Backend=exports.Base64UrlPaddedCodec=exports.Base64UrlCodec=exports.Base64Codec=exports.Objm=exports.StorageType=void 0;var types_1=require_types5();Object.defineProperty(exports,"StorageType",{enumerable:true,get:function(){return types_1.StorageType}});var objectstore_1=require_objectstore();Object.defineProperty(exports,"Objm",{enumerable:true,get:function(){return objectstore_1.Objm}});var base64_1=require_base64();Object.defineProperty(exports,"Base64Codec",{enumerable:true,get:function(){return base64_1.Base64Codec}});Object.defineProperty(exports,"Base64UrlCodec",{enumerable:true,get:function(){return base64_1.Base64UrlCodec}});Object.defineProperty(exports,"Base64UrlPaddedCodec",{enumerable:true,get:function(){return base64_1.Base64UrlPaddedCodec}});var sha256_1=require_sha2562();Object.defineProperty(exports,"getSha256Backend",{enumerable:true,get:function(){return sha256_1.getSha256Backend}});Object.defineProperty(exports,"setSha256Backend",{enumerable:true,get:function(){return sha256_1.setSha256Backend}})}});var require_mod7=__commonJS({"../../node_modules/.pnpm/@nats-io+obj@3.4.0/node_modules/@nats-io/obj/lib/mod.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.setSha256Backend=exports.getSha256Backend=exports.Base64UrlPaddedCodec=exports.Base64UrlCodec=exports.Base64Codec=exports.Objm=exports.StorageType=void 0;var internal_mod_1=require_internal_mod4();Object.defineProperty(exports,"StorageType",{enumerable:true,get:function(){return internal_mod_1.StorageType}});var internal_mod_2=require_internal_mod4();Object.defineProperty(exports,"Objm",{enumerable:true,get:function(){return internal_mod_2.Objm}});var internal_mod_3=require_internal_mod4();Object.defineProperty(exports,"Base64Codec",{enumerable:true,get:function(){return internal_mod_3.Base64Codec}});Object.defineProperty(exports,"Base64UrlCodec",{enumerable:true,get:function(){return internal_mod_3.Base64UrlCodec}});Object.defineProperty(exports,"Base64UrlPaddedCodec",{enumerable:true,get:function(){return internal_mod_3.Base64UrlPaddedCodec}});var internal_mod_4=require_internal_mod4();Object.defineProperty(exports,"getSha256Backend",{enumerable:true,get:function(){return internal_mod_4.getSha256Backend}});Object.defineProperty(exports,"setSha256Backend",{enumerable:true,get:function(){return internal_mod_4.setSha256Backend}})}});function nativeCredsAuthenticator(creds){return nonce4=>{const blocks=/\s*(?:(?:[-]{3,}[^\n]*[-]{3,}\n)(.+)(?:\n\s*[-]{3,}[^\n]*[-]{3,}\n))/ig;const text3=typeof creds==="function"?creds():creds;const jwtBlock=blocks.exec(text3);if(!jwtBlock)throw new Error("unable to parse credentials");const seedBlock=blocks.exec(text3);if(!seedBlock)throw new Error("unable to parse credentials");const seed=new TextEncoder().encode(seedBlock[1].trim());let signer;try{signer=nativeNkeySigner(seed);return{jwt:jwtBlock[1].trim(),nkey:signer.getPublicKey(),sig:nonce4?(0,import_nkeys6.encode)(signer.sign(new TextEncoder().encode(nonce4))):""}}finally{seed.fill(0);signer?.clear()}}}var import_nkeys6;var init_creds_authenticator=__esm({"../../packages/core/dist/creds-authenticator.js"(){"use strict";import_nkeys6=__toESM(require_mod(),1);init_nkey_signer()}});function parseServerVersion(v3){const m2=/^(\d+)\.(\d+)\.(\d+)/.exec(v3.trim());if(!m2)return null;return{major:Number(m2[1]),minor:Number(m2[2]),patch:Number(m2[3])}}function meetsBrokerFloor(version2){const p2=parseServerVersion(version2);if(!p2)return false;if(p2.major!==BROKER_FLOOR.major)return p2.major>BROKER_FLOOR.major;return p2.minor>=BROKER_FLOOR.minor}function requireBrokerFloor(nc){const version2=nc.info?.version;if(!version2)throw new Error("control surface: connected broker reports no server version; refusing to start (floor is nats-server >= 2.12)");if(!meetsBrokerFloor(version2))throw new Error(`control surface: nats-server ${version2} is below the required floor 2.12; upgrade the broker (no degraded mode exists)`)}var BROKER_FLOOR;var init_broker_floor=__esm({"../../packages/core/dist/broker-floor.js"(){"use strict";BROKER_FLOOR=Object.freeze({major:2,minor:12})}});async function openAclRegistry(nc,space2,opts={}){const kvm=new import_kv2.Kvm(nc);return opts.create?kvm.create(aclBucket(space2)):kvm.open(aclBucket(space2))}async function readAcl(kv,owner2,lifecycleUid){const e3=await kv.get(aclKey(owner2,lifecycleUid));if(!e3||e3.operation==="DEL"||e3.operation==="PURGE")return void 0;try{const record2=e3.json();if(!Array.isArray(record2.allowSubscribe))return void 0;return{record:record2,revision:e3.revision}}catch{return void 0}}async function aclRetired(kv,owner2,lifecycleUid){const e3=await kv.get(aclKey(owner2,lifecycleUid));return e3?.operation==="DEL"||e3?.operation==="PURGE"}async function readAclForAlias(kv,principal){const first=await enumerateLiveAclRows(kv,principal);if(first.length>1)throw new AmbiguousAclAlias(principal,first.map(l2=>l2.lifecycleUid).sort());const second=await enumerateLiveAclRows(kv,principal);if(second.length>1)throw new AmbiguousAclAlias(principal,second.map(l2=>l2.lifecycleUid).sort());if(second.length===0)return void 0;if(first.length===1&&first[0].lifecycleUid!==second[0].lifecycleUid)throw new AmbiguousAclAlias(principal,[first[0].lifecycleUid,second[0].lifecycleUid].sort());return{record:second[0].record,revision:second[0].revision,lifecycleUid:second[0].lifecycleUid}}async function enumerateLiveAclRows(kv,principal){const live=[];for(const e3 of await liveKvEntries(kv,aclAliasFilter(principal))){const parsed=parseLifecycleSubjectKey(e3.key);if(!parsed||`${parsed.owner}.${parsed.actor}`!==principal)continue;let record2;try{record2=e3.json()}catch{continue}if(!Array.isArray(record2.allowSubscribe))continue;live.push({lifecycleUid:parsed.lifecycleUid,record:record2,revision:e3.revision})}return live}async function reissueAcl(kv,owner2,lifecycleUid,allowSubscribe){return writeAcl(kv,owner2,lifecycleUid,allowSubscribe,{reissue:true})}async function commitAcl(kv,owner2,lifecycleUid,allowSubscribe){return writeAcl(kv,owner2,lifecycleUid,allowSubscribe,{reissue:false})}async function writeAcl(kv,owner2,lifecycleUid,allowSubscribe,opts){const key=aclKey(owner2,lifecycleUid);let lastErr;for(let attempt=0;attempt<5;attempt++){const cur=await readAcl(kv,owner2,lifecycleUid);let issued;if(opts.reissue||!cur){issued=[...allowSubscribe]}else{issued=[...cur.record.issuedAllowSubscribe??cur.record.allowSubscribe];const excess=allowSubscribe.filter(a3=>!patternInAllow(issued,a3));if(excess.length>0){throw new Error(`commitAcl: cannot raise ACL above mint-time ceiling without reissue (entries [${excess.join(", ")}] not within ceiling [${issued.join(", ")}]); use reissueAcl from the provisioning path that also remints the JWT`)}}const next={allowSubscribe:[...allowSubscribe],issuedAllowSubscribe:issued,revision:(cur?.record.revision??0)+1,updatedAt:Date.now()};const data=new TextEncoder().encode(JSON.stringify(next));if(!cur){try{await kv.create(key,data);return next}catch(e3){lastErr=e3;try{const raw=await kv.get(key);if(raw){await kv.update(key,data,raw.revision);return next}}catch(e22){lastErr=e22}continue}}try{await kv.update(key,data,cur.revision);return next}catch(e3){lastErr=e3;continue}}throw new Error(`acl CAS exhausted retries for ${owner2}${lastErr?` - last error: ${lastErr instanceof Error?lastErr.message:String(lastErr)}`:""}`,lastErr instanceof Error?{cause:lastErr}:void 0)}var import_kv2,AmbiguousAclAlias;var init_acls=__esm({"../../packages/core/dist/acls.js"(){"use strict";import_kv2=__toESM(require_mod6(),1);init_subjects();init_kv_scan();AmbiguousAclAlias=class extends Error{principal;lifecycleUids;constructor(principal,lifecycleUids){super(`read-ACL alias "${principal}" resolves to ${lifecycleUids.length} live lifecycle rows (${lifecycleUids.join(", ")}); at most one lifecycle may be live per alias (SPEC 13.1) - refusing to authorize on a first-match guess`);this.principal=principal;this.lifecycleUids=lifecycleUids}}}});async function openMembersRegistry(nc,space2,opts={}){const kvm=new import_kv3.Kvm(nc);return opts.create?kvm.create(membersBucket(space2)):kvm.open(membersBucket(space2))}async function readMember(kv,channel,owner2,lifecycleUid){const e3=await kv.get(memberKey(channel,owner2,lifecycleUid));if(!e3||e3.operation==="DEL"||e3.operation==="PURGE")return void 0;try{return{record:e3.json(),revision:e3.revision}}catch{return void 0}}async function commitMemberRevision(kv,next){const key=memberKey(next.channel,next.owner,next.lifecycleUid);const data=new TextEncoder().encode(JSON.stringify(next));for(let attempt=0;attempt<5;attempt++){const cur=await readMember(kv,next.channel,next.owner,next.lifecycleUid);if(!cur){try{return{record:next,revision:await kv.create(key,data)}}catch{continue}}if(next.generation<cur.record.generation)throw new StaleMembershipWrite(next.channel,next.owner,next.generation,cur.record.generation);try{return{record:next,revision:await kv.update(key,data,cur.revision)}}catch{continue}}throw new Error(`members CAS exhausted retries for ${key}`)}async function tombstoneMember(kv,channel,owner2,lifecycleUid,leaveCursor,writerIdentity,expectedGeneration){const key=memberKey(channel,owner2,lifecycleUid);let generation=expectedGeneration;for(let attempt=0;attempt<5;attempt++){const cur=await readMember(kv,channel,owner2,lifecycleUid);if(!cur)return void 0;generation??=cur.record.generation;if(cur.record.generation!==generation)throw new StaleMembershipWrite(channel,owner2,generation,cur.record.generation);if(cur.record.leaveCursor!==void 0&&cur.record.leaveCursor<=leaveCursor)return cur.record;const next={...cur.record,state:"live-confirmed",leaveCursor,writerIdentity,updatedAt:Date.now()};try{await kv.update(key,new TextEncoder().encode(JSON.stringify(next)),cur.revision);return next}catch{continue}}throw new Error(`members CAS exhausted retries for ${key}`)}async function activateMember(kv,channel,owner2,lifecycleUid,expectedGeneration,expectedJoinCursor){const key=memberKey(channel,owner2,lifecycleUid);for(let attempt=0;attempt<5;attempt++){const cur=await readMember(kv,channel,owner2,lifecycleUid);if(!cur)return void 0;const r2=cur.record;if(r2.generation!==expectedGeneration||r2.joinCursor!==expectedJoinCursor||r2.leaveCursor!==void 0)return void 0;if(r2.activated)return r2;const next={...r2,activated:true,updatedAt:Date.now()};try{await kv.update(key,new TextEncoder().encode(JSON.stringify(next)),cur.revision);return next}catch{continue}}return void 0}async function deleteMember(kv,channel,owner2,lifecycleUid){await kv.purge(memberKey(channel,owner2,lifecycleUid))}async function listMembers(kv,filter={}){const out=[];for(const e3 of await liveKvEntries(kv)){const parsed=parseMemberKey(e3.key);if(!parsed)continue;if(filter.channel!==void 0&&parsed.channel!==filter.channel)continue;if(filter.covering!==void 0&&parsed.channel!==filter.covering&&!(isChannelFamily(parsed.channel)&&subjectMatches(parsed.channel,filter.covering)))continue;if(filter.owner!==void 0&&parsed.principal!==filter.owner)continue;try{out.push(e3.json())}catch{}}return out}function durableEligible(rec,seq){if(seq<=rec.joinCursor)return false;if(rec.leaveCursor!==void 0&&seq>rec.leaveCursor)return false;return true}function inventoryPassAfterNow(kv){let passes=inventoryPasses.get(kv);if(passes===void 0)inventoryPasses.set(kv,passes={});const state=passes;if(state.next)return state.next;const next=(state.running??Promise.resolve([])).catch(()=>[]).then(()=>{state.next=void 0;const pass=liveKvEntries(kv);state.running=pass;const done=()=>{if(state.running===pass)state.running=void 0};pass.then(done,done);return pass});state.next=next;return next}async function listLifecycleMemberChannels(kv,principal,lifecycleUid){const pr2=parsePrincipalKey(principal);if(!pr2)throw new Error(`listLifecycleMemberChannels: invalid principal "${principal}"`);assertLifecycleToken(lifecycleUid);const channels=new Set;for(const e3 of await inventoryPassAfterNow(kv)){const parsed=parseMemberKey(e3.key);if(!parsed)continue;if(parsed.principal!==principal||parsed.lifecycleUid!==lifecycleUid)continue;if(!isConcreteChannel(parsed.channel)&&!isChannelFamily(parsed.channel))continue;channels.add(parsed.channel)}return[...channels].sort()}var import_kv3,StaleMembershipWrite,inventoryPasses;var init_members=__esm({"../../packages/core/dist/members.js"(){"use strict";import_kv3=__toESM(require_mod6(),1);init_subjects();init_kv_scan();StaleMembershipWrite=class extends Error{constructor(channel,owner2,attempted,current){super(`stale membership write for ${channel}/${owner2}: generation ${attempted} < current ${current}`);this.name="StaleMembershipWrite"}};inventoryPasses=new WeakMap}});var init_space_deletion_targets=__esm({"../../packages/core/dist/space-deletion-targets.js"(){"use strict";init_subjects();init_endpoint_binding();init_event_payloads()}});function historyLimitDefault(stream){if(stream==="chat")return CHAT_HISTORY_DEFAULT;return stream==="dm"?DM_HISTORY_DEFAULT:INBOX_HISTORY_DEFAULT}function historyLimitStreamOf(space2,stream){if(stream===chatStream(space2))return"chat";if(stream===inboxStream(space2))return"inbox";if(stream===dlvStream(space2))return"dlv";if(stream===dmStream(space2))return"dm";return void 0}function baseConfig(name2,subjects){return{name:name2,subjects,retention:import_jetstream10.RetentionPolicy.Limits,storage:import_jetstream10.StorageType.File,max_consumers:-1,max_msgs:-1,max_bytes:-1,max_age:0,max_msgs_per_subject:-1,max_msg_size:-1,discard:import_jetstream10.DiscardPolicy.Old,num_replicas:1,no_ack:false,duplicate_window:DEFAULT_DUPLICATE_WINDOW,compression:import_jetstream10.StoreCompression.None,allow_direct:false,mirror_direct:false,discard_new_per_subject:false,allow_rollup_hdrs:false,deny_delete:false,deny_purge:false,sealed:false,consumer_limits:{}}}function canonicalBackupStreamConfig(space2,stream,limit){const p2=spacePrefix(space2);const target2=historyLimitStreamOf(space2,stream);const limits=target2&&{max_age:(0,import_transport_node8.nanos)((limit??historyLimitDefault(target2)).maxAgeMs),max_msgs_per_subject:(limit??historyLimitDefault(target2)).perSubject};if(target2==="chat")return{...baseConfig(stream,[`${p2}.chat.>`]),...limits,allow_direct:true};if(stream===eventPayloadStream(space2))return{...baseConfig(stream,[`${p2}.evp.>`]),max_msgs_per_subject:CHAT_HISTORY_DEFAULT.perSubject,allow_direct:true};if(target2==="dm")return{...baseConfig(stream,[`${p2}.inst.>`]),...limits};if(stream===taskStream(space2)){return{...baseConfig(stream,[`${p2}.svc.>`]),retention:import_jetstream10.RetentionPolicy.Workqueue}}if(target2==="inbox")return{...baseConfig(stream,[`${p2}.dinbox.>`]),...limits,duplicate_window:PLANE3_DUPLICATE_WINDOW};if(target2==="dlv")return{...baseConfig(stream,[`${p2}.dlv.>`]),...limits,duplicate_window:PLANE3_DUPLICATE_WINDOW};if(stream===wfjStreamName(space2))return baseConfig(stream,[`${p2}.wfj.*`]);if(stream===recordsKvStreamName(space2))return{...kvStoreConfig(stream,recordsBucket(space2)),allow_direct:true,...endpointAuthorityStoreDefinitions(space2).records.hardenAfterCreate};if(stream===`KV_${admissionBucket(space2)}`)return{...kvStoreConfig(stream,admissionBucket(space2)),...admissionStoreDefinition(space2).hardenAfterCreate};for(const bucket of[channelBucket(space2),aclBucket(space2),membersBucket(space2)]){if(stream===`KV_${bucket}`){return{...baseConfig(stream,[`$KV.${bucket}.>`]),max_msgs_per_subject:1,discard:import_jetstream10.DiscardPolicy.New,allow_direct:true,allow_rollup_hdrs:true}}}throw new Error(`stream ${JSON.stringify(stream)} is not a backed-up stream for space ${JSON.stringify(space2)}`)}function kvStoreConfig(name2,bucket){return{...baseConfig(name2,[`$KV.${bucket}.>`]),max_msgs_per_subject:1,discard:import_jetstream10.DiscardPolicy.New,allow_rollup_hdrs:true}}var import_jetstream10,import_transport_node8,DEFAULT_DUPLICATE_WINDOW_MS,DEFAULT_DUPLICATE_WINDOW,PLANE3_MAX_MSGS_PER_SUBJECT,BACKUP_PLANE3_DEDUP_WINDOW_MS,PLANE3_DUPLICATE_WINDOW,DELIVERY_LIMIT_HEADER,HISTORY_NO_COUNT,CHAT_HISTORY_DEFAULT,INBOX_HISTORY_DEFAULT,DM_HISTORY_DEFAULT,HISTORY_MAX_AGE_MS;var init_backup_config=__esm({"../../packages/core/dist/backup-config.js"(){"use strict";import_jetstream10=__toESM(require_mod4(),1);import_transport_node8=__toESM(require_transport_node(),1);init_endpoint_binding();init_endpoint_records();init_run_admission();init_space_deletion_targets();init_event_payloads();init_subjects();DEFAULT_DUPLICATE_WINDOW_MS=2*60*1e3;DEFAULT_DUPLICATE_WINDOW=(0,import_transport_node8.nanos)(DEFAULT_DUPLICATE_WINDOW_MS);PLANE3_MAX_MSGS_PER_SUBJECT=1e3;BACKUP_PLANE3_DEDUP_WINDOW_MS=2*60*60*1e3;PLANE3_DUPLICATE_WINDOW=(0,import_transport_node8.nanos)(BACKUP_PLANE3_DEDUP_WINDOW_MS);DELIVERY_LIMIT_HEADER="Cotal-Delivery-Limit";HISTORY_NO_COUNT=-1;CHAT_HISTORY_DEFAULT=Object.freeze({maxAgeMs:0,perSubject:1e3});INBOX_HISTORY_DEFAULT=Object.freeze({maxAgeMs:0,perSubject:PLANE3_MAX_MSGS_PER_SUBJECT});DM_HISTORY_DEFAULT=Object.freeze({maxAgeMs:0,perSubject:HISTORY_NO_COUNT});HISTORY_MAX_AGE_MS=3650*864e5}});import{randomUUID as randomUUID3}from"node:crypto";function standaloneConnectOpts(auth){if(auth?.tls===void 0)throw new Error("standaloneConnectOpts requires an explicit `tls` boolean: pass `tls: true` to REQUIRE TLS, or `tls: false` for a plaintext broker. It has no default, because defaulting it would silently connect without the requirement that protects the credentials being passed.");const tlsOpt=auth.tls?{tls:{}}:{};if(auth.bearer!==void 0){if(!auth.sentinelCreds)throw new Error("user-mode standalone connect requires sentinelCreds alongside the bearer");if(auth.creds)throw new Error("standalone connect takes creds OR bearer+sentinelCreds, never both");const nonce4=`ibx${randomUUID3().replace(/-/g,"")}`;return{name:nonce4,inboxPrefix:`_INBOX_${nonce4}`,authenticator:[nativeCredsAuthenticator(auth.sentinelCreds),(0,import_transport_node9.tokenAuthenticator)(auth.bearer)],...tlsOpt}}const creds=auth.creds;if(!creds)return{...tlsOpt};return{authenticator:nativeCredsAuthenticator(creds),inboxPrefix:`_INBOX_${idFromCreds(typeof creds==="function"?creds():creds)}`,...tlsOpt}}function spaceMessageStreamConfigs(space2){return[...[chatStream(space2),dmStream(space2),taskStream(space2),inboxStream(space2),dlvStream(space2)].map(stream=>canonicalBackupStreamConfig(space2,stream)),{...canonicalBackupStreamConfig(space2,chatStream(space2)),name:eventPayloadStream(space2),subjects:[`${spacePrefix(space2)}.evp.>`]}]}function anycastStoreDefinition(space2){return{bucket:anycastBucket(space2),createOptions:{history:1,max_bytes:-1,maxValueSize:ANYCAST_RECORD_MAX_VALUE_SIZE}}}async function createSpaceStreams(jsm,space2){for(const definition of spaceMessageStreamConfigs(space2)){if(historyLimitStreamOf(space2,definition.name)||definition.name===eventPayloadStream(space2)){try{await jsm.streams.info(definition.name);continue}catch(e3){if(!isStreamNotFound(e3))throw e3}}await jsm.streams.add(definition)}}function dmDurableConfig(space2,owner2,actor2,lifecycleUid,opts={}){const frontier=opts.activationFrontier??0;if(!Number.isInteger(frontier)||frontier<0)throw new Error(`dmDurableConfig activationFrontier must be a non-negative integer, got ${String(frontier)}`);const cfg={durable_name:dmDurable(owner2,actor2,lifecycleUid),filter_subject:unicastRecvFilter(space2,owner2,actor2),ack_policy:import_jetstream11.AckPolicy.Explicit,ack_wait:(0,import_transport_node9.nanos)(opts.ackWaitMs??6e4),...frontier>0?{deliver_policy:import_jetstream11.DeliverPolicy.StartSequence,opt_start_seq:frontier+1}:{deliver_policy:import_jetstream11.DeliverPolicy.All}};if(opts.inactiveThresholdMs)cfg.inactive_threshold=(0,import_transport_node9.nanos)(opts.inactiveThresholdMs);return cfg}function taskDurableConfig(space2,role,opts={}){return{durable_name:taskDurable(role),filter_subject:anycastServeFilter(space2,role),ack_policy:import_jetstream11.AckPolicy.Explicit,ack_wait:(0,import_transport_node9.nanos)(opts.ackWaitMs??6e4)}}function inboxReaderConfig(space2,opts={}){return{durable_name:readerDurable(opts.shard,opts.shards),filter_subject:`${spacePrefix(space2)}.dinbox.>`,ack_policy:import_jetstream11.AckPolicy.Explicit,ack_wait:(0,import_transport_node9.nanos)(opts.ackWaitMs??6e4),deliver_policy:import_jetstream11.DeliverPolicy.All,max_ack_pending:DINBOX_MAX_ACK_PENDING}}function dlvDurableConfig(space2,owner2,actor2,lifecycleUid,opts={}){const cfg={durable_name:dlvDurable(owner2,actor2,lifecycleUid),filter_subject:dlvSubject(space2,owner2,actor2,lifecycleUid),ack_policy:import_jetstream11.AckPolicy.Explicit,ack_wait:(0,import_transport_node9.nanos)(opts.ackWaitMs??6e4),deliver_policy:import_jetstream11.DeliverPolicy.All};if(opts.inactiveThresholdMs)cfg.inactive_threshold=(0,import_transport_node9.nanos)(opts.inactiveThresholdMs);return cfg}function fanoutDurableConfig(space2,opts={}){return{durable_name:fanoutDurable(opts.shard,opts.shards),filter_subject:chatWildcard(space2),ack_policy:import_jetstream11.AckPolicy.Explicit,ack_wait:(0,import_transport_node9.nanos)(opts.ackWaitMs??6e4),deliver_policy:import_jetstream11.DeliverPolicy.New}}var import_jetstream11,import_transport_node9,import_kv4,import_obj,PRESENCE_STORAGE,MEMBERSHIP_STORAGE,DINBOX_MAX_ACK_PENDING,MANAGER_LEASE_TTL_MS,MANAGER_LEASE_RENEW_MS,MANAGER_LEASE_ATTEMPT_MS,LEGACY_MEMBERSHIP_MAX_BYTES,MEMBERSHIP_MAX_VALUE_SIZE,ANYCAST_RECORD_MAX_VALUE_SIZE,LEGACY_ARTIFACT_STORE_MAX_BYTES,TTL_RECONCILE_CANARY_KEY;var init_streams=__esm({"../../packages/core/dist/streams.js"(){"use strict";init_connection_cleanup();init_event_payloads();import_jetstream11=__toESM(require_mod4(),1);import_transport_node9=__toESM(require_transport_node(),1);init_endpoint();import_kv4=__toESM(require_mod6(),1);import_obj=__toESM(require_mod7(),1);init_subjects();init_identity();init_creds_authenticator();init_broker_floor();init_jetstream_missing();init_endpoint_records();init_endpoint_binding();init_acls();init_members();init_backup_config();PRESENCE_STORAGE=import_jetstream11.StorageType.Memory;MEMBERSHIP_STORAGE=import_jetstream11.StorageType.Memory;DINBOX_MAX_ACK_PENDING=1e3;MANAGER_LEASE_TTL_MS=1e4;MANAGER_LEASE_RENEW_MS=MANAGER_LEASE_TTL_MS/4;MANAGER_LEASE_ATTEMPT_MS=2e3;LEGACY_MEMBERSHIP_MAX_BYTES=64*1024*1024;MEMBERSHIP_MAX_VALUE_SIZE=256*1024;ANYCAST_RECORD_MAX_VALUE_SIZE=64*1024;LEGACY_ARTIFACT_STORE_MAX_BYTES=4*1024*1024*1024;TTL_RECONCILE_CANARY_KEY="_cotal_ttl_reconcile"}});function sameChannelModes(a3,b3){const ak=a3?Object.keys(a3):[];const bk=b3?Object.keys(b3):[];if(ak.length!==bk.length)return false;return ak.every(k2=>a3[k2]===b3?.[k2])}function sameRuntime(a3,b3){return a3?.id===b3?.id&&a3?.startedAt===b3?.startedAt&&a3?.source===b3?.source}function sameCondition(a3,b3){return a3?.code===b3?.code&&a3?.source===b3?.source&&a3?.message===b3?.message&&a3?.since===b3?.since}var import_transport_node10,PresenceWriteStuckError,EndpointPresence;var init_endpoint_presence=__esm({"../../packages/core/dist/endpoint-presence.js"(){"use strict";import_transport_node10=__toESM(require_transport_node(),1);init_process_runtime();init_kv_scan();init_streams();init_subjects();init_subjects();PresenceWriteStuckError=class extends Error{bucket;since;consecutiveFailures;ttlMs;lastError;code="presence-write-stuck";transient=false;constructor(bucket,since,consecutiveFailures,ttlMs,lastError){super(`presence writes to bucket ${JSON.stringify(bucket)} have failed ${consecutiveFailures} consecutive times for at least one TTL (${ttlMs}ms); the presence view is not live until a write succeeds or the broker store is repaired${lastError?` (last refusal: ${lastError})`:""}`);this.bucket=bucket;this.since=since;this.consecutiveFailures=consecutiveFailures;this.ttlMs=ttlMs;this.lastError=lastError;this.name="PresenceWriteStuckError"}};EndpointPresence=class{deps;presenceWriteFailingSince;lastPresenceWriteError;presenceWriteFailures=0;presenceWriteEscalated=false;presencePutGeneration=0;presencePutSettled;roster=new Map;presenceRead;presenceReadGeneration=0;presenceReadApplied=0;presenceSnapshot=Promise.resolve();presenceSnapshotPopulated=false;lastPresenceWatchAt=0;presenceViewState="unpopulated";presenceRebind;presenceWatchEmpty=false;presenceRebindAt=0;status="idle";activity;statusSince=Date.now();activitySince;activeAt;condition;conditionRevision=0;environment;attentionMode;channelModes;presenceBindingDrops=0;presenceWatchIter;constructor(deps){this.deps=deps}get card(){return this.deps.card()}get space(){return this.deps.space()}get kv(){return this.deps.bucket()}get nc(){return this.deps.connection()}get ownLifecycleUid(){return this.deps.lifecycleUid()}get ttlMs(){return this.deps.ttlMs()}get doRegister(){return this.deps.registers()}get doWatch(){return this.deps.watches()}get readOnce(){return this.deps.readsOnce()}get stopped(){return this.deps.stopped()}get reconnecting(){return this.deps.reconnecting()}get presenceEpoch(){return this.deps.epoch()}notLiveMsg(){return this.deps.notLiveMsg()}bindKvWatch(kv){return this.deps.bindWatch(kv)}retireKvWatch(iter){this.deps.retireWatch(iter)}emit(event,value){return this.deps.emit(event,value)}emitRecoverable(error51){this.deps.recoverable(error51)}configureEnvironment(environment){this.environment=environment}seedChannelModes(modes){this.channelModes=modes&&Object.keys(modes).length?modes:void 0}get bindingDropCount(){return this.presenceBindingDrops}values(){return this.roster.values()}cancelRebind(){this.presenceRebind=void 0}retireWatch(){if(this.presenceWatchIter)this.retireKvWatch(this.presenceWatchIter);this.presenceWatchIter=void 0}async publishOffline(){this.status="offline";await this.publishPresence()}resetConnection(){this.roster.clear();this.presenceRead=void 0;this.presenceReadGeneration++;this.presenceReadApplied=this.presenceReadGeneration;this.clearPresenceWriteFailure();this.lastPresenceWatchAt=0;this.presenceRebindAt=0;this.presenceWatchEmpty=false;this.presenceSnapshotPopulated=false;this.emitPresenceViewIfChanged()}getRoster(){return[...this.roster.values()].sort((a3,b3)=>a3.card.name.localeCompare(b3.card.name))}async readPresence(){if(this.doWatch&&!this.readOnce)throw new Error("readPresence is for an endpoint that does not watch presence; this one keeps its roster live (getRoster)");const kv=this.kv;if(!kv)throw new Error(this.nc?"readPresence needs the presence bucket open (registerPresence or watchPresence)":this.notLiveMsg());if(this.presenceRead)return this.presenceRead;const generation=++this.presenceReadGeneration;const roster=(async()=>{let entries;try{entries=await lastKvEntries(kv)}catch(e3){if(!this.deps.isPublishPermissionDenied(e3))throw e3;throw new Error(`presence read refused for ${this.card.id}: this credential may not publish $JS.API.DIRECT.GET.KV_${presenceBucket(this.space)}, the on-demand roster read (SPEC Appendix B). A credential minted by an older issuer can lack this grant even when newly minted; upgrade the manager or auth service that issues credentials, then mint a new credential. Reusing credentials or reconnecting does not add the grant.`,{cause:e3})}const at2=Date.now();const read=new Map;for(const e3 of entries){if(e3.key===TTL_RECONCILE_CANARY_KEY||e3.operation==="DEL"||e3.operation==="PURGE")continue;const p2=this.decodePresence(e3);if(p2)read.set(e3.key,p2.status==="offline"||at2-p2.ts>this.ttlMs?this.toOffline(p2):p2)}if(generation>this.presenceReadApplied){this.presenceReadApplied=generation;for(const[id2,p2]of this.roster)if(!read.has(id2))read.set(id2,p2.status==="offline"?p2:this.toOffline(p2));this.roster.clear();for(const[id2,p2]of read)this.roster.set(id2,p2)}return this.getRoster()})();this.presenceRead=roster;const settled=()=>{if(this.presenceRead===roster)this.presenceRead=void 0};roster.then(settled,settled);return roster}presenceView(){if(!this.doWatch)return{state:"current",fresh:true};if(!this.presenceSnapshotPopulated)return{state:"unpopulated",fresh:false};if(this.presenceWatchEmpty)return{state:"current",fresh:true};const staleSince=this.lastPresenceWatchAt+this.ttlMs;if(Date.now()<staleSince)return{state:"current",fresh:true};return{state:"stale",fresh:false,staleSince}}async waitForPresenceSnapshot(timeoutMs=1e3){let timer2;try{return await Promise.race([this.presenceSnapshot.then(()=>"snapshot"),new Promise(resolve6=>{timer2=setTimeout(()=>resolve6("timeout"),timeoutMs)})])}finally{if(timer2)clearTimeout(timer2)}}assertPresenceUpdate(update){assertPresenceRow({card:this.card,status:this.status,activity:this.activity,condition:this.condition,attention:this.attentionMode,ts:Date.now(),...update},this.card.id)}async setActivity(activity){this.assertPresenceUpdate({activity});if(activity!==this.activity)this.statusSince=this.activitySince=Date.now();this.activity=activity;await this.publishPresence()}async setStatus(status2,activity){this.assertPresenceUpdate({status:status2,...activity===void 0?{}:{activity}});if(activity!==void 0&&activity!==this.activity)this.statusSince=this.activitySince=Date.now();if(activity!==void 0)this.activity=activity;if(status2!==this.status)this.statusSince=Date.now();this.status=status2;await this.publishPresence()}noteActivity(at2=Date.now()){if(Number.isFinite(at2)&&at2>(this.activeAt??0))this.activeAt=at2}async setCondition(condition){this.assertPresenceUpdate({condition:condition??void 0});this.condition=condition??void 0;this.conditionRevision++;await this.publishPresence()}async setAttention(attention){this.assertPresenceUpdate({attention});this.attentionMode=attention;await this.publishPresence()}async setChannelModes(modes){this.channelModes=Object.keys(modes).length?modes:void 0;await this.publishPresence()}async setCardModel(model,variant,provider){const m2=model.trim();const v3=variant?.trim();const p2=provider?.trim();if(!m2||this.card.meta?.model===m2&&this.card.meta.variant===v3&&(p2===void 0||this.card.meta?.provider===p2))return;const meta3={...this.card.meta??{},model:m2};if(v3)meta3.variant=v3;else delete meta3.variant;if(p2)meta3.provider=p2;this.card.meta=meta3;await this.publishPresence()}async setCardCwd(cwd){if(!cwd||this.card.meta?.cwd===cwd)return;this.card.meta={...this.card.meta??{},cwd};await this.publishPresence()}async publishPresence(){if(!this.doRegister||!this.kv)return;const p2={card:this.card,...this.ownLifecycleUid!==void 0?{lifecycleUid:this.ownLifecycleUid}:{},runtime:processRuntime(this.ownLifecycleUid),status:this.status,condition:this.condition,environment:this.environment,activity:this.activity,statusSince:this.statusSince,activitySince:this.activitySince,activeAt:this.activeAt,attention:this.attentionMode,channelModes:this.channelModes,prompts:this.deps.prompts(),ts:Date.now()};const record2=this.status==="offline"?this.toOffline(p2):p2;assertPresenceRow(record2,this.card.id);const epoch=this.presenceEpoch;const conditionRevision=this.conditionRevision;const generation=++this.presencePutGeneration;try{await this.kv.put(this.card.id,JSON.stringify(record2))}catch(e3){const superseded2=(this.presencePutSettled??0)>generation;this.presencePutSettled=Math.max(this.presencePutSettled??0,generation);if(epoch===this.presenceEpoch&&!this.stopped&&!superseded2){this.presenceWriteFailingSince??=Date.now();this.lastPresenceWriteError=e3?.message??String(e3);this.presenceWriteFailures++;this.escalatePresenceWriteFailureIfStuck()}if(e3 instanceof import_transport_node10.TimeoutError)throw new Error(`${e3.message}. The presence write outcome is unknown: the broker may have stored the update. Read the roster before retrying.`,{cause:e3});throw e3}const superseded=(this.presencePutSettled??0)>generation;this.presencePutSettled=Math.max(this.presencePutSettled??0,generation);if(epoch!==this.presenceEpoch||this.stopped||superseded)return;if(conditionRevision!==this.conditionRevision){await this.publishPresence();return}this.clearPresenceWriteFailure()}clearPresenceWriteFailure(){this.presenceWriteFailingSince=void 0;this.lastPresenceWriteError=void 0;this.presenceWriteFailures=0;this.presenceWriteEscalated=false}escalatePresenceWriteFailureIfStuck(){if(this.presenceWriteEscalated||this.presenceWriteFailingSince===void 0||this.presenceWriteFailures<2||Date.now()-this.presenceWriteFailingSince<this.ttlMs)return;this.presenceWriteEscalated=true;this.emitRecoverable(new PresenceWriteStuckError(presenceBucket(this.space),this.presenceWriteFailingSince,this.presenceWriteFailures,this.ttlMs,this.lastPresenceWriteError))}presenceWriteFailure(){if(this.presenceWriteFailingSince===void 0)return void 0;return{since:this.presenceWriteFailingSince,forMs:Date.now()-this.presenceWriteFailingSince,error:this.lastPresenceWriteError,bucket:presenceBucket(this.space),consecutiveFailures:this.presenceWriteFailures,stuck:this.presenceWriteEscalated}}async startPresenceWatch(){if(!this.kv)return void 0;let hydrated;this.presenceSnapshot=new Promise(resolve6=>{hydrated=resolve6});const bound=await this.bindKvWatch(this.kv);if(!bound){hydrated();return void 0}const{iter,info}=bound;this.presenceWatchIter=iter;const empty=info.num_pending===0&&!this.doRegister;if(empty){this.presenceSnapshotPopulated=true;hydrated();this.markPresenceBucketEmpty()}void(async()=>{let ready=empty;for await(const e3 of iter){if(this.presenceWatchIter!==iter)break;this.handleKvEntry(e3);if(!ready&&e3.isUpdate){ready=true;this.presenceSnapshotPopulated=true;hydrated();this.emitPresenceViewIfChanged()}}hydrated()})().catch(e3=>this.emit("error",e3));return info}async readPresenceOnce(){if(!this.kv)return;for(const e3 of await lastKvEntries(this.kv))this.handleKvEntry(e3);this.presenceSnapshotPopulated=true;if(this.lastPresenceWatchAt===0)this.markPresenceBucketEmpty();else this.emitPresenceViewIfChanged()}rebindStalePresenceWatch(now){if(this.stopped||this.reconnecting||!this.kv||!this.nc||this.nc.isClosed())return;if(this.presenceRebind||now-this.presenceRebindAt<this.ttlMs)return;this.presenceRebindAt=now;const old=this.presenceWatchIter;const epoch=this.presenceEpoch;this.presenceRebind=(async()=>{try{const silentMs=now-this.lastPresenceWatchAt;const info=await this.startPresenceWatch();if(!info)return;if(old&&old!==this.presenceWatchIter)this.retireKvWatch(old);if(info.num_pending===0)await this.onPresenceBucketEmpty();this.emit("warning",new Error(`presence watch silent for ${silentMs}ms with the connection up; rebound it from the bucket's current state`))}catch(e3){if(epoch===this.presenceEpoch)this.emit("error",e3)}finally{if(epoch===this.presenceEpoch)this.presenceRebind=void 0}})()}async onPresenceBucketEmpty(){if(this.doRegister){await this.publishPresence();return}this.markPresenceBucketEmpty()}markPresenceBucketEmpty(){this.presenceWatchEmpty=true;this.lastPresenceWatchAt=0;let changed=false;for(const[id2,p2]of this.roster){if(p2.status==="offline")continue;const offline=this.toOffline(p2);this.roster.set(id2,offline);this.emit("presence",{type:"offline",presence:offline});changed=true}if(changed)this.emit("roster",this.getRoster());this.emitPresenceViewIfChanged()}handleKvEntry(e3){if(e3.key===TTL_RECONCILE_CANARY_KEY)return;this.lastPresenceWatchAt=Date.now();this.presenceWatchEmpty=false;if(e3.operation==="DEL"||e3.operation==="PURGE"){this.markOffline(e3.key);return}const p2=this.decodePresence(e3);if(p2)this.applyPresence(e3.key,p2)}decodePresence(e3){let p2;try{p2=e3.json()}catch{return void 0}if(!isPresenceRow(p2,e3.key)){this.presenceBindingDrops++;this.emitRecoverable(new Error(`dropped presence entry for key ${JSON.stringify(e3.key)}: not a usable presence row (a record with card.id equal to its KV key, a non-blank string card.name, a known status, a finite ts, string display fields and a condition with a string code)`));return void 0}return p2}applyPresence(id2,raw){const prev=this.roster.get(id2);const stale=Date.now()-raw.ts>this.ttlMs;if(stale&&raw.status!=="offline"){if(prev)return;this.roster.set(id2,this.toOffline(raw));this.emit("roster",this.getRoster());return}if(this.presenceSnapshotPopulated)this.emitPresenceViewIfChanged();const p2=stale||raw.status==="offline"?this.toOffline(raw):raw;if(!prev&&p2.status==="offline"){this.roster.set(id2,p2);this.emit("roster",this.getRoster());return}if(prev&&prev.status!=="offline"&&p2.status!=="offline"&&prev.lifecycleUid===p2.lifecycleUid&&sameRuntime(prev.runtime,p2.runtime)&&prev.status===p2.status&&prev.activity===p2.activity&&sameCondition(prev.condition,p2.condition)&&prev.environment===p2.environment&&prev.attention===p2.attention&&sameChannelModes(prev.channelModes,p2.channelModes)&&prev.prompts?.open===p2.prompts?.open&&prev.prompts?.seq===p2.prompts?.seq){this.roster.set(id2,p2);return}this.roster.set(id2,p2);const type=p2.status==="offline"?"offline":!prev||prev.status==="offline"?"join":"update";this.emit("presence",{type,presence:p2});this.emit("roster",this.getRoster())}toOffline(p2){return{...p2,status:"offline",statusSince:void 0,attention:void 0,channelModes:void 0,prompts:void 0}}markOffline(id2){const prev=this.roster.get(id2);if(!prev||prev.status==="offline")return;const offline=this.toOffline(prev);this.roster.set(id2,offline);this.emit("presence",{type:"offline",presence:offline});this.emit("roster",this.getRoster())}emitPresenceViewIfChanged(){const view=this.presenceView();if(view.state===this.presenceViewState)return;this.presenceViewState=view.state;this.emit("presence-view",view)}sweep(){const now=Date.now();if(this.lastPresenceWatchAt!==0&&now-this.lastPresenceWatchAt>this.ttlMs){this.emitPresenceViewIfChanged();this.rebindStalePresenceWatch(now);return}let changed=false;for(const[id2,p2]of this.roster){if(p2.status!=="offline"&&now-p2.ts>this.ttlMs&&this.lastPresenceWatchAt-p2.ts>this.ttlMs){const offline=this.toOffline(p2);this.roster.set(id2,offline);this.emit("presence",{type:"offline",presence:offline});changed=true}}if(changed)this.emit("roster",this.getRoster())}}}});function pickFree(taken,from,to){const free=[];let lo=from;for(const t2 of[...taken].sort((a3,b3)=>a3-b3)){if(t2-RENEWAL_SPACING_MS>lo)free.push([lo,Math.min(to,t2-RENEWAL_SPACING_MS)]);lo=Math.max(lo,t2+RENEWAL_SPACING_MS);if(lo>=to)break}if(lo<=to)free.push([lo,to]);const total=free.reduce((sum,[a3,b3])=>sum+(b3-a3),0);if(free.length===0)return from+Math.random()*(to-from);let r2=Math.random()*total;for(const[a3,b3]of free){if(r2<=b3-a3)return a3+r2;r2-=b3-a3}return free[free.length-1][1]}function armRenewal(space2,issuedAtMs,expiresAtMs,renew,minDelayMs=0){const now=Date.now();const life=Math.max(0,expiresAtMs-issuedAtMs);const from=Math.max(issuedAtMs+RENEWAL_WINDOW.from*life,now+minDelayMs);const to=Math.max(issuedAtMs+RENEWAL_WINDOW.to*life,from);const taken=armed.get(space2)??new Set;armed.set(space2,taken);const at2=pickFree([...taken],from,to);taken.add(at2);const release=()=>{taken.delete(at2);if(taken.size===0&&armed.get(space2)===taken)armed.delete(space2)};let timer2;const wait=()=>{const left=at2-Date.now();timer2=setTimeout(left>MAX_TIMER_MS2?wait:()=>{release();renew()},Math.min(Math.max(0,left),MAX_TIMER_MS2));timer2.unref?.()};wait();return()=>{clearTimeout(timer2);release()}}function renewalDeadlineMs(issuedAtMs,expiresAtMs){return issuedAtMs+RENEWAL_WINDOW.to*Math.max(0,expiresAtMs-issuedAtMs)}function jitteredBackoffMs(attempt,baseMs,capMs){const step=Math.min(capMs,baseMs*2**attempt);return step/2+Math.random()*(step/2)}var RENEWAL_WINDOW,RENEWAL_SPACING_MS,MAX_TIMER_MS2,armed;var init_renewal=__esm({"../../packages/core/dist/renewal.js"(){"use strict";RENEWAL_WINDOW=Object.freeze({from:.5,to:.8});RENEWAL_SPACING_MS=1e3;MAX_TIMER_MS2=2147483647;armed=new Map}});function parseSecretStoreIdentity(raw){if(raw===null||typeof raw!=="object"||Array.isArray(raw))throw new Error("secret-store identity must be an object");const o3=raw;const keys=Object.keys(o3);if(o3.kind==="fs"){if(keys.some(k2=>k2!=="kind"&&k2!=="root"&&k2!=="id"))throw new Error("secret-store identity of kind fs admits only {kind, root, id}");if(typeof o3.root!=="string"||!o3.root.trim())throw new Error("secret-store identity of kind fs requires a non-blank root");if(typeof o3.id!=="string"||!o3.id.trim())throw new Error("secret-store identity of kind fs requires a non-blank id");return{kind:"fs",root:o3.root,id:o3.id}}if(o3.kind==="injected"){if(keys.some(k2=>k2!=="kind"&&k2!=="coordinate"))throw new Error("secret-store identity of kind injected admits only {kind, coordinate}");if(typeof o3.coordinate!=="string"||!o3.coordinate.trim())throw new Error("secret-store identity of kind injected requires a non-blank coordinate");return{kind:"injected",coordinate:o3.coordinate}}throw new Error('secret-store identity kind must be "fs" or "injected"')}var init_secret_store=__esm({"../../packages/core/dist/secret-store.js"(){"use strict"}});var mintGuardClearance;var init_endpoint_guard=__esm({"../../packages/core/dist/endpoint-guard.js"(){"use strict";init_endpoint_envelope();init_deadline();init_canonical();init_endpoint_signing();init_endpoint_checkpoint();init_endpoint_action();mintGuardClearance=claimGuardClearanceMint()}});var TRAIT_SELECTORS;var init_endpoint_traits=__esm({"../../packages/core/dist/endpoint-traits.js"(){"use strict";init_canonical();init_endpoint_envelope();init_deadline();init_schema_profile();init_endpoint_cluster();init_endpoint_guard();init_endpoint_service();init_endpoint_signing();TRAIT_SELECTORS=Object.freeze(["cluster","command","attribute","event"])}});var init_endpoint_describe_observation=__esm({"../../packages/core/dist/endpoint-describe-observation.js"(){"use strict";init_canonical();init_subjects();init_endpoint_subjects();init_endpoint_envelope();init_schema_profile()}});function bindContract(env,def){if(def.digests===void 0){if(env.op.inputDigest!==void 0||env.op.outputDigest!==void 0)throw new EpEnvelopeError("contract-mismatch","describe pins no contract; a digest carried on it cannot be honored (SPEC 13.7)");return}if(env.op.inputDigest!==def.digests.input||env.op.outputDigest!==def.digests.output)throw new EpEnvelopeError("contract-mismatch",`pinned digests ${env.op.inputDigest}/${env.op.outputDigest} do not match the served contract ${def.digests.input}/${def.digests.output}; a member that cannot honor a pinned digest rejects, never coerces (SPEC 13.7)`)}function successReply(id2,data){return{v:1,id:id2,ok:true,...data!==void 0?{data}:{}}}function encodeReply(reply){return enc4.encode(JSON.stringify(reply))}async function runRequest(nc,steps,pick2,msg){const receivedAtMonotonicMs=performance.now();const parsed=steps.parse(msg.subject);if(!parsed)return;let env;let dispatched=false;let returned=false;let reply;try{const original=JSON.parse(dec4.decode(msg.data));env=parseEndpointRequest(original);checkRequestSubjectAgreement(env,parsed);steps.addressed(env,parsed);const def=pick2(parsed);if(def===void 0)throw new EpEnvelopeError("unimplemented",`command "${parsed.command}" is not served here`);assertClassMatches(env,def.class);bindContract(env,def);steps.admit(parsed,def);assertArgsValid(def.validate.args,env.args);const obligations=await steps.beforeEffect(env,parsed,def);const requestId=env.id;const ctx=steps.context({parsed,env,def,subject:msg.subject,original,receivedAtMonotonicMs,obligations,replyFits:(data2,ceiling)=>{const maxPayload=nc.info?.max_payload;if(!Number.isSafeInteger(maxPayload)||maxPayload===void 0||maxPayload<=0)throw new EpEnvelopeError("unavailable","the serving connection has no valid payload ceiling");if(!Number.isSafeInteger(ceiling)||ceiling<=0)throw new EpEnvelopeError("failed-precondition","reply byte ceiling must be a positive safe integer");return encodeReply(successReply(requestId,data2)).byteLength<=Math.min(ceiling,maxPayload)}});dispatched=true;if(!env.replyExpected){await def.handler(ctx);return}const data=await def.handler(ctx);returned=true;assertOutputValid(def.validate.output,data);reply=successReply(env.id,data)}catch(err3){if(env&&!env.replyExpected)return;const error51=err3 instanceof EpEnvelopeError?err3.toEpError():{code:"internal",message:err3?.message??String(err3)};const stated=!dispatched?"not-executed":returned?"executed":void 0;reply={v:1,id:env?.id??"invalid",ok:false,error:stated===void 0?error51:{...error51,outcome:stated}}}const outcome=reply.ok?"executed":reply.error?.outcome;let bytes;try{bytes=encodeReply(reply)}catch(err3){const fallback={v:1,id:reply.id,ok:false,error:{code:"internal",message:`the reply does not serialize: ${err3.message}`,...outcome!==void 0?{outcome}:{}}};bytes=enc4.encode(JSON.stringify(fallback))}if(steps.mayReply?.()===false)return;const replySubject=steps.replySubject(parsed);try{nc.publish(replySubject,bytes)}catch(err3){const refused3={v:1,id:reply.id,ok:false,error:{code:"resource-exhausted",message:`the serialized reply is ${bytes.length} bytes and the broker refused it (${err3?.message??String(err3)}); a reply that cannot be published is refused loudly, never dropped`,...outcome!==void 0?{outcome}:{}}};nc.publish(replySubject,enc4.encode(JSON.stringify(refused3)))}}function servePrincipalRoute(nc,space2,self2,serve){const filter=epPrincipalServeFilter(space2,serve.endpoint,self2);const cluster=parseClusterDocument(serve.cluster);const declared=new Map(cluster.commands.map(c3=>[c3.name,c3]));for(const c3 of cluster.commands){if(c3.authorities===void 0)throw new Error(`command "${c3.name}" declares no authorities; a command is served on the principal route only when it lists the words it admits (SPEC 13.21)`);if(c3.class!=="ephemeral")throw new Error(`command "${c3.name}" is class "${c3.class}"; the principal route serves ephemeral commands only (SPEC 13.21)`);const governed=(c3.traits??[]).filter(t2=>GOVERNED_TRAIT_URNS.includes(t2));if(governed.length>0)throw new Error(`command "${c3.name}" declares governed trait(s) ${governed.join(", ")}; the principal route has no governed gate, and a governed command is never served unenforced (SPEC 13.7)`)}const defs=[];for(const def of serve.handlers){assertCommandToken(def.command);if(def.command==="describe")throw new Error("describe is reserved and built from the cluster; a custom describe def is refused (SPEC 13.21)");if(defs.some(d2=>d2.command===def.command))throw new Error(`command "${def.command}" is served twice`);const decl=declared.get(def.command);if(decl===void 0)throw new Error(`command "${def.command}" is not in the cluster; the served table is exactly the cluster's commands (SPEC 13.21)`);const input=assertCompiledContract(def.contract?.input,`command "${def.command}" input contract`);const output=assertCompiledContract(def.contract?.output,`command "${def.command}" output contract`);if(input.closureDigest!==decl.inputDigest||output.closureDigest!==decl.outputDigest)throw new Error(`command "${def.command}" compiled contracts ${input.closureDigest}/${output.closureDigest} do not equal the declared ${decl.inputDigest}/${decl.outputDigest} (SPEC 13.7)`);defs.push({command:def.command,class:"ephemeral",digests:{input:decl.inputDigest,output:decl.outputDigest},validate:{args:input.validate,output:output.validate},authorities:new Set(decl.authorities),handler:def.handler})}for(const c3 of cluster.commands)if(!defs.some(d2=>d2.command===c3.name))throw new Error(`command "${c3.name}" has no def; a declared command nobody serves is a construction bug (SPEC 13.21)`);const answer=deepFreeze2({public:true,descriptor:{endpoint:serve.endpoint,owner:self2.owner,protocol:{v:1},clusters:[{digest:singleDocumentClosure(serve.cluster).closureDigest,commands:cluster.commands.map(c3=>c3.name),document:structuredClone(serve.cluster)}]}});defs.push({command:"describe",class:"ephemeral",validate:describeValidators(),authorities:new Set(EP_PRINCIPAL_AUTHORITIES),handler:()=>answer});const byCommand=new Map(defs.map(d2=>[d2.command,d2]));const steps={parse:subject=>{const parsed=parseEpSubject(subject);if(!parsed||parsed.plane!=="principal-request")return null;const h3=parsed.principal;if(parsed.endpoint!==serve.endpoint||h3.owner!==self2.owner||h3.actor!==self2.actor||h3.uid!==self2.uid||h3.runtimeId!==self2.runtimeId)return null;return parsed},addressed:()=>{},admit:(parsed,def)=>{if(!isPrincipalAuthority(parsed.authority)||!def.authorities.has(parsed.authority))throw new EpEnvelopeError("permission-denied",`command "${def.command}" does not admit the "${parsed.authority}" authority; a command serves only the words its declaration lists (SPEC 13.21)`)},beforeEffect:async()=>void 0,context:({parsed,env,receivedAtMonotonicMs,replyFits})=>({endpoint:serve.endpoint,principal:self2,caller:parsed.caller,authority:parsed.authority,request:env,receivedAtMonotonicMs,replyFits,signal:stopping.signal}),replySubject:parsed=>derivePrincipalReplySubject(space2,parsed,self2),mayReply:()=>!lateRepliesDropped};const stopping=new AbortController;let lateRepliesDropped=false;const pending=new Map;let refusal;let markRefused;const refused3=new Promise(resolve6=>{markRefused=resolve6});const sub=nc.subscribe(filter,{callback:(err3,msg)=>{if(err3){if(refusal===void 0){refusal=new EpEnvelopeError("permission-denied",`the broker refused this process's subscription to its principal-route subject "${filter}": ${err3.message}. The credential holds no serve row for it, which a credential minted before the rows existed does not; reconnect after the auth service runs a release that mints them (SPEC 13.21)`);markRefused(refusal)}return}if(carriesStoredProvenance(msg))return;const entry={};const timed={...steps,context:a3=>{entry.endsAt=a3.receivedAtMonotonicMs+a3.env.deadlineMs;return steps.context(a3)}};const run=runRequest(nc,timed,parsed=>byCommand.get(parsed.command),msg).catch(()=>{});pending.set(run,entry);void run.finally(()=>pending.delete(run))}});const check2=async()=>{await nc.flush();if(refusal!==void 0)throw refusal};const ready=check2();ready.catch(()=>{});return{filter,ready,refused:refused3,check:check2,async stop(){stopping.abort(new Error(`stopped serving "${serve.endpoint}" on the principal route`));const gone=nc.closed().then(()=>void 0);await Promise.race([sub.drain().catch(()=>void 0),gone]);await Promise.allSettled([...pending].map(([run,{endsAt}])=>endsAt===void 0?run:withinMs(run,endsAt-performance.now())));lateRepliesDropped=true}}}async function withinMs(p2,ms){if(ms<=0)return;let timer2;try{await Promise.race([p2,new Promise(resolve6=>{timer2=setTimeout(resolve6,ms)})])}finally{clearTimeout(timer2)}}function deepFreeze2(v3){if(v3!==null&&typeof v3==="object"){for(const child of Object.values(v3))deepFreeze2(child);Object.freeze(v3)}return v3}function describeValidators(){const c3=describeContracts();return{args:c3.input.validate,output:c3.output.validate}}function describeContracts(){describeCompiled??=Object.freeze({input:compileContract({root:VOID_SCHEMA}),output:compileContract({root:DESCRIBE_ANSWER_SCHEMA})});return describeCompiled}var enc4,dec4,DESCRIBE_ANSWER_SCHEMA,describeCompiled;var init_endpoint_serve=__esm({"../../packages/core/dist/endpoint-serve.js"(){"use strict";init_subjects();init_endpoint_subjects();init_endpoint_envelope();init_schema_profile();init_endpoint_service();init_endpoint_cluster();init_endpoint_traits();init_endpoint_describe_observation();init_endpoint_provenance();enc4=new TextEncoder;dec4=new TextDecoder;DESCRIBE_ANSWER_SCHEMA={type:"object",required:["public","descriptor"],additionalProperties:false,properties:{public:{type:"boolean"},descriptor:{type:"object",required:["endpoint","owner","protocol","clusters"],properties:{endpoint:{type:"string",minLength:1},owner:{type:"string",minLength:1},endpointType:{type:"string"},protocol:{type:"object",required:["v"],properties:{v:{const:1}}},clusters:{type:"array",items:{type:"object",required:["digest","commands"],properties:{digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"},commands:{type:"array",minItems:1,items:{type:"string",minLength:1}},document:{type:"object"}}}}}}}}}});var require_identity=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/identity.js"(exports){"use strict";var ALIAS=Symbol.for("yaml.alias");var DOC=Symbol.for("yaml.document");var MAP=Symbol.for("yaml.map");var PAIR=Symbol.for("yaml.pair");var SCALAR=Symbol.for("yaml.scalar");var SEQ=Symbol.for("yaml.seq");var NODE_TYPE=Symbol.for("yaml.node.type");var isAlias=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===ALIAS;var isDocument=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===DOC;var isMap=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===MAP;var isPair=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===PAIR;var isScalar=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===SCALAR;var isSeq=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===SEQ;function isCollection(node){if(node&&typeof node==="object")switch(node[NODE_TYPE]){case MAP:case SEQ:return true}return false}function isNode(node){if(node&&typeof node==="object")switch(node[NODE_TYPE]){case ALIAS:case MAP:case SCALAR:case SEQ:return true}return false}var hasAnchor=node=>(isScalar(node)||isCollection(node))&&!!node.anchor;exports.ALIAS=ALIAS;exports.DOC=DOC;exports.MAP=MAP;exports.NODE_TYPE=NODE_TYPE;exports.PAIR=PAIR;exports.SCALAR=SCALAR;exports.SEQ=SEQ;exports.hasAnchor=hasAnchor;exports.isAlias=isAlias;exports.isCollection=isCollection;exports.isDocument=isDocument;exports.isMap=isMap;exports.isNode=isNode;exports.isPair=isPair;exports.isScalar=isScalar;exports.isSeq=isSeq}});var require_visit=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/visit.js"(exports){"use strict";var identity=require_identity();var BREAK=Symbol("break visit");var SKIP=Symbol("skip children");var REMOVE=Symbol("remove node");function visit(node,visitor){const visitor_=initVisitor(visitor);if(identity.isDocument(node)){const cd=visit_(null,node.contents,visitor_,Object.freeze([node]));if(cd===REMOVE)node.contents=null}else visit_(null,node,visitor_,Object.freeze([]))}visit.BREAK=BREAK;visit.SKIP=SKIP;visit.REMOVE=REMOVE;function visit_(key,node,visitor,path4){const ctrl=callVisitor(key,node,visitor,path4);if(identity.isNode(ctrl)||identity.isPair(ctrl)){replaceNode(key,path4,ctrl);return visit_(key,ctrl,visitor,path4)}if(typeof ctrl!=="symbol"){if(identity.isCollection(node)){path4=Object.freeze(path4.concat(node));for(let i2=0;i2<node.items.length;++i2){const ci2=visit_(i2,node.items[i2],visitor,path4);if(typeof ci2==="number")i2=ci2-1;else if(ci2===BREAK)return BREAK;else if(ci2===REMOVE){node.items.splice(i2,1);i2-=1}}}else if(identity.isPair(node)){path4=Object.freeze(path4.concat(node));const ck=visit_("key",node.key,visitor,path4);if(ck===BREAK)return BREAK;else if(ck===REMOVE)node.key=null;const cv=visit_("value",node.value,visitor,path4);if(cv===BREAK)return BREAK;else if(cv===REMOVE)node.value=null}}return ctrl}async function visitAsync(node,visitor){const visitor_=initVisitor(visitor);if(identity.isDocument(node)){const cd=await visitAsync_(null,node.contents,visitor_,Object.freeze([node]));if(cd===REMOVE)node.contents=null}else await visitAsync_(null,node,visitor_,Object.freeze([]))}visitAsync.BREAK=BREAK;visitAsync.SKIP=SKIP;visitAsync.REMOVE=REMOVE;async function visitAsync_(key,node,visitor,path4){const ctrl=await callVisitor(key,node,visitor,path4);if(identity.isNode(ctrl)||identity.isPair(ctrl)){replaceNode(key,path4,ctrl);return visitAsync_(key,ctrl,visitor,path4)}if(typeof ctrl!=="symbol"){if(identity.isCollection(node)){path4=Object.freeze(path4.concat(node));for(let i2=0;i2<node.items.length;++i2){const ci2=await visitAsync_(i2,node.items[i2],visitor,path4);if(typeof ci2==="number")i2=ci2-1;else if(ci2===BREAK)return BREAK;else if(ci2===REMOVE){node.items.splice(i2,1);i2-=1}}}else if(identity.isPair(node)){path4=Object.freeze(path4.concat(node));const ck=await visitAsync_("key",node.key,visitor,path4);if(ck===BREAK)return BREAK;else if(ck===REMOVE)node.key=null;const cv=await visitAsync_("value",node.value,visitor,path4);if(cv===BREAK)return BREAK;else if(cv===REMOVE)node.value=null}}return ctrl}function initVisitor(visitor){if(typeof visitor==="object"&&(visitor.Collection||visitor.Node||visitor.Value)){return Object.assign({Alias:visitor.Node,Map:visitor.Node,Scalar:visitor.Node,Seq:visitor.Node},visitor.Value&&{Map:visitor.Value,Scalar:visitor.Value,Seq:visitor.Value},visitor.Collection&&{Map:visitor.Collection,Seq:visitor.Collection},visitor)}return visitor}function callVisitor(key,node,visitor,path4){if(typeof visitor==="function")return visitor(key,node,path4);if(identity.isMap(node))return visitor.Map?.(key,node,path4);if(identity.isSeq(node))return visitor.Seq?.(key,node,path4);if(identity.isPair(node))return visitor.Pair?.(key,node,path4);if(identity.isScalar(node))return visitor.Scalar?.(key,node,path4);if(identity.isAlias(node))return visitor.Alias?.(key,node,path4);return void 0}function replaceNode(key,path4,node){const parent=path4[path4.length-1];if(identity.isCollection(parent)){parent.items[key]=node}else if(identity.isPair(parent)){if(key==="key")parent.key=node;else parent.value=node}else if(identity.isDocument(parent)){parent.contents=node}else{const pt2=identity.isAlias(parent)?"alias":"scalar";throw new Error(`Cannot replace node with ${pt2} parent`)}}exports.visit=visit;exports.visitAsync=visitAsync}});var require_directives=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/directives.js"(exports){"use strict";var identity=require_identity();var visit=require_visit();var escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"};var escapeTagName=tn2=>tn2.replace(/[!,[\]{}]/g,ch=>escapeChars[ch]);var Directives=class _Directives{constructor(yaml,tags){this.docStart=null;this.docEnd=false;this.yaml=Object.assign({},_Directives.defaultYaml,yaml);this.tags=Object.assign({},_Directives.defaultTags,tags)}clone(){const copy2=new _Directives(this.yaml,this.tags);copy2.docStart=this.docStart;return copy2}atDocument(){const res=new _Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=true;break;case"1.2":this.atNextDocument=false;this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.2"};this.tags=Object.assign({},_Directives.defaultTags);break}return res}add(line,onError){if(this.atNextDocument){this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.1"};this.tags=Object.assign({},_Directives.defaultTags);this.atNextDocument=false}const parts=line.trim().split(/[ \t]+/);const name2=parts.shift();switch(name2){case"%TAG":{if(parts.length!==2){onError(0,"%TAG directive should contain exactly two parts");if(parts.length<2)return false}const[handle,prefix]=parts;this.tags[handle]=prefix;return true}case"%YAML":{this.yaml.explicit=true;if(parts.length!==1){onError(0,"%YAML directive should contain exactly one part");return false}const[version2]=parts;if(version2==="1.1"||version2==="1.2"){this.yaml.version=version2;return true}else{const isValid=/^\d+\.\d+$/.test(version2);onError(6,`Unsupported YAML version ${version2}`,isValid);return false}}default:onError(0,`Unknown directive ${name2}`,true);return false}}tagName(source,onError){if(source==="!")return"!";if(source[0]!=="!"){onError(`Not a valid tag: ${source}`);return null}if(source[1]==="<"){const verbatim=source.slice(2,-1);if(verbatim==="!"||verbatim==="!!"){onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);return null}if(source[source.length-1]!==">")onError("Verbatim tags must end with a >");return verbatim}const[,handle,suffix]=source.match(/^(.*!)([^!]*)$/s);if(!suffix)onError(`The ${source} tag has no suffix`);const prefix=this.tags[handle];if(prefix){try{return prefix+decodeURIComponent(suffix)}catch(error51){onError(String(error51));return null}}if(handle==="!")return source;onError(`Could not resolve tag: ${source}`);return null}tagString(tag){for(const[handle,prefix]of Object.entries(this.tags)){if(tag.startsWith(prefix))return handle+escapeTagName(tag.substring(prefix.length))}return tag[0]==="!"?tag:`!<${tag}>`}toString(doc){const lines=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[];const tagEntries=Object.entries(this.tags);let tagNames;if(doc&&tagEntries.length>0&&identity.isNode(doc.contents)){const tags={};visit.visit(doc.contents,(_key,node)=>{if(identity.isNode(node)&&node.tag)tags[node.tag]=true});tagNames=Object.keys(tags)}else tagNames=[];for(const[handle,prefix]of tagEntries){if(handle==="!!"&&prefix==="tag:yaml.org,2002:")continue;if(!doc||tagNames.some(tn2=>tn2.startsWith(prefix)))lines.push(`%TAG ${handle} ${prefix}`)}return lines.join("\n")}};Directives.defaultYaml={explicit:false,version:"1.2"};Directives.defaultTags={"!!":"tag:yaml.org,2002:"};exports.Directives=Directives}});var require_anchors=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/anchors.js"(exports){"use strict";var identity=require_identity();var visit=require_visit();function anchorIsValid(anchor){if(/[\x00-\x19\s,[\]{}]/.test(anchor)){const sa2=JSON.stringify(anchor);const msg=`Anchor must not contain whitespace or control characters: ${sa2}`;throw new Error(msg)}return true}function anchorNames(root){const anchors=new Set;visit.visit(root,{Value(_key,node){if(node.anchor)anchors.add(node.anchor)}});return anchors}function findNewAnchor(prefix,exclude){for(let i2=1;true;++i2){const name2=`${prefix}${i2}`;if(!exclude.has(name2))return name2}}function createNodeAnchors(doc,prefix){const aliasObjects=[];const sourceObjects=new Map;let prevAnchors=null;return{onAnchor:source=>{aliasObjects.push(source);prevAnchors??(prevAnchors=anchorNames(doc));const anchor=findNewAnchor(prefix,prevAnchors);prevAnchors.add(anchor);return anchor},setAnchors:()=>{for(const source of aliasObjects){const ref=sourceObjects.get(source);if(typeof ref==="object"&&ref.anchor&&(identity.isScalar(ref.node)||identity.isCollection(ref.node))){ref.node.anchor=ref.anchor}else{const error51=new Error("Failed to resolve repeated object (this should not happen)");error51.source=source;throw error51}}},sourceObjects}}exports.anchorIsValid=anchorIsValid;exports.anchorNames=anchorNames;exports.createNodeAnchors=createNodeAnchors;exports.findNewAnchor=findNewAnchor}});var require_applyReviver=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/applyReviver.js"(exports){"use strict";function applyReviver(reviver,obj,key,val){if(val&&typeof val==="object"){if(Array.isArray(val)){for(let i2=0,len=val.length;i2<len;++i2){const v0=val[i2];const v1=applyReviver(reviver,val,String(i2),v0);if(v1===void 0)delete val[i2];else if(v1!==v0)val[i2]=v1}}else if(val instanceof Map){for(const k2 of Array.from(val.keys())){const v0=val.get(k2);const v1=applyReviver(reviver,val,k2,v0);if(v1===void 0)val.delete(k2);else if(v1!==v0)val.set(k2,v1)}}else if(val instanceof Set){for(const v0 of Array.from(val)){const v1=applyReviver(reviver,val,v0,v0);if(v1===void 0)val.delete(v0);else if(v1!==v0){val.delete(v0);val.add(v1)}}}else{for(const[k2,v0]of Object.entries(val)){const v1=applyReviver(reviver,val,k2,v0);if(v1===void 0)delete val[k2];else if(v1!==v0)val[k2]=v1}}}return reviver.call(obj,key,val)}exports.applyReviver=applyReviver}});var require_toJS=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/toJS.js"(exports){"use strict";var identity=require_identity();function toJS(value,arg,ctx){if(Array.isArray(value))return value.map((v3,i2)=>toJS(v3,String(i2),ctx));if(value&&typeof value.toJSON==="function"){if(!ctx||!identity.hasAnchor(value))return value.toJSON(arg,ctx);const data={aliasCount:0,count:1,res:void 0};ctx.anchors.set(value,data);ctx.onCreate=res2=>{data.res=res2;delete ctx.onCreate};const res=value.toJSON(arg,ctx);if(ctx.onCreate)ctx.onCreate(res);return res}if(typeof value==="bigint"&&!ctx?.keep)return Number(value);return value}exports.toJS=toJS}});var require_Node=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Node.js"(exports){"use strict";var applyReviver=require_applyReviver();var identity=require_identity();var toJS=require_toJS();var NodeBase=class{constructor(type){Object.defineProperty(this,identity.NODE_TYPE,{value:type})}clone(){const copy2=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)copy2.range=this.range.slice();return copy2}toJS(doc,{mapAsMap,maxAliasCount,onAnchor,reviver}={}){if(!identity.isDocument(doc))throw new TypeError("A document argument is required");const ctx={anchors:new Map,doc,keep:true,mapAsMap:mapAsMap===true,mapKeyWarned:false,maxAliasCount:typeof maxAliasCount==="number"?maxAliasCount:100};const res=toJS.toJS(this,"",ctx);if(typeof onAnchor==="function")for(const{count,res:res2}of ctx.anchors.values())onAnchor(res2,count);return typeof reviver==="function"?applyReviver.applyReviver(reviver,{"":res},"",res):res}};exports.NodeBase=NodeBase}});var require_Alias=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Alias.js"(exports){"use strict";var anchors=require_anchors();var visit=require_visit();var identity=require_identity();var Node=require_Node();var toJS=require_toJS();var Alias=class extends Node.NodeBase{constructor(source){super(identity.ALIAS);this.source=source;Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(doc,ctx){if(ctx?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let nodes;if(ctx?.aliasResolveCache){nodes=ctx.aliasResolveCache}else{nodes=[];visit.visit(doc,{Node:(_key,node)=>{if(identity.isAlias(node)||identity.hasAnchor(node))nodes.push(node)}});if(ctx)ctx.aliasResolveCache=nodes}let found=void 0;for(const node of nodes){if(node===this)break;if(node.anchor===this.source)found=node}return found}toJSON(_arg,ctx){if(!ctx)return{source:this.source};const{anchors:anchors2,doc,maxAliasCount}=ctx;const source=this.resolve(doc,ctx);if(!source){const msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(msg)}let data=anchors2.get(source);if(!data){toJS.toJS(source,null,ctx);data=anchors2.get(source)}if(data?.res===void 0){const msg="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(msg)}if(maxAliasCount>=0){data.count+=1;if(data.aliasCount===0)data.aliasCount=getAliasCount(doc,source,anchors2);if(data.count*data.aliasCount>maxAliasCount){const msg="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(msg)}}return data.res}toString(ctx,_onComment,_onChompKeep){const src=`*${this.source}`;if(ctx){anchors.anchorIsValid(this.source);if(ctx.options.verifyAliasOrder&&!ctx.anchors.has(this.source)){const msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(msg)}if(ctx.implicitKey)return`${src} `}return src}};function getAliasCount(doc,node,anchors2){if(identity.isAlias(node)){const source=node.resolve(doc);const anchor=anchors2&&source&&anchors2.get(source);return anchor?anchor.count*anchor.aliasCount:0}else if(identity.isCollection(node)){let count=0;for(const item of node.items){const c3=getAliasCount(doc,item,anchors2);if(c3>count)count=c3}return count}else if(identity.isPair(node)){const kc=getAliasCount(doc,node.key,anchors2);const vc=getAliasCount(doc,node.value,anchors2);return Math.max(kc,vc)}return 1}exports.Alias=Alias}});var require_Scalar=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Scalar.js"(exports){"use strict";var identity=require_identity();var Node=require_Node();var toJS=require_toJS();var isScalarValue=value=>!value||typeof value!=="function"&&typeof value!=="object";var Scalar=class extends Node.NodeBase{constructor(value){super(identity.SCALAR);this.value=value}toJSON(arg,ctx){return ctx?.keep?this.value:toJS.toJS(this.value,arg,ctx)}toString(){return String(this.value)}};Scalar.BLOCK_FOLDED="BLOCK_FOLDED";Scalar.BLOCK_LITERAL="BLOCK_LITERAL";Scalar.PLAIN="PLAIN";Scalar.QUOTE_DOUBLE="QUOTE_DOUBLE";Scalar.QUOTE_SINGLE="QUOTE_SINGLE";exports.Scalar=Scalar;exports.isScalarValue=isScalarValue}});var require_createNode=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/createNode.js"(exports){"use strict";var Alias=require_Alias();var identity=require_identity();var Scalar=require_Scalar();var defaultTagPrefix="tag:yaml.org,2002:";function findTagObject(value,tagName,tags){if(tagName){const match=tags.filter(t2=>t2.tag===tagName);const tagObj=match.find(t2=>!t2.format)??match[0];if(!tagObj)throw new Error(`Tag ${tagName} not found`);return tagObj}return tags.find(t2=>t2.identify?.(value)&&!t2.format)}function createNode(value,tagName,ctx){if(identity.isDocument(value))value=value.contents;if(identity.isNode(value))return value;if(identity.isPair(value)){const map2=ctx.schema[identity.MAP].createNode?.(ctx.schema,null,ctx);map2.items.push(value);return map2}if(value instanceof String||value instanceof Number||value instanceof Boolean||typeof BigInt!=="undefined"&&value instanceof BigInt){value=value.valueOf()}const{aliasDuplicateObjects,onAnchor,onTagObj,schema,sourceObjects}=ctx;let ref=void 0;if(aliasDuplicateObjects&&value&&typeof value==="object"){ref=sourceObjects.get(value);if(ref){ref.anchor??(ref.anchor=onAnchor(value));return new Alias.Alias(ref.anchor)}else{ref={anchor:null,node:null};sourceObjects.set(value,ref)}}if(tagName?.startsWith("!!"))tagName=defaultTagPrefix+tagName.slice(2);let tagObj=findTagObject(value,tagName,schema.tags);if(!tagObj){if(value&&typeof value.toJSON==="function"){value=value.toJSON()}if(!value||typeof value!=="object"){const node2=new Scalar.Scalar(value);if(ref)ref.node=node2;return node2}tagObj=value instanceof Map?schema[identity.MAP]:Symbol.iterator in Object(value)?schema[identity.SEQ]:schema[identity.MAP]}if(onTagObj){onTagObj(tagObj);delete ctx.onTagObj}const node=tagObj?.createNode?tagObj.createNode(ctx.schema,value,ctx):typeof tagObj?.nodeClass?.from==="function"?tagObj.nodeClass.from(ctx.schema,value,ctx):new Scalar.Scalar(value);if(tagName)node.tag=tagName;else if(!tagObj.default)node.tag=tagObj.tag;if(ref)ref.node=node;return node}exports.createNode=createNode}});var require_Collection=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Collection.js"(exports){"use strict";var createNode=require_createNode();var identity=require_identity();var Node=require_Node();function collectionFromPath(schema,path4,value){let v3=value;for(let i2=path4.length-1;i2>=0;--i2){const k2=path4[i2];if(typeof k2==="number"&&Number.isInteger(k2)&&k2>=0){const a3=[];a3[k2]=v3;v3=a3}else{v3=new Map([[k2,v3]])}}return createNode.createNode(v3,void 0,{aliasDuplicateObjects:false,keepUndefined:false,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema,sourceObjects:new Map})}var isEmptyPath=path4=>path4==null||typeof path4==="object"&&!!path4[Symbol.iterator]().next().done;var Collection=class extends Node.NodeBase{constructor(type,schema){super(type);Object.defineProperty(this,"schema",{value:schema,configurable:true,enumerable:false,writable:true})}clone(schema){const copy2=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(schema)copy2.schema=schema;copy2.items=copy2.items.map(it2=>identity.isNode(it2)||identity.isPair(it2)?it2.clone(schema):it2);if(this.range)copy2.range=this.range.slice();return copy2}addIn(path4,value){if(isEmptyPath(path4))this.add(value);else{const[key,...rest]=path4;const node=this.get(key,true);if(identity.isCollection(node))node.addIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}deleteIn(path4){const[key,...rest]=path4;if(rest.length===0)return this.delete(key);const node=this.get(key,true);if(identity.isCollection(node))return node.deleteIn(rest);else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}getIn(path4,keepScalar){const[key,...rest]=path4;const node=this.get(key,true);if(rest.length===0)return!keepScalar&&identity.isScalar(node)?node.value:node;else return identity.isCollection(node)?node.getIn(rest,keepScalar):void 0}hasAllNullValues(allowScalar){return this.items.every(node=>{if(!identity.isPair(node))return false;const n2=node.value;return n2==null||allowScalar&&identity.isScalar(n2)&&n2.value==null&&!n2.commentBefore&&!n2.comment&&!n2.tag})}hasIn(path4){const[key,...rest]=path4;if(rest.length===0)return this.has(key);const node=this.get(key,true);return identity.isCollection(node)?node.hasIn(rest):false}setIn(path4,value){const[key,...rest]=path4;if(rest.length===0){this.set(key,value)}else{const node=this.get(key,true);if(identity.isCollection(node))node.setIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}};exports.Collection=Collection;exports.collectionFromPath=collectionFromPath;exports.isEmptyPath=isEmptyPath}});var require_stringifyComment=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyComment.js"(exports){"use strict";var stringifyComment=str2=>str2.replace(/^(?!$)(?: $)?/gm,"#");function indentComment(comment,indent){if(/^\n+$/.test(comment))return comment.substring(1);return indent?comment.replace(/^(?! *$)/gm,indent):comment}var lineComment=(str2,indent,comment)=>str2.endsWith("\n")?indentComment(comment,indent):comment.includes("\n")?"\n"+indentComment(comment,indent):(str2.endsWith(" ")?"":" ")+comment;exports.indentComment=indentComment;exports.lineComment=lineComment;exports.stringifyComment=stringifyComment}});var require_foldFlowLines=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/foldFlowLines.js"(exports){"use strict";var FOLD_FLOW="flow";var FOLD_BLOCK="block";var FOLD_QUOTED="quoted";function foldFlowLines(text3,indent,mode="flow",{indentAtStart,lineWidth=80,minContentWidth=20,onFold,onOverflow}={}){if(!lineWidth||lineWidth<0)return text3;if(lineWidth<minContentWidth)minContentWidth=0;const endStep=Math.max(1+minContentWidth,1+lineWidth-indent.length);if(text3.length<=endStep)return text3;const folds=[];const escapedFolds={};let end=lineWidth-indent.length;if(typeof indentAtStart==="number"){if(indentAtStart>lineWidth-Math.max(2,minContentWidth))folds.push(0);else end=lineWidth-indentAtStart}let split=void 0;let prev=void 0;let overflow=false;let i2=-1;let escStart=-1;let escEnd=-1;if(mode===FOLD_BLOCK){i2=consumeMoreIndentedLines(text3,i2,indent.length);if(i2!==-1)end=i2+endStep}for(let ch;ch=text3[i2+=1];){if(mode===FOLD_QUOTED&&ch==="\\"){escStart=i2;switch(text3[i2+1]){case"x":i2+=3;break;case"u":i2+=5;break;case"U":i2+=9;break;default:i2+=1}escEnd=i2}if(ch==="\n"){if(mode===FOLD_BLOCK)i2=consumeMoreIndentedLines(text3,i2,indent.length);end=i2+indent.length+endStep;split=void 0}else{if(ch===" "&&prev&&prev!==" "&&prev!=="\n"&&prev!==" "){const next=text3[i2+1];if(next&&next!==" "&&next!=="\n"&&next!==" ")split=i2}if(i2>=end){if(split){folds.push(split);end=split+endStep;split=void 0}else if(mode===FOLD_QUOTED){while(prev===" "||prev===" "){prev=ch;ch=text3[i2+=1];overflow=true}const j2=i2>escEnd+1?i2-2:escStart-1;if(escapedFolds[j2])return text3;folds.push(j2);escapedFolds[j2]=true;end=j2+endStep;split=void 0}else{overflow=true}}}prev=ch}if(overflow&&onOverflow)onOverflow();if(folds.length===0)return text3;if(onFold)onFold();let res=text3.slice(0,folds[0]);for(let i3=0;i3<folds.length;++i3){const fold=folds[i3];const end2=folds[i3+1]||text3.length;if(fold===0)res=`
|
|
27
|
+
computed: SHA-256 ${hex3}`))}else{controller.close()}break}}})().then(()=>{d2.resolve()}).catch(err3=>{controller.error(err3);d2.reject(err3)});r2.data=new ReadableStream({start(c3){controller=c3},cancel(){iter.stop()}});return r2}linkStore(name2,bucket){if(!(bucket instanceof _ObjectStoreImpl)){return Promise.reject("bucket required")}const osi=bucket;const{name:n2,error:error51}=this._checkNotEmpty(name2);if(error51){return Promise.reject(error51)}const meta3={name:n2,options:{link:{bucket:osi.name}}};return this._put(meta3,null)}async link(name2,info){const{name:n2,error:error51}=this._checkNotEmpty(name2);if(error51){return Promise.reject(error51)}if(info.deleted){return Promise.reject(new Error("src object is deleted"))}if(info.isLink()){return Promise.reject(new Error("src object is a link"))}const dest=await this.rawInfo(name2);if(dest!==null&&!dest.deleted){return Promise.reject(new Error("an object already exists with that name"))}const link={bucket:info.bucket,name:info.name};const mm={name:n2,bucket:info.bucket,options:{link}};await this.js.publish(this._metaSubject(name2),JSON.stringify(mm));const i2=await this.info(name2);return Promise.resolve(i2)}async delete(name2){const info=await this.rawInfo(name2);if(info===null){return Promise.resolve({purged:0,success:false})}info.deleted=true;info.size=0;info.chunks=0;info.digest="";const h3=(0,internal_1.headers)();h3.set(internal_2.JsHeaders.RollupHdr,internal_2.JsHeaders.RollupValueSubject);await this.js.publish(this._metaSubject(info.name),JSON.stringify(info),{headers:h3});return this.jsm.streams.purge(this.stream,{filter:this._chunkSubject(info.nuid)})}async update(name2,meta3={}){const info=await this.rawInfo(name2);if(info===null){return Promise.reject(new Error("object not found"))}if(info.deleted){return Promise.reject(new Error("cannot update meta for a deleted object"))}meta3.name=meta3.name??info.name;const{name:n2,error:error51}=this._checkNotEmpty(meta3.name);if(error51){return Promise.reject(error51)}if(name2!==meta3.name){const i2=await this.info(meta3.name);if(i2&&!i2.deleted){return Promise.reject(new Error("an object already exists with that name"))}}meta3.name=n2;const ii2=Object.assign({},info,toServerObjectStoreMeta(meta3));const ack=await this.js.publish(this._metaSubject(ii2.name),JSON.stringify(ii2));if(name2!==meta3.name){await this.jsm.streams.purge(this.stream,{filter:this._metaSubject(name2)})}return Promise.resolve(ack)}async watch(opts={}){opts.includeHistory=opts.includeHistory??false;opts.ignoreDeletes=opts.ignoreDeletes??false;const historyOnly=opts.historyOnly??false;const qi2=new internal_1.QueuedIteratorImpl;const subj=this._metaSubjectAll();try{await this.jsm.streams.getMessage(this.stream,{last_by_subj:subj})}catch(err3){if(!(0,internal_2.isMessageNotFound)(err3)){qi2.stop(err3)}}const cc={};cc.name=`OBJ_WATCHER_${internal_1.nuid.next()}`;cc.filter_subject=subj;if(opts.includeHistory){cc.deliver_policy=internal_2.DeliverPolicy.LastPerSubject}else{cc.deliver_policy=internal_2.DeliverPolicy.New}const oc=await this.js.consumers.getPushConsumer(this.stream,cc);const info=await oc.info(true);const count=info.num_pending;let isUpdate=cc.deliver_policy===internal_2.DeliverPolicy.New||count===0;qi2._data=oc;let i2=0;const iter=await oc.consume({callback:jm=>{if(!isUpdate){i2++;isUpdate=i2>=count}const oi2=jm.json();oi2.isUpdate=isUpdate;if(oi2.deleted&&opts.ignoreDeletes===true){}else{qi2.push(oi2)}if(historyOnly&&i2===count){iter.stop()}}});(async()=>{for await(const s3 of iter.status()){switch(s3.type){case"heartbeat":if(historyOnly){qi2.push(()=>{qi2.stop()})}}}})().then();if(historyOnly&&count===0){iter.stop()}iter.closed().then(()=>{qi2.push(()=>{qi2.stop()})});qi2.iterClosed.then(()=>{iter.stop()});return qi2}_chunkSubject(id2){return`$O.${this.name}.C.${id2}`}_metaSubject(n2){return`$O.${this.name}.M.${base64_1.Base64UrlPaddedCodec.encode(n2)}`}_metaSubjectAll(){return`$O.${this.name}.M.>`}async init(opts={}){try{this.stream=objectStoreStreamName(this.name)}catch(err3){return Promise.reject(err3)}const max_age=opts?.ttl||0;delete opts.ttl;const{replicas}=opts;delete opts.replicas;const o3=opts;this.allowBatched=o3.allowBatched===true;delete o3.allowBatched;const sc=Object.assign({max_age},opts);sc.name=this.stream;sc.allow_direct=true;sc.allow_rollup_hdrs=true;sc.num_replicas=replicas||1;sc.discard=internal_2.DiscardPolicy.New;sc.subjects=[`$O.${this.name}.C.>`,`$O.${this.name}.M.>`];const apiLvl=this.js.nc.info?.api_lvl??0;if(this.allowBatched){if(apiLvl<4){return Promise.reject(new Error("server does not support batched publishes"))}sc.allow_batched=true}if(opts.placement){sc.placement=opts.placement}if(opts.metadata){sc.metadata=opts.metadata}if(typeof opts.compression==="boolean"){sc.compression=opts.compression?internal_2.StoreCompression.S2:internal_2.StoreCompression.None}let si2;try{si2=await this.jsm.streams.info(sc.name)}catch(err3){if(err3.message==="stream not found"){si2=await this.jsm.streams.add(sc)}else{throw err3}}if(this.allowBatched&&si2.config.allow_batched!==true){return Promise.reject(new Error("existing bucket does not support batched publishes"))}return si2}static async create(js,name2,opts={}){const jsm=await js.jetstreamManager();const os3=new _ObjectStoreImpl(name2,jsm,js);await os3.init(opts);return os3}};exports.ObjectStoreImpl=ObjectStoreImpl}});var require_internal_mod4=__commonJS({"../../node_modules/.pnpm/@nats-io+obj@3.4.0/node_modules/@nats-io/obj/lib/internal_mod.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.setSha256Backend=exports.getSha256Backend=exports.Base64UrlPaddedCodec=exports.Base64UrlCodec=exports.Base64Codec=exports.Objm=exports.StorageType=void 0;var types_1=require_types5();Object.defineProperty(exports,"StorageType",{enumerable:true,get:function(){return types_1.StorageType}});var objectstore_1=require_objectstore();Object.defineProperty(exports,"Objm",{enumerable:true,get:function(){return objectstore_1.Objm}});var base64_1=require_base64();Object.defineProperty(exports,"Base64Codec",{enumerable:true,get:function(){return base64_1.Base64Codec}});Object.defineProperty(exports,"Base64UrlCodec",{enumerable:true,get:function(){return base64_1.Base64UrlCodec}});Object.defineProperty(exports,"Base64UrlPaddedCodec",{enumerable:true,get:function(){return base64_1.Base64UrlPaddedCodec}});var sha256_1=require_sha2562();Object.defineProperty(exports,"getSha256Backend",{enumerable:true,get:function(){return sha256_1.getSha256Backend}});Object.defineProperty(exports,"setSha256Backend",{enumerable:true,get:function(){return sha256_1.setSha256Backend}})}});var require_mod7=__commonJS({"../../node_modules/.pnpm/@nats-io+obj@3.4.0/node_modules/@nats-io/obj/lib/mod.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.setSha256Backend=exports.getSha256Backend=exports.Base64UrlPaddedCodec=exports.Base64UrlCodec=exports.Base64Codec=exports.Objm=exports.StorageType=void 0;var internal_mod_1=require_internal_mod4();Object.defineProperty(exports,"StorageType",{enumerable:true,get:function(){return internal_mod_1.StorageType}});var internal_mod_2=require_internal_mod4();Object.defineProperty(exports,"Objm",{enumerable:true,get:function(){return internal_mod_2.Objm}});var internal_mod_3=require_internal_mod4();Object.defineProperty(exports,"Base64Codec",{enumerable:true,get:function(){return internal_mod_3.Base64Codec}});Object.defineProperty(exports,"Base64UrlCodec",{enumerable:true,get:function(){return internal_mod_3.Base64UrlCodec}});Object.defineProperty(exports,"Base64UrlPaddedCodec",{enumerable:true,get:function(){return internal_mod_3.Base64UrlPaddedCodec}});var internal_mod_4=require_internal_mod4();Object.defineProperty(exports,"getSha256Backend",{enumerable:true,get:function(){return internal_mod_4.getSha256Backend}});Object.defineProperty(exports,"setSha256Backend",{enumerable:true,get:function(){return internal_mod_4.setSha256Backend}})}});function nativeCredsAuthenticator(creds){return nonce4=>{const blocks=/\s*(?:(?:[-]{3,}[^\n]*[-]{3,}\n)(.+)(?:\n\s*[-]{3,}[^\n]*[-]{3,}\n))/ig;const text3=typeof creds==="function"?creds():creds;const jwtBlock=blocks.exec(text3);if(!jwtBlock)throw new Error("unable to parse credentials");const seedBlock=blocks.exec(text3);if(!seedBlock)throw new Error("unable to parse credentials");const seed=new TextEncoder().encode(seedBlock[1].trim());let signer;try{signer=nativeNkeySigner(seed);return{jwt:jwtBlock[1].trim(),nkey:signer.getPublicKey(),sig:nonce4?(0,import_nkeys6.encode)(signer.sign(new TextEncoder().encode(nonce4))):""}}finally{seed.fill(0);signer?.clear()}}}var import_nkeys6;var init_creds_authenticator=__esm({"../../packages/core/dist/creds-authenticator.js"(){"use strict";import_nkeys6=__toESM(require_mod(),1);init_nkey_signer()}});function parseServerVersion(v3){const m2=/^(\d+)\.(\d+)\.(\d+)/.exec(v3.trim());if(!m2)return null;return{major:Number(m2[1]),minor:Number(m2[2]),patch:Number(m2[3])}}function meetsBrokerFloor(version2){const p2=parseServerVersion(version2);if(!p2)return false;if(p2.major!==BROKER_FLOOR.major)return p2.major>BROKER_FLOOR.major;return p2.minor>=BROKER_FLOOR.minor}function requireBrokerFloor(nc){const version2=nc.info?.version;if(!version2)throw new Error("control surface: connected broker reports no server version; refusing to start (floor is nats-server >= 2.12)");if(!meetsBrokerFloor(version2))throw new Error(`control surface: nats-server ${version2} is below the required floor 2.12; upgrade the broker (no degraded mode exists)`)}var BROKER_FLOOR;var init_broker_floor=__esm({"../../packages/core/dist/broker-floor.js"(){"use strict";BROKER_FLOOR=Object.freeze({major:2,minor:12})}});async function openAclRegistry(nc,space2,opts={}){const kvm=new import_kv2.Kvm(nc);return opts.create?kvm.create(aclBucket(space2)):kvm.open(aclBucket(space2))}async function readAcl(kv,owner2,lifecycleUid){const e3=await kv.get(aclKey(owner2,lifecycleUid));if(!e3||e3.operation==="DEL"||e3.operation==="PURGE")return void 0;try{const record2=e3.json();if(!Array.isArray(record2.allowSubscribe))return void 0;return{record:record2,revision:e3.revision}}catch{return void 0}}async function aclRetired(kv,owner2,lifecycleUid){const e3=await kv.get(aclKey(owner2,lifecycleUid));return e3?.operation==="DEL"||e3?.operation==="PURGE"}async function readAclForAlias(kv,principal){const first=await enumerateLiveAclRows(kv,principal);if(first.length>1)throw new AmbiguousAclAlias(principal,first.map(l2=>l2.lifecycleUid).sort());const second=await enumerateLiveAclRows(kv,principal);if(second.length>1)throw new AmbiguousAclAlias(principal,second.map(l2=>l2.lifecycleUid).sort());if(second.length===0)return void 0;if(first.length===1&&first[0].lifecycleUid!==second[0].lifecycleUid)throw new AmbiguousAclAlias(principal,[first[0].lifecycleUid,second[0].lifecycleUid].sort());return{record:second[0].record,revision:second[0].revision,lifecycleUid:second[0].lifecycleUid}}async function enumerateLiveAclRows(kv,principal){const live=[];for(const e3 of await liveKvEntries(kv,aclAliasFilter(principal))){const parsed=parseLifecycleSubjectKey(e3.key);if(!parsed||`${parsed.owner}.${parsed.actor}`!==principal)continue;let record2;try{record2=e3.json()}catch{continue}if(!Array.isArray(record2.allowSubscribe))continue;live.push({lifecycleUid:parsed.lifecycleUid,record:record2,revision:e3.revision})}return live}async function reissueAcl(kv,owner2,lifecycleUid,allowSubscribe){return writeAcl(kv,owner2,lifecycleUid,allowSubscribe,{reissue:true})}async function commitAcl(kv,owner2,lifecycleUid,allowSubscribe){return writeAcl(kv,owner2,lifecycleUid,allowSubscribe,{reissue:false})}async function writeAcl(kv,owner2,lifecycleUid,allowSubscribe,opts){const key=aclKey(owner2,lifecycleUid);let lastErr;for(let attempt=0;attempt<5;attempt++){const cur=await readAcl(kv,owner2,lifecycleUid);let issued;if(opts.reissue||!cur){issued=[...allowSubscribe]}else{issued=[...cur.record.issuedAllowSubscribe??cur.record.allowSubscribe];const excess=allowSubscribe.filter(a3=>!patternInAllow(issued,a3));if(excess.length>0){throw new Error(`commitAcl: cannot raise ACL above mint-time ceiling without reissue (entries [${excess.join(", ")}] not within ceiling [${issued.join(", ")}]); use reissueAcl from the provisioning path that also remints the JWT`)}}const next={allowSubscribe:[...allowSubscribe],issuedAllowSubscribe:issued,revision:(cur?.record.revision??0)+1,updatedAt:Date.now()};const data=new TextEncoder().encode(JSON.stringify(next));if(!cur){try{await kv.create(key,data);return next}catch(e3){lastErr=e3;try{const raw=await kv.get(key);if(raw){await kv.update(key,data,raw.revision);return next}}catch(e22){lastErr=e22}continue}}try{await kv.update(key,data,cur.revision);return next}catch(e3){lastErr=e3;continue}}throw new Error(`acl CAS exhausted retries for ${owner2}${lastErr?` - last error: ${lastErr instanceof Error?lastErr.message:String(lastErr)}`:""}`,lastErr instanceof Error?{cause:lastErr}:void 0)}var import_kv2,AmbiguousAclAlias;var init_acls=__esm({"../../packages/core/dist/acls.js"(){"use strict";import_kv2=__toESM(require_mod6(),1);init_subjects();init_kv_scan();AmbiguousAclAlias=class extends Error{principal;lifecycleUids;constructor(principal,lifecycleUids){super(`read-ACL alias "${principal}" resolves to ${lifecycleUids.length} live lifecycle rows (${lifecycleUids.join(", ")}); at most one lifecycle may be live per alias (SPEC 13.1) - refusing to authorize on a first-match guess`);this.principal=principal;this.lifecycleUids=lifecycleUids}}}});async function openMembersRegistry(nc,space2,opts={}){const kvm=new import_kv3.Kvm(nc);return opts.create?kvm.create(membersBucket(space2)):kvm.open(membersBucket(space2))}async function readMember(kv,channel,owner2,lifecycleUid){const e3=await kv.get(memberKey(channel,owner2,lifecycleUid));if(!e3||e3.operation==="DEL"||e3.operation==="PURGE")return void 0;try{return{record:e3.json(),revision:e3.revision}}catch{return void 0}}async function commitMemberRevision(kv,next){const key=memberKey(next.channel,next.owner,next.lifecycleUid);const data=new TextEncoder().encode(JSON.stringify(next));for(let attempt=0;attempt<5;attempt++){const cur=await readMember(kv,next.channel,next.owner,next.lifecycleUid);if(!cur){try{return{record:next,revision:await kv.create(key,data)}}catch{continue}}if(next.generation<cur.record.generation)throw new StaleMembershipWrite(next.channel,next.owner,next.generation,cur.record.generation);try{return{record:next,revision:await kv.update(key,data,cur.revision)}}catch{continue}}throw new Error(`members CAS exhausted retries for ${key}`)}async function tombstoneMember(kv,channel,owner2,lifecycleUid,leaveCursor,writerIdentity,expectedGeneration){const key=memberKey(channel,owner2,lifecycleUid);let generation=expectedGeneration;for(let attempt=0;attempt<5;attempt++){const cur=await readMember(kv,channel,owner2,lifecycleUid);if(!cur)return void 0;generation??=cur.record.generation;if(cur.record.generation!==generation)throw new StaleMembershipWrite(channel,owner2,generation,cur.record.generation);if(cur.record.leaveCursor!==void 0&&cur.record.leaveCursor<=leaveCursor)return cur.record;const next={...cur.record,state:"live-confirmed",leaveCursor,writerIdentity,updatedAt:Date.now()};try{await kv.update(key,new TextEncoder().encode(JSON.stringify(next)),cur.revision);return next}catch{continue}}throw new Error(`members CAS exhausted retries for ${key}`)}async function activateMember(kv,channel,owner2,lifecycleUid,expectedGeneration,expectedJoinCursor){const key=memberKey(channel,owner2,lifecycleUid);for(let attempt=0;attempt<5;attempt++){const cur=await readMember(kv,channel,owner2,lifecycleUid);if(!cur)return void 0;const r2=cur.record;if(r2.generation!==expectedGeneration||r2.joinCursor!==expectedJoinCursor||r2.leaveCursor!==void 0)return void 0;if(r2.activated)return r2;const next={...r2,activated:true,updatedAt:Date.now()};try{await kv.update(key,new TextEncoder().encode(JSON.stringify(next)),cur.revision);return next}catch{continue}}return void 0}async function deleteMember(kv,channel,owner2,lifecycleUid){await kv.purge(memberKey(channel,owner2,lifecycleUid))}async function listMembers(kv,filter={}){const out=[];for(const e3 of await liveKvEntries(kv)){const parsed=parseMemberKey(e3.key);if(!parsed)continue;if(filter.channel!==void 0&&parsed.channel!==filter.channel)continue;if(filter.covering!==void 0&&parsed.channel!==filter.covering&&!(isChannelFamily(parsed.channel)&&subjectMatches(parsed.channel,filter.covering)))continue;if(filter.owner!==void 0&&parsed.principal!==filter.owner)continue;try{out.push(e3.json())}catch{}}return out}function durableEligible(rec,seq){if(seq<=rec.joinCursor)return false;if(rec.leaveCursor!==void 0&&seq>rec.leaveCursor)return false;return true}function inventoryPassAfterNow(kv){let passes=inventoryPasses.get(kv);if(passes===void 0)inventoryPasses.set(kv,passes={});const state=passes;if(state.next)return state.next;const next=(state.running??Promise.resolve([])).catch(()=>[]).then(()=>{state.next=void 0;const pass=liveKvEntries(kv);state.running=pass;const done=()=>{if(state.running===pass)state.running=void 0};pass.then(done,done);return pass});state.next=next;return next}async function listLifecycleMemberChannels(kv,principal,lifecycleUid){const pr2=parsePrincipalKey(principal);if(!pr2)throw new Error(`listLifecycleMemberChannels: invalid principal "${principal}"`);assertLifecycleToken(lifecycleUid);const channels=new Set;for(const e3 of await inventoryPassAfterNow(kv)){const parsed=parseMemberKey(e3.key);if(!parsed)continue;if(parsed.principal!==principal||parsed.lifecycleUid!==lifecycleUid)continue;if(!isConcreteChannel(parsed.channel)&&!isChannelFamily(parsed.channel))continue;channels.add(parsed.channel)}return[...channels].sort()}var import_kv3,StaleMembershipWrite,inventoryPasses;var init_members=__esm({"../../packages/core/dist/members.js"(){"use strict";import_kv3=__toESM(require_mod6(),1);init_subjects();init_kv_scan();StaleMembershipWrite=class extends Error{constructor(channel,owner2,attempted,current){super(`stale membership write for ${channel}/${owner2}: generation ${attempted} < current ${current}`);this.name="StaleMembershipWrite"}};inventoryPasses=new WeakMap}});var init_space_deletion_targets=__esm({"../../packages/core/dist/space-deletion-targets.js"(){"use strict";init_subjects();init_endpoint_binding();init_event_payloads()}});function historyLimitDefault(stream){if(stream==="chat")return CHAT_HISTORY_DEFAULT;return stream==="dm"?DM_HISTORY_DEFAULT:INBOX_HISTORY_DEFAULT}function historyLimitStreamOf(space2,stream){if(stream===chatStream(space2))return"chat";if(stream===inboxStream(space2))return"inbox";if(stream===dlvStream(space2))return"dlv";if(stream===dmStream(space2))return"dm";return void 0}function baseConfig(name2,subjects){return{name:name2,subjects,retention:import_jetstream10.RetentionPolicy.Limits,storage:import_jetstream10.StorageType.File,max_consumers:-1,max_msgs:-1,max_bytes:-1,max_age:0,max_msgs_per_subject:-1,max_msg_size:-1,discard:import_jetstream10.DiscardPolicy.Old,num_replicas:1,no_ack:false,duplicate_window:DEFAULT_DUPLICATE_WINDOW,compression:import_jetstream10.StoreCompression.None,allow_direct:false,mirror_direct:false,discard_new_per_subject:false,allow_rollup_hdrs:false,deny_delete:false,deny_purge:false,sealed:false,consumer_limits:{}}}function canonicalBackupStreamConfig(space2,stream,limit){const p2=spacePrefix(space2);const target2=historyLimitStreamOf(space2,stream);const limits=target2&&{max_age:(0,import_transport_node8.nanos)((limit??historyLimitDefault(target2)).maxAgeMs),max_msgs_per_subject:(limit??historyLimitDefault(target2)).perSubject};if(target2==="chat")return{...baseConfig(stream,[`${p2}.chat.>`]),...limits,allow_direct:true};if(stream===eventPayloadStream(space2))return{...baseConfig(stream,[`${p2}.evp.>`]),max_msgs_per_subject:CHAT_HISTORY_DEFAULT.perSubject,allow_direct:true};if(target2==="dm")return{...baseConfig(stream,[`${p2}.inst.>`]),...limits};if(stream===taskStream(space2)){return{...baseConfig(stream,[`${p2}.svc.>`]),retention:import_jetstream10.RetentionPolicy.Workqueue}}if(target2==="inbox")return{...baseConfig(stream,[`${p2}.dinbox.>`]),...limits,duplicate_window:PLANE3_DUPLICATE_WINDOW};if(target2==="dlv")return{...baseConfig(stream,[`${p2}.dlv.>`]),...limits,duplicate_window:PLANE3_DUPLICATE_WINDOW};if(stream===wfjStreamName(space2))return baseConfig(stream,[`${p2}.wfj.*`]);if(stream===recordsKvStreamName(space2))return{...kvStoreConfig(stream,recordsBucket(space2)),allow_direct:true,...endpointAuthorityStoreDefinitions(space2).records.hardenAfterCreate};if(stream===`KV_${admissionBucket(space2)}`)return{...kvStoreConfig(stream,admissionBucket(space2)),...admissionStoreDefinition(space2).hardenAfterCreate};for(const bucket of[channelBucket(space2),aclBucket(space2),membersBucket(space2)]){if(stream===`KV_${bucket}`){return{...baseConfig(stream,[`$KV.${bucket}.>`]),max_msgs_per_subject:1,discard:import_jetstream10.DiscardPolicy.New,allow_direct:true,allow_rollup_hdrs:true}}}throw new Error(`stream ${JSON.stringify(stream)} is not a backed-up stream for space ${JSON.stringify(space2)}`)}function kvStoreConfig(name2,bucket){return{...baseConfig(name2,[`$KV.${bucket}.>`]),max_msgs_per_subject:1,discard:import_jetstream10.DiscardPolicy.New,allow_rollup_hdrs:true}}var import_jetstream10,import_transport_node8,DEFAULT_DUPLICATE_WINDOW_MS,DEFAULT_DUPLICATE_WINDOW,PLANE3_MAX_MSGS_PER_SUBJECT,BACKUP_PLANE3_DEDUP_WINDOW_MS,PLANE3_DUPLICATE_WINDOW,DELIVERY_LIMIT_HEADER,HISTORY_NO_COUNT,CHAT_HISTORY_DEFAULT,INBOX_HISTORY_DEFAULT,DM_HISTORY_DEFAULT,HISTORY_MAX_AGE_MS;var init_backup_config=__esm({"../../packages/core/dist/backup-config.js"(){"use strict";import_jetstream10=__toESM(require_mod4(),1);import_transport_node8=__toESM(require_transport_node(),1);init_endpoint_binding();init_endpoint_records();init_run_admission();init_space_deletion_targets();init_event_payloads();init_subjects();DEFAULT_DUPLICATE_WINDOW_MS=2*60*1e3;DEFAULT_DUPLICATE_WINDOW=(0,import_transport_node8.nanos)(DEFAULT_DUPLICATE_WINDOW_MS);PLANE3_MAX_MSGS_PER_SUBJECT=1e3;BACKUP_PLANE3_DEDUP_WINDOW_MS=2*60*60*1e3;PLANE3_DUPLICATE_WINDOW=(0,import_transport_node8.nanos)(BACKUP_PLANE3_DEDUP_WINDOW_MS);DELIVERY_LIMIT_HEADER="Cotal-Delivery-Limit";HISTORY_NO_COUNT=-1;CHAT_HISTORY_DEFAULT=Object.freeze({maxAgeMs:0,perSubject:1e3});INBOX_HISTORY_DEFAULT=Object.freeze({maxAgeMs:0,perSubject:PLANE3_MAX_MSGS_PER_SUBJECT});DM_HISTORY_DEFAULT=Object.freeze({maxAgeMs:0,perSubject:HISTORY_NO_COUNT});HISTORY_MAX_AGE_MS=3650*864e5}});import{randomUUID as randomUUID3}from"node:crypto";function standaloneConnectOpts(auth){if(auth?.tls===void 0)throw new Error("standaloneConnectOpts requires an explicit `tls` boolean: pass `tls: true` to REQUIRE TLS, or `tls: false` for a plaintext broker. It has no default, because defaulting it would silently connect without the requirement that protects the credentials being passed.");const tlsOpt=auth.tls?{tls:{}}:{};if(auth.bearer!==void 0){if(!auth.sentinelCreds)throw new Error("user-mode standalone connect requires sentinelCreds alongside the bearer");if(auth.creds)throw new Error("standalone connect takes creds OR bearer+sentinelCreds, never both");const nonce4=`ibx${randomUUID3().replace(/-/g,"")}`;return{name:nonce4,inboxPrefix:`_INBOX_${nonce4}`,authenticator:[nativeCredsAuthenticator(auth.sentinelCreds),(0,import_transport_node9.tokenAuthenticator)(auth.bearer)],...tlsOpt}}const creds=auth.creds;if(!creds)return{...tlsOpt};return{authenticator:nativeCredsAuthenticator(creds),inboxPrefix:`_INBOX_${idFromCreds(typeof creds==="function"?creds():creds)}`,...tlsOpt}}function spaceMessageStreamConfigs(space2){return[...[chatStream(space2),dmStream(space2),taskStream(space2),inboxStream(space2),dlvStream(space2)].map(stream=>canonicalBackupStreamConfig(space2,stream)),{...canonicalBackupStreamConfig(space2,chatStream(space2)),name:eventPayloadStream(space2),subjects:[`${spacePrefix(space2)}.evp.>`]}]}function anycastStoreDefinition(space2){return{bucket:anycastBucket(space2),createOptions:{history:1,max_bytes:-1,maxValueSize:ANYCAST_RECORD_MAX_VALUE_SIZE}}}async function createSpaceStreams(jsm,space2){for(const definition of spaceMessageStreamConfigs(space2)){if(historyLimitStreamOf(space2,definition.name)||definition.name===eventPayloadStream(space2)){try{await jsm.streams.info(definition.name);continue}catch(e3){if(!isStreamNotFound(e3))throw e3}}await jsm.streams.add(definition)}}function dmDurableConfig(space2,owner2,actor2,lifecycleUid,opts={}){const frontier=opts.activationFrontier??0;if(!Number.isInteger(frontier)||frontier<0)throw new Error(`dmDurableConfig activationFrontier must be a non-negative integer, got ${String(frontier)}`);const cfg={durable_name:dmDurable(owner2,actor2,lifecycleUid),filter_subject:unicastRecvFilter(space2,owner2,actor2),ack_policy:import_jetstream11.AckPolicy.Explicit,ack_wait:(0,import_transport_node9.nanos)(opts.ackWaitMs??6e4),...frontier>0?{deliver_policy:import_jetstream11.DeliverPolicy.StartSequence,opt_start_seq:frontier+1}:{deliver_policy:import_jetstream11.DeliverPolicy.All}};if(opts.inactiveThresholdMs)cfg.inactive_threshold=(0,import_transport_node9.nanos)(opts.inactiveThresholdMs);return cfg}function taskDurableConfig(space2,role,opts={}){return{durable_name:taskDurable(role),filter_subject:anycastServeFilter(space2,role),ack_policy:import_jetstream11.AckPolicy.Explicit,ack_wait:(0,import_transport_node9.nanos)(opts.ackWaitMs??6e4)}}function inboxReaderConfig(space2,opts={}){return{durable_name:readerDurable(opts.shard,opts.shards),filter_subject:`${spacePrefix(space2)}.dinbox.>`,ack_policy:import_jetstream11.AckPolicy.Explicit,ack_wait:(0,import_transport_node9.nanos)(opts.ackWaitMs??6e4),deliver_policy:import_jetstream11.DeliverPolicy.All,max_ack_pending:DINBOX_MAX_ACK_PENDING}}function dlvDurableConfig(space2,owner2,actor2,lifecycleUid,opts={}){const cfg={durable_name:dlvDurable(owner2,actor2,lifecycleUid),filter_subject:dlvSubject(space2,owner2,actor2,lifecycleUid),ack_policy:import_jetstream11.AckPolicy.Explicit,ack_wait:(0,import_transport_node9.nanos)(opts.ackWaitMs??6e4),deliver_policy:import_jetstream11.DeliverPolicy.All};if(opts.inactiveThresholdMs)cfg.inactive_threshold=(0,import_transport_node9.nanos)(opts.inactiveThresholdMs);return cfg}function fanoutDurableConfig(space2,opts={}){return{durable_name:fanoutDurable(opts.shard,opts.shards),filter_subject:chatWildcard(space2),ack_policy:import_jetstream11.AckPolicy.Explicit,ack_wait:(0,import_transport_node9.nanos)(opts.ackWaitMs??6e4),deliver_policy:import_jetstream11.DeliverPolicy.New}}var import_jetstream11,import_transport_node9,import_kv4,import_obj,PRESENCE_STORAGE,MEMBERSHIP_STORAGE,DINBOX_MAX_ACK_PENDING,MANAGER_LEASE_TTL_MS,MANAGER_LEASE_RENEW_MS,MANAGER_LEASE_ATTEMPT_MS,LEGACY_MEMBERSHIP_MAX_BYTES,MEMBERSHIP_MAX_VALUE_SIZE,ANYCAST_RECORD_MAX_VALUE_SIZE,LEGACY_ARTIFACT_STORE_MAX_BYTES,TTL_RECONCILE_CANARY_KEY;var init_streams=__esm({"../../packages/core/dist/streams.js"(){"use strict";init_connection_cleanup();init_event_payloads();import_jetstream11=__toESM(require_mod4(),1);import_transport_node9=__toESM(require_transport_node(),1);init_endpoint();import_kv4=__toESM(require_mod6(),1);import_obj=__toESM(require_mod7(),1);init_subjects();init_identity();init_creds_authenticator();init_broker_floor();init_jetstream_missing();init_endpoint_records();init_endpoint_binding();init_acls();init_members();init_backup_config();PRESENCE_STORAGE=import_jetstream11.StorageType.Memory;MEMBERSHIP_STORAGE=import_jetstream11.StorageType.Memory;DINBOX_MAX_ACK_PENDING=1e3;MANAGER_LEASE_TTL_MS=1e4;MANAGER_LEASE_RENEW_MS=MANAGER_LEASE_TTL_MS/4;MANAGER_LEASE_ATTEMPT_MS=2e3;LEGACY_MEMBERSHIP_MAX_BYTES=64*1024*1024;MEMBERSHIP_MAX_VALUE_SIZE=256*1024;ANYCAST_RECORD_MAX_VALUE_SIZE=64*1024;LEGACY_ARTIFACT_STORE_MAX_BYTES=4*1024*1024*1024;TTL_RECONCILE_CANARY_KEY="_cotal_ttl_reconcile"}});function sameChannelModes(a3,b3){const ak=a3?Object.keys(a3):[];const bk=b3?Object.keys(b3):[];if(ak.length!==bk.length)return false;return ak.every(k2=>a3[k2]===b3?.[k2])}function sameRuntime(a3,b3){return a3?.id===b3?.id&&a3?.startedAt===b3?.startedAt&&a3?.source===b3?.source}function sameCondition(a3,b3){return a3?.code===b3?.code&&a3?.source===b3?.source&&a3?.message===b3?.message&&a3?.since===b3?.since}var import_transport_node10,PresenceWriteStuckError,EndpointPresence;var init_endpoint_presence=__esm({"../../packages/core/dist/endpoint-presence.js"(){"use strict";import_transport_node10=__toESM(require_transport_node(),1);init_process_runtime();init_kv_scan();init_streams();init_subjects();init_subjects();PresenceWriteStuckError=class extends Error{bucket;since;consecutiveFailures;ttlMs;lastError;code="presence-write-stuck";transient=false;constructor(bucket,since,consecutiveFailures,ttlMs,lastError){super(`presence writes to bucket ${JSON.stringify(bucket)} have failed ${consecutiveFailures} consecutive times for at least one TTL (${ttlMs}ms); the presence view is not live until a write succeeds or the broker store is repaired${lastError?` (last refusal: ${lastError})`:""}`);this.bucket=bucket;this.since=since;this.consecutiveFailures=consecutiveFailures;this.ttlMs=ttlMs;this.lastError=lastError;this.name="PresenceWriteStuckError"}};EndpointPresence=class{deps;presenceWriteFailingSince;lastPresenceWriteError;presenceWriteFailures=0;presenceWriteEscalated=false;presencePutGeneration=0;presencePutSettled;roster=new Map;presenceRead;presenceReadGeneration=0;presenceReadApplied=0;presenceSnapshot=Promise.resolve();presenceSnapshotPopulated=false;lastPresenceWatchAt=0;presenceViewState="unpopulated";presenceRebind;presenceWatchEmpty=false;presenceRebindAt=0;status="idle";activity;statusSince=Date.now();activitySince;activeAt;condition;conditionRevision=0;environment;attentionMode;channelModes;presenceBindingDrops=0;presenceWatchIter;constructor(deps){this.deps=deps}get card(){return this.deps.card()}get space(){return this.deps.space()}get kv(){return this.deps.bucket()}get nc(){return this.deps.connection()}get ownLifecycleUid(){return this.deps.lifecycleUid()}get ttlMs(){return this.deps.ttlMs()}get doRegister(){return this.deps.registers()}get doWatch(){return this.deps.watches()}get readOnce(){return this.deps.readsOnce()}get stopped(){return this.deps.stopped()}get reconnecting(){return this.deps.reconnecting()}get presenceEpoch(){return this.deps.epoch()}notLiveMsg(){return this.deps.notLiveMsg()}bindKvWatch(kv){return this.deps.bindWatch(kv)}retireKvWatch(iter){this.deps.retireWatch(iter)}emit(event,value){return this.deps.emit(event,value)}emitRecoverable(error51){this.deps.recoverable(error51)}configureEnvironment(environment){this.environment=environment}seedChannelModes(modes){this.channelModes=modes&&Object.keys(modes).length?modes:void 0}get bindingDropCount(){return this.presenceBindingDrops}values(){return this.roster.values()}cancelRebind(){this.presenceRebind=void 0}retireWatch(){if(this.presenceWatchIter)this.retireKvWatch(this.presenceWatchIter);this.presenceWatchIter=void 0}async publishOffline(){this.status="offline";await this.publishPresence()}resetConnection(){this.roster.clear();this.presenceRead=void 0;this.presenceReadGeneration++;this.presenceReadApplied=this.presenceReadGeneration;this.clearPresenceWriteFailure();this.lastPresenceWatchAt=0;this.presenceRebindAt=0;this.presenceWatchEmpty=false;this.presenceSnapshotPopulated=false;this.emitPresenceViewIfChanged()}getRoster(){return[...this.roster.values()].sort((a3,b3)=>a3.card.name.localeCompare(b3.card.name))}async readPresence(){if(this.doWatch&&!this.readOnce)throw new Error("readPresence is for an endpoint that does not watch presence; this one keeps its roster live (getRoster)");const kv=this.kv;if(!kv)throw new Error(this.nc?"readPresence needs the presence bucket open (registerPresence or watchPresence)":this.notLiveMsg());if(this.presenceRead)return this.presenceRead;const generation=++this.presenceReadGeneration;const roster=(async()=>{let entries;try{entries=await lastKvEntries(kv)}catch(e3){if(!this.deps.isPublishPermissionDenied(e3))throw e3;throw new Error(`presence read refused for ${this.card.id}: this credential may not publish $JS.API.DIRECT.GET.KV_${presenceBucket(this.space)}, the on-demand roster read (SPEC Appendix B). A credential minted by an older issuer can lack this grant even when newly minted; upgrade the manager or auth service that issues credentials, then mint a new credential. Reusing credentials or reconnecting does not add the grant.`,{cause:e3})}const at2=Date.now();const read=new Map;for(const e3 of entries){if(e3.key===TTL_RECONCILE_CANARY_KEY||e3.operation==="DEL"||e3.operation==="PURGE")continue;const p2=this.decodePresence(e3);if(p2)read.set(e3.key,p2.status==="offline"||at2-p2.ts>this.ttlMs?this.toOffline(p2):p2)}if(generation>this.presenceReadApplied){this.presenceReadApplied=generation;for(const[id2,p2]of this.roster)if(!read.has(id2))read.set(id2,p2.status==="offline"?p2:this.toOffline(p2));this.roster.clear();for(const[id2,p2]of read)this.roster.set(id2,p2)}return this.getRoster()})();this.presenceRead=roster;const settled=()=>{if(this.presenceRead===roster)this.presenceRead=void 0};roster.then(settled,settled);return roster}presenceView(){if(!this.doWatch)return{state:"current",fresh:true};if(!this.presenceSnapshotPopulated)return{state:"unpopulated",fresh:false};if(this.presenceWatchEmpty)return{state:"current",fresh:true};const staleSince=this.lastPresenceWatchAt+this.ttlMs;if(Date.now()<staleSince)return{state:"current",fresh:true};return{state:"stale",fresh:false,staleSince}}async waitForPresenceSnapshot(timeoutMs=1e3){let timer2;try{return await Promise.race([this.presenceSnapshot.then(()=>"snapshot"),new Promise(resolve6=>{timer2=setTimeout(()=>resolve6("timeout"),timeoutMs)})])}finally{if(timer2)clearTimeout(timer2)}}assertPresenceUpdate(update){assertPresenceRow({card:this.card,status:this.status,activity:this.activity,condition:this.condition,attention:this.attentionMode,ts:Date.now(),...update},this.card.id)}async setActivity(activity){this.assertPresenceUpdate({activity});if(activity!==this.activity)this.statusSince=this.activitySince=Date.now();this.activity=activity;await this.publishPresence()}async setStatus(status2,activity){this.assertPresenceUpdate({status:status2,...activity===void 0?{}:{activity}});if(activity!==void 0&&activity!==this.activity)this.statusSince=this.activitySince=Date.now();if(activity!==void 0)this.activity=activity;if(status2!==this.status)this.statusSince=Date.now();this.status=status2;await this.publishPresence()}noteActivity(at2=Date.now()){if(Number.isFinite(at2)&&at2>(this.activeAt??0))this.activeAt=at2}async setCondition(condition){this.assertPresenceUpdate({condition:condition??void 0});this.condition=condition??void 0;this.conditionRevision++;await this.publishPresence()}async setAttention(attention){this.assertPresenceUpdate({attention});this.attentionMode=attention;await this.publishPresence()}async setChannelModes(modes){this.channelModes=Object.keys(modes).length?modes:void 0;await this.publishPresence()}async setCardModel(model,variant,provider){const m2=model.trim();const v3=variant?.trim();const p2=provider?.trim();if(!m2||this.card.meta?.model===m2&&this.card.meta.variant===v3&&(p2===void 0||this.card.meta?.provider===p2))return;const meta3={...this.card.meta??{},model:m2};if(v3)meta3.variant=v3;else delete meta3.variant;if(p2)meta3.provider=p2;this.card.meta=meta3;await this.publishPresence()}async setCardCwd(cwd){if(!cwd||this.card.meta?.cwd===cwd)return;this.card.meta={...this.card.meta??{},cwd};await this.publishPresence()}async publishPresence(){if(!this.doRegister||!this.kv)return;const p2={card:this.card,...this.ownLifecycleUid!==void 0?{lifecycleUid:this.ownLifecycleUid}:{},runtime:processRuntime(this.ownLifecycleUid),status:this.status,condition:this.condition,environment:this.environment,activity:this.activity,statusSince:this.statusSince,activitySince:this.activitySince,activeAt:this.activeAt,attention:this.attentionMode,channelModes:this.channelModes,prompts:this.deps.prompts(),ts:Date.now()};const record2=this.status==="offline"?this.toOffline(p2):p2;assertPresenceRow(record2,this.card.id);const epoch=this.presenceEpoch;const conditionRevision=this.conditionRevision;const generation=++this.presencePutGeneration;try{await this.kv.put(this.card.id,JSON.stringify(record2))}catch(e3){const superseded2=(this.presencePutSettled??0)>generation;this.presencePutSettled=Math.max(this.presencePutSettled??0,generation);if(epoch===this.presenceEpoch&&!this.stopped&&!superseded2){this.presenceWriteFailingSince??=Date.now();this.lastPresenceWriteError=e3?.message??String(e3);this.presenceWriteFailures++;this.escalatePresenceWriteFailureIfStuck()}if(e3 instanceof import_transport_node10.TimeoutError)throw new Error(`${e3.message}. The presence write outcome is unknown: the broker may have stored the update. Read the roster before retrying.`,{cause:e3});throw e3}const superseded=(this.presencePutSettled??0)>generation;this.presencePutSettled=Math.max(this.presencePutSettled??0,generation);if(epoch!==this.presenceEpoch||this.stopped||superseded)return;if(conditionRevision!==this.conditionRevision){await this.publishPresence();return}this.clearPresenceWriteFailure()}clearPresenceWriteFailure(){this.presenceWriteFailingSince=void 0;this.lastPresenceWriteError=void 0;this.presenceWriteFailures=0;this.presenceWriteEscalated=false}escalatePresenceWriteFailureIfStuck(){if(this.presenceWriteEscalated||this.presenceWriteFailingSince===void 0||this.presenceWriteFailures<2||Date.now()-this.presenceWriteFailingSince<this.ttlMs)return;this.presenceWriteEscalated=true;this.emitRecoverable(new PresenceWriteStuckError(presenceBucket(this.space),this.presenceWriteFailingSince,this.presenceWriteFailures,this.ttlMs,this.lastPresenceWriteError))}presenceWriteFailure(){if(this.presenceWriteFailingSince===void 0)return void 0;return{since:this.presenceWriteFailingSince,forMs:Date.now()-this.presenceWriteFailingSince,error:this.lastPresenceWriteError,bucket:presenceBucket(this.space),consecutiveFailures:this.presenceWriteFailures,stuck:this.presenceWriteEscalated}}async startPresenceWatch(){if(!this.kv)return void 0;let hydrated;this.presenceSnapshot=new Promise(resolve6=>{hydrated=resolve6});const bound=await this.bindKvWatch(this.kv);if(!bound){hydrated();return void 0}const{iter,info}=bound;this.presenceWatchIter=iter;const empty=info.num_pending===0&&!this.doRegister;if(empty){this.presenceSnapshotPopulated=true;hydrated();this.markPresenceBucketEmpty()}void(async()=>{let ready=empty;for await(const e3 of iter){if(this.presenceWatchIter!==iter)break;this.handleKvEntry(e3);if(!ready&&e3.isUpdate){ready=true;this.presenceSnapshotPopulated=true;hydrated();this.emitPresenceViewIfChanged()}}hydrated()})().catch(e3=>this.emit("error",e3));return info}async readPresenceOnce(){if(!this.kv)return;for(const e3 of await lastKvEntries(this.kv))this.handleKvEntry(e3);this.presenceSnapshotPopulated=true;if(this.lastPresenceWatchAt===0)this.markPresenceBucketEmpty();else this.emitPresenceViewIfChanged()}rebindStalePresenceWatch(now){if(this.stopped||this.reconnecting||!this.kv||!this.nc||this.nc.isClosed())return;if(this.presenceRebind||now-this.presenceRebindAt<this.ttlMs)return;this.presenceRebindAt=now;const old=this.presenceWatchIter;const epoch=this.presenceEpoch;this.presenceRebind=(async()=>{try{const silentMs=now-this.lastPresenceWatchAt;const info=await this.startPresenceWatch();if(!info)return;if(old&&old!==this.presenceWatchIter)this.retireKvWatch(old);if(info.num_pending===0)await this.onPresenceBucketEmpty();this.emit("warning",new Error(`presence watch silent for ${silentMs}ms with the connection up; rebound it from the bucket's current state`))}catch(e3){if(epoch===this.presenceEpoch)this.emit("error",e3)}finally{if(epoch===this.presenceEpoch)this.presenceRebind=void 0}})()}async onPresenceBucketEmpty(){if(this.doRegister){await this.publishPresence();return}this.markPresenceBucketEmpty()}markPresenceBucketEmpty(){this.presenceWatchEmpty=true;this.lastPresenceWatchAt=0;let changed=false;for(const[id2,p2]of this.roster){if(p2.status==="offline")continue;const offline=this.toOffline(p2);this.roster.set(id2,offline);this.emit("presence",{type:"offline",presence:offline});changed=true}if(changed)this.emit("roster",this.getRoster());this.emitPresenceViewIfChanged()}handleKvEntry(e3){if(e3.key===TTL_RECONCILE_CANARY_KEY)return;this.lastPresenceWatchAt=Date.now();this.presenceWatchEmpty=false;if(e3.operation==="DEL"||e3.operation==="PURGE"){this.markOffline(e3.key);return}const p2=this.decodePresence(e3);if(p2)this.applyPresence(e3.key,p2)}decodePresence(e3){let p2;try{p2=e3.json()}catch{return void 0}if(!isPresenceRow(p2,e3.key)){this.presenceBindingDrops++;this.emitRecoverable(new Error(`dropped presence entry for key ${JSON.stringify(e3.key)}: not a usable presence row (a record with card.id equal to its KV key, a non-blank string card.name, a known status, a finite ts, string display fields and a condition with a string code)`));return void 0}return p2}applyPresence(id2,raw){const prev=this.roster.get(id2);const stale=Date.now()-raw.ts>this.ttlMs;if(stale&&raw.status!=="offline"){if(prev)return;this.roster.set(id2,this.toOffline(raw));this.emit("roster",this.getRoster());return}if(this.presenceSnapshotPopulated)this.emitPresenceViewIfChanged();const p2=stale||raw.status==="offline"?this.toOffline(raw):raw;if(!prev&&p2.status==="offline"){this.roster.set(id2,p2);this.emit("roster",this.getRoster());return}if(prev&&prev.status!=="offline"&&p2.status!=="offline"&&prev.lifecycleUid===p2.lifecycleUid&&sameRuntime(prev.runtime,p2.runtime)&&prev.status===p2.status&&prev.activity===p2.activity&&sameCondition(prev.condition,p2.condition)&&prev.environment===p2.environment&&prev.attention===p2.attention&&sameChannelModes(prev.channelModes,p2.channelModes)&&prev.prompts?.open===p2.prompts?.open&&prev.prompts?.seq===p2.prompts?.seq){this.roster.set(id2,p2);return}this.roster.set(id2,p2);const type=p2.status==="offline"?"offline":!prev||prev.status==="offline"?"join":"update";this.emit("presence",{type,presence:p2});this.emit("roster",this.getRoster())}toOffline(p2){return{...p2,status:"offline",statusSince:void 0,attention:void 0,channelModes:void 0,prompts:void 0}}markOffline(id2){const prev=this.roster.get(id2);if(!prev||prev.status==="offline")return;const offline=this.toOffline(prev);this.roster.set(id2,offline);this.emit("presence",{type:"offline",presence:offline});this.emit("roster",this.getRoster())}emitPresenceViewIfChanged(){const view=this.presenceView();if(view.state===this.presenceViewState)return;this.presenceViewState=view.state;this.emit("presence-view",view)}sweep(){const now=Date.now();if(this.lastPresenceWatchAt!==0&&now-this.lastPresenceWatchAt>this.ttlMs){this.emitPresenceViewIfChanged();this.rebindStalePresenceWatch(now);return}let changed=false;for(const[id2,p2]of this.roster){if(p2.status!=="offline"&&now-p2.ts>this.ttlMs&&this.lastPresenceWatchAt-p2.ts>this.ttlMs){const offline=this.toOffline(p2);this.roster.set(id2,offline);this.emit("presence",{type:"offline",presence:offline});changed=true}}if(changed)this.emit("roster",this.getRoster())}}}});function parseSecretStoreIdentity(raw){if(raw===null||typeof raw!=="object"||Array.isArray(raw))throw new Error("secret-store identity must be an object");const o3=raw;const keys=Object.keys(o3);if(o3.kind==="fs"){if(keys.some(k2=>k2!=="kind"&&k2!=="root"&&k2!=="id"))throw new Error("secret-store identity of kind fs admits only {kind, root, id}");if(typeof o3.root!=="string"||!o3.root.trim())throw new Error("secret-store identity of kind fs requires a non-blank root");if(typeof o3.id!=="string"||!o3.id.trim())throw new Error("secret-store identity of kind fs requires a non-blank id");return{kind:"fs",root:o3.root,id:o3.id}}if(o3.kind==="injected"){if(keys.some(k2=>k2!=="kind"&&k2!=="coordinate"))throw new Error("secret-store identity of kind injected admits only {kind, coordinate}");if(typeof o3.coordinate!=="string"||!o3.coordinate.trim())throw new Error("secret-store identity of kind injected requires a non-blank coordinate");return{kind:"injected",coordinate:o3.coordinate}}throw new Error('secret-store identity kind must be "fs" or "injected"')}var init_secret_store=__esm({"../../packages/core/dist/secret-store.js"(){"use strict"}});var mintGuardClearance;var init_endpoint_guard=__esm({"../../packages/core/dist/endpoint-guard.js"(){"use strict";init_endpoint_envelope();init_deadline();init_canonical();init_endpoint_signing();init_endpoint_checkpoint();init_endpoint_action();mintGuardClearance=claimGuardClearanceMint()}});var TRAIT_SELECTORS;var init_endpoint_traits=__esm({"../../packages/core/dist/endpoint-traits.js"(){"use strict";init_canonical();init_endpoint_envelope();init_deadline();init_schema_profile();init_endpoint_cluster();init_endpoint_guard();init_endpoint_service();init_endpoint_signing();TRAIT_SELECTORS=Object.freeze(["cluster","command","attribute","event"])}});var init_endpoint_describe_observation=__esm({"../../packages/core/dist/endpoint-describe-observation.js"(){"use strict";init_canonical();init_subjects();init_endpoint_subjects();init_endpoint_envelope();init_schema_profile()}});function bindContract(env,def){if(def.digests===void 0){if(env.op.inputDigest!==void 0||env.op.outputDigest!==void 0)throw new EpEnvelopeError("contract-mismatch","describe pins no contract; a digest carried on it cannot be honored (SPEC 13.7)");return}if(env.op.inputDigest!==def.digests.input||env.op.outputDigest!==def.digests.output)throw new EpEnvelopeError("contract-mismatch",`pinned digests ${env.op.inputDigest}/${env.op.outputDigest} do not match the served contract ${def.digests.input}/${def.digests.output}; a member that cannot honor a pinned digest rejects, never coerces (SPEC 13.7)`)}function successReply(id2,data){return{v:1,id:id2,ok:true,...data!==void 0?{data}:{}}}function encodeReply(reply){return enc4.encode(JSON.stringify(reply))}async function runRequest(nc,steps,pick2,msg){const receivedAtMonotonicMs=performance.now();const parsed=steps.parse(msg.subject);if(!parsed)return;let env;let dispatched=false;let returned=false;let reply;try{const original=JSON.parse(dec4.decode(msg.data));env=parseEndpointRequest(original);checkRequestSubjectAgreement(env,parsed);steps.addressed(env,parsed);const def=pick2(parsed);if(def===void 0)throw new EpEnvelopeError("unimplemented",`command "${parsed.command}" is not served here`);assertClassMatches(env,def.class);bindContract(env,def);steps.admit(parsed,def);assertArgsValid(def.validate.args,env.args);const obligations=await steps.beforeEffect(env,parsed,def);const requestId=env.id;const ctx=steps.context({parsed,env,def,subject:msg.subject,original,receivedAtMonotonicMs,obligations,replyFits:(data2,ceiling)=>{const maxPayload=nc.info?.max_payload;if(!Number.isSafeInteger(maxPayload)||maxPayload===void 0||maxPayload<=0)throw new EpEnvelopeError("unavailable","the serving connection has no valid payload ceiling");if(!Number.isSafeInteger(ceiling)||ceiling<=0)throw new EpEnvelopeError("failed-precondition","reply byte ceiling must be a positive safe integer");return encodeReply(successReply(requestId,data2)).byteLength<=Math.min(ceiling,maxPayload)}});dispatched=true;if(!env.replyExpected){await def.handler(ctx);return}const data=await def.handler(ctx);returned=true;assertOutputValid(def.validate.output,data);reply=successReply(env.id,data)}catch(err3){if(env&&!env.replyExpected)return;const error51=err3 instanceof EpEnvelopeError?err3.toEpError():{code:"internal",message:err3?.message??String(err3)};const stated=!dispatched?"not-executed":returned?"executed":void 0;reply={v:1,id:env?.id??"invalid",ok:false,error:stated===void 0?error51:{...error51,outcome:stated}}}const outcome=reply.ok?"executed":reply.error?.outcome;let bytes;try{bytes=encodeReply(reply)}catch(err3){const fallback={v:1,id:reply.id,ok:false,error:{code:"internal",message:`the reply does not serialize: ${err3.message}`,...outcome!==void 0?{outcome}:{}}};bytes=enc4.encode(JSON.stringify(fallback))}if(steps.mayReply?.()===false)return;const replySubject=steps.replySubject(parsed);try{nc.publish(replySubject,bytes)}catch(err3){const refused3={v:1,id:reply.id,ok:false,error:{code:"resource-exhausted",message:`the serialized reply is ${bytes.length} bytes and the broker refused it (${err3?.message??String(err3)}); a reply that cannot be published is refused loudly, never dropped`,...outcome!==void 0?{outcome}:{}}};nc.publish(replySubject,enc4.encode(JSON.stringify(refused3)))}}function servePrincipalRoute(nc,space2,self2,serve){const filter=epPrincipalServeFilter(space2,serve.endpoint,self2);const cluster=parseClusterDocument(serve.cluster);const declared=new Map(cluster.commands.map(c3=>[c3.name,c3]));for(const c3 of cluster.commands){if(c3.authorities===void 0)throw new Error(`command "${c3.name}" declares no authorities; a command is served on the principal route only when it lists the words it admits (SPEC 13.21)`);if(c3.class!=="ephemeral")throw new Error(`command "${c3.name}" is class "${c3.class}"; the principal route serves ephemeral commands only (SPEC 13.21)`);const governed=(c3.traits??[]).filter(t2=>GOVERNED_TRAIT_URNS.includes(t2));if(governed.length>0)throw new Error(`command "${c3.name}" declares governed trait(s) ${governed.join(", ")}; the principal route has no governed gate, and a governed command is never served unenforced (SPEC 13.7)`)}const defs=[];for(const def of serve.handlers){assertCommandToken(def.command);if(def.command==="describe")throw new Error("describe is reserved and built from the cluster; a custom describe def is refused (SPEC 13.21)");if(defs.some(d2=>d2.command===def.command))throw new Error(`command "${def.command}" is served twice`);const decl=declared.get(def.command);if(decl===void 0)throw new Error(`command "${def.command}" is not in the cluster; the served table is exactly the cluster's commands (SPEC 13.21)`);const input=assertCompiledContract(def.contract?.input,`command "${def.command}" input contract`);const output=assertCompiledContract(def.contract?.output,`command "${def.command}" output contract`);if(input.closureDigest!==decl.inputDigest||output.closureDigest!==decl.outputDigest)throw new Error(`command "${def.command}" compiled contracts ${input.closureDigest}/${output.closureDigest} do not equal the declared ${decl.inputDigest}/${decl.outputDigest} (SPEC 13.7)`);defs.push({command:def.command,class:"ephemeral",digests:{input:decl.inputDigest,output:decl.outputDigest},validate:{args:input.validate,output:output.validate},authorities:new Set(decl.authorities),handler:def.handler})}for(const c3 of cluster.commands)if(!defs.some(d2=>d2.command===c3.name))throw new Error(`command "${c3.name}" has no def; a declared command nobody serves is a construction bug (SPEC 13.21)`);const answer=deepFreeze2({public:true,descriptor:{endpoint:serve.endpoint,owner:self2.owner,protocol:{v:1},clusters:[{digest:singleDocumentClosure(serve.cluster).closureDigest,commands:cluster.commands.map(c3=>c3.name),document:structuredClone(serve.cluster)}]}});defs.push({command:"describe",class:"ephemeral",validate:describeValidators(),authorities:new Set(EP_PRINCIPAL_AUTHORITIES),handler:()=>answer});const byCommand=new Map(defs.map(d2=>[d2.command,d2]));const steps={parse:subject=>{const parsed=parseEpSubject(subject);if(!parsed||parsed.plane!=="principal-request")return null;const h3=parsed.principal;if(parsed.endpoint!==serve.endpoint||h3.owner!==self2.owner||h3.actor!==self2.actor||h3.uid!==self2.uid||h3.runtimeId!==self2.runtimeId)return null;return parsed},addressed:()=>{},admit:(parsed,def)=>{if(!isPrincipalAuthority(parsed.authority)||!def.authorities.has(parsed.authority))throw new EpEnvelopeError("permission-denied",`command "${def.command}" does not admit the "${parsed.authority}" authority; a command serves only the words its declaration lists (SPEC 13.21)`)},beforeEffect:async()=>void 0,context:({parsed,env,receivedAtMonotonicMs,replyFits})=>({endpoint:serve.endpoint,principal:self2,caller:parsed.caller,authority:parsed.authority,request:env,receivedAtMonotonicMs,replyFits,signal:stopping.signal}),replySubject:parsed=>derivePrincipalReplySubject(space2,parsed,self2),mayReply:()=>!lateRepliesDropped};const stopping=new AbortController;let lateRepliesDropped=false;const pending=new Map;let refusal;let markRefused;const refused3=new Promise(resolve6=>{markRefused=resolve6});const sub=nc.subscribe(filter,{callback:(err3,msg)=>{if(err3){if(refusal===void 0){refusal=new EpEnvelopeError("permission-denied",`the broker refused this process's subscription to its principal-route subject "${filter}": ${err3.message}. The credential holds no serve row for it, which a credential minted before the rows existed does not; reconnect after the auth service runs a release that mints them (SPEC 13.21)`);markRefused(refusal)}return}if(carriesStoredProvenance(msg))return;const entry={};const timed={...steps,context:a3=>{entry.endsAt=a3.receivedAtMonotonicMs+a3.env.deadlineMs;return steps.context(a3)}};const run=runRequest(nc,timed,parsed=>byCommand.get(parsed.command),msg).catch(()=>{});pending.set(run,entry);void run.finally(()=>pending.delete(run))}});const check2=async()=>{await nc.flush();if(refusal!==void 0)throw refusal};const ready=check2();ready.catch(()=>{});return{filter,ready,refused:refused3,check:check2,async stop(){stopping.abort(new Error(`stopped serving "${serve.endpoint}" on the principal route`));const gone=nc.closed().then(()=>void 0);await Promise.race([sub.drain().catch(()=>void 0),gone]);await Promise.allSettled([...pending].map(([run,{endsAt}])=>endsAt===void 0?run:withinMs(run,endsAt-performance.now())));lateRepliesDropped=true}}}async function withinMs(p2,ms){if(ms<=0)return;let timer2;try{await Promise.race([p2,new Promise(resolve6=>{timer2=setTimeout(resolve6,ms)})])}finally{clearTimeout(timer2)}}function deepFreeze2(v3){if(v3!==null&&typeof v3==="object"){for(const child of Object.values(v3))deepFreeze2(child);Object.freeze(v3)}return v3}function describeValidators(){const c3=describeContracts();return{args:c3.input.validate,output:c3.output.validate}}function describeContracts(){describeCompiled??=Object.freeze({input:compileContract({root:VOID_SCHEMA}),output:compileContract({root:DESCRIBE_ANSWER_SCHEMA})});return describeCompiled}var enc4,dec4,DESCRIBE_ANSWER_SCHEMA,describeCompiled;var init_endpoint_serve=__esm({"../../packages/core/dist/endpoint-serve.js"(){"use strict";init_subjects();init_endpoint_subjects();init_endpoint_envelope();init_schema_profile();init_endpoint_service();init_endpoint_cluster();init_endpoint_traits();init_endpoint_describe_observation();init_endpoint_provenance();enc4=new TextEncoder;dec4=new TextDecoder;DESCRIBE_ANSWER_SCHEMA={type:"object",required:["public","descriptor"],additionalProperties:false,properties:{public:{type:"boolean"},descriptor:{type:"object",required:["endpoint","owner","protocol","clusters"],properties:{endpoint:{type:"string",minLength:1},owner:{type:"string",minLength:1},endpointType:{type:"string"},protocol:{type:"object",required:["v"],properties:{v:{const:1}}},clusters:{type:"array",items:{type:"object",required:["digest","commands"],properties:{digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"},commands:{type:"array",minItems:1,items:{type:"string",minLength:1}},document:{type:"object"}}}}}}}}}});var require_identity=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/identity.js"(exports){"use strict";var ALIAS=Symbol.for("yaml.alias");var DOC=Symbol.for("yaml.document");var MAP=Symbol.for("yaml.map");var PAIR=Symbol.for("yaml.pair");var SCALAR=Symbol.for("yaml.scalar");var SEQ=Symbol.for("yaml.seq");var NODE_TYPE=Symbol.for("yaml.node.type");var isAlias=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===ALIAS;var isDocument=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===DOC;var isMap=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===MAP;var isPair=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===PAIR;var isScalar=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===SCALAR;var isSeq=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===SEQ;function isCollection(node){if(node&&typeof node==="object")switch(node[NODE_TYPE]){case MAP:case SEQ:return true}return false}function isNode(node){if(node&&typeof node==="object")switch(node[NODE_TYPE]){case ALIAS:case MAP:case SCALAR:case SEQ:return true}return false}var hasAnchor=node=>(isScalar(node)||isCollection(node))&&!!node.anchor;exports.ALIAS=ALIAS;exports.DOC=DOC;exports.MAP=MAP;exports.NODE_TYPE=NODE_TYPE;exports.PAIR=PAIR;exports.SCALAR=SCALAR;exports.SEQ=SEQ;exports.hasAnchor=hasAnchor;exports.isAlias=isAlias;exports.isCollection=isCollection;exports.isDocument=isDocument;exports.isMap=isMap;exports.isNode=isNode;exports.isPair=isPair;exports.isScalar=isScalar;exports.isSeq=isSeq}});var require_visit=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/visit.js"(exports){"use strict";var identity=require_identity();var BREAK=Symbol("break visit");var SKIP=Symbol("skip children");var REMOVE=Symbol("remove node");function visit(node,visitor){const visitor_=initVisitor(visitor);if(identity.isDocument(node)){const cd=visit_(null,node.contents,visitor_,Object.freeze([node]));if(cd===REMOVE)node.contents=null}else visit_(null,node,visitor_,Object.freeze([]))}visit.BREAK=BREAK;visit.SKIP=SKIP;visit.REMOVE=REMOVE;function visit_(key,node,visitor,path4){const ctrl=callVisitor(key,node,visitor,path4);if(identity.isNode(ctrl)||identity.isPair(ctrl)){replaceNode(key,path4,ctrl);return visit_(key,ctrl,visitor,path4)}if(typeof ctrl!=="symbol"){if(identity.isCollection(node)){path4=Object.freeze(path4.concat(node));for(let i2=0;i2<node.items.length;++i2){const ci2=visit_(i2,node.items[i2],visitor,path4);if(typeof ci2==="number")i2=ci2-1;else if(ci2===BREAK)return BREAK;else if(ci2===REMOVE){node.items.splice(i2,1);i2-=1}}}else if(identity.isPair(node)){path4=Object.freeze(path4.concat(node));const ck=visit_("key",node.key,visitor,path4);if(ck===BREAK)return BREAK;else if(ck===REMOVE)node.key=null;const cv=visit_("value",node.value,visitor,path4);if(cv===BREAK)return BREAK;else if(cv===REMOVE)node.value=null}}return ctrl}async function visitAsync(node,visitor){const visitor_=initVisitor(visitor);if(identity.isDocument(node)){const cd=await visitAsync_(null,node.contents,visitor_,Object.freeze([node]));if(cd===REMOVE)node.contents=null}else await visitAsync_(null,node,visitor_,Object.freeze([]))}visitAsync.BREAK=BREAK;visitAsync.SKIP=SKIP;visitAsync.REMOVE=REMOVE;async function visitAsync_(key,node,visitor,path4){const ctrl=await callVisitor(key,node,visitor,path4);if(identity.isNode(ctrl)||identity.isPair(ctrl)){replaceNode(key,path4,ctrl);return visitAsync_(key,ctrl,visitor,path4)}if(typeof ctrl!=="symbol"){if(identity.isCollection(node)){path4=Object.freeze(path4.concat(node));for(let i2=0;i2<node.items.length;++i2){const ci2=await visitAsync_(i2,node.items[i2],visitor,path4);if(typeof ci2==="number")i2=ci2-1;else if(ci2===BREAK)return BREAK;else if(ci2===REMOVE){node.items.splice(i2,1);i2-=1}}}else if(identity.isPair(node)){path4=Object.freeze(path4.concat(node));const ck=await visitAsync_("key",node.key,visitor,path4);if(ck===BREAK)return BREAK;else if(ck===REMOVE)node.key=null;const cv=await visitAsync_("value",node.value,visitor,path4);if(cv===BREAK)return BREAK;else if(cv===REMOVE)node.value=null}}return ctrl}function initVisitor(visitor){if(typeof visitor==="object"&&(visitor.Collection||visitor.Node||visitor.Value)){return Object.assign({Alias:visitor.Node,Map:visitor.Node,Scalar:visitor.Node,Seq:visitor.Node},visitor.Value&&{Map:visitor.Value,Scalar:visitor.Value,Seq:visitor.Value},visitor.Collection&&{Map:visitor.Collection,Seq:visitor.Collection},visitor)}return visitor}function callVisitor(key,node,visitor,path4){if(typeof visitor==="function")return visitor(key,node,path4);if(identity.isMap(node))return visitor.Map?.(key,node,path4);if(identity.isSeq(node))return visitor.Seq?.(key,node,path4);if(identity.isPair(node))return visitor.Pair?.(key,node,path4);if(identity.isScalar(node))return visitor.Scalar?.(key,node,path4);if(identity.isAlias(node))return visitor.Alias?.(key,node,path4);return void 0}function replaceNode(key,path4,node){const parent=path4[path4.length-1];if(identity.isCollection(parent)){parent.items[key]=node}else if(identity.isPair(parent)){if(key==="key")parent.key=node;else parent.value=node}else if(identity.isDocument(parent)){parent.contents=node}else{const pt2=identity.isAlias(parent)?"alias":"scalar";throw new Error(`Cannot replace node with ${pt2} parent`)}}exports.visit=visit;exports.visitAsync=visitAsync}});var require_directives=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/directives.js"(exports){"use strict";var identity=require_identity();var visit=require_visit();var escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"};var escapeTagName=tn2=>tn2.replace(/[!,[\]{}]/g,ch=>escapeChars[ch]);var Directives=class _Directives{constructor(yaml,tags){this.docStart=null;this.docEnd=false;this.yaml=Object.assign({},_Directives.defaultYaml,yaml);this.tags=Object.assign({},_Directives.defaultTags,tags)}clone(){const copy2=new _Directives(this.yaml,this.tags);copy2.docStart=this.docStart;return copy2}atDocument(){const res=new _Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=true;break;case"1.2":this.atNextDocument=false;this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.2"};this.tags=Object.assign({},_Directives.defaultTags);break}return res}add(line,onError){if(this.atNextDocument){this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.1"};this.tags=Object.assign({},_Directives.defaultTags);this.atNextDocument=false}const parts=line.trim().split(/[ \t]+/);const name2=parts.shift();switch(name2){case"%TAG":{if(parts.length!==2){onError(0,"%TAG directive should contain exactly two parts");if(parts.length<2)return false}const[handle,prefix]=parts;this.tags[handle]=prefix;return true}case"%YAML":{this.yaml.explicit=true;if(parts.length!==1){onError(0,"%YAML directive should contain exactly one part");return false}const[version2]=parts;if(version2==="1.1"||version2==="1.2"){this.yaml.version=version2;return true}else{const isValid=/^\d+\.\d+$/.test(version2);onError(6,`Unsupported YAML version ${version2}`,isValid);return false}}default:onError(0,`Unknown directive ${name2}`,true);return false}}tagName(source,onError){if(source==="!")return"!";if(source[0]!=="!"){onError(`Not a valid tag: ${source}`);return null}if(source[1]==="<"){const verbatim=source.slice(2,-1);if(verbatim==="!"||verbatim==="!!"){onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);return null}if(source[source.length-1]!==">")onError("Verbatim tags must end with a >");return verbatim}const[,handle,suffix]=source.match(/^(.*!)([^!]*)$/s);if(!suffix)onError(`The ${source} tag has no suffix`);const prefix=this.tags[handle];if(prefix){try{return prefix+decodeURIComponent(suffix)}catch(error51){onError(String(error51));return null}}if(handle==="!")return source;onError(`Could not resolve tag: ${source}`);return null}tagString(tag){for(const[handle,prefix]of Object.entries(this.tags)){if(tag.startsWith(prefix))return handle+escapeTagName(tag.substring(prefix.length))}return tag[0]==="!"?tag:`!<${tag}>`}toString(doc){const lines=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[];const tagEntries=Object.entries(this.tags);let tagNames;if(doc&&tagEntries.length>0&&identity.isNode(doc.contents)){const tags={};visit.visit(doc.contents,(_key,node)=>{if(identity.isNode(node)&&node.tag)tags[node.tag]=true});tagNames=Object.keys(tags)}else tagNames=[];for(const[handle,prefix]of tagEntries){if(handle==="!!"&&prefix==="tag:yaml.org,2002:")continue;if(!doc||tagNames.some(tn2=>tn2.startsWith(prefix)))lines.push(`%TAG ${handle} ${prefix}`)}return lines.join("\n")}};Directives.defaultYaml={explicit:false,version:"1.2"};Directives.defaultTags={"!!":"tag:yaml.org,2002:"};exports.Directives=Directives}});var require_anchors=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/anchors.js"(exports){"use strict";var identity=require_identity();var visit=require_visit();function anchorIsValid(anchor){if(/[\x00-\x19\s,[\]{}]/.test(anchor)){const sa2=JSON.stringify(anchor);const msg=`Anchor must not contain whitespace or control characters: ${sa2}`;throw new Error(msg)}return true}function anchorNames(root){const anchors=new Set;visit.visit(root,{Value(_key,node){if(node.anchor)anchors.add(node.anchor)}});return anchors}function findNewAnchor(prefix,exclude){for(let i2=1;true;++i2){const name2=`${prefix}${i2}`;if(!exclude.has(name2))return name2}}function createNodeAnchors(doc,prefix){const aliasObjects=[];const sourceObjects=new Map;let prevAnchors=null;return{onAnchor:source=>{aliasObjects.push(source);prevAnchors??(prevAnchors=anchorNames(doc));const anchor=findNewAnchor(prefix,prevAnchors);prevAnchors.add(anchor);return anchor},setAnchors:()=>{for(const source of aliasObjects){const ref=sourceObjects.get(source);if(typeof ref==="object"&&ref.anchor&&(identity.isScalar(ref.node)||identity.isCollection(ref.node))){ref.node.anchor=ref.anchor}else{const error51=new Error("Failed to resolve repeated object (this should not happen)");error51.source=source;throw error51}}},sourceObjects}}exports.anchorIsValid=anchorIsValid;exports.anchorNames=anchorNames;exports.createNodeAnchors=createNodeAnchors;exports.findNewAnchor=findNewAnchor}});var require_applyReviver=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/applyReviver.js"(exports){"use strict";function applyReviver(reviver,obj,key,val){if(val&&typeof val==="object"){if(Array.isArray(val)){for(let i2=0,len=val.length;i2<len;++i2){const v0=val[i2];const v1=applyReviver(reviver,val,String(i2),v0);if(v1===void 0)delete val[i2];else if(v1!==v0)val[i2]=v1}}else if(val instanceof Map){for(const k2 of Array.from(val.keys())){const v0=val.get(k2);const v1=applyReviver(reviver,val,k2,v0);if(v1===void 0)val.delete(k2);else if(v1!==v0)val.set(k2,v1)}}else if(val instanceof Set){for(const v0 of Array.from(val)){const v1=applyReviver(reviver,val,v0,v0);if(v1===void 0)val.delete(v0);else if(v1!==v0){val.delete(v0);val.add(v1)}}}else{for(const[k2,v0]of Object.entries(val)){const v1=applyReviver(reviver,val,k2,v0);if(v1===void 0)delete val[k2];else if(v1!==v0)val[k2]=v1}}}return reviver.call(obj,key,val)}exports.applyReviver=applyReviver}});var require_toJS=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/toJS.js"(exports){"use strict";var identity=require_identity();function toJS(value,arg,ctx){if(Array.isArray(value))return value.map((v3,i2)=>toJS(v3,String(i2),ctx));if(value&&typeof value.toJSON==="function"){if(!ctx||!identity.hasAnchor(value))return value.toJSON(arg,ctx);const data={aliasCount:0,count:1,res:void 0};ctx.anchors.set(value,data);ctx.onCreate=res2=>{data.res=res2;delete ctx.onCreate};const res=value.toJSON(arg,ctx);if(ctx.onCreate)ctx.onCreate(res);return res}if(typeof value==="bigint"&&!ctx?.keep)return Number(value);return value}exports.toJS=toJS}});var require_Node=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Node.js"(exports){"use strict";var applyReviver=require_applyReviver();var identity=require_identity();var toJS=require_toJS();var NodeBase=class{constructor(type){Object.defineProperty(this,identity.NODE_TYPE,{value:type})}clone(){const copy2=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)copy2.range=this.range.slice();return copy2}toJS(doc,{mapAsMap,maxAliasCount,onAnchor,reviver}={}){if(!identity.isDocument(doc))throw new TypeError("A document argument is required");const ctx={anchors:new Map,doc,keep:true,mapAsMap:mapAsMap===true,mapKeyWarned:false,maxAliasCount:typeof maxAliasCount==="number"?maxAliasCount:100};const res=toJS.toJS(this,"",ctx);if(typeof onAnchor==="function")for(const{count,res:res2}of ctx.anchors.values())onAnchor(res2,count);return typeof reviver==="function"?applyReviver.applyReviver(reviver,{"":res},"",res):res}};exports.NodeBase=NodeBase}});var require_Alias=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Alias.js"(exports){"use strict";var anchors=require_anchors();var visit=require_visit();var identity=require_identity();var Node=require_Node();var toJS=require_toJS();var Alias=class extends Node.NodeBase{constructor(source){super(identity.ALIAS);this.source=source;Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(doc,ctx){if(ctx?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let nodes;if(ctx?.aliasResolveCache){nodes=ctx.aliasResolveCache}else{nodes=[];visit.visit(doc,{Node:(_key,node)=>{if(identity.isAlias(node)||identity.hasAnchor(node))nodes.push(node)}});if(ctx)ctx.aliasResolveCache=nodes}let found=void 0;for(const node of nodes){if(node===this)break;if(node.anchor===this.source)found=node}return found}toJSON(_arg,ctx){if(!ctx)return{source:this.source};const{anchors:anchors2,doc,maxAliasCount}=ctx;const source=this.resolve(doc,ctx);if(!source){const msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(msg)}let data=anchors2.get(source);if(!data){toJS.toJS(source,null,ctx);data=anchors2.get(source)}if(data?.res===void 0){const msg="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(msg)}if(maxAliasCount>=0){data.count+=1;if(data.aliasCount===0)data.aliasCount=getAliasCount(doc,source,anchors2);if(data.count*data.aliasCount>maxAliasCount){const msg="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(msg)}}return data.res}toString(ctx,_onComment,_onChompKeep){const src=`*${this.source}`;if(ctx){anchors.anchorIsValid(this.source);if(ctx.options.verifyAliasOrder&&!ctx.anchors.has(this.source)){const msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(msg)}if(ctx.implicitKey)return`${src} `}return src}};function getAliasCount(doc,node,anchors2){if(identity.isAlias(node)){const source=node.resolve(doc);const anchor=anchors2&&source&&anchors2.get(source);return anchor?anchor.count*anchor.aliasCount:0}else if(identity.isCollection(node)){let count=0;for(const item of node.items){const c3=getAliasCount(doc,item,anchors2);if(c3>count)count=c3}return count}else if(identity.isPair(node)){const kc=getAliasCount(doc,node.key,anchors2);const vc=getAliasCount(doc,node.value,anchors2);return Math.max(kc,vc)}return 1}exports.Alias=Alias}});var require_Scalar=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Scalar.js"(exports){"use strict";var identity=require_identity();var Node=require_Node();var toJS=require_toJS();var isScalarValue=value=>!value||typeof value!=="function"&&typeof value!=="object";var Scalar=class extends Node.NodeBase{constructor(value){super(identity.SCALAR);this.value=value}toJSON(arg,ctx){return ctx?.keep?this.value:toJS.toJS(this.value,arg,ctx)}toString(){return String(this.value)}};Scalar.BLOCK_FOLDED="BLOCK_FOLDED";Scalar.BLOCK_LITERAL="BLOCK_LITERAL";Scalar.PLAIN="PLAIN";Scalar.QUOTE_DOUBLE="QUOTE_DOUBLE";Scalar.QUOTE_SINGLE="QUOTE_SINGLE";exports.Scalar=Scalar;exports.isScalarValue=isScalarValue}});var require_createNode=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/createNode.js"(exports){"use strict";var Alias=require_Alias();var identity=require_identity();var Scalar=require_Scalar();var defaultTagPrefix="tag:yaml.org,2002:";function findTagObject(value,tagName,tags){if(tagName){const match=tags.filter(t2=>t2.tag===tagName);const tagObj=match.find(t2=>!t2.format)??match[0];if(!tagObj)throw new Error(`Tag ${tagName} not found`);return tagObj}return tags.find(t2=>t2.identify?.(value)&&!t2.format)}function createNode(value,tagName,ctx){if(identity.isDocument(value))value=value.contents;if(identity.isNode(value))return value;if(identity.isPair(value)){const map2=ctx.schema[identity.MAP].createNode?.(ctx.schema,null,ctx);map2.items.push(value);return map2}if(value instanceof String||value instanceof Number||value instanceof Boolean||typeof BigInt!=="undefined"&&value instanceof BigInt){value=value.valueOf()}const{aliasDuplicateObjects,onAnchor,onTagObj,schema,sourceObjects}=ctx;let ref=void 0;if(aliasDuplicateObjects&&value&&typeof value==="object"){ref=sourceObjects.get(value);if(ref){ref.anchor??(ref.anchor=onAnchor(value));return new Alias.Alias(ref.anchor)}else{ref={anchor:null,node:null};sourceObjects.set(value,ref)}}if(tagName?.startsWith("!!"))tagName=defaultTagPrefix+tagName.slice(2);let tagObj=findTagObject(value,tagName,schema.tags);if(!tagObj){if(value&&typeof value.toJSON==="function"){value=value.toJSON()}if(!value||typeof value!=="object"){const node2=new Scalar.Scalar(value);if(ref)ref.node=node2;return node2}tagObj=value instanceof Map?schema[identity.MAP]:Symbol.iterator in Object(value)?schema[identity.SEQ]:schema[identity.MAP]}if(onTagObj){onTagObj(tagObj);delete ctx.onTagObj}const node=tagObj?.createNode?tagObj.createNode(ctx.schema,value,ctx):typeof tagObj?.nodeClass?.from==="function"?tagObj.nodeClass.from(ctx.schema,value,ctx):new Scalar.Scalar(value);if(tagName)node.tag=tagName;else if(!tagObj.default)node.tag=tagObj.tag;if(ref)ref.node=node;return node}exports.createNode=createNode}});var require_Collection=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Collection.js"(exports){"use strict";var createNode=require_createNode();var identity=require_identity();var Node=require_Node();function collectionFromPath(schema,path4,value){let v3=value;for(let i2=path4.length-1;i2>=0;--i2){const k2=path4[i2];if(typeof k2==="number"&&Number.isInteger(k2)&&k2>=0){const a3=[];a3[k2]=v3;v3=a3}else{v3=new Map([[k2,v3]])}}return createNode.createNode(v3,void 0,{aliasDuplicateObjects:false,keepUndefined:false,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema,sourceObjects:new Map})}var isEmptyPath=path4=>path4==null||typeof path4==="object"&&!!path4[Symbol.iterator]().next().done;var Collection=class extends Node.NodeBase{constructor(type,schema){super(type);Object.defineProperty(this,"schema",{value:schema,configurable:true,enumerable:false,writable:true})}clone(schema){const copy2=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(schema)copy2.schema=schema;copy2.items=copy2.items.map(it2=>identity.isNode(it2)||identity.isPair(it2)?it2.clone(schema):it2);if(this.range)copy2.range=this.range.slice();return copy2}addIn(path4,value){if(isEmptyPath(path4))this.add(value);else{const[key,...rest]=path4;const node=this.get(key,true);if(identity.isCollection(node))node.addIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}deleteIn(path4){const[key,...rest]=path4;if(rest.length===0)return this.delete(key);const node=this.get(key,true);if(identity.isCollection(node))return node.deleteIn(rest);else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}getIn(path4,keepScalar){const[key,...rest]=path4;const node=this.get(key,true);if(rest.length===0)return!keepScalar&&identity.isScalar(node)?node.value:node;else return identity.isCollection(node)?node.getIn(rest,keepScalar):void 0}hasAllNullValues(allowScalar){return this.items.every(node=>{if(!identity.isPair(node))return false;const n2=node.value;return n2==null||allowScalar&&identity.isScalar(n2)&&n2.value==null&&!n2.commentBefore&&!n2.comment&&!n2.tag})}hasIn(path4){const[key,...rest]=path4;if(rest.length===0)return this.has(key);const node=this.get(key,true);return identity.isCollection(node)?node.hasIn(rest):false}setIn(path4,value){const[key,...rest]=path4;if(rest.length===0){this.set(key,value)}else{const node=this.get(key,true);if(identity.isCollection(node))node.setIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}};exports.Collection=Collection;exports.collectionFromPath=collectionFromPath;exports.isEmptyPath=isEmptyPath}});var require_stringifyComment=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyComment.js"(exports){"use strict";var stringifyComment=str2=>str2.replace(/^(?!$)(?: $)?/gm,"#");function indentComment(comment,indent){if(/^\n+$/.test(comment))return comment.substring(1);return indent?comment.replace(/^(?! *$)/gm,indent):comment}var lineComment=(str2,indent,comment)=>str2.endsWith("\n")?indentComment(comment,indent):comment.includes("\n")?"\n"+indentComment(comment,indent):(str2.endsWith(" ")?"":" ")+comment;exports.indentComment=indentComment;exports.lineComment=lineComment;exports.stringifyComment=stringifyComment}});var require_foldFlowLines=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/foldFlowLines.js"(exports){"use strict";var FOLD_FLOW="flow";var FOLD_BLOCK="block";var FOLD_QUOTED="quoted";function foldFlowLines(text3,indent,mode="flow",{indentAtStart,lineWidth=80,minContentWidth=20,onFold,onOverflow}={}){if(!lineWidth||lineWidth<0)return text3;if(lineWidth<minContentWidth)minContentWidth=0;const endStep=Math.max(1+minContentWidth,1+lineWidth-indent.length);if(text3.length<=endStep)return text3;const folds=[];const escapedFolds={};let end=lineWidth-indent.length;if(typeof indentAtStart==="number"){if(indentAtStart>lineWidth-Math.max(2,minContentWidth))folds.push(0);else end=lineWidth-indentAtStart}let split=void 0;let prev=void 0;let overflow=false;let i2=-1;let escStart=-1;let escEnd=-1;if(mode===FOLD_BLOCK){i2=consumeMoreIndentedLines(text3,i2,indent.length);if(i2!==-1)end=i2+endStep}for(let ch;ch=text3[i2+=1];){if(mode===FOLD_QUOTED&&ch==="\\"){escStart=i2;switch(text3[i2+1]){case"x":i2+=3;break;case"u":i2+=5;break;case"U":i2+=9;break;default:i2+=1}escEnd=i2}if(ch==="\n"){if(mode===FOLD_BLOCK)i2=consumeMoreIndentedLines(text3,i2,indent.length);end=i2+indent.length+endStep;split=void 0}else{if(ch===" "&&prev&&prev!==" "&&prev!=="\n"&&prev!==" "){const next=text3[i2+1];if(next&&next!==" "&&next!=="\n"&&next!==" ")split=i2}if(i2>=end){if(split){folds.push(split);end=split+endStep;split=void 0}else if(mode===FOLD_QUOTED){while(prev===" "||prev===" "){prev=ch;ch=text3[i2+=1];overflow=true}const j2=i2>escEnd+1?i2-2:escStart-1;if(escapedFolds[j2])return text3;folds.push(j2);escapedFolds[j2]=true;end=j2+endStep;split=void 0}else{overflow=true}}}prev=ch}if(overflow&&onOverflow)onOverflow();if(folds.length===0)return text3;if(onFold)onFold();let res=text3.slice(0,folds[0]);for(let i3=0;i3<folds.length;++i3){const fold=folds[i3];const end2=folds[i3+1]||text3.length;if(fold===0)res=`
|
|
28
28
|
${indent}${text3.slice(0,end2)}`;else{if(mode===FOLD_QUOTED&&escapedFolds[fold])res+=`${text3[fold]}\\`;res+=`
|
|
29
29
|
${indent}${text3.slice(fold+1,end2)}`}}return res}function consumeMoreIndentedLines(text3,i2,indent){let end=i2;let start=i2+1;let ch=text3[start];while(ch===" "||ch===" "){if(i2<start+indent){ch=text3[++i2]}else{do{ch=text3[++i2]}while(ch&&ch!=="\n");end=i2;start=i2+1;ch=text3[start]}}return end}exports.FOLD_BLOCK=FOLD_BLOCK;exports.FOLD_FLOW=FOLD_FLOW;exports.FOLD_QUOTED=FOLD_QUOTED;exports.foldFlowLines=foldFlowLines}});var require_stringifyString=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyString.js"(exports){"use strict";var Scalar=require_Scalar();var foldFlowLines=require_foldFlowLines();var getFoldOptions=(ctx,isBlock)=>({indentAtStart:isBlock?ctx.indent.length:ctx.indentAtStart,lineWidth:ctx.options.lineWidth,minContentWidth:ctx.options.minContentWidth});var containsDocumentMarker=str2=>/^(%|---|\.\.\.)/m.test(str2);function lineLengthOverLimit(str2,lineWidth,indentLength){if(!lineWidth||lineWidth<0)return false;const limit=lineWidth-indentLength;const strLen=str2.length;if(strLen<=limit)return false;for(let i2=0,start=0;i2<strLen;++i2){if(str2[i2]==="\n"){if(i2-start>limit)return true;start=i2+1;if(strLen-start<=limit)return false}}return true}function doubleQuotedString(value,ctx){const json2=JSON.stringify(value);if(ctx.options.doubleQuotedAsJSON)return json2;const{implicitKey}=ctx;const minMultiLineLength=ctx.options.doubleQuotedMinMultiLineLength;const indent=ctx.indent||(containsDocumentMarker(value)?" ":"");let str2="";let start=0;for(let i2=0,ch=json2[i2];ch;ch=json2[++i2]){if(ch===" "&&json2[i2+1]==="\\"&&json2[i2+2]==="n"){str2+=json2.slice(start,i2)+"\\ ";i2+=1;start=i2;ch="\\"}if(ch==="\\")switch(json2[i2+1]){case"u":{str2+=json2.slice(start,i2);const code2=json2.substr(i2+2,4);switch(code2){case"0000":str2+="\\0";break;case"0007":str2+="\\a";break;case"000b":str2+="\\v";break;case"001b":str2+="\\e";break;case"0085":str2+="\\N";break;case"00a0":str2+="\\_";break;case"2028":str2+="\\L";break;case"2029":str2+="\\P";break;default:if(code2.substr(0,2)==="00")str2+="\\x"+code2.substr(2);else str2+=json2.substr(i2,6)}i2+=5;start=i2+1}break;case"n":if(implicitKey||json2[i2+2]==='"'||json2.length<minMultiLineLength){i2+=1}else{str2+=json2.slice(start,i2)+"\n\n";while(json2[i2+2]==="\\"&&json2[i2+3]==="n"&&json2[i2+4]!=='"'){str2+="\n";i2+=2}str2+=indent;if(json2[i2+2]===" ")str2+="\\";i2+=1;start=i2+1}break;default:i2+=1}}str2=start?str2+json2.slice(start):json2;return implicitKey?str2:foldFlowLines.foldFlowLines(str2,indent,foldFlowLines.FOLD_QUOTED,getFoldOptions(ctx,false))}function singleQuotedString(value,ctx){if(ctx.options.singleQuote===false||ctx.implicitKey&&value.includes("\n")||/[ \t]\n|\n[ \t]/.test(value))return doubleQuotedString(value,ctx);const indent=ctx.indent||(containsDocumentMarker(value)?" ":"");const res="'"+value.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
30
30
|
${indent}`)+"'";return ctx.implicitKey?res:foldFlowLines.foldFlowLines(res,indent,foldFlowLines.FOLD_FLOW,getFoldOptions(ctx,false))}function quotedString(value,ctx){const{singleQuote}=ctx.options;let qs;if(singleQuote===false)qs=doubleQuotedString;else{const hasDouble=value.includes('"');const hasSingle=value.includes("'");if(hasDouble&&!hasSingle)qs=singleQuotedString;else if(hasSingle&&!hasDouble)qs=doubleQuotedString;else qs=singleQuote?singleQuotedString:doubleQuotedString}return qs(value,ctx)}var blockEndNewlines;try{blockEndNewlines=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{blockEndNewlines=/\n+(?!\n|$)/g}function blockString({comment,type,value},ctx,onComment,onChompKeep){const{blockQuote,commentString,lineWidth}=ctx.options;if(!blockQuote||/\n[\t ]+$/.test(value)){return quotedString(value,ctx)}const indent=ctx.indent||(ctx.forceBlockIndent||containsDocumentMarker(value)?" ":"");const literal2=blockQuote==="literal"?true:blockQuote==="folded"||type===Scalar.Scalar.BLOCK_FOLDED?false:type===Scalar.Scalar.BLOCK_LITERAL?true:!lineLengthOverLimit(value,lineWidth,indent.length);if(!value)return literal2?"|\n":">\n";let chomp;let endStart;for(endStart=value.length;endStart>0;--endStart){const ch=value[endStart-1];if(ch!=="\n"&&ch!==" "&&ch!==" ")break}let end=value.substring(endStart);const endNlPos=end.indexOf("\n");if(endNlPos===-1){chomp="-"}else if(value===end||endNlPos!==end.length-1){chomp="+";if(onChompKeep)onChompKeep()}else{chomp=""}if(end){value=value.slice(0,-end.length);if(end[end.length-1]==="\n")end=end.slice(0,-1);end=end.replace(blockEndNewlines,`$&${indent}`)}let startWithSpace=false;let startEnd;let startNlPos=-1;for(startEnd=0;startEnd<value.length;++startEnd){const ch=value[startEnd];if(ch===" ")startWithSpace=true;else if(ch==="\n")startNlPos=startEnd;else break}let start=value.substring(0,startNlPos<startEnd?startNlPos+1:startEnd);if(start){value=value.substring(start.length);start=start.replace(/\n+/g,`$&${indent}`)}const indentSize=indent?"2":"1";let header=(startWithSpace?indentSize:"")+chomp;if(comment){header+=" "+commentString(comment.replace(/ ?[\r\n]+/g," "));if(onComment)onComment()}if(!literal2){const foldedValue=value.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${indent}`);let literalFallback=false;const foldOptions=getFoldOptions(ctx,true);if(blockQuote!=="folded"&&type!==Scalar.Scalar.BLOCK_FOLDED){foldOptions.onOverflow=()=>{literalFallback=true}}const body=foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`,indent,foldFlowLines.FOLD_BLOCK,foldOptions);if(!literalFallback)return`>${header}
|
|
@@ -48,9 +48,9 @@ ${pointer}
|
|
|
48
48
|
${comment}`:comment}else if(afterEmptyLine||doc.directives.docStart||!dc){doc.commentBefore=comment}else if(identity.isCollection(dc)&&!dc.flow&&dc.items.length>0){let it2=dc.items[0];if(identity.isPair(it2))it2=it2.key;const cb=it2.commentBefore;it2.commentBefore=cb?`${comment}
|
|
49
49
|
${cb}`:comment}else{const cb=dc.commentBefore;dc.commentBefore=cb?`${comment}
|
|
50
50
|
${cb}`:comment}}if(afterDoc){for(let i2=0;i2<this.errors.length;++i2)doc.errors.push(this.errors[i2]);for(let i2=0;i2<this.warnings.length;++i2)doc.warnings.push(this.warnings[i2])}else{doc.errors=this.errors;doc.warnings=this.warnings}this.prelude=[];this.errors=[];this.warnings=[]}streamInfo(){return{comment:parsePrelude(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(tokens,forceDoc=false,endOffset=-1){for(const token2 of tokens)yield*this.next(token2);yield*this.end(forceDoc,endOffset)}*next(token2){if(node_process.env.LOG_STREAM)console.dir(token2,{depth:null});switch(token2.type){case"directive":this.directives.add(token2.source,(offset,message,warning)=>{const pos=getErrorPos(token2);pos[0]+=offset;this.onError(pos,"BAD_DIRECTIVE",message,warning)});this.prelude.push(token2.source);this.atDirectives=true;break;case"document":{const doc=composeDoc.composeDoc(this.options,this.directives,token2,this.onError);if(this.atDirectives&&!doc.directives.docStart)this.onError(token2,"MISSING_CHAR","Missing directives-end/doc-start indicator line");this.decorate(doc,false);if(this.doc)yield this.doc;this.doc=doc;this.atDirectives=false;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(token2.source);break;case"error":{const msg=token2.source?`${token2.message}: ${JSON.stringify(token2.source)}`:token2.message;const error51=new errors.YAMLParseError(getErrorPos(token2),"UNEXPECTED_TOKEN",msg);if(this.atDirectives||!this.doc)this.errors.push(error51);else this.doc.errors.push(error51);break}case"doc-end":{if(!this.doc){const msg="Unexpected doc-end without preceding document";this.errors.push(new errors.YAMLParseError(getErrorPos(token2),"UNEXPECTED_TOKEN",msg));break}this.doc.directives.docEnd=true;const end=resolveEnd.resolveEnd(token2.end,token2.offset+token2.source.length,this.doc.options.strict,this.onError);this.decorate(this.doc,true);if(end.comment){const dc=this.doc.comment;this.doc.comment=dc?`${dc}
|
|
51
|
-
${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.errors.push(new errors.YAMLParseError(getErrorPos(token2),"UNEXPECTED_TOKEN",`Unsupported token ${token2.type}`))}}*end(forceDoc=false,endOffset=-1){if(this.doc){this.decorate(this.doc,true);yield this.doc;this.doc=null}else if(forceDoc){const opts=Object.assign({_directives:this.directives},this.options);const doc=new Document.Document(void 0,opts);if(this.atDirectives)this.onError(endOffset,"MISSING_CHAR","Missing directives-end indicator line");doc.range=[0,endOffset,endOffset];this.decorate(doc,false);yield doc}}};exports.Composer=Composer}});var require_cst_scalar=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-scalar.js"(exports){"use strict";var resolveBlockScalar=require_resolve_block_scalar();var resolveFlowScalar=require_resolve_flow_scalar();var errors=require_errors3();var stringifyString=require_stringifyString();function resolveAsScalar(token2,strict=true,onError){if(token2){const _onError=(pos,code2,message)=>{const offset=typeof pos==="number"?pos:Array.isArray(pos)?pos[0]:pos.offset;if(onError)onError(offset,code2,message);else throw new errors.YAMLParseError([offset,offset+1],code2,message)};switch(token2.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return resolveFlowScalar.resolveFlowScalar(token2,strict,_onError);case"block-scalar":return resolveBlockScalar.resolveBlockScalar({options:{strict}},token2,_onError)}}return null}function createScalarToken(value,context){const{implicitKey=false,indent,inFlow=false,offset=-1,type="PLAIN"}=context;const source=stringifyString.stringifyString({type,value},{implicitKey,indent:indent>0?" ".repeat(indent):"",inFlow,options:{blockQuote:true,lineWidth:-1}});const end=context.end??[{type:"newline",offset:-1,indent,source:"\n"}];switch(source[0]){case"|":case">":{const he2=source.indexOf("\n");const head=source.substring(0,he2);const body=source.substring(he2+1)+"\n";const props=[{type:"block-scalar-header",offset,indent,source:head}];if(!addEndtoBlockProps(props,end))props.push({type:"newline",offset:-1,indent,source:"\n"});return{type:"block-scalar",offset,indent,props,source:body}}case'"':return{type:"double-quoted-scalar",offset,indent,source,end};case"'":return{type:"single-quoted-scalar",offset,indent,source,end};default:return{type:"scalar",offset,indent,source,end}}}function setScalarValue(token2,value,context={}){let{afterKey=false,implicitKey=false,inFlow=false,type}=context;let indent="indent"in token2?token2.indent:null;if(afterKey&&typeof indent==="number")indent+=2;if(!type)switch(token2.type){case"single-quoted-scalar":type="QUOTE_SINGLE";break;case"double-quoted-scalar":type="QUOTE_DOUBLE";break;case"block-scalar":{const header=token2.props[0];if(header.type!=="block-scalar-header")throw new Error("Invalid block scalar header");type=header.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:type="PLAIN"}const source=stringifyString.stringifyString({type,value},{implicitKey:implicitKey||indent===null,indent:indent!==null&&indent>0?" ".repeat(indent):"",inFlow,options:{blockQuote:true,lineWidth:-1}});switch(source[0]){case"|":case">":setBlockScalarValue(token2,source);break;case'"':setFlowScalarValue(token2,source,"double-quoted-scalar");break;case"'":setFlowScalarValue(token2,source,"single-quoted-scalar");break;default:setFlowScalarValue(token2,source,"scalar")}}function setBlockScalarValue(token2,source){const he2=source.indexOf("\n");const head=source.substring(0,he2);const body=source.substring(he2+1)+"\n";if(token2.type==="block-scalar"){const header=token2.props[0];if(header.type!=="block-scalar-header")throw new Error("Invalid block scalar header");header.source=head;token2.source=body}else{const{offset}=token2;const indent="indent"in token2?token2.indent:-1;const props=[{type:"block-scalar-header",offset,indent,source:head}];if(!addEndtoBlockProps(props,"end"in token2?token2.end:void 0))props.push({type:"newline",offset:-1,indent,source:"\n"});for(const key of Object.keys(token2))if(key!=="type"&&key!=="offset")delete token2[key];Object.assign(token2,{type:"block-scalar",indent,props,source:body})}}function addEndtoBlockProps(props,end){if(end)for(const st2 of end)switch(st2.type){case"space":case"comment":props.push(st2);break;case"newline":props.push(st2);return true}return false}function setFlowScalarValue(token2,source,type){switch(token2.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":token2.type=type;token2.source=source;break;case"block-scalar":{const end=token2.props.slice(1);let oa2=source.length;if(token2.props[0].type==="block-scalar-header")oa2-=token2.props[0].source.length;for(const tok of end)tok.offset+=oa2;delete token2.props;Object.assign(token2,{type,source,end});break}case"block-map":case"block-seq":{const offset=token2.offset+source.length;const nl={type:"newline",offset,indent:token2.indent,source:"\n"};delete token2.items;Object.assign(token2,{type,source,end:[nl]});break}default:{const indent="indent"in token2?token2.indent:-1;const end="end"in token2&&Array.isArray(token2.end)?token2.end.filter(st2=>st2.type==="space"||st2.type==="comment"||st2.type==="newline"):[];for(const key of Object.keys(token2))if(key!=="type"&&key!=="offset")delete token2[key];Object.assign(token2,{type,indent,source,end})}}}exports.createScalarToken=createScalarToken;exports.resolveAsScalar=resolveAsScalar;exports.setScalarValue=setScalarValue}});var require_cst_stringify=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-stringify.js"(exports){"use strict";var stringify=cst=>"type"in cst?stringifyToken(cst):stringifyItem(cst);function stringifyToken(token2){switch(token2.type){case"block-scalar":{let res="";for(const tok of token2.props)res+=stringifyToken(tok);return res+token2.source}case"block-map":case"block-seq":{let res="";for(const item of token2.items)res+=stringifyItem(item);return res}case"flow-collection":{let res=token2.start.source;for(const item of token2.items)res+=stringifyItem(item);for(const st2 of token2.end)res+=st2.source;return res}case"document":{let res=stringifyItem(token2);if(token2.end)for(const st2 of token2.end)res+=st2.source;return res}default:{let res=token2.source;if("end"in token2&&token2.end)for(const st2 of token2.end)res+=st2.source;return res}}}function stringifyItem({start,key,sep:sep4,value}){let res="";for(const st2 of start)res+=st2.source;if(key)res+=stringifyToken(key);if(sep4)for(const st2 of sep4)res+=st2.source;if(value)res+=stringifyToken(value);return res}exports.stringify=stringify}});var require_cst_visit=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-visit.js"(exports){"use strict";var BREAK=Symbol("break visit");var SKIP=Symbol("skip children");var REMOVE=Symbol("remove item");function visit(cst,visitor){if("type"in cst&&cst.type==="document")cst={start:cst.start,value:cst.value};_visit(Object.freeze([]),cst,visitor)}visit.BREAK=BREAK;visit.SKIP=SKIP;visit.REMOVE=REMOVE;visit.itemAtPath=(cst,path4)=>{let item=cst;for(const[field,index2]of path4){const tok=item?.[field];if(tok&&"items"in tok){item=tok.items[index2]}else return void 0}return item};visit.parentCollection=(cst,path4)=>{const parent=visit.itemAtPath(cst,path4.slice(0,-1));const field=path4[path4.length-1][0];const coll=parent?.[field];if(coll&&"items"in coll)return coll;throw new Error("Parent collection not found")};function _visit(path4,item,visitor){let ctrl=visitor(item,path4);if(typeof ctrl==="symbol")return ctrl;for(const field of["key","value"]){const token2=item[field];if(token2&&"items"in token2){for(let i2=0;i2<token2.items.length;++i2){const ci2=_visit(Object.freeze(path4.concat([[field,i2]])),token2.items[i2],visitor);if(typeof ci2==="number")i2=ci2-1;else if(ci2===BREAK)return BREAK;else if(ci2===REMOVE){token2.items.splice(i2,1);i2-=1}}if(typeof ctrl==="function"&&field==="key")ctrl=ctrl(item,path4)}}return typeof ctrl==="function"?ctrl(item,path4):ctrl}exports.visit=visit}});var require_cst=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst.js"(exports){"use strict";var cstScalar=require_cst_scalar();var cstStringify=require_cst_stringify();var cstVisit=require_cst_visit();var BOM="\uFEFF";var DOCUMENT="";var FLOW_END="";var SCALAR="";var isCollection=token2=>!!token2&&"items"in token2;var isScalar=token2=>!!token2&&(token2.type==="scalar"||token2.type==="single-quoted-scalar"||token2.type==="double-quoted-scalar"||token2.type==="block-scalar");function prettyToken(token2){switch(token2){case BOM:return"<BOM>";case DOCUMENT:return"<DOC>";case FLOW_END:return"<FLOW_END>";case SCALAR:return"<SCALAR>";default:return JSON.stringify(token2)}}function tokenType(source){switch(source){case BOM:return"byte-order-mark";case DOCUMENT:return"doc-mode";case FLOW_END:return"flow-error-end";case SCALAR:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case"\n":case"\r\n":return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(source[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}exports.createScalarToken=cstScalar.createScalarToken;exports.resolveAsScalar=cstScalar.resolveAsScalar;exports.setScalarValue=cstScalar.setScalarValue;exports.stringify=cstStringify.stringify;exports.visit=cstVisit.visit;exports.BOM=BOM;exports.DOCUMENT=DOCUMENT;exports.FLOW_END=FLOW_END;exports.SCALAR=SCALAR;exports.isCollection=isCollection;exports.isScalar=isScalar;exports.prettyToken=prettyToken;exports.tokenType=tokenType}});var require_lexer=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/lexer.js"(exports){"use strict";var cst=require_cst();function isEmpty(ch){switch(ch){case void 0:case" ":case"\n":case"\r":case" ":return true;default:return false}}var hexDigits=new Set("0123456789ABCDEFabcdef");var tagChars=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");var flowIndicatorChars=new Set(",[]{}");var invalidAnchorChars=new Set(" ,[]{}\n\r ");var isNotAnchorChar=ch=>!ch||invalidAnchorChars.has(ch);var Lexer=class{constructor(){this.atEnd=false;this.blockScalarIndent=-1;this.blockScalarKeep=false;this.buffer="";this.flowKey=false;this.flowLevel=0;this.indentNext=0;this.indentValue=0;this.lineEndPos=null;this.next=null;this.pos=0}*lex(source,incomplete=false){if(source){if(typeof source!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+source:source;this.lineEndPos=null}this.atEnd=!incomplete;let next=this.next??"stream";while(next&&(incomplete||this.hasChars(1)))next=yield*this.parseNext(next)}atLineEnd(){let i2=this.pos;let ch=this.buffer[i2];while(ch===" "||ch===" ")ch=this.buffer[++i2];if(!ch||ch==="#"||ch==="\n")return true;if(ch==="\r")return this.buffer[i2+1]==="\n";return false}charAt(n2){return this.buffer[this.pos+n2]}continueScalar(offset){let ch=this.buffer[offset];if(this.indentNext>0){let indent=0;while(ch===" ")ch=this.buffer[++indent+offset];if(ch==="\r"){const next=this.buffer[indent+offset+1];if(next==="\n"||!next&&!this.atEnd)return offset+indent+1}return ch==="\n"||indent>=this.indentNext||!ch&&!this.atEnd?offset+indent:-1}if(ch==="-"||ch==="."){const dt2=this.buffer.substr(offset,3);if((dt2==="---"||dt2==="...")&&isEmpty(this.buffer[offset+3]))return-1}return offset}getLine(){let end=this.lineEndPos;if(typeof end!=="number"||end!==-1&&end<this.pos){end=this.buffer.indexOf("\n",this.pos);this.lineEndPos=end}if(end===-1)return this.atEnd?this.buffer.substring(this.pos):null;if(this.buffer[end-1]==="\r")end-=1;return this.buffer.substring(this.pos,end)}hasChars(n2){return this.pos+n2<=this.buffer.length}setNext(state){this.buffer=this.buffer.substring(this.pos);this.pos=0;this.lineEndPos=null;this.next=state;return null}peek(n2){return this.buffer.substr(this.pos,n2)}*parseNext(next){switch(next){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let line=this.getLine();if(line===null)return this.setNext("stream");if(line[0]===cst.BOM){yield*this.pushCount(1);line=line.substring(1)}if(line[0]==="%"){let dirEnd=line.length;let cs=line.indexOf("#");while(cs!==-1){const ch=line[cs-1];if(ch===" "||ch===" "){dirEnd=cs-1;break}else{cs=line.indexOf("#",cs+1)}}while(true){const ch=line[dirEnd-1];if(ch===" "||ch===" ")dirEnd-=1;else break}const n2=(yield*this.pushCount(dirEnd))+(yield*this.pushSpaces(true));yield*this.pushCount(line.length-n2);this.pushNewline();return"stream"}if(this.atLineEnd()){const sp=yield*this.pushSpaces(true);yield*this.pushCount(line.length-sp);yield*this.pushNewline();return"stream"}yield cst.DOCUMENT;return yield*this.parseLineStart()}*parseLineStart(){const ch=this.charAt(0);if(!ch&&!this.atEnd)return this.setNext("line-start");if(ch==="-"||ch==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const s3=this.peek(3);if((s3==="---"||s3==="...")&&isEmpty(this.charAt(3))){yield*this.pushCount(3);this.indentValue=0;this.indentNext=0;return s3==="---"?"doc":"stream"}}this.indentValue=yield*this.pushSpaces(false);if(this.indentNext>this.indentValue&&!isEmpty(this.charAt(1)))this.indentNext=this.indentValue;return yield*this.parseBlockStart()}*parseBlockStart(){const[ch0,ch1]=this.peek(2);if(!ch1&&!this.atEnd)return this.setNext("block-start");if((ch0==="-"||ch0==="?"||ch0===":")&&isEmpty(ch1)){const n2=(yield*this.pushCount(1))+(yield*this.pushSpaces(true));this.indentNext=this.indentValue+1;this.indentValue+=n2;return"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(true);const line=this.getLine();if(line===null)return this.setNext("doc");let n2=yield*this.pushIndicators();switch(line[n2]){case"#":yield*this.pushCount(line.length-n2);case void 0:yield*this.pushNewline();return yield*this.parseLineStart();case"{":case"[":yield*this.pushCount(1);this.flowKey=false;this.flowLevel=1;return"flow";case"}":case"]":yield*this.pushCount(1);return"doc";case"*":yield*this.pushUntil(isNotAnchorChar);return"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":n2+=yield*this.parseBlockScalarHeader();n2+=yield*this.pushSpaces(true);yield*this.pushCount(line.length-n2);yield*this.pushNewline();return yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let nl,sp;let indent=-1;do{nl=yield*this.pushNewline();if(nl>0){sp=yield*this.pushSpaces(false);this.indentValue=indent=sp}else{sp=0}sp+=yield*this.pushSpaces(true)}while(nl+sp>0);const line=this.getLine();if(line===null)return this.setNext("flow");if(indent!==-1&&indent<this.indentNext&&line[0]!=="#"||indent===0&&(line.startsWith("---")||line.startsWith("..."))&&isEmpty(line[3])){const atFlowEndMarker=indent===this.indentNext-1&&this.flowLevel===1&&(line[0]==="]"||line[0]==="}");if(!atFlowEndMarker){this.flowLevel=0;yield cst.FLOW_END;return yield*this.parseLineStart()}}let n2=0;while(line[n2]===","){n2+=yield*this.pushCount(1);n2+=yield*this.pushSpaces(true);this.flowKey=false}n2+=yield*this.pushIndicators();switch(line[n2]){case void 0:return"flow";case"#":yield*this.pushCount(line.length-n2);return"flow";case"{":case"[":yield*this.pushCount(1);this.flowKey=false;this.flowLevel+=1;return"flow";case"}":case"]":yield*this.pushCount(1);this.flowKey=true;this.flowLevel-=1;return this.flowLevel?"flow":"doc";case"*":yield*this.pushUntil(isNotAnchorChar);return"flow";case'"':case"'":this.flowKey=true;return yield*this.parseQuotedScalar();case":":{const next=this.charAt(1);if(this.flowKey||isEmpty(next)||next===","){this.flowKey=false;yield*this.pushCount(1);yield*this.pushSpaces(true);return"flow"}}default:this.flowKey=false;return yield*this.parsePlainScalar()}}*parseQuotedScalar(){const quote=this.charAt(0);let end=this.buffer.indexOf(quote,this.pos+1);if(quote==="'"){while(end!==-1&&this.buffer[end+1]==="'")end=this.buffer.indexOf("'",end+2)}else{while(end!==-1){let n2=0;while(this.buffer[end-1-n2]==="\\")n2+=1;if(n2%2===0)break;end=this.buffer.indexOf('"',end+1)}}const qb=this.buffer.substring(0,end);let nl=qb.indexOf("\n",this.pos);if(nl!==-1){while(nl!==-1){const cs=this.continueScalar(nl+1);if(cs===-1)break;nl=qb.indexOf("\n",cs)}if(nl!==-1){end=nl-(qb[nl-1]==="\r"?2:1)}}if(end===-1){if(!this.atEnd)return this.setNext("quoted-scalar");end=this.buffer.length}yield*this.pushToIndex(end+1,false);return this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1;this.blockScalarKeep=false;let i2=this.pos;while(true){const ch=this.buffer[++i2];if(ch==="+")this.blockScalarKeep=true;else if(ch>"0"&&ch<="9")this.blockScalarIndent=Number(ch)-1;else if(ch!=="-")break}return yield*this.pushUntil(ch=>isEmpty(ch)||ch==="#")}*parseBlockScalar(){let nl=this.pos-1;let indent=0;let ch;loop:for(let i3=this.pos;ch=this.buffer[i3];++i3){switch(ch){case" ":indent+=1;break;case"\n":nl=i3;indent=0;break;case"\r":{const next=this.buffer[i3+1];if(!next&&!this.atEnd)return this.setNext("block-scalar");if(next==="\n")break}default:break loop}}if(!ch&&!this.atEnd)return this.setNext("block-scalar");if(indent>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=indent;else{this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext)}do{const cs=this.continueScalar(nl+1);if(cs===-1)break;nl=this.buffer.indexOf("\n",cs)}while(nl!==-1);if(nl===-1){if(!this.atEnd)return this.setNext("block-scalar");nl=this.buffer.length}}let i2=nl+1;ch=this.buffer[i2];while(ch===" ")ch=this.buffer[++i2];if(ch===" "){while(ch===" "||ch===" "||ch==="\r"||ch==="\n")ch=this.buffer[++i2];nl=i2-1}else if(!this.blockScalarKeep){do{let i3=nl-1;let ch2=this.buffer[i3];if(ch2==="\r")ch2=this.buffer[--i3];const lastChar=i3;while(ch2===" ")ch2=this.buffer[--i3];if(ch2==="\n"&&i3>=this.pos&&i3+1+indent>lastChar)nl=i3;else break}while(true)}yield cst.SCALAR;yield*this.pushToIndex(nl+1,true);return yield*this.parseLineStart()}*parsePlainScalar(){const inFlow=this.flowLevel>0;let end=this.pos-1;let i2=this.pos-1;let ch;while(ch=this.buffer[++i2]){if(ch===":"){const next=this.buffer[i2+1];if(isEmpty(next)||inFlow&&flowIndicatorChars.has(next))break;end=i2}else if(isEmpty(ch)){let next=this.buffer[i2+1];if(ch==="\r"){if(next==="\n"){i2+=1;ch="\n";next=this.buffer[i2+1]}else end=i2}if(next==="#"||inFlow&&flowIndicatorChars.has(next))break;if(ch==="\n"){const cs=this.continueScalar(i2+1);if(cs===-1)break;i2=Math.max(i2,cs-2)}}else{if(inFlow&&flowIndicatorChars.has(ch))break;end=i2}}if(!ch&&!this.atEnd)return this.setNext("plain-scalar");yield cst.SCALAR;yield*this.pushToIndex(end+1,true);return inFlow?"flow":"doc"}*pushCount(n2){if(n2>0){yield this.buffer.substr(this.pos,n2);this.pos+=n2;return n2}return 0}*pushToIndex(i2,allowEmpty){const s3=this.buffer.slice(this.pos,i2);if(s3){yield s3;this.pos+=s3.length;return s3.length}else if(allowEmpty)yield"";return 0}*pushIndicators(){let n2=0;loop:while(true){switch(this.charAt(0)){case"!":n2+=yield*this.pushTag();n2+=yield*this.pushSpaces(true);continue loop;case"&":n2+=yield*this.pushUntil(isNotAnchorChar);n2+=yield*this.pushSpaces(true);continue loop;case"-":case"?":case":":{const inFlow=this.flowLevel>0;const ch1=this.charAt(1);if(isEmpty(ch1)||inFlow&&flowIndicatorChars.has(ch1)){if(!inFlow)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=false;n2+=yield*this.pushCount(1);n2+=yield*this.pushSpaces(true);continue loop}}}break loop}return n2}*pushTag(){if(this.charAt(1)==="<"){let i2=this.pos+2;let ch=this.buffer[i2];while(!isEmpty(ch)&&ch!==">")ch=this.buffer[++i2];return yield*this.pushToIndex(ch===">"?i2+1:i2,false)}else{let i2=this.pos+1;let ch=this.buffer[i2];while(ch){if(tagChars.has(ch))ch=this.buffer[++i2];else if(ch==="%"&&hexDigits.has(this.buffer[i2+1])&&hexDigits.has(this.buffer[i2+2])){ch=this.buffer[i2+=3]}else break}return yield*this.pushToIndex(i2,false)}}*pushNewline(){const ch=this.buffer[this.pos];if(ch==="\n")return yield*this.pushCount(1);else if(ch==="\r"&&this.charAt(1)==="\n")return yield*this.pushCount(2);else return 0}*pushSpaces(allowTabs){let i2=this.pos-1;let ch;do{ch=this.buffer[++i2]}while(ch===" "||allowTabs&&ch===" ");const n2=i2-this.pos;if(n2>0){yield this.buffer.substr(this.pos,n2);this.pos=i2}return n2}*pushUntil(test){let i2=this.pos;let ch=this.buffer[i2];while(!test(ch))ch=this.buffer[++i2];return yield*this.pushToIndex(i2,false)}};exports.Lexer=Lexer}});var require_line_counter=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/line-counter.js"(exports){"use strict";var LineCounter=class{constructor(){this.lineStarts=[];this.addNewLine=offset=>this.lineStarts.push(offset);this.linePos=offset=>{let low=0;let high=this.lineStarts.length;while(low<high){const mid=low+high>>1;if(this.lineStarts[mid]<offset)low=mid+1;else high=mid}if(this.lineStarts[low]===offset)return{line:low+1,col:1};if(low===0)return{line:0,col:offset};const start=this.lineStarts[low-1];return{line:low,col:offset-start+1}}}};exports.LineCounter=LineCounter}});var require_parser2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/parser.js"(exports){"use strict";var node_process=__require("process");var cst=require_cst();var lexer=require_lexer();function includesToken(list,type){for(let i2=0;i2<list.length;++i2)if(list[i2].type===type)return true;return false}function findNonEmptyIndex(list){for(let i2=0;i2<list.length;++i2){switch(list[i2].type){case"space":case"comment":case"newline":break;default:return i2}}return-1}function isFlowToken(token2){switch(token2?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return true;default:return false}}function getPrevProps(parent){switch(parent.type){case"document":return parent.start;case"block-map":{const it2=parent.items[parent.items.length-1];return it2.sep??it2.start}case"block-seq":return parent.items[parent.items.length-1].start;default:return[]}}function getFirstKeyStartProps(prev){if(prev.length===0)return[];let i2=prev.length;loop:while(--i2>=0){switch(prev[i2].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break loop}}while(prev[++i2]?.type==="space"){}return prev.splice(i2,prev.length)}function arrayPushArray(target2,source){if(source.length<1e5)Array.prototype.push.apply(target2,source);else for(let i2=0;i2<source.length;++i2)target2.push(source[i2])}function fixFlowSeqItems(fc){if(fc.start.type==="flow-seq-start"){for(const it2 of fc.items){if(it2.sep&&!it2.value&&!includesToken(it2.start,"explicit-key-ind")&&!includesToken(it2.sep,"map-value-ind")){if(it2.key)it2.value=it2.key;delete it2.key;if(isFlowToken(it2.value)){if(it2.value.end)arrayPushArray(it2.value.end,it2.sep);else it2.value.end=it2.sep}else arrayPushArray(it2.start,it2.sep);delete it2.sep}}}}var Parser2=class{constructor(onNewLine){this.atNewLine=true;this.atScalar=false;this.indent=0;this.offset=0;this.onKeyLine=false;this.stack=[];this.source="";this.type="";this.lexer=new lexer.Lexer;this.onNewLine=onNewLine}*parse(source,incomplete=false){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(const lexeme of this.lexer.lex(source,incomplete))yield*this.next(lexeme);if(!incomplete)yield*this.end()}*next(source){this.source=source;if(node_process.env.LOG_TOKENS)console.log("|",cst.prettyToken(source));if(this.atScalar){this.atScalar=false;yield*this.step();this.offset+=source.length;return}const type=cst.tokenType(source);if(!type){const message=`Not a YAML token: ${source}`;yield*this.pop({type:"error",offset:this.offset,message,source});this.offset+=source.length}else if(type==="scalar"){this.atNewLine=false;this.atScalar=true;this.type="scalar"}else{this.type=type;yield*this.step();switch(type){case"newline":this.atNewLine=true;this.indent=0;if(this.onNewLine)this.onNewLine(this.offset+source.length);break;case"space":if(this.atNewLine&&source[0]===" ")this.indent+=source.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=source.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=false}this.offset+=source.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){const st2={type:this.type,offset:this.offset,indent:this.indent,source:this.source};return st2}*step(){const top=this.peek(1);if(this.type==="doc-end"&&top?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!top)return yield*this.stream();switch(top.type){case"document":return yield*this.document(top);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(top);case"block-scalar":return yield*this.blockScalar(top);case"block-map":return yield*this.blockMap(top);case"block-seq":return yield*this.blockSequence(top);case"flow-collection":return yield*this.flowCollection(top);case"doc-end":return yield*this.documentEnd(top)}yield*this.pop()}peek(n2){return this.stack[this.stack.length-n2]}*pop(error51){const token2=error51??this.stack.pop();if(!token2){const message="Tried to pop an empty stack";yield{type:"error",offset:this.offset,source:"",message}}else if(this.stack.length===0){yield token2}else{const top=this.peek(1);if(token2.type==="block-scalar"){token2.indent="indent"in top?top.indent:0}else if(token2.type==="flow-collection"&&top.type==="document"){token2.indent=0}if(token2.type==="flow-collection")fixFlowSeqItems(token2);switch(top.type){case"document":top.value=token2;break;case"block-scalar":top.props.push(token2);break;case"block-map":{const it2=top.items[top.items.length-1];if(it2.value){top.items.push({start:[],key:token2,sep:[]});this.onKeyLine=true;return}else if(it2.sep){it2.value=token2}else{Object.assign(it2,{key:token2,sep:[]});this.onKeyLine=!it2.explicitKey;return}break}case"block-seq":{const it2=top.items[top.items.length-1];if(it2.value)top.items.push({start:[],value:token2});else it2.value=token2;break}case"flow-collection":{const it2=top.items[top.items.length-1];if(!it2||it2.value)top.items.push({start:[],key:token2,sep:[]});else if(it2.sep)it2.value=token2;else Object.assign(it2,{key:token2,sep:[]});return}default:yield*this.pop();yield*this.pop(token2)}if((top.type==="document"||top.type==="block-map"||top.type==="block-seq")&&(token2.type==="block-map"||token2.type==="block-seq")){const last=token2.items[token2.items.length-1];if(last&&!last.sep&&!last.value&&last.start.length>0&&findNonEmptyIndex(last.start)===-1&&(token2.indent===0||last.start.every(st2=>st2.type!=="comment"||st2.indent<token2.indent))){if(top.type==="document")top.end=last.start;else top.items.push({start:last.start});token2.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{const doc={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")doc.start.push(this.sourceToken);this.stack.push(doc);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(doc){if(doc.value)return yield*this.lineEnd(doc);switch(this.type){case"doc-start":{if(findNonEmptyIndex(doc.start)!==-1){yield*this.pop();yield*this.step()}else doc.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":doc.start.push(this.sourceToken);return}const bv=this.startBlockValue(doc);if(bv)this.stack.push(bv);else{yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}}*scalar(scalar){if(this.type==="map-value-ind"){const prev=getPrevProps(this.peek(2));const start=getFirstKeyStartProps(prev);let sep4;if(scalar.end){sep4=scalar.end;sep4.push(this.sourceToken);delete scalar.end}else sep4=[this.sourceToken];const map2={type:"block-map",offset:scalar.offset,indent:scalar.indent,items:[{start,key:scalar,sep:sep4}]};this.onKeyLine=true;this.stack[this.stack.length-1]=map2}else yield*this.lineEnd(scalar)}*blockScalar(scalar){switch(this.type){case"space":case"comment":case"newline":scalar.props.push(this.sourceToken);return;case"scalar":scalar.source=this.source;this.atNewLine=true;this.indent=0;if(this.onNewLine){let nl=this.source.indexOf("\n")+1;while(nl!==0){this.onNewLine(this.offset+nl);nl=this.source.indexOf("\n",nl)+1}}yield*this.pop();break;default:yield*this.pop();yield*this.step()}}*blockMap(map2){const it2=map2.items[map2.items.length-1];switch(this.type){case"newline":this.onKeyLine=false;if(it2.value){const end="end"in it2.value?it2.value.end:void 0;const last=Array.isArray(end)?end[end.length-1]:void 0;if(last?.type==="comment")end?.push(this.sourceToken);else map2.items.push({start:[this.sourceToken]})}else if(it2.sep){it2.sep.push(this.sourceToken)}else{it2.start.push(this.sourceToken)}return;case"space":case"comment":if(it2.value){map2.items.push({start:[this.sourceToken]})}else if(it2.sep){it2.sep.push(this.sourceToken)}else{if(this.atIndentedComment(it2.start,map2.indent)){const prev=map2.items[map2.items.length-2];const end=prev?.value?.end;if(Array.isArray(end)){arrayPushArray(end,it2.start);end.push(this.sourceToken);map2.items.pop();return}}it2.start.push(this.sourceToken)}return}if(this.indent>=map2.indent){const atMapIndent=!this.onKeyLine&&this.indent===map2.indent;const atNextItem=atMapIndent&&(it2.sep||it2.explicitKey)&&this.type!=="seq-item-ind";let start=[];if(atNextItem&&it2.sep&&!it2.value){const nl=[];for(let i2=0;i2<it2.sep.length;++i2){const st2=it2.sep[i2];switch(st2.type){case"newline":nl.push(i2);break;case"space":break;case"comment":if(st2.indent>map2.indent)nl.length=0;break;default:nl.length=0}}if(nl.length>=2)start=it2.sep.splice(nl[1])}switch(this.type){case"anchor":case"tag":if(atNextItem||it2.value){start.push(this.sourceToken);map2.items.push({start});this.onKeyLine=true}else if(it2.sep){it2.sep.push(this.sourceToken)}else{it2.start.push(this.sourceToken)}return;case"explicit-key-ind":if(!it2.sep&&!it2.explicitKey){it2.start.push(this.sourceToken);it2.explicitKey=true}else if(atNextItem||it2.value){start.push(this.sourceToken);map2.items.push({start,explicitKey:true})}else{this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:true}]})}this.onKeyLine=true;return;case"map-value-ind":if(it2.explicitKey){if(!it2.sep){if(includesToken(it2.start,"newline")){Object.assign(it2,{key:null,sep:[this.sourceToken]})}else{const start2=getFirstKeyStartProps(it2.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key:null,sep:[this.sourceToken]}]})}}else if(it2.value){map2.items.push({start:[],key:null,sep:[this.sourceToken]})}else if(includesToken(it2.sep,"map-value-ind")){this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]})}else if(isFlowToken(it2.key)&&!includesToken(it2.sep,"newline")){const start2=getFirstKeyStartProps(it2.start);const key=it2.key;const sep4=it2.sep;sep4.push(this.sourceToken);delete it2.key;delete it2.sep;this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key,sep:sep4}]})}else if(start.length>0){it2.sep=it2.sep.concat(start,this.sourceToken)}else{it2.sep.push(this.sourceToken)}}else{if(!it2.sep){Object.assign(it2,{key:null,sep:[this.sourceToken]})}else if(it2.value||atNextItem){map2.items.push({start,key:null,sep:[this.sourceToken]})}else if(includesToken(it2.sep,"map-value-ind")){this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]})}else{it2.sep.push(this.sourceToken)}}this.onKeyLine=true;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const fs2=this.flowScalar(this.type);if(atNextItem||it2.value){map2.items.push({start,key:fs2,sep:[]});this.onKeyLine=true}else if(it2.sep){this.stack.push(fs2)}else{Object.assign(it2,{key:fs2,sep:[]});this.onKeyLine=true}return}default:{const bv=this.startBlockValue(map2);if(bv){if(bv.type==="block-seq"){if(!it2.explicitKey&&it2.sep&&!includesToken(it2.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(atMapIndent){map2.items.push({start})}this.stack.push(bv);return}}}}yield*this.pop();yield*this.step()}*blockSequence(seq){const it2=seq.items[seq.items.length-1];switch(this.type){case"newline":if(it2.value){const end="end"in it2.value?it2.value.end:void 0;const last=Array.isArray(end)?end[end.length-1]:void 0;if(last?.type==="comment")end?.push(this.sourceToken);else seq.items.push({start:[this.sourceToken]})}else it2.start.push(this.sourceToken);return;case"space":case"comment":if(it2.value)seq.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(it2.start,seq.indent)){const prev=seq.items[seq.items.length-2];const end=prev?.value?.end;if(Array.isArray(end)){arrayPushArray(end,it2.start);end.push(this.sourceToken);seq.items.pop();return}}it2.start.push(this.sourceToken)}return;case"anchor":case"tag":if(it2.value||this.indent<=seq.indent)break;it2.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==seq.indent)break;if(it2.value||includesToken(it2.start,"seq-item-ind"))seq.items.push({start:[this.sourceToken]});else it2.start.push(this.sourceToken);return}if(this.indent>seq.indent){const bv=this.startBlockValue(seq);if(bv){this.stack.push(bv);return}}yield*this.pop();yield*this.step()}*flowCollection(fc){const it2=fc.items[fc.items.length-1];if(this.type==="flow-error-end"){let top;do{yield*this.pop();top=this.peek(1)}while(top?.type==="flow-collection")}else if(fc.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!it2||it2.sep)fc.items.push({start:[this.sourceToken]});else it2.start.push(this.sourceToken);return;case"map-value-ind":if(!it2||it2.value)fc.items.push({start:[],key:null,sep:[this.sourceToken]});else if(it2.sep)it2.sep.push(this.sourceToken);else Object.assign(it2,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!it2||it2.value)fc.items.push({start:[this.sourceToken]});else if(it2.sep)it2.sep.push(this.sourceToken);else it2.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const fs2=this.flowScalar(this.type);if(!it2||it2.value)fc.items.push({start:[],key:fs2,sep:[]});else if(it2.sep)this.stack.push(fs2);else Object.assign(it2,{key:fs2,sep:[]});return}case"flow-map-end":case"flow-seq-end":fc.end.push(this.sourceToken);return}const bv=this.startBlockValue(fc);if(bv)this.stack.push(bv);else{yield*this.pop();yield*this.step()}}else{const parent=this.peek(2);if(parent.type==="block-map"&&(this.type==="map-value-ind"&&parent.indent===fc.indent||this.type==="newline"&&!parent.items[parent.items.length-1].sep)){yield*this.pop();yield*this.step()}else if(this.type==="map-value-ind"&&parent.type!=="flow-collection"){const prev=getPrevProps(parent);const start=getFirstKeyStartProps(prev);fixFlowSeqItems(fc);const sep4=fc.end.splice(1,fc.end.length);sep4.push(this.sourceToken);const map2={type:"block-map",offset:fc.offset,indent:fc.indent,items:[{start,key:fc,sep:sep4}]};this.onKeyLine=true;this.stack[this.stack.length-1]=map2}else{yield*this.lineEnd(fc)}}}flowScalar(type){if(this.onNewLine){let nl=this.source.indexOf("\n")+1;while(nl!==0){this.onNewLine(this.offset+nl);nl=this.source.indexOf("\n",nl)+1}}return{type,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(parent){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=true;const prev=getPrevProps(parent);const start=getFirstKeyStartProps(prev);start.push(this.sourceToken);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,explicitKey:true}]}}case"map-value-ind":{this.onKeyLine=true;const prev=getPrevProps(parent);const start=getFirstKeyStartProps(prev);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(start,indent){if(this.type!=="comment")return false;if(this.indent<=indent)return false;return start.every(st2=>st2.type==="newline"||st2.type==="space")}*documentEnd(docEnd){if(this.type!=="doc-mode"){if(docEnd.end)docEnd.end.push(this.sourceToken);else docEnd.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(token2){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop();yield*this.step();break;case"newline":this.onKeyLine=false;case"space":case"comment":default:if(token2.end)token2.end.push(this.sourceToken);else token2.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}};exports.Parser=Parser2}});var require_public_api=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/public-api.js"(exports){"use strict";var composer=require_composer();var Document=require_Document();var errors=require_errors3();var log=require_log();var identity=require_identity();var lineCounter=require_line_counter();var parser=require_parser2();function parseOptions(options){const prettyErrors=options.prettyErrors!==false;const lineCounter$1=options.lineCounter||prettyErrors&&new lineCounter.LineCounter||null;return{lineCounter:lineCounter$1,prettyErrors}}function parseAllDocuments(source,options={}){const{lineCounter:lineCounter2,prettyErrors}=parseOptions(options);const parser$1=new parser.Parser(lineCounter2?.addNewLine);const composer$1=new composer.Composer(options);const docs=Array.from(composer$1.compose(parser$1.parse(source)));if(prettyErrors&&lineCounter2)for(const doc of docs){doc.errors.forEach(errors.prettifyError(source,lineCounter2));doc.warnings.forEach(errors.prettifyError(source,lineCounter2))}if(docs.length>0)return docs;return Object.assign([],{empty:true},composer$1.streamInfo())}function parseDocument(source,options={}){const{lineCounter:lineCounter2,prettyErrors}=parseOptions(options);const parser$1=new parser.Parser(lineCounter2?.addNewLine);const composer$1=new composer.Composer(options);let doc=null;for(const _doc of composer$1.compose(parser$1.parse(source),true,source.length)){if(!doc)doc=_doc;else if(doc.options.logLevel!=="silent"){doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}}if(prettyErrors&&lineCounter2){doc.errors.forEach(errors.prettifyError(source,lineCounter2));doc.warnings.forEach(errors.prettifyError(source,lineCounter2))}return doc}function parse3(src,reviver,options){let _reviver=void 0;if(typeof reviver==="function"){_reviver=reviver}else if(options===void 0&&reviver&&typeof reviver==="object"){options=reviver}const doc=parseDocument(src,options);if(!doc)return null;doc.warnings.forEach(warning=>log.warn(doc.options.logLevel,warning));if(doc.errors.length>0){if(doc.options.logLevel!=="silent")throw doc.errors[0];else doc.errors=[]}return doc.toJS(Object.assign({reviver:_reviver},options))}function stringify(value,replacer,options){let _replacer=null;if(typeof replacer==="function"||Array.isArray(replacer)){_replacer=replacer}else if(options===void 0&&replacer){options=replacer}if(typeof options==="string")options=options.length;if(typeof options==="number"){const indent=Math.round(options);options=indent<1?void 0:indent>8?{indent:8}:{indent}}if(value===void 0){const{keepUndefined}=options??replacer??{};if(!keepUndefined)return void 0}if(identity.isDocument(value)&&!_replacer)return value.toString(options);return new Document.Document(value,_replacer,options).toString(options)}exports.parse=parse3;exports.parseAllDocuments=parseAllDocuments;exports.parseDocument=parseDocument;exports.stringify=stringify}});var require_dist=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js"(exports){"use strict";var composer=require_composer();var Document=require_Document();var Schema=require_Schema();var errors=require_errors3();var Alias=require_Alias();var identity=require_identity();var Pair=require_Pair();var Scalar=require_Scalar();var YAMLMap=require_YAMLMap();var YAMLSeq=require_YAMLSeq();var cst=require_cst();var lexer=require_lexer();var lineCounter=require_line_counter();var parser=require_parser2();var publicApi=require_public_api();var visit=require_visit();exports.Composer=composer.Composer;exports.Document=Document.Document;exports.Schema=Schema.Schema;exports.YAMLError=errors.YAMLError;exports.YAMLParseError=errors.YAMLParseError;exports.YAMLWarning=errors.YAMLWarning;exports.Alias=Alias.Alias;exports.isAlias=identity.isAlias;exports.isCollection=identity.isCollection;exports.isDocument=identity.isDocument;exports.isMap=identity.isMap;exports.isNode=identity.isNode;exports.isPair=identity.isPair;exports.isScalar=identity.isScalar;exports.isSeq=identity.isSeq;exports.Pair=Pair.Pair;exports.Scalar=Scalar.Scalar;exports.YAMLMap=YAMLMap.YAMLMap;exports.YAMLSeq=YAMLSeq.YAMLSeq;exports.CST=cst;exports.Lexer=lexer.Lexer;exports.LineCounter=lineCounter.LineCounter;exports.Parser=parser.Parser;exports.parse=publicApi.parse;exports.parseAllDocuments=publicApi.parseAllDocuments;exports.parseDocument=publicApi.parseDocument;exports.stringify=publicApi.stringify;exports.visit=visit.visit;exports.visitAsync=visit.visitAsync}});function peerLabel(card){return(card.role?`${card.name}/${card.role}`:card.name).replace(/[\p{Cc}\p{Zl}\p{Zp}[\]"]+/gu," ")}function shownPeerName(name2,id2){return name2.trim()?peerLabel({name:name2}):id2}var LINE_BREAK;var init_peer_label=__esm({"../../packages/core/dist/peer-label.js"(){"use strict";LINE_BREAK=/\r\n?|[\n\v\f\u0085\u2028\u2029]/}});function candidate(p2){return{id:p2.card.id,name:p2.card.name,role:p2.card.role,status:p2.status,ts:p2.ts}}function resolvePeer(roster,target2,opts={}){const peers=opts.selfId?roster.filter(p2=>p2.card.id!==opts.selfId):roster;const byId=peers.find(p2=>p2.card.id===target2);if(byId)return byId;const want=target2.trim().toLowerCase();if(!want)return void 0;const matches=peers.filter(p2=>p2.card.name.toLowerCase()===want);if(matches.length===0){const labelled=peers.find(p2=>p2.card.role&&peerLabel(p2.card).trim().toLowerCase()===want);if(labelled)throw new Error(`"${target2}" is the roster label of ${labelled.card.name} (role ${labelled.card.role}), not an address: use the name "${labelled.card.name}" or its instance id`);return void 0}const live=matches.filter(p2=>p2.status!=="offline");const pool=live.length>0?live:matches;if(pool.length===1)return pool[0];throw new AmbiguousPeerError(target2,pool.map(candidate))}function sharedNameIds(roster,opts={}){const peers=opts.selfId?roster.filter(p2=>p2.card.id!==opts.selfId):roster;const groups=new Map;for(const p2 of peers){const key=p2.card.name.trim().toLowerCase();const group=groups.get(key);if(group)group.push(p2);else groups.set(key,[p2])}const ids=new Set;for(const group of groups.values()){const live=group.filter(p2=>p2.status!=="offline");const pool=live.length>0?live:group;if(pool.length>1)for(const p2 of pool)ids.add(p2.card.id)}return ids}function assertValidName(name2){if(name2.length===0||name2!==name2.trim())throw new Error(`invalid name ${JSON.stringify(name2)}: must be non-empty with no surrounding whitespace`);if(name2.length>MAX_NAME_LENGTH)throw new Error(`invalid name ${JSON.stringify(name2.slice(0,32))}\u2026: ${name2.length} characters exceeds the ${MAX_NAME_LENGTH}-character limit (the CONNECT line budget that carries it)`);if(LINE_BREAK.test(name2))throw new Error(`invalid name ${JSON.stringify(name2)}: must be a single line`);if(name2.includes("/"))throw new Error(`invalid name ${JSON.stringify(name2)}: "/" is reserved (the owner/name separator)`);if(name2.includes("\\"))throw new Error(`invalid name ${JSON.stringify(name2)}: "\\" is reserved (a Windows path separator)`);if(!isWellFormedUnicode(name2))throw new Error(`invalid name ${JSON.stringify(name2)}: contains an unpaired UTF-16 surrogate. Such a name cannot survive UTF-8 encoding \u2014 it is replaced with U+FFFD \u2014 so distinct names would silently become one identity.`)}var AmbiguousPeerError,MAX_NAME_LENGTH;var init_resolve=__esm({"../../packages/core/dist/resolve.js"(){"use strict";init_peer_label();init_peer_label();init_canonical_json();init_peer_label();AmbiguousPeerError=class extends Error{target;candidates;constructor(target2,candidates){super(`"${target2}" is ambiguous - ${candidates.length} peers share that name: `+candidates.map(c3=>`${shownPeerName(c3.name,c3.id)} (${c3.id}, ${c3.status})`).join("; ")+`. Re-send to the exact instance id.`);this.target=target2;this.candidates=candidates;this.name="AmbiguousPeerError"}};MAX_NAME_LENGTH=128}});function utf16Problem(text3){return text3.startsWith("\uFFFD\uFFFD")||text3.includes("\0")?"it is saved as UTF-16, and Cotal reads only UTF-8":void 0}var init_text_encoding=__esm({"../../packages/core/dist/text-encoding.js"(){"use strict"}});function parsePersonaEndpoints(raw,where){if(raw===void 0||raw===null)return void 0;const fail2=detail=>{throw new Error(`${where}: "endpoints" ${detail}`)};if(!Array.isArray(raw))fail2("must be a list of { endpoint, commands, instanceId? } entries");const merged=new Map;let total=0;for(const item of raw){if(item===null||typeof item!=="object"||Array.isArray(item))fail2("entries must be mappings of endpoint, commands and an optional instanceId");const proto=Object.getPrototypeOf(item);if(proto!==Object.prototype&&proto!==null)fail2("entries must be plain mappings");const rec=item;const extra=Reflect.ownKeys(rec).find(k2=>typeof k2!=="string"||!ENTRY_KEYS.includes(k2));if(extra!==void 0)fail2(`entry has unknown key ${String(extra)}; an entry takes endpoint, commands and instanceId`);const endpoint=rec.endpoint;if(typeof endpoint!=="string")fail2("entry needs an endpoint name");try{endpointToken(endpoint)}catch(e3){fail2(`entry: ${e3.message}`)}if(!endpoint.includes("."))fail2(`entry names "${endpoint}", a single-label endpoint; those are the reference endpoints, reached through the baseline and the spawn, run and admin capabilities. A persona hands on a reverse-DNS endpoint such as com.example.orders`);let instanceId;if(rec.instanceId!==void 0){if(typeof rec.instanceId!=="string")fail2(`entry for ${endpoint}: instanceId must be a string`);try{instanceId=assertLifecycleToken(rec.instanceId,"instanceId")}catch(e3){fail2(`entry for ${endpoint}: ${e3.message}`)}}const commands=rec.commands;if(!Array.isArray(commands)||commands.length===0)fail2(`entry for ${endpoint} needs a non-empty commands list`);const key=`${endpoint}\0${instanceId??""}`;const into=merged.get(key)??{endpoint,commands:[],...instanceId!==void 0?{instanceId}:{}};for(const c3 of commands){if(typeof c3!=="string")fail2(`entry for ${endpoint}: commands must be strings`);try{assertCommandToken(c3)}catch(e3){fail2(`entry for ${endpoint}: ${e3.message}`)}if(RESERVED_COMMANDS.includes(c3))fail2(`entry for ${endpoint} names the reserved command "${c3}"; describe is granted on every endpoint and cancel is not handed on`);if(!into.commands.includes(c3)){into.commands.push(c3);total++}}merged.set(key,into)}if(total>PERSONA_ENDPOINT_MAX_COMMANDS)fail2(`names ${total} commands; a persona may name at most ${PERSONA_ENDPOINT_MAX_COMMANDS}`);return[...merged.values()].map(e3=>({...e3,commands:[...e3.commands].sort()})).sort((a3,b3)=>a3.endpoint<b3.endpoint?-1:a3.endpoint>b3.endpoint?1:(a3.instanceId??"")<(b3.instanceId??"")?-1:1)}var PERSONA_ENDPOINT_MAX_COMMANDS,ENTRY_KEYS;var init_persona_endpoints=__esm({"../../packages/core/dist/persona-endpoints.js"(){"use strict";init_endpoint_subjects();PERSONA_ENDPOINT_MAX_COMMANDS=256;ENTRY_KEYS=["endpoint","commands","instanceId"]}});import{accessSync,constants as constants2,lstatSync as lstatSync3,mkdirSync as mkdirSync4,readdirSync,readFileSync as readFileSync2,readlinkSync,realpathSync,statSync as statSync2}from"node:fs";function parseFrontmatter(src,path4){let doc;try{doc=(0,import_yaml.parse)(src)}catch(e3){throw new Error(`agent file ${path4}: invalid YAML frontmatter; ${e3.message}`)}if(doc===null||doc===void 0)return{};if(typeof doc!=="object"||Array.isArray(doc))throw new Error(`agent file ${path4}: frontmatter must be a YAML mapping (key: value pairs)`);return doc}function assertLaunchSelectors(def,where){for(const k2 of["model","variant"]){const v3=def[k2];if(v3!==void 0&&!v3.trim())throw new Error(`${where}: "${k2}" must not be empty`)}}function assertValidKind(kind,where){if(kind==="agent"||kind==="endpoint")return kind;throw new Error(`${where?`${where}: `:`invalid kind ${JSON.stringify(kind)}: `}"kind" must be "agent" or "endpoint"`)}function loadAgentFile(path4,options){return parseAgentFileSource(readFileSync2(path4,"utf8"),path4,options)}function parseAgentFileSource(src,path4,options){const encoding=utf16Problem(src);if(encoding)throw new Error(`agent file ${path4}: ${encoding}; save it as UTF-8`);const m2=AGENT_FILE_FENCE.exec(src.replace(/^\uFEFF/,"").replace(/\r\n/g,"\n"));if(!m2)throw new Error(`agent file ${path4}: missing "---" frontmatter block`);const fm=parseFrontmatter(m2[1],path4);const persona=m2[2].trim();const yamlType=v3=>v3===null?"null":Array.isArray(v3)?"array":typeof v3==="object"?"mapping":typeof v3;const str2=k2=>{const v3=fm[k2];if(v3===void 0)return void 0;if(typeof v3!=="string")throw new Error(`agent file ${path4}: "${k2}" must be a string; got ${yamlType(v3)}`);return v3};const list=k2=>{const v3=fm[k2];if(v3===void 0)return void 0;if(!Array.isArray(v3))throw new Error(`agent file ${path4}: "${k2}" must be an array of strings; got ${yamlType(v3)}`);return v3.map((x2,index2)=>{if(typeof x2!=="string")throw new Error(`agent file ${path4}: "${k2}" must be an array of strings; item ${index2} got ${yamlType(x2)}`);return x2})};const name2=str2("name");if(!name2)throw new Error(`agent file ${path4}: "name" is required`);assertValidName(name2);const model=str2("model");const variant=str2("variant");assertLaunchSelectors({model,variant},`agent file ${path4}`);const rawKind=str2("kind");const kind=rawKind!==void 0?assertValidKind(rawKind,`agent file ${path4}`):void 0;for(const old of RENAMED_KEYS)if(old in fm)throw new Error(`agent file ${path4}: "${old}" was renamed - use "subscribe"/"allowSubscribe" (read) and "allowPublish" (post)`);for(const key of["cwd","worktree"])if(key in fm)throw new Error(`agent file ${path4}: "${key}" is not supported in frontmatter; the working directory comes from the spawn request (use --cwd)`);const subscribe=list("subscribe");const allowSubscribe=list("allowSubscribe");const allowPublish=list("allowPublish");const quiet=list("quiet");const muted=list("muted");for(const ch of[...subscribe??[],...allowSubscribe??[],...allowPublish??[]])try{assertValidChannel(ch)}catch(e3){throw new Error(`agent file ${path4}: ${e3.message}`)}let effAllow;try{effAllow=resolveReadAcl(subscribe??[],allowSubscribe)}catch(e3){throw new Error(`agent file ${path4}: ${e3.message}`)}const both=(quiet??[]).filter(c3=>(muted??[]).includes(c3));if(both.length)throw new Error(`agent file ${path4}: channel(s) [${both.join(", ")}] are in both quiet and muted - pick one`);for(const[field,chans]of[["quiet",quiet],["muted",muted]])for(const ch of chans??[]){try{assertValidChannel(ch)}catch(e3){throw new Error(`agent file ${path4}: ${e3.message}`)}if(!isConcreteChannel(ch))throw new Error(`agent file ${path4}: ${field} channel "${ch}" must be a concrete channel (no wildcard)`);if(!channelInAllow(effAllow,ch))throw new Error(`agent file ${path4}: ${field} channel "${ch}" is not within your read ACL / allowSubscribe [${effAllow.join(", ")}]`)}if(fm.eventPayloads!==void 0&&typeof fm.eventPayloads!=="boolean")throw new Error(`agent file ${path4}: "eventPayloads" must be a boolean`);const launchOptionsRaw=fm["launchOptions"];let launchOptions;if(launchOptionsRaw!==void 0){if(launchOptionsRaw===null||typeof launchOptionsRaw!=="object"||Array.isArray(launchOptionsRaw))throw new Error(`agent file ${path4}: "launchOptions" must be a mapping of key: value pairs`);launchOptions=launchOptionsRaw}const role=str2("role");if(role!==void 0&&!options?.deferRoleValidation){try{assertValidRole(role)}catch{throw new Error(`agent file ${path4}: "role" must be a single token using letters, digits, underscores or hyphens`)}}const meta3={};for(const[k2,v3]of Object.entries(fm))if(!MODELED_KEYS.has(k2)&&v3!==null&&typeof v3!=="object")meta3[k2]=String(v3);return{name:name2,role,kind,description:str2("description"),tags:list("tags"),agent:str2("agent"),subscribe,allowSubscribe,allowPublish,quiet,muted,model,variant,launchOptions,eventPayloads:fm.eventPayloads,capabilities:list("capabilities"),endpoints:parsePersonaEndpoints(fm["endpoints"],`agent file ${path4}`),owner:str2("owner"),meta:Object.keys(meta3).length?meta3:void 0,persona:persona||void 0}}var import_yaml,AGENT_FILE_FENCE,MODELED_KEYS,RENAMED_KEYS;var init_agent_file=__esm({"../../packages/core/dist/agent-file.js"(){"use strict";import_yaml=__toESM(require_dist(),1);init_resolve();init_secret_fs();init_text_encoding();init_subjects();init_endpoint_subjects();init_persona_endpoints();AGENT_FILE_FENCE=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;MODELED_KEYS=new Set(["name","role","kind","description","tags","subscribe","allowSubscribe","allowPublish","quiet","muted","agent","model","variant","launchOptions","eventPayloads","capabilities","endpoints","owner"]);RENAMED_KEYS=["channels","publish"]}});function nextHeartbeat(phaseMs,intervalMs,lastBeat,nowMs){const beat=Math.max(lastBeat+1,Math.ceil((nowMs-phaseMs)/intervalMs));return{beat,delayMs:Math.max(0,phaseMs+beat*intervalMs-nowMs)}}var init_presence_heartbeat=__esm({"../../packages/core/dist/presence-heartbeat.js"(){"use strict"}});async function openDeliveryRegistry(nc,space2){return new import_kv5.Kvm(nc).open(deliveryBucket(space2))}var import_kv5,import_transport_node11;var init_lease=__esm({"../../packages/core/dist/lease.js"(){"use strict";init_connection_cleanup();import_kv5=__toESM(require_mod6(),1);import_transport_node11=__toESM(require_transport_node(),1);init_endpoint();init_subjects();init_identity();init_streams()}});import{randomUUID as randomUUID4}from"node:crypto";var EndpointDeliveryLease;var init_endpoint_delivery_lease=__esm({"../../packages/core/dist/endpoint-delivery-lease.js"(){"use strict";init_lease();init_subjects();EndpointDeliveryLease=class{deps;deliveryKv;leaseIncarnation=randomUUID4();leaseAcquiredAt=new Map;leaseWatchIntent;leaseWatchIter;leaseWatchDeletes=new Set;leaseWatchBinds=new Set;constructor(deps){this.deps=deps}get card(){return this.deps.card()}get space(){return this.deps.space()}get nc(){return this.deps.connection()}get presenceEpoch(){return this.deps.epoch()}notLiveMsg(){return this.deps.notLiveMsg()}emitRecoverable(error51){this.deps.recoverable(error51)}emit(event,error51){return this.deps.emit(event,error51)}get hasWatchIntent(){return this.leaseWatchIntent!==void 0}resetConnection(){this.deliveryKv=void 0}async deliveryRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.deliveryKv??=await openDeliveryRegistry(this.nc,this.space);return this.deliveryKv}encodeLease(shardIndex,ready,acquiredAt=this.leaseAcquiredAt.get(shardIndex)){return new TextEncoder().encode(JSON.stringify({holder:this.card.id,incarnation:this.leaseIncarnation,acquiredAt,since:Date.now(),ready}))}ownsDeliveryLease(info){return info.holder===this.card.id&&info.incarnation!==void 0&&info.incarnation===this.leaseIncarnation}async acquireDeliveryLease(shardIndex){const acquiredAt=Date.now();const revision=await(await this.deliveryRegistry()).create(leaseKey(shardIndex),this.encodeLease(shardIndex,false,acquiredAt));this.leaseAcquiredAt.set(shardIndex,acquiredAt);return revision}async markDeliveryLeaseReady(shardIndex,revision){return(await this.deliveryRegistry()).update(leaseKey(shardIndex),this.encodeLease(shardIndex,true),revision)}async markDeliveryLeaseNotReady(shardIndex,revision){return(await this.deliveryRegistry()).update(leaseKey(shardIndex),this.encodeLease(shardIndex,false),revision)}async renewDeliveryLease(shardIndex,revision){return(await this.deliveryRegistry()).update(leaseKey(shardIndex),this.encodeLease(shardIndex,true),revision)}async releaseDeliveryLease(shardIndex,revision){if(revision===void 0)return;await(await this.deliveryRegistry()).delete(leaseKey(shardIndex),{previousSeq:revision})}async readDeliveryLease(shardIndex){return(await this.readDeliveryLeaseEntry(shardIndex))?.info}async watchDeliveryLease(shardIndex,onEvent){this.leaseWatchIntent={shardIndex,onEvent};await this.bindDeliveryLeaseWatch();return()=>{if(this.leaseWatchIntent?.onEvent!==onEvent)return;this.leaseWatchIntent=void 0;this.stopDeliveryLeaseWatch()}}stopDeliveryLeaseWatch(){if(this.leaseWatchIter)this.retireDeliveryLeaseWatch(this.leaseWatchIter);this.leaseWatchIter=void 0}retireDeliveryLeaseWatch(iter){try{iter.stop()}catch{}if(!this.nc||this.nc.isClosed())return;const deleting=this.deps.deleteWatchConsumer(iter).catch(e3=>this.emitRecoverable(new Error(`a retired delivery lease watch consumer was not deleted (${e3.message}); the broker reaps it at its inactive threshold`)));this.leaseWatchDeletes.add(deleting);void deleting.then(()=>this.leaseWatchDeletes.delete(deleting))}async settleDeliveryLeaseWatches(){await Promise.allSettled(this.leaseWatchBinds);await Promise.all(this.leaseWatchDeletes)}bindDeliveryLeaseWatch(){const binding=this.bindDeliveryLeaseWatchOnce();const settled=()=>{this.leaseWatchBinds.delete(binding)};this.leaseWatchBinds.add(binding);void binding.then(settled,settled);return binding}async bindDeliveryLeaseWatchOnce(){const intent=this.leaseWatchIntent;const epoch=this.presenceEpoch;const iter=await(await this.deliveryRegistry()).watch({key:leaseKey(intent.shardIndex)});if(this.leaseWatchIntent!==intent||epoch!==this.presenceEpoch){this.retireDeliveryLeaseWatch(iter);return}this.leaseWatchIter=iter;void(async()=>{for await(const e3 of iter){if(this.leaseWatchIter!==iter)break;if(e3.operation==="DEL"||e3.operation==="PURGE"){intent.onEvent(void 0);continue}try{intent.onEvent(e3.json())}catch{intent.onEvent(void 0)}}})().catch(e3=>this.emit("error",e3))}async deliveryLeaseHolder(shardIndex){try{return(await this.readDeliveryLeaseEntry(shardIndex))?.info.holder}catch{return void 0}}async readDeliveryLeaseEntry(shardIndex){const e3=await(await this.deliveryRegistry()).get(leaseKey(shardIndex));if(!e3||e3.operation==="DEL"||e3.operation==="PURGE")return void 0;try{return{info:e3.json(),revision:e3.revision}}catch(err3){throw new Error(`delivery lease row "${leaseKey(shardIndex)}" exists but does not parse as a lease record (${err3.message}) - it is unreadable, not absent`)}}}}});function anycastRecordKey(epoch,seq){return`r.${epoch.replace(/[^0-9A-Za-z]/g,"")}.${seq}`}function isAnycastSeq(seq){return typeof seq==="number"&&Number.isSafeInteger(seq)&&seq>0}function holderOf(t2){return{id:t2.id,name:t2.name}}function shownHolderName(name2,id2){const ident=id2.trim()?id2:"(unnamed)";return name2.trim()?name2:ident}function holderText(h3){const ident=h3.id.trim()?h3.id:"(unnamed)";return h3.name.trim()?`${h3.name} (${ident})`:ident}function noticeEvent(row,notice){const{taker,previous,role,seq}=notice;const text3=notice.event==="taken"?`${holderText(taker)} took your @${role} request (seq ${seq}).`:`${holderText(previous)} did not confirm your @${role} request (seq ${seq}) before its ack wait ran out, and ${holderText(taker)} took it. ${shownHolderName(previous.name,previous.id)} may already have started it.`;return{key:`anycast.${anycastRecordKey(row.epoch,row.seq).slice(2)}.${row.rev}`,text:text3,notice}}function decideTake(row,stored,t2){const taker={...holderOf(t2.holder),count:t2.count,at:t2.now};if(!row){const next={v:1,epoch:t2.epoch,seq:t2.seq,id:stored.id,role:stored.role,sender:stored.sender,rev:1,state:"taken",taker,outbox:[]};next.outbox.push(noticeEvent(next,{seq:t2.seq,role:stored.role,event:"taken",taker:holderOf(taker)}));return{reply:{ok:true},next}}if(row.state==="cancelled")return{reply:{ok:false,code:"cancelled",error:`request seq ${t2.seq} was cancelled by its sender`}};const current=row.taker;if(current.id===t2.holder.id&¤t.count===t2.count)return{reply:{ok:true}};if(t2.count>current.count){const moved=current.id!==t2.holder.id;const next={...row,rev:row.rev+1,taker,previous:moved?{...holderOf(current),count:current.count}:row.previous,outbox:[...row.outbox]};if(moved)next.outbox.push(noticeEvent(next,{seq:t2.seq,role:row.role,event:"redelivered",taker:holderOf(taker),previous:holderOf(current)}));return{reply:{ok:true},next}}return{reply:{ok:false,code:"taken",error:`request seq ${t2.seq} was taken by ${holderText(current)} on delivery ${current.count}`}}}function statusFor(row,stored,q2){if(row){if(row.sender!==q2.caller||q2.id!==void 0&&row.id!==q2.id)return{state:"unknown",seq:q2.seq};if(row.state==="cancelled")return{state:"cancelled",seq:q2.seq,role:row.role,removal:row.removal??"pending"};const taker=row.taker;return{state:"taken",seq:q2.seq,role:row.role,taker:holderOf(taker),at:taker.at,...row.previous?{previous:holderOf(row.previous)}:{}}}if(!stored||stored.sender!==q2.caller||q2.id!==void 0&&stored.id!==q2.id)return{state:"unknown",seq:q2.seq};return{state:"waiting",seq:q2.seq,role:stored.role}}function decideCancel(row,stored,q2){const status2=statusFor(row,stored,q2);if(status2.state!=="waiting")return{status:status2};const s3=stored;return{status:{state:"cancelled",seq:q2.seq,role:s3.role,removal:"pending"},next:{v:1,epoch:q2.epoch,seq:q2.seq,id:s3.id,role:s3.role,sender:s3.sender,rev:1,state:"cancelled",removal:"pending",outbox:[]}}}function storedRequest(subject,data){const parsed=parseSubject(subject);if(!parsed||parsed.kind!=="svc")return void 0;let id2;try{id2=JSON.parse(new TextDecoder().decode(data)).id}catch{return void 0}if(typeof id2!=="string")return void 0;return{role:parsed.rest,sender:parsed.sender,id:id2}}function isNoMessageFound(e3){return e3?.code===10043||/no message found/i.test(String(e3?.message??""))}function readRow(e3){if(!e3||e3.operation!=="PUT")return void 0;const row=e3.json();if(row?.v!==1||typeof row.epoch!=="string"||!isAnycastSeq(row.seq)||!Array.isArray(row.outbox))throw new Error(`anycast record ${e3.key} is not a version-1 record`);return row}var ANYCAST_RECORD_RETENTION_MS,ANYCAST_STATUS_OP,ANYCAST_CANCEL_OP,ANYCAST_TAKES_OP,ANYCAST_RECORDS_CREDENTIAL_OUTDATED,ANYCAST_NOTICE_KEY,encoder,AnycastRequestAuthority;var init_anycast_requests=__esm({"../../packages/core/dist/anycast-requests.js"(){"use strict";init_endpoint_records();init_subjects();ANYCAST_RECORD_RETENTION_MS=24*60*60*1e3;ANYCAST_STATUS_OP="anycastStatus";ANYCAST_CANCEL_OP="anycastCancel";ANYCAST_TAKES_OP="anycastTakes";ANYCAST_RECORDS_CREDENTIAL_OUTDATED="this delivery daemon's credential was minted before anycast request records existed, so it records no takes and answers no status or cancel; restart the daemon on a credential minted at this version (`cotal up` mints one)";ANYCAST_NOTICE_KEY="cotalAnycastNotice";encoder=new TextEncoder;AnycastRequestAuthority=class{deps;flushing=new Map;constructor(deps){this.deps=deps}now(){return this.deps.now?.()??Date.now()}async queued(seq){for(let attempt=0;attempt<3;attempt++){const before=(await this.deps.jsm.streams.info(this.deps.stream)).created;const sm=await this.deps.jsm.streams.getMessage(this.deps.stream,{seq});const after=(await this.deps.jsm.streams.info(this.deps.stream)).created;if(before!==after)continue;return{epoch:before,stored:sm?storedRequest(sm.subject,sm.data):void 0}}throw new Error(`the ${this.deps.stream} stream was recreated during the read; retry`)}async take(role,req){for(let attempt=0;attempt<5;attempt++){const{epoch,stored}=await this.queued(req.seq);if(req.epoch!==epoch)return{ok:false,code:"mismatch",error:`the copy of seq ${req.seq} came from a ${this.deps.stream} stream that has since been recreated`};if(!stored){const row=readRow(await this.deps.kv.get(anycastRecordKey(epoch,req.seq)));if(row?.state==="cancelled"&&row.id===req.id)return{ok:false,code:"cancelled",error:`request seq ${req.seq} was cancelled by its sender`};return{ok:false,code:"gone",error:`request seq ${req.seq} is no longer on the queue`}}if(stored.role!==role||stored.id!==req.id)return{ok:false,code:"mismatch",error:`seq ${req.seq} on the queue is not the @${role} request ${req.id}`};const key=anycastRecordKey(epoch,req.seq);const entry=await this.deps.kv.get(key);const{reply,next}=decideTake(readRow(entry),stored,{epoch,seq:req.seq,holder:req.from,count:req.count,now:this.now()});if(!next)return reply;if(!this.deps.mayAct())return{ok:false,code:"busy",error:"the delivery daemon stopped serving while the take was in flight; retry"};if(!await this.write(key,next,entry))continue;if(next.outbox.length)this.flushSoon(key);return reply}return{ok:false,code:"busy",error:`request seq ${req.seq} changed under five takes in a row; retry`}}async status(caller,q2){const{epoch,stored}=await this.queued(q2.seq);const row=readRow(await this.deps.kv.get(anycastRecordKey(epoch,q2.seq)));return statusFor(row,stored,{...q2,caller})}async cancel(caller,q2){for(let attempt=0;attempt<5;attempt++){const{epoch,stored}=await this.queued(q2.seq);const key=anycastRecordKey(epoch,q2.seq);const entry=await this.deps.kv.get(key);const row=readRow(entry);const{status:status2,next}=decideCancel(row,stored,{...q2,epoch,caller,now:this.now()});if(!next){if(status2.state==="cancelled"&&status2.removal==="pending")return this.remove(key);return status2}if(!this.deps.mayAct())throw new Error("the delivery daemon stopped serving while the cancel was in flight; retry");if(!await this.write(key,next,entry))continue;return this.remove(key)}throw new Error(`request seq ${q2.seq} changed under five cancels in a row; retry`)}async remove(key){let removal;for(let attempt=0;attempt<5;attempt++){const entry=await this.deps.kv.get(key);const row=readRow(entry);if(!row||row.state!=="cancelled")throw new Error(`anycast record ${key} is not a cancelled request`);if(row.removal!=="pending")return{state:"cancelled",seq:row.seq,role:row.role,removal:row.removal??"pending"};if(removal===void 0){const epoch=(await this.deps.jsm.streams.info(this.deps.stream)).created;if(epoch!==row.epoch)removal="already-gone";else{if(!this.deps.mayAct())return{state:"cancelled",seq:row.seq,role:row.role,removal:"pending"};try{await this.deps.jsm.streams.deleteMessage(this.deps.stream,row.seq,false);removal="deleted"}catch(e3){if(!isNoMessageFound(e3))throw e3;removal="already-gone"}}}if(await this.write(key,{...row,removal},entry))return{state:"cancelled",seq:row.seq,role:row.role,removal}}throw new Error(`anycast record ${key} changed under five writes in a row; retry`)}async write(key,row,entry){try{const bytes=encoder.encode(JSON.stringify(row));if(entry&&entry.operation==="PUT")await this.deps.kv.update(key,bytes,entry.revision);else await this.deps.kv.create(key,bytes);return true}catch(e3){if(isCasLoss(e3))return false;throw e3}}flushSoon(key){void this.flush(key).catch(e3=>this.deps.onError(e3))}flush(key){const prior=this.flushing.get(key)??Promise.resolve();const run=prior.then(async()=>{for(let attempt=0;attempt<16;attempt++){if(!this.deps.mayAct())return;const entry=await this.deps.kv.get(key);const row=readRow(entry);const event=row?.outbox[0];if(!row||!event)return;await this.deps.send(row.sender,event);await this.write(key,{...row,outbox:row.outbox.filter(e3=>e3.key!==event.key)},entry)}});const settled=run.finally(()=>{if(this.flushing.get(key)===settled)this.flushing.delete(key)});this.flushing.set(key,settled);return settled}async sweep(){if((await this.deps.kv.status()).values===0)return;const keys=[];for await(const k2 of await this.deps.kv.keys("r.>"))keys.push(k2);for(const key of keys){if(!this.deps.mayAct())return;try{await this.maintain(key)}catch(e3){this.deps.onError(e3)}}}async maintain(key){let row=readRow(await this.deps.kv.get(key));if(!row)return;if(row.outbox.length)await this.flush(key);if(row.state==="cancelled"&&row.removal==="pending")await this.remove(key);const entry=await this.deps.kv.get(key);row=readRow(entry);if(!row||!this.deps.mayAct())return;if(row.leftAt===void 0){const{epoch,stored}=await this.queued(row.seq);if(epoch===row.epoch&&stored?.id===row.id)return;await this.write(key,{...row,leftAt:this.now()},entry)}else if(this.now()-row.leftAt>ANYCAST_RECORD_RETENTION_MS&&!row.outbox.length){try{await this.deps.kv.delete(key,{previousSeq:entry.revision})}catch(e3){if(!isCasLoss(e3))throw e3}}}}}});function isArtifactPart(value){if(!value||typeof value!=="object")return false;const p2=value;return p2.kind===ARTIFACT_PART_KIND&&typeof p2.name==="string"&&p2.name.length>0&&typeof p2.mediaType==="string"&&p2.mediaType.length>0&&typeof p2.digest==="string"&&isContractDigest(p2.digest)&&typeof p2.size==="number"&&Number.isSafeInteger(p2.size)&&p2.size>=0}var ARTIFACT_PART_KIND;var init_artifact=__esm({"../../packages/core/dist/artifact.js"(){"use strict";init_canonical();ARTIFACT_PART_KIND="artifact"}});function principalFromDurable(name2,prefix){if(!name2.startsWith(prefix))return void 0;const match=/^([A-Za-z0-9_]+)-([A-Za-z0-9_]+)-([a-z0-9]+)$/.exec(name2.slice(prefix.length));return match?{owner:match[1],actor:match[2],lifecycleUid:match[3]}:void 0}function expectedConsumerConfig(space2,stream,name2){if(stream===chatStream(space2)&&name2===FANOUT_DURABLE)return fanoutDurableConfig(space2);if(stream===inboxStream(space2)&&name2===INBOX_READER_DURABLE)return inboxReaderConfig(space2);if(stream===dmStream(space2)){const principal=principalFromDurable(name2,"dm_");if(principal)return dmDurableConfig(space2,principal.owner,principal.actor,principal.lifecycleUid)}if(stream===dlvStream(space2)){const principal=principalFromDurable(name2,"dlv_");if(principal)return dlvDurableConfig(space2,principal.owner,principal.actor,principal.lifecycleUid)}if(stream===taskStream(space2)&&/^svc_[A-Za-z0-9_-]+$/.test(name2))return{...taskDurableConfig(space2,name2.slice("svc_".length)),deliver_policy:import_jetstream12.DeliverPolicy.All};throw new Error(`unsupported persistent consumer ${stream}/${name2}`)}function validatePersistentConsumer(space2,stream,info){validatePullConsumerReadConfig(stream,info,expectedConsumerConfig(space2,stream,info.name),{allowStartSequence:stream!==taskStream(space2),allowImplicitAll:stream===taskStream(space2)})}function validatePullConsumerReadConfig(stream,info,expected,options={}){if(expected.durable_name!==info.name)throw new Error(`${stream}/${info.name} is not the expected durable`);const config2=info.config;const unknown2=Object.keys(config2).filter(key=>!CONSUMER_KEYS.has(key));if(unknown2.length)throw new Error(`${stream}/${info.name} has unsupported consumer fields: ${unknown2.sort().join(", ")}`);if(config2.name!==void 0&&config2.name!==info.name)throw new Error(`${stream}/${info.name} has a mismatched name`);if(config2.durable_name!==info.name)throw new Error(`${stream}/${info.name} is not a canonical durable`);if(config2.deliver_subject||config2.deliver_group)throw new Error(`${stream}/${info.name} is a push consumer`);if(config2.filter_subject!==expected.filter_subject||(config2.filter_subjects?.length??0)!==0)throw new Error(`${stream}/${info.name} has a noncanonical filter`);if(config2.ack_policy!==import_jetstream12.AckPolicy.Explicit||config2.ack_wait!==expected.ack_wait)throw new Error(`${stream}/${info.name} has noncanonical ACK settings`);const migrated=options.allowStartSequence===true&&config2.deliver_policy===import_jetstream12.DeliverPolicy.StartSequence;const implicitTaskAll=options.allowImplicitAll===true&&expected.deliver_policy===import_jetstream12.DeliverPolicy.All&&config2.deliver_policy===void 0;if(config2.deliver_policy!==expected.deliver_policy&&!migrated&&!implicitTaskAll)throw new Error(`${stream}/${info.name} has a noncanonical delivery policy`);if(migrated){if(!Number.isSafeInteger(config2.opt_start_seq)||(config2.opt_start_seq??0)<1)throw new Error(`${stream}/${info.name} has an invalid creation lower bound`)}else if(config2.opt_start_seq!==void 0||config2.opt_start_time!==void 0){throw new Error(`${stream}/${info.name} has an unexpected start bound`)}const expectedMaxAck=expected.max_ack_pending??1e3;if((config2.max_ack_pending??1e3)!==expectedMaxAck)throw new Error(`${stream}/${info.name} has noncanonical max_ack_pending`);if((config2.max_deliver??-1)!==-1||(config2.max_waiting??512)!==512)throw new Error(`${stream}/${info.name} has noncanonical delivery limits`);if((config2.replay_policy??import_jetstream12.ReplayPolicy.Instant)!==import_jetstream12.ReplayPolicy.Instant||(config2.num_replicas??0)!==0)throw new Error(`${stream}/${info.name} has noncanonical replay/replica settings`);for(const key of["backoff","description","flow_control","headers_only","idle_heartbeat","inactive_threshold","max_batch","max_bytes","max_expires","mem_storage","metadata","pause_until","priority_groups","priority_policy","priority_timeout","rate_limit_bps","sample_freq"]){const value=config2[key];if(key==="metadata"&&value&&typeof value==="object"&&!Array.isArray(value)&&Object.entries(value).every(([metadataKey,metadataValue])=>metadataKey.startsWith("_nats.")&&typeof metadataValue==="string"))continue;if(value!==void 0&&value!==false&&value!==0&&value!==""&&!(Array.isArray(value)&&value.length===0)&&!(typeof value==="object"&&value!==null&&Object.keys(value).length===0))throw new Error(`${stream}/${info.name} has active unsupported setting ${key}`)}}function isRestoredConsumer(space2,stream,info,wanted){if(info.name!==wanted.durable_name||info.config.deliver_policy!==import_jetstream12.DeliverPolicy.StartSequence||info.config.ack_wait!==wanted.ack_wait)return false;try{validatePersistentConsumer(space2,stream,info)}catch{return false}return true}var import_jetstream12,import_transport_node12,DEFAULT_TRANSFER_TIMEOUT_MS,CONSUMER_KEYS;var init_backup=__esm({"../../packages/core/dist/backup.js"(){"use strict";import_jetstream12=__toESM(require_mod4(),1);import_transport_node12=__toESM(require_transport_node(),1);init_backup_config();init_deadline();init_endpoint_binding();init_streams();init_subjects();DEFAULT_TRANSFER_TIMEOUT_MS=5*60*1e3;CONSUMER_KEYS=new Set(["ack_policy","ack_wait","backoff","deliver_group","deliver_policy","deliver_subject","description","durable_name","filter_subject","filter_subjects","flow_control","headers_only","idle_heartbeat","inactive_threshold","max_ack_pending","max_batch","max_bytes","max_deliver","max_expires","max_waiting","mem_storage","metadata","name","num_replicas","opt_start_seq","opt_start_time","pause_until","priority_groups","priority_policy","priority_timeout","rate_limit_bps","replay_policy","sample_freq"])}});function authenticatedChannelMessage(msg,channel){if(msg.channel===channel&&msg.to===void 0&&msg.toService===void 0)return msg;const{to:_to,toService:_toService,...base}=msg;return{...base,channel}}async function ackWaitOf(consumer){const{config:config2}=await consumer.info(true);if(config2.ack_wait===void 0)throw new Error(`consumer ${config2.durable_name} reports no ack wait`);return(0,import_transport_node13.millis)(config2.ack_wait)}function durableDelivery(m2,ackWaitMs){return{ack:()=>m2.ack(),nak:()=>m2.nak(),durable:true,redelivery:{deliveryCount:m2.info.deliveryCount,ackWaitMs,working:()=>m2.working()}}}function isRecord(value){return!!value&&typeof value==="object"&&!Array.isArray(value)}var import_transport_node13;var init_endpoint_inbound=__esm({"../../packages/core/dist/endpoint-inbound.js"(){"use strict";import_transport_node13=__toESM(require_transport_node(),1)}});function isPlane3DeliveryFrame(value){if(!isRecord(value))return false;const keys=Object.keys(value);if(keys.length!==3||!keys.includes("version")||!keys.includes("channel")||!keys.includes("msg"))return false;if(value.version!==1||typeof value.channel!=="string"||!isConcreteChannel(value.channel))return false;return isCotalMessage(value.msg)&&value.msg.channel===value.channel}function isCotalMessage(value){if(!isRecord(value))return false;const routes=["channel","to","toService"].filter(key=>key in value);if(routes.length!==1||typeof value[routes[0]]!=="string")return false;if(typeof value.id!=="string"||typeof value.ts!=="number"||!Number.isFinite(value.ts)||typeof value.space!=="string"||!isEndpointRef(value.from)||!Array.isArray(value.parts)||!value.parts.every(isMessagePart))return false;if(value.mentions!==void 0&&(!Array.isArray(value.mentions)||!value.mentions.every(name2=>typeof name2==="string")))return false;if(value.replyTo!==void 0&&typeof value.replyTo!=="string")return false;if(value.contextId!==void 0&&typeof value.contextId!=="string")return false;return true}function isEndpointRef(value){return isRecord(value)&&typeof value.id==="string"&&typeof value.name==="string"&&(value.role===void 0||typeof value.role==="string")}function isMessagePart(value){if(!isRecord(value)||typeof value.kind!=="string")return false;if(value.kind==="text")return typeof value.text==="string";if(value.kind==="data")return Object.prototype.hasOwnProperty.call(value,"data");if(value.kind===ARTIFACT_PART_KIND)return isArtifactPart(value);return/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/.test(value.kind)}var import_jetstream13,import_transport_node14,PLANE3_FRAME_HEADER,ANYCAST_CONTROL_OPS,DELIVERY_LIMIT_READ_MS,READER_MAX_REDELIVERIES,READ_HISTORY_DEFAULT_LIMIT,READ_HISTORY_MAX_LIMIT,EndpointDeliveryPlane;var init_endpoint_delivery_plane=__esm({"../../packages/core/dist/endpoint-delivery-plane.js"(){"use strict";init_acls();init_anycast_requests();init_artifact();init_backup_config();init_backup();init_endpoint_inbound();init_endpoint();init_evict();init_issued_authority();init_jetstream_missing();init_members();init_secret_store();init_streams();init_subjects();import_jetstream13=__toESM(require_mod4(),1);import_transport_node14=__toESM(require_transport_node(),1);PLANE3_FRAME_HEADER="Cotal-Delivery-Frame";ANYCAST_CONTROL_OPS=new Set([ANYCAST_STATUS_OP,ANYCAST_CANCEL_OP,ANYCAST_TAKES_OP]);DELIVERY_LIMIT_READ_MS=5e3;READER_MAX_REDELIVERIES=10;READ_HISTORY_DEFAULT_LIMIT=100;READ_HISTORY_MAX_LIMIT=200;EndpointDeliveryPlane=class{deps;deliveryServeSub;deliveryAdminServeSub;retiringLifecycles=new Map;membershipWrites=new Map;plane3Quiesced=false;plane3;deliveryLimitRead;aclForAlias;channelHistory;deliveryClassFresh;durableJoinFor;durableLeaveFor;ownerMemberships;ownsDeliveryLease;readDeliveryLease;readDeliveryLeaseEntry;reloadCreds;serveControl;aclRegistry;membersRegistry;armAnycastRequests;deliveryAnycast;dropAnycastRequests;manager;notLiveMsg;plane3MsgId;publishDinbox;resolveOwnerByName;scheduleResidentSwap;sendMentionNotice;emit;constructor(deps){this.deps=deps;this.aclForAlias=deps.aclForAlias;this.channelHistory=deps.channelHistory;this.deliveryClassFresh=deps.deliveryClassFresh;this.durableJoinFor=deps.durableJoinFor;this.durableLeaveFor=deps.durableLeaveFor;this.ownerMemberships=deps.ownerMemberships;this.ownsDeliveryLease=deps.ownsDeliveryLease;this.readDeliveryLease=deps.readDeliveryLease;this.readDeliveryLeaseEntry=deps.readDeliveryLeaseEntry;this.reloadCreds=deps.reloadCreds;this.serveControl=deps.serveControl;this.aclRegistry=deps.aclRegistry;this.membersRegistry=deps.membersRegistry;this.armAnycastRequests=deps.armAnycastRequests;this.deliveryAnycast=deps.deliveryAnycast;this.dropAnycastRequests=deps.dropAnycastRequests;this.manager=deps.manager;this.notLiveMsg=deps.notLiveMsg;this.plane3MsgId=deps.plane3MsgId;this.publishDinbox=deps.publishDinbox;this.resolveOwnerByName=deps.resolveOwnerByName;this.scheduleResidentSwap=deps.scheduleResidentSwap;this.sendMentionNotice=deps.sendMentionNotice;this.emit=deps.emit}get ackWaitMs(){return this.deps.ackWaitMs()}get actor(){return this.deps.actor()}get owner(){return this.deps.owner()}get allowSubscribe(){return this.deps.allowSubscribe()}get anycastUnavailable(){return this.deps.anycastUnavailable()}get card(){return this.deps.card()}get js(){return this.deps.js()}get jsm(){return this.deps.jsm()}get nc(){return this.deps.nc()}get ownLifecycleUid(){return this.deps.ownLifecycleUid()}get residentSwap(){return this.deps.residentSwap()}get space(){return this.deps.space()}get stopped(){return this.deps.stopped()}get streamMsgs(){return this.deps.streamMsgs()}get subs(){return this.deps.subs()}get userMode(){return this.deps.userMode()}get watchDeletePermissions(){return this.deps.watchDeletePermissions()}get maxPayload(){return this.deps.maxPayload()}async startPlane3(aclFor,opts={}){if(!this.js)throw new Error(this.notLiveMsg());this.plane3={aclFor,reloadMembershipCreds:opts.reloadMembershipCreds,evictPrincipal:opts.evictPrincipal,evictPrincipals:opts.evictPrincipals,planeConnLiveness:opts.planeConnLiveness,principalLiveness:opts.principalLiveness,reloadStoreIdentity:opts.reloadStoreIdentity,onDeliveryCredsAdopted:opts.onDeliveryCredsAdopted,startupComplete:opts.startupComplete};await this.armPlane3()}plane3MayAct(){return!this.plane3Quiesced}async handleDeliveryControl(req){if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon is not serving this shard (it is re-checking ownership); retry"};const caller=req.from.id;const args=req.args??{};if(req.op==="durableJoin")return this.deliveryJoin(caller,args);if(req.op==="durableLeave")return this.deliveryLeave(caller,args);if(req.op==="readHistory")return this.deliveryReadHistory(caller,args);if(req.op===ANYCAST_TAKES_OP)return this.anycastUnavailable?{ok:false,error:`delivery: ${this.anycastUnavailable}`}:{ok:true,data:{takes:true}};if(req.op===ANYCAST_STATUS_OP||req.op===ANYCAST_CANCEL_OP)return this.deliveryAnycast(req.op,caller,args);if(req.op==="listMemberships"){if(typeof args.lifecycleUid!=="string")return{ok:false,error:"listMemberships: the caller's lifecycleUid is required (membership rows are lifecycle-keyed, SPEC 13.1)"};let uid2;try{uid2=assertLifecycleToken(args.lifecycleUid)}catch(e3){return{ok:false,error:e3.message}}let memberships;if(args.channel!==void 0){const channel=this.checkDurableChannelArg(args,"listMemberships",{family:true});if(typeof channel!=="string")return channel;memberships=(await listMembers(await this.membersRegistry(),{owner:caller})).filter(r2=>r2.channel===channel&&r2.leaveCursor===void 0).map(r2=>({channel:r2.channel,generation:r2.generation,activated:r2.activated===true,lifecycleUid:r2.lifecycleUid}))}else{memberships=await this.ownerMemberships(caller,uid2)}if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon stopped serving this shard while the request was in flight; retry"};return{ok:true,data:{memberships}}}return{ok:false,error:`op "${req.op}" not supported on the delivery control service`}}checkDurableChannelArg(args,op,opts={}){const channel=typeof args.channel==="string"?args.channel.trim():"";if(!channel)return{ok:false,error:`${op}: channel must be a non-blank string`};try{assertValidChannel(channel)}catch(e3){return{ok:false,error:e3.message}}if(opts.family&&isChannelFamily(channel))return channel;if(!isConcreteChannel(channel))return{ok:false,error:opts.family?`${op}: "${channel}" stays live only: a durable membership takes a concrete channel or a family such as review.>, never the root > or a pattern with *`:`${op}: "${channel}" must be a concrete channel (durable membership is per-concrete-channel, not wildcard)`};return channel}async deliveryJoin(caller,args){const channel=this.checkDurableChannelArg(args,"durableJoin",{family:true});if(typeof channel!=="string")return channel;let acl;try{acl=await this.aclForAlias(caller)}catch(e3){return{ok:false,error:e3.message}}if(acl===void 0)return{ok:false,error:`durableJoin: no read ACL on record for ${caller} (not provisioned for durable delivery)`};if(!membershipInAllow(acl.allowSubscribe,channel))return{ok:false,error:`channel "${channel}" is not within your read ACL [${acl.allowSubscribe.join(", ")}]`};const uid2=acl.lifecycleUid;try{return{ok:true,data:await this.membershipWrite(caller,uid2,()=>this.durableJoinFor(caller,channel,uid2,{aclFence:true}))}}catch(e3){return{ok:false,error:e3.message}}}async lifecycleAclUnfenced(principal,lifecycleUid){try{const row=await readAcl(await this.aclRegistry(),principal,lifecycleUid);return row!==void 0&&row.record.allowSubscribe.length>0}catch{return true}}async membershipWrite(principal,lifecycleUid,write){if(this.retiringLifecycles.get(principal)?.has(lifecycleUid))throw new Error(`lifecycle ${lifecycleUid} of ${principal} is retiring: its membership inventory was requested, so its durable memberships no longer change`);const key=`${principal}/${lifecycleUid}`;const running=write();let writes=this.membershipWrites.get(key);if(writes===void 0)this.membershipWrites.set(key,writes=new Set);writes.add(running);try{return await running}finally{writes.delete(running);if(writes.size===0)this.membershipWrites.delete(key)}}async deliveryLeave(caller,args){const channel=this.checkDurableChannelArg(args,"durableLeave",{family:true});if(typeof channel!=="string")return channel;if(typeof args.generation!=="number"||!Number.isFinite(args.generation))return{ok:false,error:"durableLeave: a finite generation is required (fail-closed stale-leave guard)"};if(typeof args.lifecycleUid!=="string")return{ok:false,error:"durableLeave: the leaving incarnation's lifecycleUid is required (membership rows are lifecycle-keyed, SPEC 13.1)"};let uid2;try{uid2=assertLifecycleToken(args.lifecycleUid)}catch(e3){return{ok:false,error:e3.message}}const existing=await readMember(await this.membersRegistry(),channel,caller,uid2);if(!existing)return{ok:true,data:{channel,alreadyLeft:true}};const generation=args.generation;try{await this.membershipWrite(caller,uid2,()=>this.durableLeaveFor(caller,channel,uid2,generation))}catch(e3){return{ok:false,error:e3.message}}return{ok:true,data:{channel}}}async deliveryReadHistory(caller,args){const channel=this.checkDurableChannelArg(args,"readHistory");if(typeof channel!=="string")return channel;const asked=args.limit===void 0?READ_HISTORY_DEFAULT_LIMIT:args.limit;if(typeof asked!=="number"||!Number.isInteger(asked)||asked<1)return{ok:false,error:`readHistory: limit must be a positive integer (got ${JSON.stringify(args.limit)})`};const limit=Math.min(asked,READ_HISTORY_MAX_LIMIT);let acl;try{acl=await this.aclForAlias(caller)}catch(e3){return{ok:false,error:e3.message}}if(acl===void 0)return{ok:false,error:`readHistory: no read ACL on record for ${caller} - not permitted`};const inLive=channelInAllow(acl.allowSubscribe,channel);const inIssued=channelInAllow(acl.issuedAllowSubscribe,channel);if(!inLive||!inIssued){return{ok:false,error:`readHistory: channel "${channel}" is not within your read ACL [${acl.allowSubscribe.join(", ")}] - refused`}}let page;try{page=await this.channelHistory(channel,{limit:limit+1})}catch(e3){return{ok:false,error:`readHistory: ${e3.message}`}}const reachedStart=page.length<=limit;const wanted=reachedStart?page:page.slice(-limit);const fitted=fitHistoryPage(wanted,this.maxPayload);if(wanted.length>0&&fitted.length===0)return{ok:false,error:`readHistory: the newest message on "${channel}" alone exceeds the broker payload budget (${this.maxPayload} bytes) - refused loudly rather than served as an empty page`};return{ok:true,data:{items:fitted,complete:reachedStart&&fitted.length===wanted.length}}}async quiescePlane3(){this.plane3Quiesced=true;if(this.deliveryServeSub){try{this.deliveryServeSub.unsubscribe()}catch{}this.deliveryServeSub=void 0}if(this.deliveryAdminServeSub){try{this.deliveryAdminServeSub.unsubscribe()}catch{}this.deliveryAdminServeSub=void 0}this.dropAnycastRequests();for(const msgs of this.streamMsgs.splice(0)){try{msgs.stop()}catch{}}}plane3IsQuiesced(){return this.plane3Quiesced}async rearmPlane3(){if(!this.plane3Quiesced)return;this.plane3Quiesced=false;try{await this.armPlane3()}catch(e3){this.plane3Quiesced=true;this.quiescePlane3();throw e3}}async armPlane3(){if(!this.plane3||!this.js)return;if(this.plane3Quiesced)return;await this.manager();this.armDeliveryControl();await this.armAnycastRequests();await this.runFanout();await this.runReader()}armDeliveryControl(){if(this.deliveryServeSub){try{this.deliveryServeSub.unsubscribe()}catch{}const i2=this.subs.indexOf(this.deliveryServeSub);if(i2>=0)this.subs.splice(i2,1)}this.deliveryServeSub=this.serveControl(CONTROL_DELIVERY,req=>this.handleDeliveryControl(req),{boundReply:true,concurrent:req=>ANYCAST_CONTROL_OPS.has(req.op)});if(this.deliveryAdminServeSub){try{this.deliveryAdminServeSub.unsubscribe()}catch{}const i2=this.subs.indexOf(this.deliveryAdminServeSub);if(i2>=0)this.subs.splice(i2,1)}this.deliveryAdminServeSub=this.serveControl(CONTROL_DELIVERY_ADMIN,req=>this.handleDeliveryAdmin(req),{boundReply:true,concurrent:req=>req.op==="lifecycleMemberships"})}async handleDeliveryAdmin(req){await this.residentSwap;if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon is not serving this shard (it is re-checking ownership); retry"};if(req.op==="reloadCreds"){if(this.plane3?.startupComplete?.()===false)return{ok:false,error:"delivery: this daemon has not finished starting; nothing adopted - the next renewal pass or the daemon's 75% re-read adopts the re-signed creds"};const expected=req.args?.expected??{};const[delivery,membership]=await Promise.all([this.reloadCreds(expected.delivery).then(brokerAccepted=>({ok:true,brokerAccepted,residentSwap:"scheduled"}),e3=>({ok:false,error:e3.message})),this.plane3?.reloadMembershipCreds?this.plane3.reloadMembershipCreds(expected.membership).then(result=>({ok:true,...result}),e3=>({ok:false,error:e3.message})):Promise.resolve({ok:true,skipped:"no-membership-hook"})]);const failures=[delivery.ok?void 0:`delivery: ${delivery.error}`,membership.ok?void 0:`membership: ${membership.error}`].filter(m2=>m2!==void 0);if(delivery.ok){this.plane3?.onDeliveryCredsAdopted?.();this.scheduleResidentSwap()}return failures.length?{ok:false,error:failures.join("; "),data:{delivery,membership}}:{ok:true,data:{delivery,membership}}}if(req.op==="evictPrincipal"){if(!this.plane3?.evictPrincipal)return{ok:false,error:"evictPrincipal: no eviction executor wired on this daemon"};const principal=typeof req.args?.principal==="string"?req.args.principal.trim():"";if(!principal)return{ok:false,error:"evictPrincipal: a principal (owner.actor dot-form) is required"};try{return{ok:true,data:await this.plane3.evictPrincipal(principal)}}catch(e3){return{ok:false,error:e3.message}}}if(req.op==="evictPrincipals"){if(!this.plane3?.evictPrincipals)return{ok:false,error:"evictPrincipals: no batch eviction executor wired on this daemon"};const raw=req.args?.principals;const principals=Array.isArray(raw)?raw.map(p2=>typeof p2==="string"?p2.trim():""):[];if(principals.length===0||principals.some(p2=>!p2))return{ok:false,error:"evictPrincipals: principals must be a non-empty array of owner.actor dot-form principals"};if(principals.length>EVICT_PRINCIPALS_MAX||new Set(principals).size!==principals.length)return{ok:false,error:`evictPrincipals: principals must be distinct and at most ${EVICT_PRINCIPALS_MAX}`};try{return{ok:true,data:await this.plane3.evictPrincipals(principals)}}catch(e3){return{ok:false,error:e3.message}}}if(req.op==="planeConnLiveness"){if(!this.plane3?.planeConnLiveness)return{ok:false,error:"planeConnLiveness: no plane-liveness oracle wired on this daemon"};try{return{ok:true,data:await this.plane3.planeConnLiveness(req.args?.query)}}catch(e3){return{ok:false,error:e3.message}}}if(req.op==="lifecycleMemberships"){const principal=typeof req.args?.principal==="string"?req.args.principal.trim():"";const uid2=typeof req.args?.lifecycleUid==="string"?req.args.lifecycleUid:"";if(!parsePrincipalKey(principal))return{ok:false,error:"lifecycleMemberships: a principal (owner.actor dot-form) is required"};try{assertLifecycleToken(uid2)}catch(e3){return{ok:false,error:`lifecycleMemberships: ${e3.message}`}}let marked=this.retiringLifecycles.get(principal);if(marked===void 0)this.retiringLifecycles.set(principal,marked=new Set);for(const earlier of[...marked])if(earlier!==uid2&&await aclRetired(await this.aclRegistry(),principal,earlier).catch(()=>false))marked.delete(earlier);if(await this.lifecycleAclUnfenced(principal,uid2))marked.add(uid2);else if(marked.size===0)this.retiringLifecycles.delete(principal);await Promise.allSettled(this.membershipWrites.get(`${principal}/${uid2}`)??[]);try{const channels=await listLifecycleMemberChannels(await this.membersRegistry(),principal,uid2);return{ok:true,data:{complete:true,channels}}}catch(e3){return{ok:false,error:`lifecycleMemberships: the inventory read did not complete (${e3.message})`}}}if(req.op==="principalLiveness"){if(!this.plane3?.principalLiveness)return{ok:false,error:"principalLiveness: no liveness oracle wired on this daemon"};const principal=typeof req.args?.principal==="string"?req.args.principal.trim():"";if(!principal)return{ok:false,error:"principalLiveness: a principal (owner.actor dot-form) is required"};try{return{ok:true,data:await this.plane3.principalLiveness(principal)}}catch(e3){return{ok:false,error:e3.message}}}if(req.op==="reloadStoreIdentity"){if(!this.plane3?.reloadStoreIdentity)return{ok:false,error:"reloadStoreIdentity: this daemon did not name the SecretStore it reloads from"};try{const identity=this.plane3.reloadStoreIdentity();let holdsDeliveryLease=false;try{const own=await this.readDeliveryLeaseEntry(0);holdsDeliveryLease=own!==void 0&&this.ownsDeliveryLease(own.info)}catch{holdsDeliveryLease=false}return{ok:true,data:{identity:parseSecretStoreIdentity(identity),responder:this.card.id,holdsDeliveryLease}}}catch(e3){return{ok:false,error:e3.message}}}return{ok:false,error:`op "${req.op}" not supported on the delivery admin service`}}async addPlane3Durable(stream,config2){try{await this.jsm.consumers.add(stream,config2)}catch(e3){if(!isConsumerAlreadyExists(e3)||!isRestoredConsumer(this.space,stream,await this.jsm.consumers.info(stream,config2.durable_name),config2))throw e3}}async runFanout(){if(!this.js||!this.jsm)return;await this.addPlane3Durable(chatStream(this.space),fanoutDurableConfig(this.space,{ackWaitMs:this.ackWaitMs}));const consumer=await this.js.consumers.get(chatStream(this.space),FANOUT_DURABLE);const msgs=await consumer.consume();this.streamMsgs.push(msgs);void(async()=>{for await(const m2 of msgs){try{await this.fanOutMessage(m2)}catch(e3){if(!this.stopped)this.emit("error",e3);try{m2.nak()}catch{}}}})().catch(e3=>{if(!this.stopped)this.emit("error",e3)})}async fanOutMessage(m2){if(!this.plane3MayAct())return;const parsed=parseSubject(m2.subject);if(!parsed||parsed.kind!=="chat"){m2.ack();return}const channel=parsed.rest;let msg;try{msg=m2.json()}catch{m2.ack();return}if(!isFromSubjectSender(msg,parsed)){m2.ack();return}const seq=m2.seq;const normalizedMsg=authenticatedChannelMessage(msg,channel);if(!this.plane3MayAct())return;const durable=await this.deliveryClassFresh(channel)==="durable";const mentioned=[];for(const name2 of msg.mentions??[]){const owner2=this.resolveOwnerByName(name2);if(!owner2||owner2===msg.from.id)continue;let row;try{row=await this.aclForAlias(owner2)}catch(e3){this.emit("error",e3);continue}if(row)mentioned.push({name:name2,owner:owner2,row})}if(durable){for(const rec of await listMembers(await this.membersRegistry(),{covering:channel})){if(rec.owner===msg.from.id)continue;if(!durableEligible(rec,seq))continue;if(!this.plane3MayAct())return;await this.publishDinbox(rec.owner,rec.lifecycleUid,{msg:normalizedMsg,channel,seq,reason:"durable-channel",generation:rec.generation,...rec.channel!==channel?{row:rec.channel}:{}})}}else{for(const{owner:owner2,row}of mentioned){if(!channelInAllow(row.allowSubscribe,channel))continue;if(!this.plane3MayAct())return;await this.publishDinbox(owner2,row.lifecycleUid,{msg:normalizedMsg,channel,seq,reason:"live-mention",generation:0})}}const unreadable=mentioned.filter(({row})=>!channelInAllow(row.allowSubscribe,channel)).map(({name:name2})=>name2);if(unreadable.length){if(!this.plane3MayAct())return;await this.sendMentionNotice(msg,channel,seq,unreadable)}if(!this.plane3MayAct())return;m2.ack()}async deliveryLimitStamp(){const at2=Date.now();if(this.deliveryLimitRead&&at2-this.deliveryLimitRead.at<DELIVERY_LIMIT_READ_MS)return this.deliveryLimitRead.stamp;const count=(await this.jsm.streams.info(dlvStream(this.space))).config.max_msgs_per_subject;const stamp2=count===HISTORY_NO_COUNT||count<1?"none":String(count);this.deliveryLimitRead={at:at2,stamp:stamp2};return stamp2}async runReader(){if(!this.js||!this.jsm)return;await this.addPlane3Durable(inboxStream(this.space),inboxReaderConfig(this.space,{ackWaitMs:this.ackWaitMs}));const consumer=await this.js.consumers.get(inboxStream(this.space),INBOX_READER_DURABLE);const msgs=await consumer.consume();this.streamMsgs.push(msgs);void(async()=>{for await(const m2 of msgs){try{await this.readerHandle(m2)}catch(e3){if(!this.stopped)this.emit("error",e3);try{m2.nak()}catch{}}}})().catch(e3=>{if(!this.stopped)this.emit("error",e3)})}async lifecycleCoversPost(owner2,lifecycleUid,channel,seq){const kv=await this.membersRegistry();for(const row of[channel,...familiesCovering(channel).reverse()]){const rec=await readMember(kv,row,owner2,lifecycleUid);if(rec&&durableEligible(rec.record,seq))return true}return false}async removeRetiredMemberRow(channel,owner2,lifecycleUid){try{const kv=await this.membersRegistry();if(await readMember(kv,channel,owner2,lifecycleUid)===void 0)return;await deleteMember(kv,channel,owner2,lifecycleUid)}catch(e3){this.emit("warning",new Error(`plane-3 reader: could not remove retired lifecycle ${owner2}.${lifecycleUid}'s "${channel}" member row: ${e3.message}`))}}async readerHandle(m2){if(!this.plane3MayAct())return;const pr2=parseDinboxPrincipal(m2.subject);if(!pr2){m2.ack();return}const owner2=`${pr2.owner}.${pr2.actor}`;let entry;try{entry=m2.json()}catch{m2.ack();return}if(!isRecord(entry)){m2.ack();return}const redeliveries=m2.info?.deliveryCount??1;const acl=await this.plane3?.aclFor(owner2,pr2.lifecycleUid);if(acl===void 0){if(await aclRetired(await this.aclRegistry(),owner2,pr2.lifecycleUid)){if(!this.plane3MayAct())return;let failure;try{await this.jsm.streams.deleteMessage(inboxStream(this.space),m2.seq,false)}catch(e3){if(!isJetStreamMissing(e3,10043))failure=e3 instanceof Error?e3:new Error(String(e3))}if(!this.plane3MayAct())return;if(failure){if(redeliveries>=READER_MAX_REDELIVERIES){m2.term();this.emit("error",new Error(`plane-3 reader: gave up removing entry ${m2.seq} for retired lifecycle ${owner2}.${pr2.lifecycleUid} after ${redeliveries} redeliveries: ${failure.message}`));return}m2.nak(2e3);return}if(entry.reason==="durable-channel")await this.removeRetiredMemberRow(entry.row??entry.channel,owner2,pr2.lifecycleUid);if(!this.plane3MayAct())return;m2.ack();return}if(redeliveries>=READER_MAX_REDELIVERIES){m2.term();this.emit("error",new Error(`plane-3 reader: gave up on entry for unknown owner ${owner2} after ${redeliveries} redeliveries`));return}m2.nak(2e3);return}if(!channelInAllow(acl,entry.channel)){m2.ack();return}if(entry.reason==="durable-channel"&&!await this.lifecycleCoversPost(owner2,pr2.lifecycleUid,entry.channel,entry.seq)){m2.ack();return}if(!this.plane3MayAct())return;try{const frame={version:1,channel:entry.channel,msg:authenticatedChannelMessage(entry.msg,entry.channel)};const frameHeaders=(0,import_transport_node14.headers)();frameHeaders.set(PLANE3_FRAME_HEADER,"1");frameHeaders.set(DELIVERY_LIMIT_HEADER,await this.deliveryLimitStamp());if(!this.plane3MayAct())return;await this.js.publish(dlvSubject(this.space,pr2.owner,pr2.actor,pr2.lifecycleUid),JSON.stringify(frame),{...this.plane3MsgId(entry,`${owner2}:${pr2.lifecycleUid}`),headers:frameHeaders})}catch{if(redeliveries>=READER_MAX_REDELIVERIES){m2.term();this.emit("error",new Error(`plane-3 reader: gave up transferring ${entry.msg.id} for ${owner2} after ${redeliveries} redeliveries`));return}m2.nak(2e3);return}if(!this.plane3MayAct())return;m2.ack()}async pumpDlv(){if(!this.js)return;if(!this.ownLifecycleUid)return;if(this.allowSubscribe?.length===0)return;const durable=dlvDurable(this.owner,this.actor,this.ownLifecycleUid);if(this.allowSubscribe===void 0&&!this.userMode&&this.nc){const permission2=this.watchDeletePermissions.get(this.nc)?.();if(permission2&&!issuedPermitsSubject({...permission2,deny:[]},`$JS.API.CONSUMER.INFO.${dlvStream(this.space)}.${durable}`))return}let consumer;try{consumer=await this.js.consumers.get(dlvStream(this.space),durable)}catch(e3){if(isJetStreamMissing(e3,import_jetstream13.JetStreamApiCodes.ConsumerNotFound)){const issued=this.nc&&this.watchDeletePermissions.get(this.nc)?.();if((this.allowSubscribe?.length??0)>0&&issued&&!issuedPermitsSubject({...issued,deny:[]},`$JS.API.CONSUMER.MSG.NEXT.${dlvStream(this.space)}.${durable}`))throw new Error(`this connection declared a read list, but its credential cannot fetch delivery durable "${durable}" for space "${this.space}"; the read list and the credential disagree`);return}throw e3}const lease=await this.readDeliveryLease(0);const liveDeliveryPlane=lease?.ready===true;if(!liveDeliveryPlane)this.emit("warning",new Error(`delivery durable "${durable}" for space "${this.space}" bound while the plane this connection reaches has no ready delivery lease, so the durable delivers nothing until a delivery daemon serves this plane. If a daemon serves this space on another plane, reconnect against it, which re-binds the durable there.`));const ackWaitMs=await ackWaitOf(consumer);const msgs=await consumer.consume();this.streamMsgs.push(msgs);void(async()=>{for await(const m2 of msgs){let limit;try{limit=deliveryLimitOf(m2.headers?.get(DELIVERY_LIMIT_HEADER))}catch(e3){this.emit("error",e3);limit=null}if(limit!==null&&m2.info.pending>=limit-1)this.emit("stored-copies-full",{limit});if(m2.headers?.get(PLANE3_FRAME_HEADER)!=="1"){this.emit("error",new Error("plane-3 delivery: unauthenticated or unversioned DLV entry terminated"));try{m2.term()}catch{}continue}let raw;try{raw=m2.json()}catch(e3){this.emit("error",e3);try{m2.term()}catch{}continue}if(!isPlane3DeliveryFrame(raw)){this.emit("error",new Error("plane-3 delivery: malformed versioned DLV entry terminated"));try{m2.term()}catch{}continue}const msg=authenticatedChannelMessage(raw.msg,raw.channel);if(msg.from?.id===this.card.id){m2.ack();continue}this.emit("message",msg,durableDelivery(m2,ackWaitMs),{historical:false,kind:"channel"})}})().catch(e3=>{if(!this.stopped)this.emit("error",e3)})}}}});import{randomUUID as randomUUID5}from"node:crypto";var import_transport_node15,EndpointControlPlane;var init_endpoint_control_plane=__esm({"../../packages/core/dist/endpoint-control-plane.js"(){"use strict";import_transport_node15=__toESM(require_transport_node(),1);init_deadline();init_endpoint();init_endpoint_invoke();init_endpoint_envelope();init_endpoint_grants();init_registry_contract();init_registry_client();init_subjects();EndpointControlPlane=class{deps;constructor(deps){this.deps=deps}get nc(){return this.deps.nc()}get space(){return this.deps.space()}get owner(){return this.deps.owner()}get actor(){return this.deps.actor()}get stopped(){return this.deps.stopped()}get authed(){return this.deps.authed()}get connId(){return this.deps.connId()}get presentedExp(){return this.deps.presentedExp()}get issuedGeneration(){return this.deps.issuedGeneration()}get acceptedToken(){return this.deps.acceptedToken()}get rebuildPromise(){return this.deps.rebuildPromise()}get subs(){return this.deps.subs()}get resolvedServices(){return this.deps.resolvedServices()}get resolvedCommandServices(){return this.deps.resolvedCommandServices()}get serviceInvocations(){return this.deps.serviceInvocations()}get requestsAwaitingReply(){return this.deps.requestsAwaitingReply()}get activeGoalFollowers(){return this.deps.activeGoalFollowers()}get splitsRecovered(){return this.deps.splitsRecovered()}set splitsRecovered(count){this.deps.setSplitsRecovered(count)}notLiveMsg(){return this.deps.notLiveMsg()}requireLifecycleUid(what2){return this.deps.requireLifecycleUid(what2)}reportSubscriptionDenial(error51){return this.deps.reportSubscriptionDenial(error51)}ref(){return this.deps.ref()}reconnect(){return this.deps.reconnect()}emit(event,...args){return this.deps.emit(event,...args)}serveControl(service,handler,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());const sub=this.nc.subscribe(controlServiceSubject(this.space,service,"*","*"),{queue:service});this.subs.push(sub);const inOwnTime=opts.concurrent;let inOrder=Promise.resolve();void(async()=>{for await(const m2 of sub){if(opts.boundReply&&(!m2.reply||!m2.reply.startsWith(`${m2.subject}.reply.`))){this.emit("error",new Error(`rejected ${service} request on ${m2.subject}: reply target "${m2.reply??"(none)"}" is not under the sender's own reply subtree`));continue}const answer=()=>this.answerControl(service,handler,m2);if(inOwnTime===void 0){await answer();continue}let own=false;try{own=inOwnTime(m2.json())}catch{}if(own)void answer().catch(e3=>this.emit("error",e3));else inOrder=inOrder.then(answer).catch(e3=>{this.emit("error",e3)})}})().catch(e3=>{if(!this.reportSubscriptionDenial(e3))this.emit("error",e3)});return sub}async answerControl(service,handler,m2){let body;try{let reply;const req=m2.json();const parsed=parseSubject(m2.subject);if(!parsed||!isFromSubjectSender(req,parsed)){this.emit("error",new Error(`rejected control request on ${m2.subject}: from ${req.from?.id??"(none)"} does not match subject sender ${parsed?.sender??"(unparseable)"}`));reply={ok:false,error:"sender mismatch - request rejected"}}else{reply=await handler(req)}body=JSON.stringify(reply)}catch(e3){body=JSON.stringify({ok:false,error:e3.message})}try{m2.respond(body)}catch(e3){const refused3={ok:false,error:`the ${service} reply is ${Buffer.byteLength(body)} bytes and was not published: ${e3.message}`};try{m2.respond(JSON.stringify(refused3))}catch(err3){this.emit("error",new Error(`could not answer ${service} request on ${m2.subject}: ${refused3.error}, and the refusal failed too: ${err3.message}`))}}}async requestBoundReply(nc,subject,body,reply,timeoutMs){let pending=this.requestsAwaitingReply.get(nc);if(!pending){const waiting=new Set;this.requestsAwaitingReply.set(nc,waiting);void nc.closed().then(error51=>{this.requestsAwaitingReply.delete(nc);const failure=error51??new import_transport_node15.ClosedConnectionError;for(const reject of waiting)reject(failure);waiting.clear()});pending=waiting}let rejectClosed;const closed4=new Promise((_resolve,reject)=>{rejectClosed=reject;pending.add(reject)});try{return await Promise.race([nc.request(subject,body,{timeout:timeoutMs,noMux:true,reply}),closed4])}finally{pending.delete(rejectClosed)}}async requestControl(service,req,timeoutMs=5e3){if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=controlServiceSubject(this.space,service,this.owner,this.actor);const reply=`${reqSubject}.reply.${randomUUID5()}`;const body={...req,from:req.from??this.ref()};const m2=await this.requestBoundReply(this.nc,reqSubject,JSON.stringify(body),reply,timeoutMs);return m2.json()}serviceRailCaller(){return this.serviceCaller()}serviceCaller(){const triple={owner:this.owner,actor:this.actor,uid:this.requireLifecycleUid("invokeService")};if(this.acceptedToken===void 0)return triple;if(this.issuedGeneration===void 0)throw new Error("invokeService: the issued generation is not yet discovered on this connection");return{...triple,generation:this.issuedGeneration}}async followServiceGoal(endpoint,submit,deadlineMs=1e4,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());if(this.stopped)throw new Error("endpoint stopped - cannot follow goal");const abortController=new AbortController;const onAbort=()=>abortController.abort();if(opts.signal?.aborted)onAbort();else opts.signal?.addEventListener("abort",onAbort,{once:true});let reconnectHandler;const entry={cancel:()=>abortController.abort(),reconnected:nc=>reconnectHandler?.(nc)};this.activeGoalFollowers.add(entry);try{const reconcile=opts.reconcile??(async(goalId,_attributed,context)=>{const current=this.serviceCaller();if(current.owner!==context.caller.owner||current.actor!==context.caller.actor||current.uid!==context.caller.uid)throw new Error("the renewed goal reader no longer has the accepting caller's full identity");const q2=await this.invokeService(endpoint,"goal-result",{goalId},{deadlineMs:Math.min(deadlineMs,context.deadlineMs),signal:context.signal});if(q2.reply.ok!==true)throw new Error(q2.reply.error.message);return q2.reply.data});return await submitAndFollowGoal(this.nc,this.space,endpoint,this.serviceCaller(),deadlineMs,submit,{reconcile,currentNc:()=>this.nc,onReconnect:cb=>{reconnectHandler=cb;return()=>{reconnectHandler=void 0}},signal:abortController.signal,prepare:opts.prepare})}finally{opts.signal?.removeEventListener("abort",onAbort);this.activeGoalFollowers.delete(entry)}}clearResolvedService(endpoint){this.resolvedServices.delete(endpoint);this.resolvedCommandServices.delete(endpoint)}beginServiceInvocation(nc){let pending=this.serviceInvocations.get(nc);if(!pending){pending=new Set;this.serviceInvocations.set(nc,pending)}let settle;const request=new Promise(resolve6=>{settle=resolve6});pending.add(request);return()=>{pending.delete(request);settle()}}async waitServiceRecovery(recovery,deadline,signal,timeout){let onAbort;const cancelled=new Promise((_3,reject)=>{onAbort=()=>reject(signal?.reason);if(signal?.aborted)onAbort();else signal?.addEventListener("abort",onAbort,{once:true})});try{await withDeadline(Promise.race([recovery,cancelled]),deadline-Date.now(),timeout)}finally{if(onAbort)signal?.removeEventListener("abort",onAbort)}signal?.throwIfAborted();if(deadline<=Date.now())throw timeout()}async describeService(endpoint,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());if(opts.refresh)this.clearResolvedService(endpoint);const cached2=opts.instanceId===void 0?this.resolvedServices.get(endpoint):void 0;if(cached2)return cached2;const svc=await resolveService(this.nc,this.space,endpoint,this.serviceCaller(),{deadlineMs:opts.deadlineMs??1e4,signal:opts.signal,...opts.instanceId!==void 0?{instanceId:opts.instanceId}:{}});if(opts.instanceId===void 0)this.resolvedServices.set(endpoint,svc);return svc}async listingCaller(){if(!this.nc)throw new Error(this.notLiveMsg());return registryListingCaller(this.nc,this.space,this.serviceCaller(),{connId:this.connId,...this.presentedExp!==void 0?{exp:this.presentedExp}:{}})}async listEndpoints(input,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());const nc=this.nc;const listing=this.authed?await this.listingCaller():void 0;if(this.authed&&listing===void 0)return{unbound:true};return this.listEndpointsOver(nc,listing,input,opts)}async listEndpointsOver(nc,listing,input,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());const own=this.nc;const result=await listRegistryEndpoints(this.space,(deadlineMs,signal)=>resolveService(own,this.space,REGISTRY_ENDPOINT,this.serviceCaller(),{deadlineMs,signal,commands:[REGISTRY_ENDPOINTS_COMMAND]}),{nc,...listing?{caller:listing}:{}},input,opts);if(result.unbound)return result;for(const row of result.page?.rows??[])this.clearResolvedService(row.endpoint);return result}async invokeService(endpoint,command,args,opts={}){const deadline=Date.now()+(opts.deadlineMs??1e4);const rebuilding=this.rebuildPromise;if(rebuilding){await this.waitServiceRecovery(rebuilding,deadline,opts.signal,()=>new EpEnvelopeError("deadline-exceeded","the invocation deadline elapsed waiting for connection recovery",void 0,"not-executed"));opts={...opts,deadlineMs:deadline-Date.now()}}const nc=this.nc;if(!nc)throw new Error(this.notLiveMsg());try{return await this.invokeServiceOnce(endpoint,command,args,opts,rebuilding?deadline:void 0)}catch(e3){if(!(e3 instanceof EpEnvelopeError)||e3.code!=="permission-denied"||e3.outcome!=="not-executed"||deadline<=Date.now())throw e3;opts.signal?.throwIfAborted();const recovery=(async()=>{for(;;){opts.signal?.throwIfAborted();if(deadline<=Date.now())throw e3;const pending=this.serviceInvocations.get(nc);if(!pending?.size)break;await Promise.allSettled([...pending])}if(this.nc===nc)await this.reconnect();else await this.rebuildPromise})();await this.waitServiceRecovery(recovery,deadline,opts.signal,()=>e3);this.clearResolvedService(endpoint);return this.invokeServiceOnce(endpoint,command,args,{...opts,deadlineMs:deadline-Date.now()},deadline)}}async invokeServiceOnce(endpoint,command,args,opts={},retryDeadline){if(!this.nc)throw new Error(this.notLiveMsg());const nc=this.nc;const caller=this.serviceCaller();const resolve6=async(signal=opts.signal,deadlineMs=opts.deadlineMs??1e4)=>{signal?.throwIfAborted();if(retryDeadline!==void 0)deadlineMs=Math.min(deadlineMs,retryDeadline-Date.now());if(deadlineMs<=0)throw new EpEnvelopeError("deadline-exceeded","the invocation deadline elapsed before resolve",void 0,"not-executed");const needed=opts.follow?[command,"goal-result"]:[command];const classSelected=opts.instanceId===void 0&&opts.classInstanceId===void 0;const full=classSelected?this.resolvedServices.get(endpoint):void 0;if(full&&needed.every(name2=>full.commands.has(name2)))return full;const cacheKey=[...needed].sort().join("\0");const commandCache=classSelected?this.resolvedCommandServices.get(endpoint):void 0;const cached2=commandCache?.get(cacheKey);if(cached2)return cached2;const svc=await resolveService(nc,this.space,endpoint,caller,{deadlineMs,signal,commands:needed,...opts.follow&&command!=="goal-result"?{optionalCommands:["goal-result"]}:{},...opts.instanceId!==void 0?{instanceId:opts.instanceId}:{},...opts.classInstanceId!==void 0?{classInstanceId:opts.classInstanceId}:{}});if(classSelected){let byCommand=this.resolvedCommandServices.get(endpoint);if(!byCommand){byCommand=new Map;this.resolvedCommandServices.set(endpoint,byCommand)}byCommand.set(cacheKey,svc)}return svc};const invokeOpts={...opts.target?{target:opts.target}:{},...opts.deadlineMs!==void 0?{deadlineMs:opts.deadlineMs}:{}};const invokeResolved=(service,signal)=>{signal?.throwIfAborted();const unfollowable=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable)return Promise.resolve(unfollowable);const deadlineMs=retryDeadline===void 0?invokeOpts.deadlineMs:retryDeadline-Date.now();if(deadlineMs!==void 0&&deadlineMs<=0)throw new EpEnvelopeError("deadline-exceeded","the invocation deadline elapsed before publish",void 0,"not-executed");return invokeCommand(nc,this.space,service,command,args,{...invokeOpts,deadlineMs,signal})};const resolveFirst=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{try{return await resolve6(signal,deadline-Date.now())}catch(e3){if(!(e3 instanceof EpEnvelopeError)||e3.code!=="failed-precondition")throw e3;const left=deadline-Date.now();if(left<=0)throw e3;return await resolve6(signal,left)}};const doInvoke=async(service,signal=opts.signal)=>{signal?.throwIfAborted();try{let r2=await invokeResolved(service,signal);const unmappedHere=x2=>opts.instanceId===void 0&&replyTargetUnmapped(x2.reply.error);let unmapped=unmappedHere(r2)?r2:void 0;for(let reissues=0;reissues<BIND_SPLIT_REISSUES&&r2.reply.ok===false&&(replyRefusedBeforeEffect(r2.reply.error)||unmappedHere(r2));reissues++){this.splitsRecovered++;this.emit("split-recovered",{endpoint,command,servedBy:r2.responder,splitsRecovered:this.splitsRecovered,boundTo:(r2.reply.error.details??[]).find(d2=>d2.kind===EP_BIND_REFUSED)?.boundTo});this.clearResolvedService(endpoint);const raw=r2.reply.error.code;const refusalCode=raw==="expired"?"expired":raw==="failed-precondition"?"failed-precondition":void 0;if(refusalCode===void 0)throw new EpEnvelopeError("internal",`${endpoint}.${command} came back marked as refused before it ran, but with code ${String(raw)}; the fence produces only failed-precondition or expired (SPEC 13.2)`,r2.reply.error.details);let reissueTarget;try{reissueTarget=await resolve6(signal);const unfollowable=opts.follow?goalFollowRefusal(reissueTarget):void 0;if(unfollowable)throw new Error(unfollowable.reply.error.message)}catch(reissue){throw new EpEnvelopeError(refusalCode,`${endpoint}.${command} WAS NOT RUN - the incarnation that received it refused it before any effect, and the re-issue could not be resolved: ${reissue instanceof Error?reissue.message:String(reissue)}. Re-resolve and re-issue when the endpoint is reachable (SPEC 13.2)`,r2.reply.error.details,"not-executed")}r2=await invokeResolved(reissueTarget,signal);if(unmappedHere(r2))unmapped=r2}return replyRefusedBeforeEffect(r2.reply.error)?unmapped??r2:r2}catch(e3){if(respondedButUnbound(e3)){this.clearResolvedService(endpoint);if(!isRepeatSafeCommand(endpoint,command))throw e3;return await invokeResolved(await resolve6(signal),signal)}throw e3}};const release=this.beginServiceInvocation(nc);try{if(!opts.follow)return await doInvoke(await resolveFirst());let service;return await this.followServiceGoal(endpoint,async signal=>{try{return await doInvoke(service,signal)}finally{release()}},opts.deadlineMs??1e4,{signal:opts.signal,prepare:async(signal,deadline)=>{service=await resolveFirst(signal,deadline)}})}finally{release()}}}}});import{randomUUID as randomUUID6}from"node:crypto";function jsonPathProblem(path4,value,seen){if(value===null)return void 0;const t2=typeof value;if(t2==="boolean"||t2==="string")return void 0;if(t2==="number")return Number.isFinite(value)?void 0:`${path4} is not a finite number`;if(t2==="undefined"||t2==="function"||t2==="symbol"||t2==="bigint")return`${path4} is not a JSON value`;if(typeof value==="object"){if(seen.has(value))return`${path4} is cyclic`;seen.add(value);let problem;if(Array.isArray(value)){for(let i2=0;i2<value.length;i2++){problem=jsonPathProblem(`${path4}[${i2}]`,value[i2],seen);if(problem)return problem}}else{const proto=Object.getPrototypeOf(value);if(proto!==null&&proto!==Object.prototype){seen.delete(value);return`${path4} is not a plain object`}for(const key of Object.keys(value)){if(value[key]===void 0)continue;problem=jsonPathProblem(`${path4}.${key}`,value[key],seen);if(problem)return problem}}seen.delete(value);return void 0}return`${path4} is not a JSON value`}function assertPartsSerializable(parts){for(const p2 of parts){if(p2.kind!=="data")continue;const problem=jsonPathProblem("data",p2.data,new Set);if(problem!==void 0){throw new Error(`cannot publish a data part carrying a non-JSON value (SPEC \xA75) - ${problem}`)}}}var import_transport_node16,import_jetstream14,EndpointMessaging;var init_endpoint_messaging=__esm({"../../packages/core/dist/endpoint-messaging.js"(){"use strict";import_transport_node16=__toESM(require_transport_node(),1);import_jetstream14=__toESM(require_mod4(),1);init_event_payloads();init_endpoint_subjects();init_endpoint_records();init_jetstream_missing();init_subjects();EndpointMessaging=class{deps;constructor(deps){this.deps=deps}get nc(){return this.deps.nc()}get js(){return this.deps.js()}get jsm(){return this.deps.jsm()}get space(){return this.deps.space()}get owner(){return this.deps.owner()}get actor(){return this.deps.actor()}get channels(){return this.deps.channels()}notLiveMsg(){return this.deps.notLiveMsg()}ref(){return this.deps.ref()}publishMsg(subject,msg){return this.deps.publishMsg(subject,msg)}streamHistory(stream,subjects,limit,before,signal){return this.deps.streamHistory(stream,subjects,limit,before,signal)}emitRecoverable(err3){this.deps.emitRecoverable(err3)}async multicast(text3,opts){const channel=opts?.channel??this.channels.find(isConcreteChannel);if(channel===void 0)throw new Error("no default channel: this endpoint is not on any concrete channel, so there is nothing to broadcast to - name a channel explicitly, or join one first");if(!isConcreteChannel(channel))throw new Error(`cannot publish to wildcard channel "${channel}" - pick a concrete sub-channel`);const msg={id:randomUUID6(),ts:Date.now(),space:this.space,from:this.ref(),channel,mentions:normalizeMentions(opts?.mentions),parts:opts?.parts??[{kind:"text",text:text3}],replyTo:opts?.replyTo,contextId:opts?.contextId};await this.publishMsg(chatSubject(this.space,this.owner,this.actor,channel),msg);return msg}get maxPayload(){const max=this.nc?.info?.max_payload;if(typeof max!=="number"||!Number.isFinite(max)||max<=0)throw new Error(`${this.notLiveMsg()} - max_payload is only known while connected`);return max}async assertExpectationSemantics(){if(!this.jsm)throw new Error(this.notLiveMsg());const stream=chatStream(this.space);let replicas;try{replicas=(await this.jsm.streams.info(stream)).config.num_replicas}catch(e3){throw new Error(`cannot verify expectation semantics: stream "${stream}" info unavailable (${e3.message}). Serialized appends are refused rather than run on an unverified stream.`)}if(replicas!==1)throw new Error(`stream "${stream}" reports num_replicas=${String(replicas)}; serialized appends on THIS stream require 1 \u2014 a property of this one stream, not of the broker, so a clustered deployment is fine so long as this stream is R1, which a cluster can host. On a replicated stream the dedup cache is consulted before the subject expectation, so a retry returns a duplicate ack instead of a conflict and a lost message reads as success.`)}casEnvelope(opts){return{id:opts.id,ts:Date.now(),space:this.space,from:this.ref(),channel:opts.channel,mentions:normalizeMentions(opts.mentions),parts:opts.parts,replyTo:opts.replyTo,contextId:opts.contextId}}encodedSize(opts){if(!isConcreteChannel(opts.channel))throw new Error(`cannot publish to wildcard channel "${opts.channel}" - pick a concrete sub-channel`);assertIdToken(opts.id,"publish id");if(!Number.isSafeInteger(opts.expectedLastSubjectSeq)||opts.expectedLastSubjectSeq<0)throw new Error(`expectedLastSubjectSeq must be a non-negative safe integer, got ${JSON.stringify(opts.expectedLastSubjectSeq)}`);if(!Array.isArray(opts.parts)||opts.parts.length===0)throw new Error("encodedSize requires at least one part");const mh=(0,import_transport_node16.headers)();mh.set("Nats-Msg-Id",opts.id);mh.set("Nats-Expected-Last-Subject-Sequence",`${opts.expectedLastSubjectSeq}`);if(opts.expectedLastMsgId!==void 0){assertIdToken(opts.expectedLastMsgId,"expected last msg id");mh.set("Nats-Expected-Last-Msg-Id",opts.expectedLastMsgId)}const headerBytes=mh.encode().length;return headerBytes+Buffer.byteLength(JSON.stringify(this.casEnvelope(opts)),"utf8")}async multicastExpecting(opts){if(!this.js)throw new Error(this.notLiveMsg());if(!isConcreteChannel(opts.channel))throw new Error(`cannot publish to wildcard channel "${opts.channel}" - pick a concrete sub-channel`);assertIdToken(opts.id,"publish id");const expected=opts.expectedLastSubjectSeq;if(!Number.isSafeInteger(expected)||expected<0)throw new Error(`expectedLastSubjectSeq must be a non-negative safe integer, got ${JSON.stringify(expected)}`);if(!Array.isArray(opts.parts)||opts.parts.length===0)throw new Error("multicastExpecting requires at least one part");if(opts.expectedLastMsgId!==void 0)assertIdToken(opts.expectedLastMsgId,"expected last msg id");const message=this.casEnvelope(opts);assertPartsSerializable(message.parts);const ack=await this.js.publish(chatSubject(this.space,this.owner,this.actor,opts.channel),JSON.stringify(message),{msgID:opts.id,expect:{lastSubjectSequence:expected,...opts.expectedLastMsgId!==void 0?{lastMsgID:opts.expectedLastMsgId}:{}}});return{message,ack:{seq:ack.seq,duplicate:ack.duplicate===true}}}async publishEventPayload(opts){if(!this.js)throw new Error(this.notLiveMsg());assertIdToken(opts.id,"publish id");if(!Number.isSafeInteger(opts.expectedLastSubjectSeq)||opts.expectedLastSubjectSeq<0)throw new Error("payload expectation must be a non-negative safe integer");if(!opts.parts.length)throw new Error("payload frame requires parts");const message=this.casEnvelope({...opts,channel:`events.${this.owner}.${this.actor}`});assertPartsSerializable(message.parts);const ack=await this.js.publish(eventPayloadSubject(this.space,this.owner,this.actor),JSON.stringify(message),{msgID:opts.id,expect:{lastSubjectSequence:opts.expectedLastSubjectSeq}});return{ack:{seq:ack.seq,duplicate:ack.duplicate===true}}}async eventPayloadHistory(owner2,actor2,opts){return(await this.streamHistory(eventPayloadStream(this.space),[eventPayloadSubject(this.space,assertValidOwnerToken(owner2),assertValidOwnerToken(actor2))],opts?.limit??100,void 0,opts?.signal)).map(row=>row.msg)}async eventPayloadLimit(){if(!this.jsm)throw new Error(this.notLiveMsg());const stream=eventPayloadStream(this.space);const info=await this.jsm.streams.info(stream).catch(err3=>{const denial=err3 instanceof import_transport_node16.PermissionViolationError?err3:err3?.cause;const infoDenied=denial instanceof import_transport_node16.PermissionViolationError&&denial.operation==="publish"&&denial.subject===`$JS.API.STREAM.INFO.${stream}`;if(!infoDenied&&!isJetStreamMissing(err3,import_jetstream14.JetStreamApiCodes.StreamNotFound))throw err3;const reason=infoDenied?`missing publish permission on $JS.API.STREAM.INFO.${stream}`:`stream ${stream} is absent`;this.emitRecoverable(new Error(`event payloads unavailable: ${reason}; publishing tool names and times only. Upgrade the space's broker setup and credentials to enable payloads`));return null});if(info===null)return null;const{config:config2}=info;if(config2.num_replicas!==1)throw new Error("event payload stream requires one replica for serialized appends");const limits=[this.maxPayload,config2.max_msg_size,config2.max_bytes].filter(n2=>typeof n2==="number"&&n2>0);return Math.min(...limits)}async unicast(instanceId,text3,opts){const{msg}=await this.unicastAttributed(instanceId,text3,opts);return msg}async unicastAttributed(instanceId,text3,opts){if(!this.js)throw new Error(this.notLiveMsg());const msg={id:randomUUID6(),ts:Date.now(),space:this.space,from:this.ref(),to:instanceId,parts:opts?.parts??[{kind:"text",text:text3}],replyTo:opts?.replyTo,contextId:opts?.contextId};const recip=parsePrincipalKey(instanceId);if(!recip)throw new Error(`unicast: "${instanceId}" is not a valid recipient principal <owner>.<actor>`);assertPartsSerializable(msg.parts);const subject=unicastSubject(this.space,recip.owner,recip.actor,this.owner,this.actor);try{const ack=await this.js.publish(subject,JSON.stringify(msg),{msgID:msg.id});return{msg,ack:{seq:ack.seq,duplicate:ack.duplicate===true}}}catch(error51){if(error51 instanceof import_transport_node16.TimeoutError)throw new Error(`${error51.message} publishing to ${JSON.stringify(subject)}. The send outcome is unknown: the broker may have stored the message. Check before resending.`,{cause:error51});throw error51}}async anycast(service,text3,opts){const{msg}=await this.anycastAttributed(service,text3,opts);return msg}async anycastAttributed(service,text3,opts){if(!this.js)throw new Error(this.notLiveMsg());assertValidRole(service);const msg={id:randomUUID6(),ts:Date.now(),space:this.space,from:this.ref(),toService:service,parts:opts?.parts??[{kind:"text",text:text3}],replyTo:opts?.replyTo,contextId:opts?.contextId};assertPartsSerializable(msg.parts);const ack=await this.js.publish(anycastSubject(this.space,service,this.owner,this.actor),JSON.stringify(msg),{msgID:msg.id});return{msg,ack:{seq:ack.seq,duplicate:ack.duplicate===true}}}}}});function validateChannelConfig(cfg){validateChannelDefaults(cfg);validateText("description",cfg.description,MAX_CHANNEL_DESCRIPTION);validateText("instructions",cfg.instructions,MAX_CHANNEL_INSTRUCTIONS)}function validateText(field,text3,max){if(text3===void 0)return;if(typeof text3!=="string")throw new Error(`channel ${field} must be a string`);if(text3.length>max)throw new Error(`channel ${field} too long (${text3.length} > ${max} chars)`)}function validateChannelDefaults(d2){if(d2.replay!==void 0&&typeof d2.replay!=="boolean")throw new Error(`invalid replay "${d2.replay}" - expected true or false`);if(d2.replayWindow!==void 0)parseDuration(d2.replayWindow);if(d2.deliveryClass!==void 0&&d2.deliveryClass!=="live"&&d2.deliveryClass!=="durable")throw new Error(`invalid deliveryClass "${d2.deliveryClass}" - expected "live" or "durable"`)}function decodeChannelEntry(e3){const value=e3.json();if(typeof value!=="object"||value===null||Array.isArray(value))throw new Error("not a JSON object");if(e3.key===CHANNEL_DEFAULTS_KEY)validateChannelDefaults(value);else validateChannelConfig(value);return value}function parseDuration(s3){const m2=/^(\d+)(s|m|h|d)$/.exec(s3.trim());if(!m2)throw new Error(`invalid duration "${s3}" - expected <number><s|m|h|d>, e.g. "24h"`);const n2=Number(m2[1]);const unit={s:1e3,m:6e4,h:36e5,d:864e5}[m2[2]];return n2*unit}function effectiveReplay(cfg,defaults){return cfg?.replay??defaults?.replay??true}function effectiveReplayWindowMs(cfg,defaults){const w2=cfg?.replayWindow??defaults?.replayWindow;return w2===void 0?void 0:parseDuration(w2)}function effectiveDeliveryClass(cfg,defaults){return cfg?.deliveryClass??defaults?.deliveryClass??"durable"}async function openChannelRegistry(nc,space2,opts={}){const kvm=new import_kv6.Kvm(nc);return opts.create?kvm.create(channelBucket(space2)):kvm.open(channelBucket(space2))}async function readChannelConfig(kv,channel){return decode2(kv,channel)}async function readChannelDefaults(kv){return decode2(kv,CHANNEL_DEFAULTS_KEY)}async function decode2(kv,key){return entryValue(await kv.get(key))}function entryValue(e3){return entryDecode(e3).value}function entryDecode(e3){if(!e3||e3.operation==="DEL"||e3.operation==="PURGE")return{};try{return{value:decodeChannelEntry(e3)}}catch(err3){return{error:err3.message}}}var import_kv6,import_transport_node17,MAX_CHANNEL_DESCRIPTION,MAX_CHANNEL_INSTRUCTIONS;var init_channels=__esm({"../../packages/core/dist/channels.js"(){"use strict";import_kv6=__toESM(require_mod6(),1);init_connection_cleanup();import_transport_node17=__toESM(require_transport_node(),1);init_endpoint();init_subjects();init_streams();init_kv_scan();init_endpoint_records();init_jetstream_missing();MAX_CHANNEL_DESCRIPTION=200;MAX_CHANNEL_INSTRUCTIONS=2e3}});var import_jetstream15,import_kv7,EndpointDurableBackstop;var init_endpoint_durable_backstop=__esm({"../../packages/core/dist/endpoint-durable-backstop.js"(){"use strict";import_jetstream15=__toESM(require_mod4(),1);import_kv7=__toESM(require_mod6(),1);init_acls();init_channels();init_endpoint_records();init_members();init_streams();init_subjects();EndpointDurableBackstop=class{deps;constructor(deps){this.deps=deps}get nc(){return this.deps.nc()}get js(){return this.deps.js()}get jsm(){return this.deps.jsm()}set jsm(manager){if(manager)this.deps.setJsm(manager)}get space(){return this.deps.space()}get card(){return this.deps.card()}get authed(){return this.deps.authed()}get channelKv(){return this.deps.channelKv()}get presence(){return this.deps.presence()}get deliveryPlane(){return this.deps.deliveryPlane()}get membersKv(){return this.deps.membersKv()}set membersKv(kv){this.deps.setMembersKv(kv)}get aclKv(){return this.deps.aclKv()}set aclKv(kv){this.deps.setAclKv(kv)}get managerLeaseKv(){return this.deps.managerLeaseKv()}set managerLeaseKv(kv){this.deps.setManagerLeaseKv(kv)}get daemonRenewalLeaseRevision(){return this.deps.daemonRenewalLeaseRevision()}set daemonRenewalLeaseRevision(revision){this.deps.setDaemonRenewalLeaseRevision(revision)}notLiveMsg(){return this.deps.notLiveMsg()}consumerInfo(stream,durable){return this.deps.consumerInfo(stream,durable)}manager(){return this.deps.manager()}chatFrontier(){return this.deps.chatFrontier()}aclAllows(owner2,lifecycleUid,channel){return this.deps.aclAllows(owner2,lifecycleUid,channel)}catchupCopy(owner2,lifecycleUid,channel,fromSeqExcl,toSeqIncl,generation){return this.deps.catchupCopy(owner2,lifecycleUid,channel,fromSeqExcl,toSeqIncl,generation)}async membersRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.membersKv??=await openMembersRegistry(this.nc,this.space);return this.membersKv}async aclRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.aclKv??=await openAclRegistry(this.nc,this.space);return this.aclKv}async commitAcl(targetId,lifecycleUid,allowSubscribe){await commitAcl(await this.aclRegistry(),targetId,lifecycleUid,allowSubscribe)}async reissueAcl(targetId,lifecycleUid,allowSubscribe){await reissueAcl(await this.aclRegistry(),targetId,lifecycleUid,allowSubscribe)}async aclForOwner(owner2,lifecycleUid){return(await readAcl(await this.aclRegistry(),owner2,lifecycleUid))?.record.allowSubscribe}async aclForAlias(principal){const row=await readAclForAlias(await this.aclRegistry(),principal);if(row===void 0)return void 0;const allow=row.record.allowSubscribe;const issued=row.record.issuedAllowSubscribe??allow;return{allowSubscribe:allow,issuedAllowSubscribe:issued,lifecycleUid:row.lifecycleUid}}async managerLeaseRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());if(this.managerLeaseKv)return this.managerLeaseKv;const kvm=new import_kv7.Kvm((0,import_jetstream15.jetstream)(this.nc,{timeout:MANAGER_LEASE_ATTEMPT_MS}));if(this.authed){this.managerLeaseKv=await kvm.open(managerBucket(this.space))}else{try{this.managerLeaseKv=await kvm.create(managerBucket(this.space),{ttl:MANAGER_LEASE_TTL_MS})}catch{this.managerLeaseKv=await kvm.open(managerBucket(this.space))}}return this.managerLeaseKv}async holdDaemonRenewalLease(instanceId){const kv=await this.managerLeaseRegistry();const held2=this.daemonRenewalLeaseRevision;if(held2!==void 0){try{this.daemonRenewalLeaseRevision=await kv.update(MANAGER_RENEWAL_LEASE_KEY,this.encodeDaemonRenewalLease(instanceId),held2);return true}catch{this.daemonRenewalLeaseRevision=void 0}}try{this.daemonRenewalLeaseRevision=await kv.create(MANAGER_RENEWAL_LEASE_KEY,this.encodeDaemonRenewalLease(instanceId));return true}catch{return false}}async releaseDaemonRenewalLease(){const held2=this.daemonRenewalLeaseRevision;this.daemonRenewalLeaseRevision=void 0;if(held2===void 0)return;try{await(await this.managerLeaseRegistry()).delete(MANAGER_RENEWAL_LEASE_KEY,{previousSeq:held2})}catch{}}encodeDaemonRenewalLease(instanceId){return new TextEncoder().encode(JSON.stringify({instanceId,since:Date.now()}))}async readDaemonRenewalLease(){const e3=await(await this.managerLeaseRegistry()).get(MANAGER_RENEWAL_LEASE_KEY);if(!e3||e3.operation!=="PUT")return void 0;return JSON.parse(new TextDecoder().decode(e3.value))}encodeManagerLease(info){return new TextEncoder().encode(JSON.stringify(info))}async acquireManagerLease(info){return(await this.managerLeaseRegistry()).create(managerLeaseKey(info.instanceId),this.encodeManagerLease({...info,since:Date.now()}))}async renewManagerLease(info,revision){return(await this.managerLeaseRegistry()).update(managerLeaseKey(info.instanceId),this.encodeManagerLease({...info,since:Date.now()}),revision)}async readOwnManagerLease(instanceId){const e3=await(await this.managerLeaseRegistry()).get(managerLeaseKey(instanceId));if(!e3||e3.operation!=="PUT")return void 0;return{info:JSON.parse(new TextDecoder().decode(e3.value)),revision:e3.revision,created:e3.created.getTime()}}async releaseManagerLease(instanceId,revision){const kv=await this.managerLeaseRegistry();if(revision===void 0)await kv.delete(managerLeaseKey(instanceId));else await kv.delete(managerLeaseKey(instanceId),{previousSeq:revision})}async readManagerLease(){if(!this.nc)return void 0;try{const jsm=this.jsm??(this.jsm=await(0,import_jetstream15.jetstreamManager)(this.nc));const stream=`KV_${managerBucket(this.space)}`;const prefix=`$KV.${managerBucket(this.space)}.${MANAGER_LEASE_KEY}.`;const info=await jsm.streams.info(stream,{subjects_filter:`${prefix}*`});let newest;for(const subject of Object.keys(info.state.subjects??{})){let m2;try{m2=await jsm.streams.getMessage(stream,{last_by_subj:subject})}catch(e3){if(e3.code===import_jetstream15.JetStreamApiCodes.NoMessageFound)continue;throw e3}if(m2===null)continue;const op=m2.header?.get("KV-Operation");if(op==="DEL"||op==="PURGE"||m2.data.length===0)continue;if(newest===void 0||m2.seq>newest.seq)newest={data:m2.data,seq:m2.seq}}if(newest===void 0)return void 0;return JSON.parse(new TextDecoder().decode(newest.data))}catch(e3){const code2=e3.code;if(code2===10037)return void 0;if(code2===404||/stream not found/i.test(e3?.message??""))return void 0;throw e3}}async ownerMemberships(owner2,lifecycleUid){const recs=await listMembers(await this.membersRegistry(),{owner:owner2});return recs.filter(r2=>r2.lifecycleUid===lifecycleUid&&r2.leaveCursor===void 0).map(r2=>({channel:r2.channel,generation:r2.generation,activated:r2.activated===true}))}async deliveryClassFresh(channel){if(!this.channelKv)return effectiveDeliveryClass(void 0,void 0);const[cfg,defaults]=await Promise.all([isConcreteChannel(channel)?readChannelConfig(this.channelKv,channel):Promise.resolve(void 0),readChannelDefaults(this.channelKv)]);return effectiveDeliveryClass(cfg,defaults)}resolveOwnerByName(name2){const matches=[...this.presence.values()].filter(p2=>p2.card.name.toLowerCase()===name2.toLowerCase());return matches.length===1?matches[0].card.id:void 0}plane3MsgId(entry,keySuffix){return entry.msg.id===""?{}:{msgID:`${entry.msg.id}:${keySuffix}`}}async publishDinbox(principal,lifecycleUid,entry){if(!this.js)return;const p2=parsePrincipalKey(principal);if(!p2)throw new Error(`publishDinbox: "${principal}" is not a valid member principal <owner>.<actor>`);await this.js.publish(dinboxSubject(this.space,p2.owner,p2.actor,lifecycleUid),JSON.stringify(entry),{...this.plane3MsgId(entry,`${principal}:${lifecycleUid}`)})}async fanoutDeliveredSeq(){const info=await this.consumerInfo(chatStream(this.space),FANOUT_DURABLE);return info?.delivered?.stream_seq??0}async durableJoinFor(owner2,channel,lifecycleUid,opts={}){if(!this.js)throw new Error(this.notLiveMsg());await this.manager();const kv=await this.membersRegistry();const existing=await readMember(kv,channel,owner2,lifecycleUid);const open7=existing?.record.state==="durable-active"&&existing.record.leaveCursor===void 0;if(open7&&existing.record.activated)return{durable:true,generation:existing.record.generation};const joinCursor=open7?existing.record.joinCursor:await this.chatFrontier();const generation=open7?existing.record.generation:(existing?.record.generation??0)+1;const base={channel,owner:owner2,lifecycleUid,state:"durable-active",joinCursor,generation,activated:false,writerIdentity:this.card.id,updatedAt:Date.now()};if(!open7){if(opts.aclFence&&!await this.aclAllows(owner2,lifecycleUid,channel))throw new Error(`durableJoin: "${channel}" is no longer within the read ACL of lifecycle ${lifecycleUid} (narrowed or retired); no membership row was written`);const written=await commitMemberRevision(kv,base);if(opts.aclFence)await this.keepRowIfAclAllows(kv,owner2,lifecycleUid,channel,written.revision)}const fence=Math.max(await this.chatFrontier(),await this.fanoutDeliveredSeq());await this.catchupCopy(owner2,lifecycleUid,channel,joinCursor,fence,generation);const activated=await activateMember(kv,channel,owner2,lifecycleUid,generation,joinCursor);if(!activated)return{durable:false,reason:"activation superseded by a concurrent leave or rejoin",generation};return{durable:true,generation}}async keepRowIfAclAllows(kv,owner2,lifecycleUid,channel,revision){let disallowed=false;let why;try{if(await this.aclAllows(owner2,lifecycleUid,channel))return;disallowed=true;why="was narrowed or retired while the row was written"}catch(e3){why=`could not be re-read after the row was written (${e3.message})`}const fail2=(outcome,cause)=>new Error(`durableJoin: the read ACL of lifecycle ${lifecycleUid} ${why}; ${outcome}`,cause===void 0?void 0:{cause});try{if(disallowed)await deleteMember(kv,channel,owner2,lifecycleUid);else await kv.purge(memberKey(channel,owner2,lifecycleUid),{previousSeq:revision})}catch(e3){if(!disallowed&&isCasLoss(e3))throw fail2(`a later write replaced its "${channel}" row, which was left to that write`);throw fail2(`removing its "${channel}" row failed (${e3.message})`,e3)}throw fail2(`its "${channel}" row was removed`)}async durableLeaveFor(owner2,channel,lifecycleUid,expectedGeneration){if(!this.deliveryPlane.plane3)return;const kv=await this.membersRegistry();await tombstoneMember(kv,channel,owner2,lifecycleUid,await this.chatFrontier(),this.card.id,expectedGeneration)}}}});function membershipChange(e3,update){const operation=e3.operation;if(e3.key===MEMBERSHIP_FEED_KEY){let asOf;if(operation==="PUT"){try{asOf=e3.json().observedAt}catch{}}return{type:"heartbeat",revision:e3.revision,update,asOf}}let member;if(operation==="PUT"){try{const rec=e3.json();member={id:e3.key,live:rec.live??[],durable:rec.durable??[],observedAt:rec.observedAt}}catch{}}return{type:"member",id:e3.key,operation,revision:e3.revision,update,member}}function membershipConsumerReleased(err3){return isJetStreamMissing(err3,import_jetstream16.JetStreamApiCodes.ConsumerNotFound,import_jetstream16.JetStreamApiCodes.StreamNotFound)||isPublishPermissionDenied(err3)}var import_transport_node18,import_jetstream16,import_kv8,import_internal2,EndpointSubscriptions;var init_endpoint_subscriptions=__esm({"../../packages/core/dist/endpoint-subscriptions.js"(){"use strict";import_transport_node18=__toESM(require_transport_node(),1);import_jetstream16=__toESM(require_mod4(),1);import_kv8=__toESM(require_mod6(),1);import_internal2=__toESM(require_internal_mod3(),1);init_channels();init_endpoint();init_jetstream_missing();init_kv_scan();init_subjects();EndpointSubscriptions=class{deps;constructor(deps){this.deps=deps}get nc(){return this.deps.nc()}get jsm(){return this.deps.jsm()}get space(){return this.deps.space()}get card(){return this.deps.card()}get stopped(){return this.deps.stopped()}get authed(){return this.deps.authed()}get channels(){return this.deps.channels()}get channelConfigs(){return this.deps.channelConfigs()}get channelDefaults(){return this.deps.channelDefaults()}get chatSubDenied(){return this.deps.chatSubDenied()}get plane3Channels(){return this.deps.plane3Channels()}get readsChannelsOnDemand(){return this.deps.readsChannelsOnDemand()}get membershipFeedKv(){return this.deps.membershipFeedKv()}set membershipFeedKv(kv){this.deps.setMembershipFeedKv(kv)}get membershipFeedWatches(){return this.deps.membershipFeedWatches()}get watchDeletePermissions(){return this.deps.watchDeletePermissions()}notLiveMsg(){return this.deps.notLiveMsg()}readChannels(){return this.deps.readChannels()}armJoin(channels){return this.deps.armJoin(channels)}backfillArmed(frontiers,floorSeq){return this.deps.backfillArmed(frontiers,floorSeq)}subscribeChat(channel){this.deps.subscribeChat(channel)}unsubscribeChat(channel){this.deps.unsubscribeChat(channel)}confirmChatSub(){return this.deps.confirmChatSub()}durableJoinChannel(channel){return this.deps.durableJoinChannel(channel)}durableLeaveChannel(channel,generation,lifecycleUid){return this.deps.durableLeaveChannel(channel,generation,lifecycleUid)}fetchMemberships(channel){return this.deps.fetchMemberships(channel)}recordOwnWatchConsumer(info){return this.deps.recordOwnWatchConsumer(info)}watchConsumerDeleteDenied(stream,name2,owner2){return this.deps.watchConsumerDeleteDenied(stream,name2,owner2)}deleteMembershipConsumer(jsm,stream,name2){return this.deps.deleteMembershipConsumer(jsm,stream,name2)}emit(event,...args){return this.deps.emit(event,...args)}joinedChannels(){return[...this.channels]}async joinChannel(channel){if(!this.jsm)throw new Error(this.notLiveMsg());if(this.channels.includes(channel))return{joined:false,backfilled:0,durable:this.plane3Channels.has(channel)};if(this.readsChannelsOnDemand)await this.readChannels();const armed2=await this.armJoin([channel]);this.subscribeChat(channel);try{await this.confirmChatSub()}catch(e3){this.unsubscribeChat(channel);throw new Error(`cannot join "${channel}": live subscription could not be confirmed (${e3.message})`)}if(this.chatSubDenied.has(channel)){this.unsubscribeChat(channel);throw new Error(`cannot join "${channel}": not within this agent's read ACL (allowSubscribe)`)}this.channels.push(channel);let durable=false;let reason;const family=isChannelFamily(channel);if(!family&&!isConcreteChannel(channel))reason="a pattern with * or the root > has no stored copies; follow a concrete channel or a family such as review.>";else if(family||effectiveDeliveryClass(this.channelConfigs.get(channel),this.channelDefaults)==="durable"){try{const r2=await this.durableJoinChannel(channel);if(r2.durable){this.plane3Channels.set(channel,r2.generation??0);durable=true}else{reason=r2.reason??"durable backstop unavailable"}}catch(e3){reason=`durable backstop unavailable (${e3.message})`}}const backfilled=await this.backfillArmed(armed2);return{joined:true,backfilled,durable,...reason!==void 0?{reason}:{}}}async leaveChannel(channel,legacyDiscoveryMessage){if(!this.jsm)throw new Error(this.notLiveMsg());let left=this.channels.includes(channel);if(this.authed&&(isChannelFamily(channel)||isConcreteChannel(channel))){const memberships=await this.fetchMemberships(channel);if(memberships===void 0&&this.plane3Channels.has(channel))await this.durableLeaveChannel(channel,this.plane3Channels.get(channel));for(const member of memberships??[]){if(member.lifecycleUid===void 0)throw new Error(legacyDiscoveryMessage??"the delivery daemon predates lifecycle-aware membership discovery, so this durable leave was not applied and the channel stays joined; restart the daemon at this version (`cotal up` runs it)");await this.durableLeaveChannel(channel,member.generation,member.lifecycleUid);left=true}if(memberships!==void 0)this.plane3Channels.delete(channel)}this.unsubscribeChat(channel);const i2=this.channels.indexOf(channel);if(i2>=0)this.channels.splice(i2,1);return{left}}async chatRetention(){if(!this.nc)throw new Error(this.notLiveMsg());const mgr=await(0,import_jetstream16.jetstreamManager)(this.nc);let info;try{info=await mgr.streams.info(chatStream(this.space),{subjects_filter:">"})}catch(e3){if(!isJetStreamMissing(e3,import_jetstream16.JetStreamApiCodes.StreamNotFound))throw e3;return{perSender:null,maxAgeMs:null,oldestAt:null,senders:[],stream:false,lastSeq:0}}const senders=[];for(const[subject,messages]of Object.entries(info.state.subjects??{})){const p2=parseSubject(subject);if(p2?.kind==="chat"&&isPrincipalOwnerToken(p2.owner))senders.push({channel:p2.rest,sender:p2.sender,messages})}const cap=info.config.max_msgs_per_subject;const age=info.config.max_age;return{perSender:typeof cap==="number"&&cap>0?cap:null,maxAgeMs:typeof age==="number"&&age>0?Math.round(age/1e6):null,oldestAt:info.state.messages>0?info.state.first_ts:null,senders:senders.sort((a3,b3)=>a3.channel.localeCompare(b3.channel)||a3.sender.localeCompare(b3.sender)),stream:true,lastSeq:info.state.last_seq}}async dmStreamPresent(){if(!this.nc)throw new Error(this.notLiveMsg());try{await(await(0,import_jetstream16.jetstreamManager)(this.nc)).streams.info(dmStream(this.space));return true}catch(e3){if(!isJetStreamMissing(e3,import_jetstream16.JetStreamApiCodes.StreamNotFound))throw e3;return false}}async listChannels(){if(!this.nc)throw new Error(this.notLiveMsg());if(this.readsChannelsOnDemand)await this.readChannels();const mgr=await(0,import_jetstream16.jetstreamManager)(this.nc);const counts=new Map;try{const info=await mgr.streams.info(chatStream(this.space),{subjects_filter:">"});if(info.state.subjects){for(const[subject,count]of Object.entries(info.state.subjects)){const p2=parseSubject(subject);if(p2?.kind==="chat"&&isPrincipalOwnerToken(p2.owner))counts.set(p2.rest,(counts.get(p2.rest)??0)+count)}}}catch(e3){if(!isJetStreamMissing(e3,import_jetstream16.JetStreamApiCodes.StreamNotFound))throw e3}const channels=new Set([...counts.keys(),...this.channelConfigs.keys()]);return[...channels].map(channel=>({channel,messages:counts.get(channel)??0,config:this.channelConfigs.get(channel)})).sort((a3,b3)=>a3.channel.localeCompare(b3.channel))}async membershipFeedRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.membershipFeedKv??=await new import_kv8.Kvm(this.nc).open(membershipBucket(this.space));return this.membershipFeedKv}async readMembership(){const kv=await this.membershipFeedRegistry();const members=[];let asOf;let entries;try{entries=await lastKvEntries(kv)}catch(e3){if(!isPublishPermissionDenied(e3))throw e3;throw new Error(`membership read refused for ${this.card.id}: this credential may not publish $JS.API.DIRECT.GET.KV_${membershipBucket(this.space)}, the membership feed read (SPEC Appendix B). A credential minted by an older issuer can lack this grant even when newly minted; upgrade the manager or auth service that issues credentials, then mint a new credential. Reusing credentials or reconnecting does not add the grant.`,{cause:e3})}for(const e3 of entries){if(e3.key===MEMBERSHIP_FEED_KEY){try{asOf=e3.json().observedAt}catch{}continue}try{const rec=e3.json();members.push({id:e3.key,live:rec.live??[],durable:rec.durable??[],observedAt:rec.observedAt})}catch{}}return{asOf,members}}async watchMembership(onChange,onClosed){if(this.stopped)throw new Error("endpoint stopped - cannot watch membership");const watch={onChange,onClosed,stopped:false,arm:Promise.resolve()};this.membershipFeedWatches.add(watch);watch.arm=watch.arm.catch(()=>{}).then(()=>this.armMembershipWatch(watch));try{await watch.arm}catch(err3){watch.stopped=true;this.membershipFeedWatches.delete(watch);await this.disarmMembershipWatch(watch);throw err3}return{stop:async()=>{if(watch.stopPromise)return watch.stopPromise;watch.stopped=true;watch.stopPromise=new Promise((resolve6,reject)=>{watch.resolveStop=resolve6;watch.rejectStop=reject});watch.arm=watch.arm.catch(()=>{}).then(async()=>{await this.disarmMembershipWatch(watch);await this.deleteRetainedMembershipConsumer(watch);this.finishMembershipWatchStop(watch)}).catch(err3=>{watch.rejectStop?.(err3)});return watch.stopPromise}}}async armMembershipWatch(watch){if(watch.stopped)return;const kv=await this.membershipFeedRegistry();await this.deleteRetainedMembershipConsumer(watch);if(!(kv instanceof import_internal2.Bucket))throw new Error("membership watch needs the @nats-io/kv Bucket implementation");const cc=kv._buildCC(">",import_internal2.KvWatchInclude.LastValue,{headers_only:false});const consumer=await kv.js.consumers.getPushConsumer(kv.stream,cc);const info=await consumer.info(true);this.recordOwnWatchConsumer(info);watch.consumer=consumer;const permission2=this.nc&&this.watchDeletePermissions.get(this.nc);if(permission2)this.watchDeletePermissions.set(consumer,permission2);watch.consumerStream=info.stream_name;watch.consumerName=info.name;let replaying=info.num_pending>0;let iter;try{iter=await consumer.consume({callback:jm=>{if(watch.stopped||watch.consumer!==consumer)return;const entry=kv.jmToWatchEntry(jm,!replaying);watch.onChange(membershipChange(entry,!replaying));if(replaying&&jm.info.pending===0){replaying=false;watch.onChange({type:"replayed",revision:entry.revision})}}})}catch(err3){await this.disarmMembershipWatch(watch);throw err3}watch.iter=iter;if(watch.stopped){await this.disarmMembershipWatch(watch);return}if(!replaying)watch.onChange({type:"replayed",revision:0});iter.closed().then(()=>{if(watch.stopped||watch.consumer!==consumer)return;const err3=new Error("membership watch closed");watch.onClosed?.(err3);this.emit("error",err3)}).catch(()=>{})}async deleteRetainedMembershipConsumer(watch){if(!watch.consumerStream||!watch.consumerName)return;if(!this.nc||this.nc.isClosed())return;if(this.watchConsumerDeleteDenied(watch.consumerStream,watch.consumerName,this.nc)){watch.consumerStream=void 0;watch.consumerName=void 0;return}const jsm=await(0,import_jetstream16.jetstreamManager)(this.nc);if(await this.deleteMembershipConsumer(jsm,watch.consumerStream,watch.consumerName)){watch.consumerStream=void 0;watch.consumerName=void 0}}finishMembershipWatchStop(watch){if(!watch.stopped||watch.consumer||watch.iter||watch.consumerStream||watch.consumerName)return;this.membershipFeedWatches.delete(watch);watch.resolveStop?.();watch.resolveStop=void 0;watch.rejectStop=void 0}async disarmMembershipWatch(watch){const iter=watch.iter;const consumer=watch.consumer;watch.iter=void 0;watch.consumer=void 0;try{iter?.stop()}catch{}if(consumer){if(watch.consumerStream&&watch.consumerName&&this.watchConsumerDeleteDenied(watch.consumerStream,watch.consumerName,consumer)){watch.consumerStream=void 0;watch.consumerName=void 0;return}try{const deleted=await consumer.delete();if(deleted){watch.consumerStream=void 0;watch.consumerName=void 0}}catch(err3){if(membershipConsumerReleased(err3)){watch.consumerStream=void 0;watch.consumerName=void 0}else{const closedEpoch=err3 instanceof import_transport_node18.ClosedConnectionError;const timeout=err3 instanceof import_transport_node18.TimeoutError;if(timeout||closedEpoch){this.emit("error",err3)}else{throw err3}}}}}async rearmMembershipWatches(){await Promise.all([...this.membershipFeedWatches].map(async watch=>{watch.arm=watch.arm.catch(()=>{}).then(async()=>{await this.disarmMembershipWatch(watch);await this.deleteRetainedMembershipConsumer(watch);if(!watch.stopped)await this.armMembershipWatch(watch)});try{await watch.arm;this.finishMembershipWatchStop(watch)}catch(err3){this.emit("error",err3)}}))}}}});var import_jetstream17,EndpointChannelDiscovery;var init_endpoint_channel_discovery=__esm({"../../packages/core/dist/endpoint-channel-discovery.js"(){"use strict";import_jetstream17=__toESM(require_mod4(),1);init_channels();init_endpoint();init_jetstream_missing();init_kv_scan();init_subjects();EndpointChannelDiscovery=class{deps;constructor(deps){this.deps=deps}get nc(){return this.deps.nc()}get space(){return this.deps.space()}get card(){return this.deps.card()}get doConsume(){return this.deps.doConsume()}get doWatch(){return this.deps.doWatch()}get doWatchChannels(){return this.deps.doWatchChannels()}get channelKv(){return this.deps.channelKv()}set channelWatchIter(iter){this.deps.setChannelWatchIter(iter)}get channelConfigs(){return this.deps.channelConfigs()}get channelDefaults(){return this.deps.channelDefaults()}set channelDefaults(defaults){this.deps.setChannelDefaults(defaults)}get channelRead(){return this.deps.channelRead()}set channelRead(read){this.deps.setChannelRead(read)}get channelReadGeneration(){return this.deps.channelReadGeneration()}set channelReadGeneration(n2){this.deps.setChannelReadGeneration(n2)}get channelReadApplied(){return this.deps.channelReadApplied()}set channelReadApplied(n2){this.deps.setChannelReadApplied(n2)}notLiveMsg(){return this.deps.notLiveMsg()}bindKvWatch(kv){return this.deps.bindKvWatch(kv)}emitRecoverable(err3){this.deps.emitRecoverable(err3)}emit(event,...args){return this.deps.emit(event,...args)}get readsChannelsOnDemand(){return this.doConsume&&this.doWatchChannels&&!this.doWatch}async readChannels(){if(!this.readsChannelsOnDemand)throw new Error("readChannels is for a consumer that reads presence on demand; this endpoint watches the channel registry or keeps no cache of it");const kv=this.channelKv;if(!kv)throw new Error(this.notLiveMsg());if(this.channelRead)return this.channelRead;const generation=++this.channelReadGeneration;const read=(async()=>{let entries;try{entries=await lastKvEntries(kv)}catch(e3){if(!isPublishPermissionDenied(e3))throw e3;throw new Error(`channel registry read refused for ${this.card.id}: this credential may not publish $JS.API.DIRECT.GET.KV_${channelBucket(this.space)}, the on-demand registry read (SPEC Appendix B). A credential minted by an older issuer can lack this grant even when newly minted; upgrade the manager or auth service that issues credentials, then mint a new credential. Reusing credentials or reconnecting does not add the grant.`,{cause:e3})}if(generation<=this.channelReadApplied)return;this.channelReadApplied=generation;this.channelConfigs.clear();this.channelDefaults={};for(const e3 of entries)this.handleChannelEntry(e3)})();this.channelRead=read;const settled=()=>{if(this.channelRead===read)this.channelRead=void 0};read.then(settled,settled);return read}getChannelConfig(channel){return this.channelConfigs.get(channel)}channelReplay(channel){return effectiveReplay(this.channelConfigs.get(channel),this.channelDefaults)}channelReplayWindow(channel){return this.channelConfigs.get(channel)?.replayWindow??this.channelDefaults.replayWindow}async channelReplayPolicy(channel){if(!this.nc)throw new Error(this.notLiveMsg());const kv=this.channelKv??await openChannelRegistry(this.nc,this.space,{create:false});let cfg;let defaults;try{[cfg,defaults]=await Promise.all([isConcreteChannel(channel)?readChannelConfig(kv,channel):Promise.resolve(void 0),readChannelDefaults(kv)])}catch(e3){if(!isJetStreamMissing(e3,import_jetstream17.JetStreamApiCodes.StreamNotFound))throw e3}return{replay:effectiveReplay(cfg,defaults),window:cfg?.replayWindow??defaults?.replayWindow??null,registered:cfg!==void 0}}channelDeliveryClass(channel){return effectiveDeliveryClass(this.channelConfigs.get(channel),this.channelDefaults)}async startChannelWatch(){if(!this.channelKv)return;const bound=await this.bindKvWatch(this.channelKv);if(!bound)return;const{iter}=bound;this.channelWatchIter=iter;void(async()=>{for await(const e3 of iter)this.handleChannelEntry(e3)})().catch(e3=>this.emit("error",e3))}async readChannelsOnce(){if(!this.channelKv)return;for(const e3 of await lastKvEntries(this.channelKv))this.handleChannelEntry(e3)}handleChannelEntry(e3){const isDefaults=e3.key===CHANNEL_DEFAULTS_KEY;if(isDefaults)this.channelDefaults={};else this.channelConfigs.delete(e3.key);if(e3.operation==="DEL"||e3.operation==="PURGE")return;try{if(isDefaults)this.channelDefaults=decodeChannelEntry(e3);else this.channelConfigs.set(e3.key,decodeChannelEntry(e3))}catch(err3){this.emitRecoverable(new Error(`dropped channel registry entry for key ${JSON.stringify(e3.key)}: ${err3.message}`))}}}}});import{randomUUID as randomUUID7}from"node:crypto";var import_transport_node19,EndpointLiveness;var init_endpoint_liveness=__esm({"../../packages/core/dist/endpoint-liveness.js"(){"use strict";import_transport_node19=__toESM(require_transport_node(),1);init_liveness();init_subjects();EndpointLiveness=class{deps;constructor(deps){this.deps=deps}get nc(){return this.deps.nc()}get space(){return this.deps.space()}get owner(){return this.deps.owner()}get actor(){return this.deps.actor()}get subs(){return this.deps.subs()}get livenessResponders(){return this.deps.livenessResponders()}notLiveMsg(){return this.deps.notLiveMsg()}requestBoundReply(nc,subject,body,reply,timeoutMs){return this.deps.requestBoundReply(nc,subject,body,reply,timeoutMs)}isNoResponders(e3){return this.deps.isNoResponders(e3)}emitRecoverable(err3){this.deps.emitRecoverable(err3)}emit(event,...args){return this.deps.emit(event,...args)}serveLiveness(plane,readState){if(!this.nc)throw new Error(this.notLiveMsg());const held2=this.livenessResponders.get(plane);if(held2)held2.readState=readState;else this.livenessResponders.set(plane,{readState});this.bindLiveness(plane)}bindLiveness(plane){const held2=this.livenessResponders.get(plane);if(!held2||!this.nc)return;if(held2.sub){try{held2.sub.unsubscribe()}catch{}const i2=this.subs.indexOf(held2.sub);if(i2>=0)this.subs.splice(i2,1)}const{readState}=held2;const sub=this.nc.subscribe(livenessServeFilter(this.space,plane),{queue:`live.${plane}`});held2.sub=sub;this.subs.push(sub);const instance=randomUUID7();void(async()=>{for await(const m2 of sub){if(!m2.reply||!m2.reply.startsWith(`${m2.subject}.reply.`)){this.emitRecoverable(new Error(`rejected liveness probe on ${m2.subject}: reply target "${m2.reply??"(none)"}" is not under the sender's own reply subtree`));continue}let responder;try{responder=await readState()}catch{responder="unknown"}const answer={plane,responder,instance};try{m2.respond(JSON.stringify(answer))}catch{}}})().catch(e3=>this.emit("error",e3))}async probeLiveness(plane,timeoutMs=2e3){if(!isLivenessPlane(plane))throw new Error(`liveness: "${plane}" is not a plane this surface answers for (${[...LIVENESS_PLANES].join(", ")})`);if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=livenessSubject(this.space,plane,this.owner,this.actor);const reply=`${reqSubject}.reply.${randomUUID7()}`;let outcome;let answered;let instance;try{const m2=await this.requestBoundReply(this.nc,reqSubject,"",reply,timeoutMs);let body;try{body=m2.json()}catch{body=void 0}const parsed=parseLivenessAnswer(body,plane);outcome=parsed?"replied":"malformed";answered=parsed?.responder;instance=parsed?.instance}catch(e3){outcome=this.isNoResponders(e3)?"noResponders":this.probeFailureOutcome(e3)}const verdict={plane,responder:responderFromProbe(outcome,answered)};return instance===void 0?verdict:{...verdict,instance}}probeFailureOutcome(e3){if(e3 instanceof import_transport_node19.AuthorizationError||e3 instanceof import_transport_node19.PermissionViolationError)return"refused";if(e3 instanceof import_transport_node19.TimeoutError)return"timeout";return"refused"}}}});var import_jetstream18,EndpointProvisioning;var init_endpoint_provisioning=__esm({"../../packages/core/dist/endpoint-provisioning.js"(){"use strict";import_jetstream18=__toESM(require_mod4(),1);init_jetstream_missing();init_permission_denied();init_streams();init_subjects();EndpointProvisioning=class{deps;constructor(deps){this.deps=deps}get jsm(){return this.deps.jsm()}get space(){return this.deps.space()}get authed(){return this.deps.authed()}notLiveMsg(){return this.deps.notLiveMsg()}manager(){return this.deps.manager()}async ensureStreams(){if(!this.jsm)throw new Error(this.notLiveMsg());await createSpaceStreams(this.jsm,this.space)}async ensureOpenSpaceStreams(){if(this.authed)throw new Error(`the streams of ${this.space} come from its broker's setup on an authenticated space; a sender does not create them`);await createSpaceStreams(await this.manager(),this.space)}async provisionDmInbox(owner2,actor2,lifecycleUid){await this.ensureDmDurable(owner2,actor2,lifecycleUid,{})}async ensureDmDurable(owner2,actor2,lifecycleUid,opts){const jsm=await this.manager();const stream=dmStream(this.space);const name2=dmDurable(owner2,actor2,lifecycleUid);try{await jsm.consumers.info(stream,name2);return}catch(e3){if(!isJetStreamMissing(e3,import_jetstream18.JetStreamApiCodes.ConsumerNotFound))throw e3}const frontier=(await jsm.streams.info(stream)).state.last_seq;try{await jsm.consumers.add(stream,dmDurableConfig(this.space,owner2,actor2,lifecycleUid,{...opts,activationFrontier:frontier}))}catch(e3){try{await jsm.consumers.info(stream,name2);return}catch(probeError){if(isPermissionDenied(probeError))throw probeError}throw e3}}async provisionDlvInbox(owner2,actor2,lifecycleUid){const jsm=await this.manager();await jsm.consumers.add(dlvStream(this.space),dlvDurableConfig(this.space,owner2,actor2,lifecycleUid))}async provisionTaskQueue(role){const jsm=await this.manager();await jsm.consumers.add(taskStream(this.space),taskDurableConfig(this.space,role))}}}});var EndpointBootMemberships;var init_endpoint_boot_memberships=__esm({"../../packages/core/dist/endpoint-boot-memberships.js"(){"use strict";init_subjects();EndpointBootMemberships=class{deps;constructor(deps){this.deps=deps}get channels(){return this.deps.channels()}get plane3Channels(){return this.deps.plane3Channels()}get pendingBootJoins(){return this.deps.pendingBootJoins()}get stopped(){return this.deps.stopped()}requestDelivery(op,args,timeoutMs){return this.deps.requestDelivery(op,args,timeoutMs)}requireLifecycleUid(what2){return this.deps.requireLifecycleUid(what2)}deliveryClassFresh(channel){return this.deps.deliveryClassFresh(channel)}durableJoinChannel(channel){return this.deps.durableJoinChannel(channel)}membershipPause(attempt){return this.deps.membershipPause(attempt)}isNoResponders(e3){return this.deps.isNoResponders(e3)}emitRecoverable(err3){this.deps.emitRecoverable(err3)}async fetchMemberships(channel){let reply;try{reply=await this.requestDelivery("listMemberships",{lifecycleUid:this.requireLifecycleUid("listing durable memberships"),...channel===void 0?{}:{channel}},5e3)}catch(e3){if(this.isNoResponders(e3))return void 0;throw e3}if(!reply.ok)throw new Error(reply.error??"listMemberships failed");return reply.data?.memberships??[]}async armBootDurableMemberships(){for(const channel of this.channels){if(this.plane3Channels.has(channel))continue;if(!isChannelFamily(channel)){if(!isConcreteChannel(channel))continue;const cls=await this.deliveryClassFresh(channel);if(cls!=="durable")continue}try{const r2=await this.durableJoinChannel(channel);if(r2.durable)this.plane3Channels.set(channel,r2.generation??0);else void this.reconcileBootJoin(channel)}catch(e3){if(!this.isNoResponders(e3))this.emitRecoverable(e3);void this.reconcileBootJoin(channel)}}}async reconcileBootJoin(channel){if(this.pendingBootJoins.has(channel))return;this.pendingBootJoins.add(channel);for(let attempt=0;;attempt++){await this.membershipPause(attempt);if(this.stopped||!this.channels.includes(channel)||this.plane3Channels.has(channel)){this.pendingBootJoins.delete(channel);return}try{const r2=await this.durableJoinChannel(channel);if(r2.durable){this.plane3Channels.set(channel,r2.generation??0);this.pendingBootJoins.delete(channel);return}}catch(e3){if(attempt===0&&!this.isNoResponders(e3))this.emitRecoverable(new Error(`channel "${channel}": boot durable self-join not yet established - retrying until the delivery daemon is reachable (${e3.message})`))}}}hasDurableMembership(channel){return this.plane3Channels.has(channel)}}}});var import_transport_node20;var init_broker_identity=__esm({"../../packages/core/dist/broker-identity.js"(){"use strict";import_transport_node20=__toESM(require_transport_node(),1);init_identity()}});var init_space_quiescence_resources=__esm({"../../packages/core/dist/space-quiescence-resources.js"(){"use strict";init_subjects();init_endpoint_binding();init_endpoint_records();init_broker_identity()}});var PLACEMENT_COMMANDS,PLACED_LIFECYCLE_COMMANDS;var init_run_driver_grants=__esm({"../../packages/core/dist/run-driver-grants.js"(){"use strict";init_subjects();init_endpoint_subjects();init_endpoint_records();init_run_admission();init_endpoint_binding();init_endpoint_grants();PLACEMENT_COMMANDS=Object.freeze(["describe","resolve-cwd","spawn"]);PLACED_LIFECYCLE_COMMANDS=Object.freeze(["turn"])}});var import_nats_core6,import_jetstream19,import_obj2,TRANSFER_CHUNK_MAX,HEADER_ROOM;var init_transfer=__esm({"../../packages/core/dist/transfer.js"(){"use strict";import_nats_core6=__toESM(require_mod3(),1);import_jetstream19=__toESM(require_mod4(),1);import_obj2=__toESM(require_mod7(),1);init_subjects();init_artifact();init_endpoint_records();TRANSFER_CHUNK_MAX=128*1024;HEADER_ROOM=4*1024}});var import_nkeys7,REMOTE_MANAGER_AUTHORITY_OPERATIONS,REMOTE_MANAGER_MAINTENANCE_OPERATIONS,MANAGED_AGENT_RUNTIME_STATES,MANAGED_AGENT_RUNTIME_READINESS,MANAGED_AGENT_RETIREMENT_PHASES,REMOTE_MANAGER_IDENTITY_NAMES;var init_remote_manager_authority=__esm({"../../packages/core/dist/remote-manager-authority.js"(){"use strict";import_nkeys7=__toESM(require_mod(),1);init_canonical();init_endpoint_error();init_identity();init_subjects();REMOTE_MANAGER_AUTHORITY_OPERATIONS=Object.freeze(["prepare","activate","renew","session","retire","renewStandingBundle","renewRunDriver","transferReader"]);REMOTE_MANAGER_MAINTENANCE_OPERATIONS=Object.freeze(["evict-family-principal","reconcile-registration"]);MANAGED_AGENT_RUNTIME_STATES=Object.freeze(["reserved","creating","bound","create-unknown","closing","closed"]);MANAGED_AGENT_RUNTIME_READINESS=Object.freeze(["ready","bound-not-ready","none"]);MANAGED_AGENT_RETIREMENT_PHASES=Object.freeze(["intent","released","retired","deprovisioned","terminal"]);REMOTE_MANAGER_IDENTITY_NAMES=Object.freeze(["supervisor","executor","serve","goalWriter","sessionLedger"])}});var init_environment_manager_grants=__esm({"../../packages/core/dist/environment-manager-grants.js"(){"use strict";init_endpoint_grants();init_endpoint_binding();init_remote_manager_authority();init_subjects();init_endpoint_subjects()}});var enc5,dec5;var init_run_submission=__esm({"../../packages/core/dist/run-submission.js"(){"use strict";init_canonical();init_endpoint_error();init_run_admission();init_endpoint_subjects();init_endpoint_subjects();enc5=new TextEncoder;dec5=new TextDecoder("utf-8",{fatal:true})}});var init_lifecycle_state=__esm({"../../packages/core/dist/lifecycle-state.js"(){"use strict";init_canonical();init_service_gate();init_endpoint_envelope();init_endpoint_records();init_endpoint_subjects();init_subjects()}});var SPAWN_VIEW_READS;var init_provision_permission_builders=__esm({"../../packages/core/dist/provision-permission-builders.js"(){"use strict";init_event_payloads();init_streams();init_space_deletion_targets();init_broker_identity();init_subjects();init_endpoint_grants();init_endpoint_service();init_endpoint_binding();init_endpoint_subjects();init_issued_authority();init_registry_contract();init_run_admission();init_run_submission();init_endpoint_records();init_lifecycle_state();init_backup();SPAWN_VIEW_READS=Object.freeze(["status","models","resolve-cwd","list-dir","ps"])}});var init_provision_permissions=__esm({"../../packages/core/dist/provision-permissions.js"(){"use strict";init_space_quiescence_resources();init_event_payloads();init_subjects();init_liveness();init_endpoint_grants();init_endpoint_binding();init_endpoint_subjects();init_issued_authority();init_registry_contract();init_run_driver_grants();init_transfer();init_environment_manager_grants();init_backup();init_provision_permission_builders();init_provision_permission_builders()}});function inspectCredHealth(creds,nowSec=Math.floor(Date.now()/1e3)){let claims2;try{claims2=credsClaims(creds)}catch(e3){return{state:"unreadable",error:e3.message}}const{iat,exp}=claims2;if(typeof exp!=="number")return{state:"unbounded",iat};if(typeof iat!=="number")return{state:"unreadable",iat:void 0,exp,error:"user JWT carries exp but no iat - cannot place the renewal point"};const renewAt=Math.floor(iat+.75*(exp-iat));if(nowSec>=exp)return{state:"expired",iat,exp,renewAt};if(nowSec>=renewAt)return{state:"near-expiry",iat,exp,renewAt};return{state:"healthy",iat,exp,renewAt}}var import_nkeys8,FIVE_MINUTES,MAX_CONTROL_LINE_BYTES,CONNECT_ENVELOPE_OVERHEAD_BYTES,MAX_MINTED_JWT_BYTES,STANDING_RENEWABLE_TTL_SEC,ROTATION_RENEWED_TTL_SEC,CREDENTIAL_LIFETIMES,LIFETIME_TTL_SNAP,BASE_LIMITS,DATA_LIMITS,SYS_LIMITS;var init_provision_jwt=__esm({"../../packages/core/dist/provision-jwt.js"(){"use strict";init_nkey_signer();init_jwt();import_nkeys8=__toESM(require_mod(),1);init_subjects();init_endpoint_grants();init_endpoint_service();init_service_gate();init_service_authority_limits();init_issued_authority();init_run_driver_grants();init_lifecycle_state();init_environment_manager_grants();init_identity();init_backup();init_provision_permissions();FIVE_MINUTES=5*60;MAX_CONTROL_LINE_BYTES=65536;CONNECT_ENVELOPE_OVERHEAD_BYTES=512;MAX_MINTED_JWT_BYTES=MAX_CONTROL_LINE_BYTES-CONNECT_ENVELOPE_OVERHEAD_BYTES;STANDING_RENEWABLE_TTL_SEC=24*60*60;ROTATION_RENEWED_TTL_SEC=30*24*60*60;CREDENTIAL_LIFETIMES={agent:{class:"mixed",note:"manager children, foreground spawn/join, and `cotal mint` static outputs all use this profile; split or repair flow required before default exp"},"manager-caller":{class:"mixed",note:"short-lived user-auth view bound to the bearer expiry and one manager instance"},observer:{class:"static-operator-managed",note:"out-of-band dashboard/audit credential from `cotal mint`"},admin:{class:"static-operator-managed",note:"out-of-band elevated dashboard/audit credential from `cotal mint`"},supervisor:{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"manager's always-on endpoint; the manager holds the DATA seed and self-remints via the endpoint creds source"},delivery:{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"server-side Plane-3 daemon; seed-less - the manager re-signs .cotal/delivery.creds for the SAME nkey, requests delivery-admin reloadCreds for explicit adoption, and the endpoint source re-read is only a backstop"},"membership-rw":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"membership feed writer; seed-less - the manager re-signs the membership-rw.creds store key for the SAME nkey, the feed adopts it on a 75% preflight-proven renewal timer (its active self-heal), and delivery-admin reloadCreds is the explicit adoption on top"},provisioner:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"setup/spawn provisioning window only"},deprovisioner:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"target-pinned teardown window only"},"retirement-requester":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one despawn's retirement request window; request+reply only"},"lifecycle-executor":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one static lifecycle operation's 13.1 state-write window (activation / terminal / renewal ledger append)"},"endpoint-serve-executor":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one endpoint registration/serve-mint window (13.1 epgate CAS + epcred stage/revoke + eprepair cursor for one (endpoint, instanceId))"},operator:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"send/dm/join/probe-style operator command"},purger:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"history purge command"},backup:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"offline snapshot phase; exact stream and delivery subject, memory-only"},restore:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"offline restore initiation or exact-ID upload phase, memory-only"},"space-quiescence-reader":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"host-only idle-work observation; no writes, ACKs, consumer creation or renewal"},probe:{class:"one-shot",defaultTtlSeconds:60,note:"connect-only preflight"},"channel-writer":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"channel registry mutation command"},"channel-purger":{class:"mixed",note:"one-shot for CLI, standing inside web; split or renewal required before default exp"},teardown:{class:"one-shot",note:"space teardown can be long/destructive; needs TTL budget/remint guard before default exp"},"membership-store-recreate":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one stopped-space conversion of the derived membership stream from File to Memory; exact stream info/delete only"},"issued-store-recreate":{class:"one-shot",defaultTtlSeconds:30*60,note:"one `up --recreate-issued-stores` step: snapshot and delete the two pre-retention issued-authority stores of one space; 30 minutes bounds a large store's snapshot"},"control-caller-privileged":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"ps/start control call"},"control-caller-admin":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"stop/attach admin control call"},deployer:{class:"one-shot",note:"manifest deploy spans planning/launch/ledger; needs near-expiry guard or remint before default exp"},"endpoint-serve":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"per-instance endpoint serve credential (SPEC 13.9); the managing authority re-mints on renewal and on takeover (new epoch), and the 13.1 barrier revokes the superseded one"},"goal-writer":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"self-mediated goal-writer for spawn-as-action; the manager re-mints for the SAME nkey on renewal, disjoint from the serve credential"},"session-caller":{class:"one-shot",defaultTtlSeconds:24*60*60,note:"per-session console/CLI caller cred: rails-only for ONE \xA713.6 session; TTL-BOUND to the session (the face mints with expiresAt = the session exp; the 24h default is the SESSION_GRANT_MAX_TTL ceiling, never a standing lifetime); NEVER renewed - a new session mints a new cred"},"dm-reader":{class:"mixed",note:"user-auth own-DM reader view: one dm_ durable's INFO/NEXT/ACK, bound to the bearer expiry (which the IdP proof bounds); renewed by re-exchange, never a standing credential"},"session-serving":{class:"one-shot",defaultTtlSeconds:24*60*60,note:"per-session SERVING cred: rails-only for ONE \xA713.6 session, the mirror of session-caller with the directions swapped; minted at redemption and TTL-BOUND to the session (the 24h default is the SESSION_GRANT_MAX_TTL ceiling, never a standing lifetime); NEVER renewed - a new session mints a new cred, and the session's terminal revokes this one by name"},"session-ledger":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"manager's session LEDGER: the dedicated sessions-bucket `session.<id>` rows and NOTHING else - no session rail of any shape. Standing because SPEC 13.6 makes it the durable revocation authority that must survive the serving endpoint; the manager re-mints for the SAME nkey on the half-TTL loop (the goal-writer precedent)"},"run-driver":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"one workflow run's driver, per takeover attempt (SPEC 14.6): the hosting manager mints it when it takes the run over and re-mints for the SAME nkey on renewal; a new takeover mints a new one"},"run-mediator":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"trusted workflow host operations, bound to one run and attempt; kept on the hosting process's connection"},"run-operator":{class:"one-shot",defaultTtlSeconds:60,note:"one served run-status / run-ps / run-answer call (SPEC 14.3): the hosting manager mints it per call on its own connection, never the serve rails; 60s bounds a copied cred to a minute"},"registry-reader":{class:"standing-renewable",defaultTtlSeconds:60*60,renewalOwner:"registry host",note:"the registry's reads (SPEC 13.20), no write of any shape; the evidence-store read is stream-scoped, so it can read every recorded ceiling in the space (a NAMED RESIDUAL), and one hour bounds a copied credential; the process hosting the registry re-mints it"},issuer:{class:"mixed",defaultTtlSeconds:FIVE_MINUTES,renewalOwner:"auth-service",note:"renewed as the auth plane's held session for connect-time issuance (re-minted before exp, closed with the plane); one-shot for every other issuance window and for a lifecycle terminal's issuance retirement (SPEC 13.15)"},"run-admitter":{class:"one-shot",defaultTtlSeconds:60,note:"one hosted run's admission record create, or its revocation marker (SPEC 14.8); 60s bounds a copied cred to a minute"},"transfer-writer":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one carried resume per CLI call: one object's chunk and meta subjects in one instance's transfer bucket"},"transfer-reader":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one transcript-receive or sweep over the minting instance's own transfer bucket"},"endpoint-evictor":{class:"one-shot",defaultTtlSeconds:60,note:"one re-registration's verify-evict window: a scoped delivery-admin caller that kicks+verifies the SUPERSEDED serve family before the epoch advances; 60s bounds a copied cred to a minute"},"remote-manager":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"auth-service",note:"the scoped remote manager lifecycle: own lease/presence plus same-owner agent provisioning; issued only by the typed supervise protocol, never by `cotal mint` or a raw view/profile string"},"environment-bootstrap":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one admitted environment's bootstrap caller; explicit expiry capped by admission and five minutes"},"environment-manager-supervisor":{class:"standing-renewable",renewalOwner:"environment-authority",note:"own lease/presence/liveness; explicit expiry capped by admission, no auth-store access"},"environment-manager-executor":{class:"standing-renewable",renewalOwner:"environment-authority",note:"own admitted authority instance RPC; explicit expiry capped by admission, no direct store access"},"environment-manager-goal-writer":{class:"standing-renewable",renewalOwner:"environment-authority",note:"manager goal rows without the auth-read belt; explicit expiry capped by admission"},"membership-observer":{class:"rotation-renewed",defaultTtlSeconds:ROTATION_RENEWED_TTL_SEC,renewalOwner:"system-account rotation",note:"$SYS-account CONNZ observer; NOT online-renewable ($SYS seed dies at `up`) - bounded exp, renewed only by rotateSystemAccount + broker restart; doctor warns near expiry"},"account-census":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"Host-only account CONNZ and account-qualified replies; at most five minutes, no KICK or client-side renewal"},"connection-evictor":{class:"rotation-renewed",defaultTtlSeconds:ROTATION_RENEWED_TTL_SEC,renewalOwner:"system-account rotation",note:"$SYS-account KICK-only live-eviction cred; same rotation-renewed posture as the observer"}};for(const p2 of Object.values(CREDENTIAL_LIFETIMES))Object.freeze(p2);Object.freeze(CREDENTIAL_LIFETIMES);LIFETIME_TTL_SNAP=new Map(Object.entries(CREDENTIAL_LIFETIMES).map(([k2,p2])=>[k2,p2.defaultTtlSeconds]));BASE_LIMITS={subs:-1,conn:-1,leaf:-1,imports:-1,exports:-1,data:-1,payload:-1,wildcards:true};DATA_LIMITS={...BASE_LIMITS,mem_storage:-1,disk_storage:-1};SYS_LIMITS={...BASE_LIMITS,mem_storage:0,disk_storage:0}}});var init_provision_resources=__esm({"../../packages/core/dist/provision-resources.js"(){"use strict";init_subjects();init_identity();init_provision_jwt();init_provision_permissions()}});var init_provision_server_config=__esm({"../../packages/core/dist/provision-server-config.js"(){"use strict";init_provision_jwt()}});var init_provision=__esm({"../../packages/core/dist/provision.js"(){"use strict";init_provision_permissions();init_provision_jwt();init_provision_resources();init_provision_server_config()}});import{createConnection,isIP}from"node:net";function authOpts(a3){const tls=a3.tls?{}:void 0;if(a3.bearer){if(a3.creds||a3.token||a3.user||a3.pass)throw new Error("bearer (user-mode auth) is mutually exclusive with creds/token/user/pass");if(!a3.sentinelCreds)throw new Error("user-mode bearer requires sentinelCreds");return{authenticator:[nativeCredsAuthenticator(a3.sentinelCreds),(0,import_transport_node21.tokenAuthenticator)(a3.bearer)],tls}}if(a3.creds){if(a3.token||a3.user||a3.pass)throw new Error("creds are mutually exclusive with token/user/pass auth");const creds=a3.creds;const authenticator=nonce4=>{const presented=typeof creds==="function"?creds():creds;const authenticated=nativeCredsAuthenticator(presented)(nonce4);a3.onCreds?.(presented);return authenticated};return{authenticator,tls}}return{token:a3.token,user:a3.user,pass:a3.pass,tls}}function bearerExpiryMs(bearer){return bearerLifetimeMs(bearer,0).expiresAtMs}function bearerLifetimeMs(bearer,adoptedAtMs){const payload=bearer.split(".")[1];if(!payload)throw new Error("user-mode bearer is not a JWT (no payload segment)");let claims2;try{claims2=JSON.parse(Buffer.from(payload,"base64url").toString("utf8"))}catch{throw new Error("user-mode bearer payload is not valid base64url JSON")}if(typeof claims2.exp!=="number")throw new Error("user-mode bearer is missing a numeric exp claim");const expiresAtMs=claims2.exp*1e3;return{issuedAtMs:Math.min(typeof claims2.iat==="number"?claims2.iat*1e3:adoptedAtMs,expiresAtMs),expiresAtMs}}function bearerRenewalDeadlineMs(bearer,adoptedAtMs){const{issuedAtMs,expiresAtMs}=bearerLifetimeMs(bearer,adoptedAtMs);return renewalDeadlineMs(issuedAtMs,expiresAtMs)}function decodeBearerPrincipal(bearer){const payload=bearer.split(".")[1];if(!payload)throw new Error("user-mode bearer is not a JWT (no payload segment)");let claims2;try{claims2=JSON.parse(Buffer.from(payload,"base64url").toString("utf8"))}catch{throw new Error("user-mode bearer payload is not valid base64url JSON")}const owner2=claims2.sub,actor2=claims2.act?.actor;if(typeof owner2!=="string"||typeof actor2!=="string")throw new Error("user-mode bearer is missing a string sub (owner) / act.actor claim");return{owner:owner2,actor:actor2}}function describeStatusError(err3){if(err3 instanceof import_transport_node21.PermissionViolationError){return new Error(`NATS permission denied: cannot ${err3.operation} "${err3.subject}" - check this endpoint's ACLs (a denied peer looks "absent" rather than blocked)`,{cause:err3})}return err3}function kvWatchConsumer(iter){const consumer=iter._data;if(!consumer)throw new Error("KV watch carries no consumer - the pinned nats.js changed shape");return consumer}function isPublishPermissionDenied(e3){const typed=e3 instanceof import_transport_node21.PermissionViolationError?e3:e3?.cause instanceof import_transport_node21.PermissionViolationError?e3.cause:void 0;return typed?.operation==="publish"}function wsServers(servers){return/^wss?:\/\//i.test((servers.split(",")[0]??"").trim())}function defaultProbeTimeoutMs(servers){return wsServers(servers)?5e3:1e3}function dialerFor(servers){if(!wsServers(servers))return(opts=>(0,import_transport_node21.connect)(withDialedTlsHost(servers,opts)));return(opts=>{const{tls,...rest}=opts??{};const targets=Array.isArray(rest.servers)?rest.servers:String(rest.servers??servers).split(",");if(tls&&targets.some(target2=>!/^wss:\/\//i.test(String(target2).trim())))return Promise.reject(new Error("TLS-required WebSocket connections must use wss:// for every server"));return(0,import_nats_core7.wsconnect)(rest)})}function withDialedTlsHost(servers,opts){const urls=servers.split(",").map(url2=>url2.trim()).filter(Boolean);const tls=opts?.tls;if(urls.length!==1||tls===null||tls===void 0&&!/^tls:\/\//i.test(urls[0]))return opts;let host;try{({host}=hostPort(urls[0]))}catch{return opts}return isIP(host)?{...opts,tls:{host,...tls}}:opts}function hostPort(server){const raw=(server.split(",")[0]??"").trim();const scheme=raw.match(/^([a-z][a-z0-9+.-]*):\/\//i)?.[1]?.toLowerCase();const first=raw.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"");const u2=new URL(`http://${first}`);const fallback=scheme==="wss"?443:scheme==="ws"?80:4222;return{host:u2.hostname,port:u2.port?Number(u2.port):fallback}}function tcpInfoProbe(server,timeoutMs){return new Promise(resolve6=>{let socket;let done=false;let connected=false;const finish=live=>{if(done)return;done=true;try{socket?.destroy()}catch{}resolve6(live)};let host,port;try{({host,port}=hostPort(server))}catch{return resolve6(false)}socket=createConnection({host,port});socket.setTimeout(timeoutMs);let buf="";socket.on("data",chunk=>{buf+=chunk.toString("utf8");const nl=buf.indexOf("\r\n");if(nl===-1){if(buf.length>4096)finish(false);return}const line=buf.slice(0,nl);const brace=line.indexOf("{");if(!/^INFO\b/.test(line)||brace===-1)return finish(false);try{finish({authRequired:JSON.parse(line.slice(brace))?.auth_required===true})}catch{finish(false)}});socket.on("connect",()=>{connected=true});socket.on("timeout",()=>finish(connected?"silent":false));socket.on("error",()=>finish(false));socket.on("close",()=>finish(false))})}function tcpDialable(server,timeoutMs){return new Promise(resolve6=>{let socket;let done=false;const finish=dialable=>{if(done)return;done=true;try{socket?.destroy()}catch{}resolve6(dialable)};let host,port;try{({host,port}=hostPort(server))}catch{return resolve6(false)}socket=createConnection({host,port});socket.setTimeout(timeoutMs);socket.on("connect",()=>finish(true));socket.on("timeout",()=>finish(false));socket.on("error",()=>finish(false));socket.on("close",()=>finish(false))})}function isAuthRejection(e3){return e3 instanceof import_transport_node21.AuthorizationError||e3 instanceof import_transport_node21.UserAuthenticationExpiredError}function retryAfterMs(e3){const seconds=e3?.retryAfterSeconds;return typeof seconds==="number"&&Number.isFinite(seconds)&&seconds>0?seconds*1e3:0}async function probeConnect(server=DEFAULT_SERVER,opts={}){const timeoutMs=opts.timeoutMs??defaultProbeTimeoutMs(server);const started=Date.now();const gate=opts.tls||wsServers(server)?tcpDialable:tcpInfoProbe;const greeting=await gate(server,timeoutMs);if(!greeting)return classifyProbeFailure(void 0,opts);if(greeting==="silent")return classifyProbeFailure(void 0,opts,false,"timeout");try{const nc=await dialerFor(server)({servers:server,timeout:Math.max(1,timeoutMs-(Date.now()-started)),reconnect:false,maxReconnectAttempts:0,...authOpts(opts)});await nc.close();return{ok:true}}catch(e3){return classifyProbeFailure(e3,opts,greeting!==true&&greeting.authRequired)}}function classifyProbeFailure(e3,opts,authRequired=false,otherwise="unreachable"){if(typeof opts.creds==="string"){try{if(inspectCredHealth(opts.creds).state==="expired")return{ok:false,reason:"stale-auth"}}catch{}}if(e3 instanceof import_transport_node21.UserAuthenticationExpiredError)return{ok:false,reason:"stale-auth"};if(e3 instanceof import_transport_node21.AuthorizationError)return{ok:false,reason:"auth-required"};if(e3 instanceof import_transport_node21.TimeoutError)return{ok:false,reason:"timeout"};if(e3 instanceof import_transport_node21.ConnectionError&&e3.message==="server does not support 'tls'")return{ok:false,reason:"tls-unsupported"};if(authRequired&&e3?.code==="ECONNRESET")return{ok:false,reason:"auth-required",inferred:true};return{ok:false,reason:otherwise}}var import_transport_node21,import_nats_core7,import_jetstream20,import_kv9,DEFAULT_SERVER,RepeatedRefusal;var init_endpoint_dial=__esm({"../../packages/core/dist/endpoint-dial.js"(){"use strict";import_transport_node21=__toESM(require_transport_node(),1);import_nats_core7=__toESM(require_mod3(),1);import_jetstream20=__toESM(require_mod4(),1);import_kv9=__toESM(require_mod6(),1);init_creds_authenticator();init_renewal();init_provision();DEFAULT_SERVER="nats://127.0.0.1:4222";RepeatedRefusal=class extends Error{}}});function deliveryLimitOf(value){if(value===void 0||value==="")return PLANE3_MAX_MSGS_PER_SUBJECT;if(value==="none")return null;if(!/^[1-9]\d*$/.test(value)||!Number.isSafeInteger(Number(value)))throw new Error(`plane-3 delivery: ${DELIVERY_LIMIT_HEADER} ${JSON.stringify(value)} is not a count`);return Number(value)}function fitHistoryPage(items,budget){const enc8=new TextEncoder;let used=enc8.encode(JSON.stringify({ok:true,data:{items:[],complete:false}})).length;let first=items.length;for(let i2=items.length-1;i2>=0;i2--){const size=enc8.encode(JSON.stringify(items[i2])).length+1;if(used+size>budget)break;used+=size;first=i2}return first===items.length?[]:items.slice(first)}var MAX_TAKES_IN_FLIGHT,ANYCAST_SWEEP_MS,ANYCAST_TAKE_TIMEOUT_MS,MAX_TIMER_MS3,DmDurableMissingError,DmBindRefusedError;var init_endpoint_options=__esm({"../../packages/core/dist/endpoint-options.js"(){"use strict";init_backup_config();MAX_TAKES_IN_FLIGHT=64;ANYCAST_SWEEP_MS=10*60*1e3;ANYCAST_TAKE_TIMEOUT_MS=5e3;MAX_TIMER_MS3=2147483647;DmDurableMissingError=class extends Error{stream;durable;code="dm-durable-missing";constructor(stream,durable){super(`dm-durable-missing: durable "${durable}" on stream "${stream}" does not exist; this endpoint binds an existing durable and never creates one`);this.stream=stream;this.durable=durable;this.name="DmDurableMissingError"}};DmBindRefusedError=class extends Error{stream;durable;code="dm-bind-refused";constructor(stream,durable,cause){super(`dm-bind-refused: binding durable "${durable}" on stream "${stream}" was refused (${cause instanceof Error?cause.message:String(cause)})`,{cause});this.stream=stream;this.durable=durable;this.name="DmBindRefusedError"}}}});function isUsableMessageId(id2){return typeof id2==="string"}function kindFromParsed(kind){switch(kind){case"chat":return"channel";case"inst":return"dm";case"svc":return"anycast";default:throw new Error(`cannot derive a message kind from subject kind "${kind}"`)}}function isFromSubjectSender(msg,parsed){return isRecord(msg)&&isRecord(msg.from)&&msg.from.id===parsed.sender&&isPrincipalOwnerToken(parsed.owner)}function authenticatedMessage(msg,parsed){if(parsed.kind==="chat"||parsed.kind==="evp")return authenticatedChannelMessage(msg,parsed.rest);if(parsed.kind==="inst")return authenticatedDmMessage(msg,parsed.rest);if(parsed.kind==="svc")return authenticatedAnycastMessage(msg,parsed.rest);return msg}function authenticatedDmMessage(msg,to){if(msg.to===to&&msg.channel===void 0&&msg.toService===void 0)return msg;const{channel:_channel,toService:_toService,...base}=msg;return{...base,to}}function authenticatedAnycastMessage(msg,toService){if(msg.toService===toService&&msg.to===void 0&&msg.channel===void 0)return msg;const{to:_to,channel:_channel,...base}=msg;return{...base,toService}}function dmOnlyDelivery(m2,ackWaitMs,nc){const open7=what2=>{if(!nc||nc.isClosed())throw new Error(`DM-only ${what2} refused: the connection that delivered this copy is closed; the broker will redeliver it`)};return{ack:()=>{open7("ack");m2.ack()},nak:()=>{open7("nak");m2.nak()},durable:true,redelivery:{deliveryCount:m2.info.deliveryCount,ackWaitMs,working:()=>{open7("in-progress signal");m2.working()}}}}function historyMessageFromDelivery(m2){let raw;try{raw=m2.json()}catch{return void 0}if(!isHistoryDrainEnvelope(raw))return void 0;if(!isVerifiedHistoryRow(raw))return void 0;const parsed=parseSubject(m2.subject);if(!parsed||!isFromSubjectSender(raw,parsed))return void 0;return authenticatedMessage(raw,parsed)}function isVerifiedHistoryRow(row){if(typeof row.from.name!=="string")return false;if(row.from.role!==void 0&&typeof row.from.role!=="string")return false;if(typeof row.ts!=="number"||!Number.isFinite(row.ts))return false;if(typeof row.space!=="string")return false;if(!Array.isArray(row.parts)||!row.parts.every(isReadableMessagePart))return false;if(row.mentions!==void 0&&(!Array.isArray(row.mentions)||!row.mentions.every(name2=>typeof name2==="string")))return false;if(row.replyTo!==void 0&&typeof row.replyTo!=="string")return false;if(row.contextId!==void 0&&typeof row.contextId!=="string")return false;return true}function isReadableMessagePart(value){return isRecord(value)&&typeof value.kind==="string"}function isHistoryDrainEnvelope(value){return isRecord(value)&&isUsableMessageId(value.id)&&isRecord(value.from)}var init_endpoint_messages=__esm({"../../packages/core/dist/endpoint-messages.js"(){"use strict";init_subjects();init_endpoint_inbound()}});import{EventEmitter}from"node:events";import{randomUUID as randomUUID8}from"node:crypto";var import_transport_node22,import_jetstream21,import_jetstream22,import_kv10,promptsSeqs,principalServers,CotalEndpoint;var init_endpoint=__esm({"../../packages/core/dist/endpoint.js"(){"use strict";init_endpoint_history();init_endpoint_history();init_request_safe_reconnect();init_native_connection();init_connection_cleanup();import_transport_node22=__toESM(require_transport_node(),1);init_liveness();init_endpoint_presence();init_endpoint_presence();init_identity();init_renewal();init_broker_floor();init_deadline();init_secret_store();init_endpoint_invoke();init_endpoint_envelope();init_endpoint_grants();init_endpoint_subjects();init_endpoint_serve();init_endpoint_call();init_agent_endpoint();init_process_runtime();init_issued_authority();init_registry_client();init_jetstream_missing();init_agent_file();init_resolve();init_presence_heartbeat();init_streams();import_jetstream21=__toESM(require_mod4(),1);import_jetstream22=__toESM(require_mod4(),1);import_kv10=__toESM(require_mod6(),1);init_members();init_acls();init_endpoint_delivery_lease();init_endpoint_delivery_plane();init_endpoint_control_plane();init_endpoint_messaging();init_endpoint_durable_backstop();init_endpoint_subscriptions();init_endpoint_channel_discovery();init_endpoint_liveness();init_endpoint_provisioning();init_endpoint_boot_memberships();init_endpoint_inbound();init_channels();init_endpoint_records();init_anycast_requests();init_subjects();init_permission_denied();init_endpoint_dial();init_endpoint_dial();init_endpoint_options();init_endpoint_options();init_endpoint_messages();init_endpoint_messages();promptsSeqs=new Map;principalServers=new Map;CotalEndpoint=class _CotalEndpoint extends EventEmitter{card;space;channels;allowSubscribe;servers;token;user;pass;credsSource;currentCreds;credsTimer;watchDeletePermissions=new WeakMap;userMode=false;bearerSource;currentBearer;presentedExp;cancelBearerRenewal;bearerRenewalFailures=0;bearerRefusalSurfaced=false;bearerAdoptedAtMs=0;authExpiryReconnectTimer;sentinelCreds;tls;transportPingIntervalMs;transportMaxPingOut;transportConnectTimeoutMs;heartbeatMs;ttlMs;doRegister;doWatch;doWatchChannels;readOnce;doConsume;dmOnly;dmOnlyInFlight;ackWaitMs;inactiveThresholdMs;nc;requestsAwaitingReply=new Map;onConnection;overlapOnConnectionRenewal;beforeBind;js;jsm;kv;channelKv;channelWatchIter;kvWatchDeletes=new Set;kvWatchBinds=new Set;membersKv;aclKv;managerLeaseKv;daemonRenewalLeaseRevision;membershipFeedKv;membershipFeedWatches=new Set;deliveryPlane=new EndpointDeliveryPlane({ackWaitMs:()=>this.ackWaitMs,actor:()=>this.actor,owner:()=>this.owner,allowSubscribe:()=>this.allowSubscribe,anycastUnavailable:()=>this.anycastUnavailable,card:()=>this.card,js:()=>this.js,jsm:()=>this.jsm,nc:()=>this.nc,ownLifecycleUid:()=>this.ownLifecycleUid,residentSwap:()=>this.residentSwap,space:()=>this.space,stopped:()=>this.stopped,streamMsgs:()=>this.streamMsgs,subs:()=>this.subs,userMode:()=>this.userMode,watchDeletePermissions:()=>this.watchDeletePermissions,maxPayload:()=>this.maxPayload,aclForAlias:(...args)=>this.aclForAlias(...args),channelHistory:(...args)=>this.channelHistory(...args),deliveryClassFresh:(...args)=>this.deliveryClassFresh(...args),durableJoinFor:(...args)=>this.durableJoinFor(...args),durableLeaveFor:(...args)=>this.durableLeaveFor(...args),ownerMemberships:(...args)=>this.ownerMemberships(...args),ownsDeliveryLease:(...args)=>this.ownsDeliveryLease(...args),readDeliveryLease:(...args)=>this.readDeliveryLease(...args),readDeliveryLeaseEntry:(...args)=>this.readDeliveryLeaseEntry(...args),reloadCreds:(...args)=>this.reloadCreds(...args),serveControl:(...args)=>this.serveControl(...args),aclRegistry:(...args)=>this.aclRegistry(...args),membersRegistry:(...args)=>this.membersRegistry(...args),armAnycastRequests:(...args)=>this.armAnycastRequests(...args),deliveryAnycast:(...args)=>this.deliveryAnycast(...args),dropAnycastRequests:(...args)=>this.dropAnycastRequests(...args),manager:(...args)=>this.manager(...args),notLiveMsg:(...args)=>this.notLiveMsg(...args),plane3MsgId:(...args)=>this.plane3MsgId(...args),publishDinbox:(...args)=>this.publishDinbox(...args),resolveOwnerByName:(...args)=>this.resolveOwnerByName(...args),scheduleResidentSwap:(...args)=>this.scheduleResidentSwap(...args),sendMentionNotice:(...args)=>this.sendMentionNotice(...args),emit:(event,...args)=>this.emit(event,...args)});takeServeSub;anycastAuthority;taskEpoch;anycastUnavailable;anycastSweep;takesInFlight=0;channelConfigs=new Map;channelDefaults={};channelRead;channelReadGeneration=0;channelReadApplied=0;history=new EndpointHistory({connection:()=>this.nc,jetstream:()=>this.js,manager:()=>this.jsm,setManager:manager=>{this.jsm=manager},space:()=>this.space,owner:()=>this.owner,actor:()=>this.actor,userMode:()=>this.userMode,connectionId:()=>this.connId,card:()=>this.card,notLiveMsg:()=>this.notLiveMsg(),requireLifecycleUid:operation=>this.requireLifecycleUid(operation),requestDelivery:(op,args)=>this.requestDelivery(op,args),deleteConsumerIfPresent:(stream,name2)=>this.deleteConsumerIfPresent(stream,name2),joinPolicyFresh:channel=>this.joinPolicyFresh(channel),chatMayHaveLost:(subject,sinceSeq)=>this.chatMayHaveLost(subject,sinceSeq),emit:(event,...args)=>this.emit(event,...args),decodeHistory:historyMessageFromDelivery,isRecord,isUsableMessageId,isFromSubjectSender,authenticatedMessage,isPublishPermissionDenied});subs=[];taps=[];livenessResponders=new Map;principalServes=new Map;promptsPresence;streamMsgs=[];chatSubs=new Map;chatSubDenied=new Set;plane3Channels=new Map;pendingDurableLeave=new Map;pendingBootJoins=new Set;chatSubRefusals=new WeakSet;reportedSubRefusals=new WeakSet;ownWatchDeletePrefixes=new Set;firstConnect=true;heartbeatTimer;sweepTimer;deliveryLease=new EndpointDeliveryLease({card:()=>this.card,space:()=>this.space,connection:()=>this.nc,epoch:()=>this.presenceEpoch,notLiveMsg:()=>this.notLiveMsg(),deleteWatchConsumer:iter=>this.deleteOwnConsumer(kvWatchConsumer(iter)),recoverable:error51=>this.emitRecoverable(error51),emit:(event,error51)=>this.emit(event,error51)});presence=new EndpointPresence({card:()=>this.card,space:()=>this.space,bucket:()=>this.kv,connection:()=>this.nc,lifecycleUid:()=>this.ownLifecycleUid,prompts:()=>this.servedPrompts(),ttlMs:()=>this.ttlMs,registers:()=>this.doRegister,watches:()=>this.doWatch,readsOnce:()=>this.readOnce,stopped:()=>this.stopped,reconnecting:()=>this.reconnecting,epoch:()=>this.presenceEpoch,notLiveMsg:()=>this.notLiveMsg(),bindWatch:kv=>this.bindKvWatch(kv),retireWatch:iter=>this.retireKvWatch(iter),emit:(event,value)=>this.emit(event,value),recoverable:error51=>this.emitRecoverable(error51),isPublishPermissionDenied});presenceEpoch=0;stopped=false;stopPromise;startPromise;ownedConnections=new Set;nativeBound=false;credsTxnsRunning=0;rebuildPromise;reconnecting=false;reestablishing=false;backoffResolve;backoffTimer;membershipPauses=new Set;retryMs=3e3;retryAttempt=0;connId;owner;actor;actorIsEphemeral;ownLifecycleUid;backfillFloor;acceptedToken;issuedGeneration;resolvedServices=new Map;serviceInvocations=new WeakMap;resolvedCommandServices=new Map;activeGoalFollowers=new Set;splitsRecovered=0;get principal(){return{owner:this.owner,actor:this.actor}}get splitRecoveryCount(){return this.splitsRecovered}get presenceBindingDropCount(){return this.presence.bindingDropCount}requireLifecycleUid(what2){if(!this.ownLifecycleUid)throw new Error(`${what2} requires this endpoint's lifecycleUid (EndpointOptions.lifecycleUid): dm/dlv/chathist broker resources are lifecycle-keyed names (SPEC 13.1)`);return this.ownLifecycleUid}constructor(opts){super();this.on("transport",state=>{this.nativeBound=state.connected});let selfMintedConnId=false;this.space=opts.space;assertValidName(opts.card.name);assertValidKind(opts.card.kind);if(opts.card.role!==void 0)assertValidRole(opts.card.role);if(opts.bearer){if(opts.creds||opts.token||opts.user||opts.pass)throw new Error("bearer (user-mode auth) is mutually exclusive with creds/token/user/pass");if(!opts.sentinelCreds)throw new Error("user-mode bearer requires sentinelCreds (the shared auth-account creds presented alongside it)")}if(opts.bearer){this.userMode=true;if(typeof opts.bearer==="function"){if(!opts.card.owner||!opts.card.actor)throw new Error("a bearer source requires explicit card.owner + card.actor (no bearer to derive them from at construction)");this.owner=opts.card.owner;this.actor=opts.card.actor;this.bearerSource=opts.bearer}else{const claims2=decodeBearerPrincipal(opts.bearer);if(opts.card.owner&&opts.card.owner!==claims2.owner)throw new Error(`card.owner ${opts.card.owner} != bearer owner ${claims2.owner}`);if(opts.card.actor&&opts.card.actor!==claims2.actor)throw new Error(`card.actor ${opts.card.actor} != bearer actor ${claims2.actor}`);this.owner=claims2.owner;this.actor=claims2.actor;this.currentBearer=opts.bearer}this.connId=assertInboxConnId(`ibx${randomUUID8().replace(/-/g,"")}`);this.sentinelCreds=opts.sentinelCreds;this.actorIsEphemeral=false}else{if(typeof opts.creds==="function"){if(!opts.card.id)throw new Error("a creds source requires an explicit card.id (no cred to derive the identity from at construction)");this.credsSource=opts.creds;this.connId=opts.card.id;selfMintedConnId=false}else{const credId=opts.creds?idFromCreds(opts.creds):void 0;if(opts.card.id&&credId&&opts.card.id!==credId)throw new Error(`card.id ${opts.card.id} != creds identity ${credId} - they must be the same nkey`);this.currentCreds=opts.creds;selfMintedConnId=opts.card.id===void 0&&credId===void 0;this.connId=opts.card.id??credId??randomUUID8().replace(/-/g,"")}this.owner=opts.card.owner??DEV_OWNER;this.actor=opts.card.actor??this.connId;this.actorIsEphemeral=opts.card.actor===void 0&&selfMintedConnId}this.ownLifecycleUid=opts.lifecycleUid!==void 0?assertLifecycleToken(opts.lifecycleUid):this.authed?void 0:mintLifecycleUid();if(opts.backfillFloor!==void 0){if(!Number.isInteger(opts.backfillFloor)||opts.backfillFloor<0)throw new Error(`EndpointOptions.backfillFloor must be a non-negative integer stream sequence, got ${opts.backfillFloor}`);this.backfillFloor=opts.backfillFloor}if(opts.acceptedToken!==void 0){if(!opts.creds)throw new Error("EndpointOptions.acceptedToken names a static issuance and needs creds beside it (SPEC 13.15)");this.acceptedToken=assertGeneration(opts.acceptedToken,"acceptedToken")}const principal=principalKey(this.owner,this.actor);this.card={...opts.card,id:principal.key,owner:this.owner,actor:this.actor};this.presence.configureEnvironment((opts.environment===void 0?process.env.COTAL_ENVIRONMENT:opts.environment)?.trim()||void 0);this.servers=opts.servers??DEFAULT_SERVER;this.token=opts.token;this.user=opts.user;this.pass=opts.pass;this.tls=opts.tls??false;for(const[label,value]of[["transportPingIntervalMs",opts.transportPingIntervalMs],["transportMaxPingOut",opts.transportMaxPingOut],["transportConnectTimeoutMs",opts.transportConnectTimeoutMs]]){if(value!==void 0&&(!Number.isSafeInteger(value)||value<=0))throw new Error(`EndpointOptions.${label} must be a positive safe integer`)}if(opts.transportPingIntervalMs===void 0!==(opts.transportMaxPingOut===void 0))throw new Error("EndpointOptions transportPingIntervalMs and transportMaxPingOut must be configured together");this.onConnection=opts.onConnection;this.overlapOnConnectionRenewal=opts.overlapOnConnectionRenewal===true;this.beforeBind=opts.beforeBind;this.transportPingIntervalMs=opts.transportPingIntervalMs??1e4;this.transportMaxPingOut=opts.transportMaxPingOut??2;this.transportConnectTimeoutMs=opts.transportConnectTimeoutMs;this.channels=opts.channels??[];this.allowSubscribe=opts.allowSubscribe;this.heartbeatMs=opts.heartbeatMs??2e3;this.ttlMs=opts.ttlMs??6e3;this.doRegister=opts.registerPresence??true;this.doWatch=opts.watchPresence??true;this.doWatchChannels=opts.watchChannels??true;this.doConsume=opts.consume??true;this.readOnce=opts.readOnce??false;if(this.readOnce&&(this.doConsume||this.doRegister))throw new Error("EndpointOptions.readOnce requires consume and registerPresence false: a one-time read cannot keep a consumer's channel cache or its own presence current");if(opts.dmOnly!==void 0){if(typeof opts.dmOnly.handler!=="function")throw new Error("EndpointOptions.dmOnly.handler must be a function");const settle=opts.dmOnly.settleTimeoutMs;if(settle!==void 0&&(!Number.isSafeInteger(settle)||settle<=0))throw new Error("EndpointOptions.dmOnly.settleTimeoutMs must be a positive safe integer");if(!this.authed)throw new Error("EndpointOptions.dmOnly requires creds or a bearer: it binds a provisioned durable and never creates one");if(!this.doConsume||this.doRegister||this.doWatch||this.doWatchChannels||this.readOnce)throw new Error("EndpointOptions.dmOnly requires consume true and registerPresence, watchPresence, watchChannels and readOnce false");if(this.channels.length||opts.card.role||opts.acceptedToken!==void 0)throw new Error("EndpointOptions.dmOnly takes no channels, role or acceptedToken: the endpoint reads only its own DM durable");this.requireLifecycleUid("EndpointOptions.dmOnly");this.dmOnly=opts.dmOnly}this.presence.seedChannelModes(opts.channelModes);this.ackWaitMs=opts.ackWaitMs??6e4;this.inactiveThresholdMs=opts.inactiveThresholdMs??6e5}ref(){return{id:this.card.id,name:this.card.name,role:this.card.role}}get authed(){return Boolean(this.currentCreds||this.credsSource)||this.userMode}start(){if(this.startPromise)return this.startPromise;const flight=this.startOnce().finally(()=>{if(this.startPromise===flight)this.startPromise=void 0});this.startPromise=flight;return flight}async startOnce(){try{await this.connectAndBind()}catch(error51){if(!this.stopped)throw error51}if(await this.tearDownIfStopped())return;this.superviseConnection()}static BEARER_MIN_RENEWAL_MS=5e3;static BEARER_RETRY_MS=5e3;static BEARER_RETRY_CAP_MS=6e4;emitRecoverable(err3){this.emit("warning",err3)}async refreshBearer(initial=false){try{const bearer=await this.bearerSource();const claims2=decodeBearerPrincipal(bearer);if(claims2.owner!==this.owner||claims2.actor!==this.actor)throw new Error(`bearer source returned principal ${claims2.owner}.${claims2.actor}, expected ${this.owner}.${this.actor}`);const expiryMs=bearerExpiryMs(bearer);const held2=this.currentBearer;if(held2!==void 0){if(expiryMs<=Date.now())throw new Error("the bearer source returned a token that has already expired - nothing adopted");if(bearer===held2&&Date.now()>=bearerRenewalDeadlineMs(held2,this.bearerAdoptedAtMs))throw new Error("the bearer source re-served the token already held and it cannot carry another cycle (the auth service has not issued a fresh one) - nothing adopted")}if(bearer!==held2)this.bearerAdoptedAtMs=Date.now();this.currentBearer=bearer;this.bearerRenewalFailures=0;const{issuedAtMs,expiresAtMs}=bearerLifetimeMs(bearer,this.bearerAdoptedAtMs);this.armBearerTimer(armRenewal(this.space,issuedAtMs,expiresAtMs,()=>void this.renewBearerOnTimer(),_CotalEndpoint.BEARER_MIN_RENEWAL_MS))}catch(e3){if(initial)throw e3;if(this.bearerRenewalFailures===0)this.emitRecoverable(new Error(`bearer refresh failed (${e3 instanceof Error?e3.message:String(e3)}) - retrying with backoff; this connection dies at its current token's expiry if the auth service stays down`));const named=retryAfterMs(e3);const delay3=named>0?named:jitteredBackoffMs(this.bearerRenewalFailures,_CotalEndpoint.BEARER_RETRY_MS,_CotalEndpoint.BEARER_RETRY_CAP_MS);this.bearerRenewalFailures++;const timer2=setTimeout(()=>void this.renewBearerOnTimer(),delay3);timer2.unref?.();this.armBearerTimer(()=>clearTimeout(timer2))}}armBearerTimer(cancel){this.cancelBearerRenewal?.();this.cancelBearerRenewal=cancel;if(this.stopped)cancel()}async renewBearerOnTimer(){const held2=this.currentBearer;await this.refreshBearer();if(this.stopped||this.currentBearer===held2)return;if(this.nc&&!this.nc.isClosed())await this.swapConnectionOntoFreshCreds();else this.kickBackoff()}bearerForWire(){const bearer=this.currentBearer;if(bearer!==void 0&&bearerExpiryMs(bearer)>Date.now())return bearer;throw new Error(this.bearerSource?"this endpoint's user bearer has expired and renewal through the auth exchange is failing - not presenting the expired token to the broker; retrying with backoff":"this endpoint's user bearer has expired and it holds no bearer source to renew it - re-authenticate and rebuild the endpoint (construct it with a bearer FUNCTION for standing renewal)")}static CREDS_RETRY_MS=6e4;static presentableCreds(creds,opts){const{exp}=credsClaims(creds);if(typeof exp==="number"&&exp*1e3<=Date.now())throw new Error(opts.renewable?"this endpoint's creds have expired and renewal is failing - not presenting the expired credential to the broker; retrying with backoff":"this endpoint's creds have expired and it holds no creds source to renew them - replace the credential and rebuild the endpoint (pass a creds FUNCTION for standing renewal)");return creds}presentCreds(){const creds=this.credsForWire();this.presentedExp=credsClaims(creds).exp;return creds}presentBearer(){const bearer=this.bearerForWire();this.presentedExp=bearerExpiryMs(bearer)/1e3;return bearer}credsForWire(){if(!this.currentCreds)throw new Error(this.credsSource?"this endpoint has no credential to present yet (the creds source has not returned one) - not dialing without auth material":"this endpoint was constructed with an empty creds string - not dialing without auth material (an empty credential is not anonymous access)");return _CotalEndpoint.presentableCreds(this.currentCreds,{renewable:Boolean(this.credsSource)})}wireCreds(){return this.credsForWire()}static assertRenewableGeneration(candidate2,current,delayMs){const{exp}=credsClaims(candidate2);if(typeof exp==="number"&&exp*1e3<=Date.now())throw new Error("the creds source returned an already-expired credential (its `exp` is in the past) - nothing adopted; the renewal owner has not re-signed it, or the store is serving a stale generation");if(current!==void 0&&credsFingerprint(candidate2)===credsFingerprint(current)&&delayMs<=0)throw new Error("the creds source still holds the previous generation past its renewal point (the renewal owner has not re-signed it) - nothing adopted")}static PREFLIGHT_MS=4e3;static RESIDENT_SWAP_DEFER_MS=250;static RESIDENT_SWAP_GATE_MS=5e3;residentSwap;static RELOAD_DEADLINE_MS=12e3;async fetchFreshCreds(){const creds=await this.credsSource();const id2=idFromCreds(creds);if(id2!==this.connId)throw new Error(`creds source returned identity ${id2}, expected ${this.connId} - renewal may not swap the connection's nkey`);const delay3=credsRenewalDelayMs(creds);_CotalEndpoint.assertRenewableGeneration(creds,this.currentCreds,delay3);this.currentCreds=creds;this.armCredsRefresh(delay3);const{iat,exp}=credsClaims(creds);return{iat,exp}}async swapConnectionOntoFreshCreds(){const nc=this.nc;if(!(nc&&!this.stopped))return;const overlap=this.overlapOnConnectionRenewal&&this.onConnection?await this.openRenewalOverlap().catch(()=>void 0):void 0;try{await nc.reconnect().catch(()=>{});if(overlap&&!nc.isClosed())await withDeadline(nc.flush(),1e4,()=>new Error("resident renewal flush did not finish")).catch(()=>{});if(this.nc===nc&&!this.stopped)this.armAuthExpiryReconnectFence(nc)}finally{if(overlap&&!overlap.isClosed())await this.closeWithoutLibraryReconnect(overlap).catch(()=>{})}}async openRenewalOverlap(){const overlap=await dialerFor(this.servers)({servers:this.servers,noAsyncTraces:true,name:`cotal:${this.card.name}:renewal`,inboxPrefix:`_INBOX_renew_${randomUUID8()}`,maxReconnectAttempts:0,...authOpts({token:this.token,user:this.user,pass:this.pass,creds:this.currentCreds!==void 0||this.credsSource?()=>this.presentCreds():void 0,bearer:this.userMode?()=>this.presentBearer():void 0,sentinelCreds:this.sentinelCreds,tls:this.tls})});this.ownedConnections.add(overlap);try{this.onConnection?.(overlap);await withDeadline(overlap.flush(),5e3,()=>new Error("renewal overlap flush did not finish"));return overlap}catch(error51){await this.closeWithoutLibraryReconnect(overlap).catch(()=>{});throw error51}}disableLibraryReconnect(nc){const protocol=nc.protocol;if(protocol?.options)protocol.options.reconnect=false}async closeWithoutLibraryReconnect(nc){if(!nc)return;this.disableLibraryReconnect(nc);await nc.close();if(!nc.isClosed())throw new Error("endpoint connection closure is unproved; consumer custody must be retained");this.ownedConnections.delete(nc)}armAuthExpiryReconnectFence(nc){clearTimeout(this.authExpiryReconnectTimer);this.authExpiryReconnectTimer=void 0;const credsExp=this.currentCreds&&credsClaims(this.currentCreds).exp;const expiryMs=this.userMode&&this.currentBearer?bearerExpiryMs(this.currentBearer):typeof credsExp==="number"?credsExp*1e3:void 0;if(expiryMs===void 0||this.stopped)return;const delay3=Math.max(0,expiryMs-Date.now()-500);this.authExpiryReconnectTimer=delay3>MAX_TIMER_MS3?setTimeout(()=>{if(this.nc===nc)this.armAuthExpiryReconnectFence(nc)},MAX_TIMER_MS3):setTimeout(()=>{if(this.nc===nc)this.disableLibraryReconnect(nc)},delay3);this.authExpiryReconnectTimer.unref?.()}async refreshCreds(initial=false){try{await this.fetchFreshCreds()}catch(e3){if(initial)throw e3;this.emitRecoverable(new Error(`creds refresh failed (${e3 instanceof Error?e3.message:String(e3)}) - retrying; this connection dies at its current JWT's expiry if renewal keeps failing`));this.armCredsRefresh(_CotalEndpoint.CREDS_RETRY_MS)}}credsTxn=Promise.resolve();runCredsTxn(fn2){const counted=async()=>{this.credsTxnsRunning++;try{return await fn2()}finally{this.credsTxnsRunning--}};const next=this.credsTxn.then(counted,counted);this.credsTxn=next.then(()=>void 0,()=>void 0);return next}async adoptFreshCreds(opts={}){const deadline=opts.deadline??Date.now()+_CotalEndpoint.RELOAD_DEADLINE_MS;if(Date.now()>deadline)throw new Error("reloadCreds: the request deadline elapsed while queued behind another credential transaction; nothing adopted");const candidate2=await withDeadline(this.credsSource(),deadline-Date.now(),()=>new Error("reloadCreds: the creds source did not return before the daemon deadline; nothing adopted"));const id2=idFromCreds(candidate2);if(id2!==this.connId)throw new Error(`creds source returned identity ${id2}, expected ${this.connId} - renewal may not swap the connection's nkey`);if(opts.expected!==void 0&&credsFingerprint(candidate2)!==opts.expected)throw new Error("reloadCreds: re-read credential generation did not match the expected re-signed generation (a different store, or a torn/stale read); nothing adopted");const proven=_CotalEndpoint.presentableCreds(candidate2,{renewable:true});const probe=await probeConnect(this.servers,{creds:proven,tls:this.tls,timeoutMs:Math.max(500,Math.min(_CotalEndpoint.PREFLIGHT_MS,deadline-Date.now()))});if(!probe.ok)throw new Error(`reloadCreds: the broker did not accept the re-signed credential (${probe.reason}); nothing adopted`);if(Date.now()>deadline)throw new Error("reloadCreds: the proof exceeded the daemon deadline; nothing adopted");const delay3=credsRenewalDelayMs(candidate2);_CotalEndpoint.assertRenewableGeneration(candidate2,this.currentCreds,delay3);this.currentCreds=candidate2;this.armCredsRefresh(delay3);this.emit("creds-adopted",credsClaims(candidate2));return credsClaims(candidate2)}async renewCredsOnTimer(){const deadline=Date.now()+_CotalEndpoint.RELOAD_DEADLINE_MS;try{await this.runCredsTxn(()=>this.adoptFreshCreds({deadline}));await this.swapConnectionOntoFreshCreds()}catch(e3){this.emitRecoverable(new Error(`creds refresh failed (${e3 instanceof Error?e3.message:String(e3)}) - retrying; this connection dies at its current JWT's expiry if renewal keeps failing`));this.armCredsRefresh(_CotalEndpoint.CREDS_RETRY_MS)}}async refreshCredsRequestSafe(){if(!this.credsSource)throw new Error("credential refresh requires a creds source");const nc=this.nc;if(!nc&&!this.stopped&&(this.reconnecting||this.reestablishing))return await this.reconnect();if(!nc||this.stopped)throw new Error("credential refresh requires a running endpoint");const deadline=Date.now()+_CotalEndpoint.RELOAD_DEADLINE_MS;await this.runCredsTxn(async()=>{await this.adoptFreshCreds({deadline});if(this.nc!==nc||this.stopped)throw new Error("endpoint connection changed during credential refresh");await requestSafeReconnect(nc,()=>this.requestsAwaitingReply.get(nc)?.size??0);if(this.nc===nc&&!this.stopped)this.armAuthExpiryReconnectFence(nc)})}async reloadCreds(expected){if(!this.credsSource)throw new Error("reloadCreds: this endpoint has no creds source (a static cred cannot be renewed in place)");const deadline=Date.now()+_CotalEndpoint.RELOAD_DEADLINE_MS;const{iat,exp}=await this.runCredsTxn(()=>this.adoptFreshCreds({expected,deadline}));return{identity:this.connId,iat,exp}}scheduleResidentSwap(){if(this.stopped)return;const swap=new Promise(resolve6=>{setTimeout(resolve6,_CotalEndpoint.RESIDENT_SWAP_DEFER_MS).unref?.()}).then(async()=>{const back=this.transportBack(_CotalEndpoint.RESIDENT_SWAP_GATE_MS);await this.swapConnectionOntoFreshCreds();await back}).finally(()=>{if(this.residentSwap===swap)this.residentSwap=void 0});this.residentSwap=swap}transportBack(ms){return new Promise(resolve6=>{const done=()=>{clearTimeout(timer2);this.off("transport",seen);resolve6()};const seen=state=>{if(state.connected)done()};const timer2=setTimeout(done,ms);timer2.unref?.();this.on("transport",seen)})}armCredsRefresh(delayMs){if(this.stopped)return;clearTimeout(this.credsTimer);this.credsTimer=delayMs>MAX_TIMER_MS3?setTimeout(()=>this.armCredsRefresh(delayMs-MAX_TIMER_MS3),MAX_TIMER_MS3):setTimeout(()=>void this.renewCredsOnTimer(),Math.max(1e3,delayMs));this.credsTimer.unref?.()}async connectAndBind(){try{await this.bindConnection()}catch(error51){await this.closeFailedBind();throw error51}}async bindConnection(){this.clearConnectionScoped();if(this.bearerSource){if(!this.currentBearer)await this.refreshBearer(true);else if(this.bearerRenewalFailures===0&&Date.now()>=bearerRenewalDeadlineMs(this.currentBearer,this.bearerAdoptedAtMs))await this.refreshBearer()}if(this.credsSource){const stale=!this.currentCreds||credsRenewalDelayMs(this.currentCreds)<=0;if(stale)await this.refreshCreds(!this.currentCreds)}if(this.userMode){try{this.bearerForWire();this.bearerRefusalSurfaced=false}catch(e3){if(!this.bearerRefusalSurfaced){this.bearerRefusalSurfaced=true;throw e3}throw new RepeatedRefusal(e3.message)}}let watchDeletePermission;this.nc=await dialerFor(this.servers)({servers:this.servers,noAsyncTraces:true,name:this.userMode?this.connId:`cotal:${this.card.name}`,inboxPrefix:`_INBOX_${this.connId}`,...this.transportPingIntervalMs===void 0?{}:{pingInterval:this.transportPingIntervalMs},...this.transportMaxPingOut===void 0?{}:{maxPingOut:this.transportMaxPingOut},...this.transportConnectTimeoutMs===void 0?{}:{timeout:this.transportConnectTimeoutMs},...authOpts({token:this.token,user:this.user,pass:this.pass,creds:this.currentCreds!==void 0||this.credsSource?()=>this.presentCreds():void 0,bearer:this.userMode?()=>this.presentBearer():void 0,sentinelCreds:this.sentinelCreds,tls:this.tls,onCreds:creds=>{watchDeletePermission=void 0;try{const nats=credsClaims(creds).nats;if(nats?.pub!==void 0)watchDeletePermission=importNativeSubjectPermissions({pub:nats.pub}).publish}catch{}}})});this.watchDeletePermissions.set(this.nc,()=>watchDeletePermission);this.ownedConnections.add(this.nc);const owned=this.nc;void owned.closed().then(()=>this.ownedConnections.delete(owned));this.onConnection?.(this.nc);requireBrokerFloor(this.nc);this.armAuthExpiryReconnectFence(this.nc);this.watchStatus();this.js=(0,import_jetstream21.jetstream)(this.nc);if(this.dmOnly){await this.beforeBind?.();if(this.stopped)return;await this.bindDmOnly(this.dmOnly);if(this.stopped)return;this.emit("connection",{connected:true});return}if(this.acceptedToken!==void 0){const ref=await readAcceptedRow(this.nc,this.space,this.acceptedToken);const uid2=this.requireLifecycleUid("an issued endpoint");if(ref.owner!==this.owner||ref.actor!==this.actor||ref.uid!==uid2)throw new Error(`the accepted row names ${ref.owner}.${ref.actor} (uid ${ref.uid}), not this endpoint ${this.owner}.${this.actor} (uid ${uid2}); refusing to ride a foreign issuance (SPEC 13.15)`);this.issuedGeneration=ref.generation}await this.beforeBind?.();if(this.stopped)return;if(this.doWatch||this.doRegister){const kvm=new import_kv10.Kvm(this.nc);this.kv=this.authed?await kvm.open(presenceBucket(this.space)):await kvm.create(presenceBucket(this.space),{ttl:this.ttlMs,storage:PRESENCE_STORAGE})}if(this.doWatch&&this.readOnce)await this.readPresenceOnce();else if(this.doWatch){await this.startPresenceWatch();this.sweepTimer=setInterval(()=>this.sweep(),Math.max(500,Math.floor(this.ttlMs/3)))}const watchChannels=this.doWatch&&this.doWatchChannels;if(watchChannels||this.doConsume){this.channelKv=await openChannelRegistry(this.nc,this.space,{create:!this.authed});if(watchChannels)await(this.readOnce?this.readChannelsOnce():this.startChannelWatch());else if(this.readsChannelsOnDemand)await this.readChannels()}if(this.deliveryLease.hasWatchIntent)await this.bindDeliveryLeaseWatch();if(this.authed&&(this.doConsume||this.doRegister))this.requireLifecycleUid(this.doConsume?"an authed consuming endpoint":"an authed presence-registering endpoint");if(this.doConsume){this.jsm=await(0,import_jetstream21.jetstreamManager)(this.nc);if(!this.authed)await this.ensureStreams();await this.startConsumers()}if(this.doRegister&&!this.doConsume&&this.authed&&this.card.kind==="agent"){const jsm=this.jsm??(this.jsm=await(0,import_jetstream21.jetstreamManager)(this.nc));const uid2=this.requireLifecycleUid("an authed presence-registering agent");try{await jsm.consumers.info(dmStream(this.space),dmDurable(this.owner,this.actor,uid2))}catch(e3){throw new Error(`lifecycle proof failed for ${this.card.id} (uid ${uid2}): its dm_ durable is not present at the broker, so this incarnation's uid does not match its provisioned resources - refusing to publish presence (SPEC 13.1 fail-before-presence): ${e3?.message??String(e3)}`)}}if(this.doRegister){try{await this.publishPresence()}catch(e3){const detail=e3?.message??String(e3);throw new Error(`presence registration failed for ${this.card.id}: the space's presence KV bucket "${presenceBucket(this.space)}" did not accept this endpoint's first write (${detail}). The bucket can be OPENED and WATCHED while refusing every write, so a healthy-looking connection does not rule this out; a broker whose store has latched refuses until it is restarted, and no client can clear it (#1356).`)}const phase=Date.now();let beat=0;const arm=()=>{const next=nextHeartbeat(phase,this.heartbeatMs,beat,Date.now());beat=next.beat;const handle=setTimeout(()=>{this.publishPresence().catch(e3=>this.emitRecoverable(e3));if(this.heartbeatTimer===handle)arm()},next.delayMs);this.heartbeatTimer=handle};arm()}await this.rearmMembershipWatches();await this.armPlane3();for(const plane of this.livenessResponders.keys())this.bindLiveness(plane);this.rebindPrincipalServes(false);for(const tap of this.taps)this.bindTap(tap);if(this.stopped)return;this.emit("connection",{connected:true});if(this.nc){for(const follower of this.activeGoalFollowers){follower.reconnected(this.nc)}}}clearConnectionScoped(){if(this.authExpiryReconnectTimer){clearTimeout(this.authExpiryReconnectTimer);this.authExpiryReconnectTimer=void 0}if(this.heartbeatTimer){clearInterval(this.heartbeatTimer);this.heartbeatTimer=void 0}if(this.sweepTimer){clearInterval(this.sweepTimer);this.sweepTimer=void 0}for(const msgs of this.streamMsgs){try{msgs.stop()}catch{}}this.streamMsgs.length=0;this.presenceEpoch++;this.presence.cancelRebind();this.presence.retireWatch();if(this.channelWatchIter)this.retireKvWatch(this.channelWatchIter);this.channelWatchIter=void 0;this.stopDeliveryLeaseWatch();for(const sub of this.chatSubs.values()){try{sub.unsubscribe()}catch{}}this.chatSubs.clear();this.chatSubDenied.clear();this.ownWatchDeletePrefixes.clear();this.presence.resetConnection();this.channelConfigs.clear();this.channelDefaults={};this.channelRead=void 0;this.channelReadGeneration++;this.channelReadApplied=this.channelReadGeneration;for(const watch of this.membershipFeedWatches)watch.arm=watch.arm.catch(()=>{}).then(()=>this.disarmMembershipWatch(watch)).catch(err3=>{this.emit("error",err3)})}async closeFailedBind(){const failedNc=this.nc;if(failedNc)this.disableLibraryReconnect(failedNc);this.clearConnectionScoped();this.nc=void 0;this.js=void 0;this.jsm=void 0;this.kv=void 0;this.channelKv=void 0;this.membersKv=void 0;this.aclKv=void 0;this.membershipFeedKv=void 0;this.deliveryLease.resetConnection();this.managerLeaseKv=void 0;this.daemonRenewalLeaseRevision=void 0;if(this.deliveryPlane.deliveryServeSub){try{this.deliveryPlane.deliveryServeSub.unsubscribe()}catch{}this.deliveryPlane.deliveryServeSub=void 0}if(this.deliveryPlane.deliveryAdminServeSub){try{this.deliveryPlane.deliveryAdminServeSub.unsubscribe()}catch{}this.deliveryPlane.deliveryAdminServeSub=void 0}this.dropAnycastRequests();for(const sub of this.subs){try{sub.unsubscribe()}catch{}}this.subs.length=0;if(!failedNc)return;this.emit("transport",{connected:false});this.emit("connection",{connected:false});try{await failedNc.close();return}catch{}if(!failedNc.isClosed?.()){try{await drainAndClose(failedNc);return}catch{}}const proto=failedNc.protocol;const transport=proto?.transport;if(transport&&!transport.isClosed){try{await transport.close?.()}catch{}if(!transport.isClosed){try{transport.disconnect?.()}catch{}}}}async tearDownIfStopped(){if(!this.stopped)return false;const nc=this.nc;if(nc)this.disableLibraryReconnect(nc);this.clearConnectionScoped();await this.closeWithoutLibraryReconnect(nc);this.nc=void 0;return true}superviseConnection(){const nc=this.nc;if(!nc)return;void nc.closed().then(err3=>{if(this.stopped)return;if(this.nc!==nc)return;this.emit("connection",{connected:false});this.emit("error",new Error(`mesh connection closed${err3?`: ${err3.message||err3.name}`:""} - re-establishing`));void this.reestablishLoop()})}rebuild(){if(this.rebuildPromise)return this.rebuildPromise;const p2=this.doRebuild().finally(()=>{if(this.rebuildPromise===p2)this.rebuildPromise=void 0});this.rebuildPromise=p2;return p2}async doRebuild(){const oldNc=this.nc;if(oldNc)this.disableLibraryReconnect(oldNc);this.reconnecting=true;try{this.clearConnectionScoped();if(oldNc&&!oldNc.isClosed())await Promise.all([...[...this.membershipFeedWatches].map(watch=>watch.arm),this.settleDeliveryLeaseWatches(),this.settleKvWatches()]);this.nc=void 0;this.js=void 0;this.jsm=void 0;this.kv=void 0;this.channelKv=void 0;this.membersKv=void 0;this.aclKv=void 0;this.membershipFeedKv=void 0;this.deliveryLease.resetConnection();this.managerLeaseKv=void 0;this.daemonRenewalLeaseRevision=void 0;this.emit("transport",{connected:false});this.emit("connection",{connected:false});await this.closeWithoutLibraryReconnect(oldNc);if(this.stopped)return;try{await this.connectAndBind()}catch(error51){if(!this.stopped)throw error51}if(await this.tearDownIfStopped())return;this.superviseConnection()}finally{this.reconnecting=false}}static RETRY_BACKOFF_CAP_MS=6e4;nextRetryDelayMs(){const delay3=Math.min(this.retryMs*2**this.retryAttempt,_CotalEndpoint.RETRY_BACKOFF_CAP_MS);this.retryAttempt++;return Math.round(delay3/2+Math.random()*(delay3/2))}async reestablishLoop(){if(this.reestablishing)return;this.reestablishing=true;try{while(!this.stopped){try{await this.rebuild();this.retryAttempt=0;return}catch(e3){const delay3=this.nextRetryDelayMs();if(!this.stopped&&!(e3 instanceof RepeatedRefusal))this.emitRecoverable(this.userMode&&isAuthRejection(e3)?new Error(`the broker refused this endpoint's bearer for ${this.owner}.${this.actor} - retrying in ${Math.ceil(delay3/1e3)}s; the space's auth service logs why`,{cause:e3}):e3);if(this.stopped)return;await new Promise(resolve6=>{this.backoffResolve=resolve6;this.backoffTimer=setTimeout(resolve6,delay3)})}}}finally{this.reestablishing=false}}retryNow(){if(!this.stopped&&this.reestablishing&&!this.rebuildPromise)this.kickBackoff()}kickBackoff(){this.backoffResolve?.();if(this.backoffTimer){clearTimeout(this.backoffTimer);this.backoffTimer=void 0}}membershipPause(attempt){if(this.stopped)return Promise.resolve();return new Promise(resolve6=>{const wake=()=>{clearTimeout(timer2);this.membershipPauses.delete(wake);resolve6()};const timer2=setTimeout(wake,Math.min(3e4,1e3*2**attempt));this.membershipPauses.add(wake)})}async reconnect(){if(this.stopped)throw new Error("endpoint stopped - cannot reconnect");this.kickBackoff();try{await this.rebuild()}catch(e3){void this.reestablishLoop();throw e3}}stop(){return this.stopPromise??=this.stopOnce()}async stopOnce(){if(this.nc)this.disableLibraryReconnect(this.nc);this.stopped=true;for(const follower of this.activeGoalFollowers){follower.cancel()}this.activeGoalFollowers.clear();this.presenceEpoch++;const principalStops=[...this.principalServes.values()].map(intent=>this.stopPrincipalServe(intent,false));this.presence.cancelRebind();this.kickBackoff();for(const wake of[...this.membershipPauses])wake();if(this.heartbeatTimer)clearInterval(this.heartbeatTimer);if(this.sweepTimer)clearInterval(this.sweepTimer);this.cancelBearerRenewal?.();if(this.credsTimer)clearTimeout(this.credsTimer);if(this.authExpiryReconnectTimer)clearTimeout(this.authExpiryReconnectTimer);for(const watch of this.membershipFeedWatches){watch.stopped=true;watch.arm=watch.arm.catch(()=>{}).then(async()=>{await this.disarmMembershipWatch(watch);await this.deleteRetainedMembershipConsumer(watch)})}await Promise.all([...this.membershipFeedWatches].map(watch=>watch.arm.catch(err3=>{if(this.nc&&!this.nc.isClosed())throw err3})));for(const watch of this.membershipFeedWatches){watch.resolveStop?.();watch.resolveStop=void 0;watch.rejectStop=void 0}this.membershipFeedWatches.clear();for(const msgs of this.streamMsgs){try{msgs.stop()}catch{}}this.presence.retireWatch();if(this.channelWatchIter)this.retireKvWatch(this.channelWatchIter);this.channelWatchIter=void 0;this.stopDeliveryLeaseWatch();await Promise.all(principalStops);try{if(this.doRegister){await this.presence.publishOffline()}}catch{}await Promise.all([this.settleDeliveryLeaseWatches(),this.settleKvWatches()]);let dmOnlyUnsettled=false;if(this.dmOnly&&this.dmOnlyInFlight){const settleMs=this.dmOnly.settleTimeoutMs??3e4;dmOnlyUnsettled=await withDeadline(this.dmOnlyInFlight.then(()=>false),settleMs,()=>new Error("unsettled")).catch(()=>true)}await this.closeWithoutLibraryReconnect(this.nc);this.clearPresenceWriteFailure();await this.rebuildPromise;await this.startPromise;if([...this.ownedConnections].some(nc=>!nc.isClosed()))throw new Error("endpoint stop could not prove its connection closed; local consumer custody must be retained");if(dmOnlyUnsettled)throw new Error(`endpoint stop closed the connection but the DM-only handler did not settle within ${this.dmOnly?.settleTimeoutMs??3e4}ms; its copy stays unacked and handler custody must be retained`)}nativeConnections(){const unsettled=why=>new Error(`endpoint connection inventory is unsettled: ${why}`);if(this.startPromise!==void 0||this.rebuildPromise!==void 0||this.reconnecting)throw unsettled("a start or rebuild is in flight");const open7=[...this.ownedConnections].filter(nc=>!nc.isClosed());if(this.stopped){if(open7.length>0)throw unsettled("the endpoint stopped but a connection has not closed");return[]}if(this.credsTxnsRunning>0||this.residentSwap!==void 0)throw unsettled("a credential adoption is in flight");if(!this.nc||!this.nativeBound)throw unsettled("the connection is down or redialing");return open7.map(nc=>nativeConnectionBinding(nc,"endpoint connection"))}messaging=new EndpointMessaging({nc:()=>this.nc,js:()=>this.js,jsm:()=>this.jsm,space:()=>this.space,owner:()=>this.owner,actor:()=>this.actor,channels:()=>this.channels,notLiveMsg:()=>this.notLiveMsg(),ref:()=>this.ref(),publishMsg:(subject,msg)=>this.publishMsg(subject,msg),streamHistory:(...args)=>this.streamHistory(...args),emitRecoverable:err3=>this.emitRecoverable(err3)});async multicast(text3,opts){return this.messaging.multicast(text3,opts)}get maxPayload(){return this.messaging.maxPayload}async assertExpectationSemantics(){return this.messaging.assertExpectationSemantics()}encodedSize(opts){return this.messaging.encodedSize(opts)}async multicastExpecting(opts){return this.messaging.multicastExpecting(opts)}async publishEventPayload(opts){return this.messaging.publishEventPayload(opts)}async eventPayloadHistory(owner2,actor2,opts){return this.messaging.eventPayloadHistory(owner2,actor2,opts)}async eventPayloadLimit(){return this.messaging.eventPayloadLimit()}async unicast(instanceId,text3,opts){return this.messaging.unicast(instanceId,text3,opts)}async unicastAttributed(instanceId,text3,opts){return this.messaging.unicastAttributed(instanceId,text3,opts)}async anycast(service,text3,opts){return this.messaging.anycast(service,text3,opts)}async anycastAttributed(service,text3,opts){return this.messaging.anycastAttributed(service,text3,opts)}tap(handler,opts){const tap={handler,subject:opts?.subject??spaceWildcard(this.space)};this.taps.push(tap);this.bindTap(tap)}bindTap(tap){if(!this.nc)return;const sub=this.nc.subscribe(tap.subject);this.subs.push(sub);void(async()=>{for await(const m2 of sub){let decoded;try{decoded=m2.json()}catch{decoded=void 0}const parsed=parseSubject(m2.subject);if(decoded!==void 0&&(parsed?.kind==="chat"||parsed?.kind==="evp"||parsed?.kind==="inst"||parsed?.kind==="svc")){if(!isFromSubjectSender(decoded,parsed))continue;if(parsed.kind!=="evp"&&(!Array.isArray(decoded.parts)||!decoded.parts.every(isReadableMessagePart)))continue;decoded=authenticatedMessage(decoded,parsed)}try{tap.handler(m2.subject,decoded)}catch(e3){this.emit("error",e3)}}})().catch(e3=>this.emit("error",e3))}controlPlane=new EndpointControlPlane({nc:()=>this.nc,space:()=>this.space,owner:()=>this.owner,actor:()=>this.actor,stopped:()=>this.stopped,authed:()=>this.authed,connId:()=>this.connId,presentedExp:()=>this.presentedExp,issuedGeneration:()=>this.issuedGeneration,acceptedToken:()=>this.acceptedToken,rebuildPromise:()=>this.rebuildPromise,subs:()=>this.subs,resolvedServices:()=>this.resolvedServices,resolvedCommandServices:()=>this.resolvedCommandServices,serviceInvocations:()=>this.serviceInvocations,requestsAwaitingReply:()=>this.requestsAwaitingReply,activeGoalFollowers:()=>this.activeGoalFollowers,splitsRecovered:()=>this.splitsRecovered,setSplitsRecovered:count=>{this.splitsRecovered=count},notLiveMsg:()=>this.notLiveMsg(),requireLifecycleUid:what2=>this.requireLifecycleUid(what2),reportSubscriptionDenial:error51=>this.reportSubscriptionDenial(error51),ref:()=>this.ref(),reconnect:()=>this.reconnect(),emit:(event,...args)=>this.emit(event,...args)});serveControl(service,handler,opts={}){return this.controlPlane.serveControl(service,handler,opts)}async requestBoundReply(nc,subject,body,reply,timeoutMs){return this.controlPlane.requestBoundReply(nc,subject,body,reply,timeoutMs)}async requestControl(service,req,timeoutMs=5e3){return this.controlPlane.requestControl(service,req,timeoutMs)}serviceRailCaller(){return this.controlPlane.serviceRailCaller()}async followServiceGoal(endpoint,submit,deadlineMs=1e4,opts={}){return this.controlPlane.followServiceGoal(endpoint,submit,deadlineMs,opts)}async describeService(endpoint,opts={}){return this.controlPlane.describeService(endpoint,opts)}async listingCaller(){return this.controlPlane.listingCaller()}async listEndpoints(input,opts={}){return this.controlPlane.listEndpoints(input,opts)}async listEndpointsOver(nc,listing,input,opts={}){return this.controlPlane.listEndpointsOver(nc,listing,input,opts)}async invokeService(endpoint,command,args,opts={}){return this.controlPlane.invokeService(endpoint,command,args,opts)}async requestDelivery(op,args,timeoutMs=5e3){if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=controlServiceSubject(this.space,CONTROL_DELIVERY,this.owner,this.actor);const reply=`${reqSubject}.reply.${randomUUID8()}`;const body={op,args,from:this.ref()};const m2=await this.requestBoundReply(this.nc,reqSubject,JSON.stringify(body),reply,timeoutMs);return m2.json()}async requestDeliveryAdmin(op,args,timeoutMs=5e3){if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=controlServiceSubject(this.space,CONTROL_DELIVERY_ADMIN,this.owner,this.actor);const reply=`${reqSubject}.reply.${randomUUID8()}`;const body={op,args,from:this.ref()};const m2=await this.requestBoundReply(this.nc,reqSubject,JSON.stringify(body),reply,timeoutMs);return m2.json()}getRoster(){return this.presence.getRoster()}async readPresence(){return this.presence.readPresence()}presenceView(){return this.presence.presenceView()}async waitForPresenceSnapshot(timeoutMs=1e3){return this.presence.waitForPresenceSnapshot(timeoutMs)}async setActivity(activity){return this.presence.setActivity(activity)}async setStatus(status2,activity){return this.presence.setStatus(status2,activity)}noteActivity(at2=Date.now()){return this.presence.noteActivity(at2)}async setCondition(condition){return this.presence.setCondition(condition)}async setAttention(attention){return this.presence.setAttention(attention)}async setChannelModes(modes){return this.presence.setChannelModes(modes)}async setCardModel(model,variant,provider){return this.presence.setCardModel(model,variant,provider)}async setCardCwd(cwd){return this.presence.setCardCwd(cwd)}channelDiscovery=new EndpointChannelDiscovery({nc:()=>this.nc,space:()=>this.space,card:()=>this.card,doConsume:()=>this.doConsume,doWatch:()=>this.doWatch,doWatchChannels:()=>this.doWatchChannels,channelKv:()=>this.channelKv,setChannelWatchIter:iter=>{this.channelWatchIter=iter},channelConfigs:()=>this.channelConfigs,channelDefaults:()=>this.channelDefaults,setChannelDefaults:defaults=>{this.channelDefaults=defaults},channelRead:()=>this.channelRead,setChannelRead:read=>{this.channelRead=read},channelReadGeneration:()=>this.channelReadGeneration,setChannelReadGeneration:n2=>{this.channelReadGeneration=n2},channelReadApplied:()=>this.channelReadApplied,setChannelReadApplied:n2=>{this.channelReadApplied=n2},notLiveMsg:()=>this.notLiveMsg(),bindKvWatch:kv=>this.bindKvWatch(kv),emitRecoverable:err3=>this.emitRecoverable(err3),emit:(event,...args)=>this.emit(event,...args)});get readsChannelsOnDemand(){return this.channelDiscovery.readsChannelsOnDemand}async readChannels(){return this.channelDiscovery.readChannels()}getChannelConfig(channel){return this.channelDiscovery.getChannelConfig(channel)}channelReplay(channel){return this.channelDiscovery.channelReplay(channel)}channelReplayWindow(channel){return this.channelDiscovery.channelReplayWindow(channel)}async channelReplayPolicy(channel){return this.channelDiscovery.channelReplayPolicy(channel)}channelDeliveryClass(channel){return this.channelDiscovery.channelDeliveryClass(channel)}subscriptions=new EndpointSubscriptions({nc:()=>this.nc,jsm:()=>this.jsm,space:()=>this.space,card:()=>this.card,stopped:()=>this.stopped,authed:()=>this.authed,channels:()=>this.channels,channelConfigs:()=>this.channelConfigs,channelDefaults:()=>this.channelDefaults,chatSubDenied:()=>this.chatSubDenied,plane3Channels:()=>this.plane3Channels,readsChannelsOnDemand:()=>this.readsChannelsOnDemand,membershipFeedKv:()=>this.membershipFeedKv,setMembershipFeedKv:kv=>{this.membershipFeedKv=kv},membershipFeedWatches:()=>this.membershipFeedWatches,watchDeletePermissions:()=>this.watchDeletePermissions,notLiveMsg:()=>this.notLiveMsg(),readChannels:()=>this.readChannels(),armJoin:channels=>this.armJoin(channels),backfillArmed:(frontiers,floorSeq)=>this.backfillArmed(frontiers,floorSeq),subscribeChat:channel=>this.subscribeChat(channel),unsubscribeChat:channel=>this.unsubscribeChat(channel),confirmChatSub:()=>this.confirmChatSub(),durableJoinChannel:channel=>this.durableJoinChannel(channel),durableLeaveChannel:(...args)=>this.durableLeaveChannel(...args),fetchMemberships:channel=>this.fetchMemberships(channel),recordOwnWatchConsumer:info=>this.recordOwnWatchConsumer(info),watchConsumerDeleteDenied:(stream,name2,owner2)=>this.watchConsumerDeleteDenied(stream,name2,owner2),deleteMembershipConsumer:(jsm,stream,name2)=>this.deleteMembershipConsumer(jsm,stream,name2),emit:(event,...args)=>this.emit(event,...args)});joinedChannels(){return this.subscriptions.joinedChannels()}async joinChannel(channel){return this.subscriptions.joinChannel(channel)}async leaveChannel(channel,legacyDiscoveryMessage){return this.subscriptions.leaveChannel(channel,legacyDiscoveryMessage)}async chatRetention(){return this.subscriptions.chatRetention()}async dmStreamPresent(){return this.subscriptions.dmStreamPresent()}async listChannels(){return this.subscriptions.listChannels()}async channelMembers(channel){const members=(await listMembers(await this.membersRegistry())).filter(r2=>r2.leaveCursor===void 0&&r2.activated===true);const byId=new Map;for(const p2 of this.presence.values())byId.set(p2.card.id,p2);const memberForId=id2=>{const p2=byId.get(id2);return p2?{id:p2.card.id,name:p2.card.name,role:p2.card.role,live:p2.status!=="offline"}:{id:id2,name:id2,live:false}};const byName=(a3,b3)=>a3.name.localeCompare(b3.name);if(channel!==void 0){const stored=await this.deliveryClassFresh(channel)==="durable";const ids=new Set(members.filter(r2=>r2.channel===channel||stored&&isChannelFamily(r2.channel)&&subjectMatches(r2.channel,channel)).map(r2=>r2.owner));return[...ids].map(memberForId).sort(byName)}const map2=new Map;for(const r2 of members){const arr=map2.get(r2.channel);const m2=memberForId(r2.owner);if(arr){if(!arr.some(x2=>x2.id===m2.id))arr.push(m2)}else{map2.set(r2.channel,[m2])}}for(const arr of map2.values())arr.sort(byName);return map2}async readMembership(){return this.subscriptions.readMembership()}async watchMembership(onChange,onClosed){return this.subscriptions.watchMembership(onChange,onClosed)}async deleteRetainedMembershipConsumer(watch){return this.subscriptions.deleteRetainedMembershipConsumer(watch)}recordOwnWatchConsumer({stream_name,name:name2}){const prefix=`$JS.API.CONSUMER.DELETE.${stream_name}.${name2.slice(0,name2.lastIndexOf("_")+1)}`;this.ownWatchDeletePrefixes.add(prefix);return prefix}isOwnWatchDelete(subject){const cut2=subject.lastIndexOf("_")+1;return/^\d+$/.test(subject.slice(cut2))&&this.ownWatchDeletePrefixes.has(subject.slice(0,cut2))}watchConsumerDeleteDenied(stream,name2,owner2){const permission2=owner2&&this.watchDeletePermissions.get(owner2)?.();return Boolean(permission2&&!issuedPermitsSubject(permission2,`$JS.API.CONSUMER.DELETE.${stream}.${name2}`))}async deleteOwnConsumer(consumer){const{stream_name,name:name2}=await consumer.info(true);if(this.watchConsumerDeleteDenied(stream_name,name2,consumer))return;try{await consumer.delete()}catch(e3){if(!isJetStreamMissing(e3,import_jetstream21.JetStreamApiCodes.ConsumerNotFound)&&!isPublishPermissionDenied(e3))throw e3}}async deleteMembershipConsumer(jsm,stream,name2){try{return await jsm.consumers.delete(stream,name2)}catch(err3){if(membershipConsumerReleased(err3))return true;throw err3}}async disarmMembershipWatch(watch){return this.subscriptions.disarmMembershipWatch(watch)}async rearmMembershipWatches(){return this.subscriptions.rearmMembershipWatches()}async channelHistory(channel,opts){return this.history.channelHistory(channel,opts)}async channelHistoryPage(channel,opts){return this.history.channelHistoryPage(channel,opts)}async multiChannelHistory(channels,opts){return this.history.multiChannelHistory(channels,opts)}async readHistory(channel,opts){return this.history.readHistory(channel,opts)}async dmHistory(opts){return this.history.dmHistory(opts)}async dmHistoryOf(principals,opts){const keys=[...new Set(principals)].map(p2=>{const key=parsePrincipalKey(p2);if(!key)throw new Error(`dmHistoryOf: "${p2}" is not a principal <owner>.<actor>`);return key});if(!keys.length)return{state:"read",items:[]};const limit=opts?.limit??100;const read=subjects=>this.streamHistory(dmStream(this.space),subjects,limit,void 0,opts?.signal);let rows;try{rows=(await Promise.all([read(keys.map(k2=>unicastRecvFilter(this.space,k2.owner,k2.actor))),read(keys.map(k2=>unicastSubject(this.space,"*","*",k2.owner,k2.actor)))])).flat()}catch(e3){if(isPermissionDenied(e3))return{state:"denied",reason:e3.message};throw e3}const bySeq=new Map(rows.map(r2=>[r2.seq,r2.msg]));return{state:"read",items:[...bySeq].sort(([a3],[b3])=>a3-b3).slice(-limit).map(([,msg])=>msg)}}async streamHistory(stream,subjects,limit,before,signal){return this.history.streamHistory(stream,subjects,limit,before,signal)}watchStatus(){const nc=this.nc;if(!nc)return;const handedToRequest=this.trackRequestDenials(nc);void(async()=>{for await(const s3 of nc.status()){if(this.nc!==nc)continue;if(nativeBindingAfter(s3.type)===false)this.nativeBound=false;if(s3.type==="disconnect"){this.emit("transport",{connected:false,server:s3.server});continue}if(s3.type==="reconnect"){this.armAuthExpiryReconnectFence(nc);this.rebindPrincipalServes(true);this.emit("transport",{connected:true,server:s3.server});for(const follower of this.activeGoalFollowers){follower.reconnected(nc)}continue}if(s3.type==="close"){this.emit("transport",{connected:false});continue}if(s3.type!=="error")continue;if(s3.error instanceof import_transport_node22.PermissionViolationError&&this.chatSubRefusals.has(s3.error))continue;if(s3.error instanceof import_transport_node22.PermissionViolationError&&this.ownedPrincipalRouteRefusal(s3.error))continue;if(s3.error instanceof import_transport_node22.PermissionViolationError&&handedToRequest.has(s3.error))continue;if(s3.error instanceof import_transport_node22.PermissionViolationError&&s3.error.operation==="publish"&&this.isOwnWatchDelete(s3.error.subject))continue;if(!this.reportSubscriptionDenial(s3.error))this.emit("error",describeStatusError(s3.error))}})().catch(e3=>{if(!this.stopped&&this.nc===nc)this.emit("error",e3)});if(this.stopped)return;this.emit("transport",{connected:true,server:nc.getServer()})}reportSubscriptionDenial(error51){if(!(error51 instanceof import_transport_node22.PermissionViolationError)||error51.operation!=="subscription")return false;if(!this.reportedSubRefusals.has(error51)){this.reportedSubRefusals.add(error51);this.emit("error",describeStatusError(error51))}return true}trackRequestDenials(nc){const handed=new WeakSet;const request=nc.request.bind(nc);nc.request=(subject,payload,opts)=>{if(typeof subject==="string"&&this.ungrantedOwnWatchDelete(subject)){const violation=new import_transport_node22.PermissionViolationError(`Permissions Violation for Publish to "${subject}"`,"publish",subject);handed.add(violation);return Promise.reject(new import_transport_node22.RequestError("permissions violation",{cause:violation}))}const reply=request(subject,payload,opts);reply.catch(({cause})=>{if(cause instanceof import_transport_node22.PermissionViolationError&&cause.operation==="publish")handed.add(cause)});return reply};return handed}ungrantedOwnWatchDelete(subject){if(!this.isOwnWatchDelete(subject))return false;const permission2=this.watchDeletePermissions.get(this.nc)?.();return Boolean(permission2&&!issuedPermitsSubject(permission2,subject))}notLiveMsg(){return this.reconnecting||this.reestablishing?"reconnecting - try again shortly":"endpoint not started"}async publishMsg(subject,msg){if(!this.js)throw new Error(this.notLiveMsg());assertPartsSerializable(msg.parts);try{await this.js.publish(subject,JSON.stringify(msg),{msgID:msg.id})}catch(error51){if(error51 instanceof import_transport_node22.TimeoutError)throw new Error(`${error51.message} publishing to ${JSON.stringify(subject)}. The send outcome is unknown: the broker may have stored the message. Check before resending.`,{cause:error51});throw error51}}provisioning=new EndpointProvisioning({jsm:()=>this.jsm,space:()=>this.space,authed:()=>this.authed,notLiveMsg:()=>this.notLiveMsg(),manager:()=>this.manager()});async ensureStreams(){return this.provisioning.ensureStreams()}async ensureOpenSpaceStreams(){return this.provisioning.ensureOpenSpaceStreams()}async provisionDmInbox(owner2,actor2,lifecycleUid){return this.provisioning.provisionDmInbox(owner2,actor2,lifecycleUid)}async ensureDmDurable(owner2,actor2,lifecycleUid,opts){return this.provisioning.ensureDmDurable(owner2,actor2,lifecycleUid,opts)}async provisionDlvInbox(owner2,actor2,lifecycleUid){return this.provisioning.provisionDlvInbox(owner2,actor2,lifecycleUid)}async provisionTaskQueue(role){return this.provisioning.provisionTaskQueue(role)}durableBackstop=new EndpointDurableBackstop({nc:()=>this.nc,js:()=>this.js,jsm:()=>this.jsm,setJsm:manager=>{this.jsm=manager},space:()=>this.space,card:()=>this.card,authed:()=>this.authed,channelKv:()=>this.channelKv,presence:()=>this.presence,deliveryPlane:()=>this.deliveryPlane,membersKv:()=>this.membersKv,setMembersKv:kv=>{this.membersKv=kv},aclKv:()=>this.aclKv,setAclKv:kv=>{this.aclKv=kv},managerLeaseKv:()=>this.managerLeaseKv,setManagerLeaseKv:kv=>{this.managerLeaseKv=kv},daemonRenewalLeaseRevision:()=>this.daemonRenewalLeaseRevision,setDaemonRenewalLeaseRevision:revision=>{this.daemonRenewalLeaseRevision=revision},notLiveMsg:()=>this.notLiveMsg(),consumerInfo:(stream,durable)=>this.consumerInfo(stream,durable),manager:()=>this.manager(),chatFrontier:()=>this.chatFrontier(),aclAllows:(owner2,lifecycleUid,channel)=>this.aclAllows(owner2,lifecycleUid,channel),catchupCopy:(...args)=>this.catchupCopy(...args)});async membersRegistry(){return this.durableBackstop.membersRegistry()}async aclRegistry(){return this.durableBackstop.aclRegistry()}async commitAcl(targetId,lifecycleUid,allowSubscribe){return this.durableBackstop.commitAcl(targetId,lifecycleUid,allowSubscribe)}async reissueAcl(targetId,lifecycleUid,allowSubscribe){return this.durableBackstop.reissueAcl(targetId,lifecycleUid,allowSubscribe)}async aclForOwner(owner2,lifecycleUid){return this.durableBackstop.aclForOwner(owner2,lifecycleUid)}async aclForAlias(principal){return this.durableBackstop.aclForAlias(principal)}ownsDeliveryLease(info){return this.deliveryLease.ownsDeliveryLease(info)}async acquireDeliveryLease(shardIndex){return this.deliveryLease.acquireDeliveryLease(shardIndex)}async markDeliveryLeaseReady(shardIndex,revision){return this.deliveryLease.markDeliveryLeaseReady(shardIndex,revision)}async markDeliveryLeaseNotReady(shardIndex,revision){return this.deliveryLease.markDeliveryLeaseNotReady(shardIndex,revision)}async renewDeliveryLease(shardIndex,revision){return this.deliveryLease.renewDeliveryLease(shardIndex,revision)}async releaseDeliveryLease(shardIndex,revision){return this.deliveryLease.releaseDeliveryLease(shardIndex,revision)}async readDeliveryLease(shardIndex){return this.deliveryLease.readDeliveryLease(shardIndex)}async watchDeliveryLease(shardIndex,onEvent){return this.deliveryLease.watchDeliveryLease(shardIndex,onEvent)}stopDeliveryLeaseWatch(){return this.deliveryLease.stopDeliveryLeaseWatch()}async settleDeliveryLeaseWatches(){return this.deliveryLease.settleDeliveryLeaseWatches()}retireKvWatch(iter){try{iter.stop()}catch{}if(!this.nc||this.nc.isClosed())return;const deleting=this.deleteOwnConsumer(kvWatchConsumer(iter)).catch(e3=>this.emitRecoverable(new Error(`a retired KV watch consumer was not deleted (${e3.message}); the broker reaps it at its inactive threshold`)));this.kvWatchDeletes.add(deleting);void deleting.then(()=>this.kvWatchDeletes.delete(deleting))}async settleKvWatches(){await Promise.allSettled(this.kvWatchBinds);await Promise.all(this.kvWatchDeletes)}bindKvWatch(kv){if(this.stopped)return Promise.resolve(void 0);const epoch=this.presenceEpoch;const binding=(async()=>{const permission2=this.nc&&this.watchDeletePermissions.get(this.nc);const iter=await kv.watch();const info=await kvWatchConsumer(iter).info(true);this.recordOwnWatchConsumer(info);if(permission2)this.watchDeletePermissions.set(kvWatchConsumer(iter),permission2);if(epoch===this.presenceEpoch&&!this.stopped)return{iter,info};this.retireKvWatch(iter);return void 0})();const settled=()=>{this.kvWatchBinds.delete(binding)};this.kvWatchBinds.add(binding);void binding.then(settled,settled);return binding}bindDeliveryLeaseWatch(){return this.deliveryLease.bindDeliveryLeaseWatch()}async deliveryLeaseHolder(shardIndex){return this.deliveryLease.deliveryLeaseHolder(shardIndex)}async readDeliveryLeaseEntry(shardIndex){return this.deliveryLease.readDeliveryLeaseEntry(shardIndex)}async holdDaemonRenewalLease(instanceId){return this.durableBackstop.holdDaemonRenewalLease(instanceId)}async releaseDaemonRenewalLease(){return this.durableBackstop.releaseDaemonRenewalLease()}async readDaemonRenewalLease(){return this.durableBackstop.readDaemonRenewalLease()}async acquireManagerLease(info){return this.durableBackstop.acquireManagerLease(info)}async renewManagerLease(info,revision){return this.durableBackstop.renewManagerLease(info,revision)}async readOwnManagerLease(instanceId){return this.durableBackstop.readOwnManagerLease(instanceId)}async releaseManagerLease(instanceId,revision){return this.durableBackstop.releaseManagerLease(instanceId,revision)}async readManagerLease(){return this.durableBackstop.readManagerLease()}async ownerMemberships(owner2,lifecycleUid){return this.durableBackstop.ownerMemberships(owner2,lifecycleUid)}async deliveryClassFresh(channel){return this.durableBackstop.deliveryClassFresh(channel)}resolveOwnerByName(name2){return this.durableBackstop.resolveOwnerByName(name2)}plane3MsgId(entry,keySuffix){return this.durableBackstop.plane3MsgId(entry,keySuffix)}async publishDinbox(principal,lifecycleUid,entry){return this.durableBackstop.publishDinbox(principal,lifecycleUid,entry)}async durableJoinFor(owner2,channel,lifecycleUid,opts={}){return this.durableBackstop.durableJoinFor(owner2,channel,lifecycleUid,opts)}async aclAllows(owner2,lifecycleUid,channel){const row=await readAcl(await this.aclRegistry(),owner2,lifecycleUid);return row!==void 0&&membershipInAllow(row.record.allowSubscribe,channel)}async durableLeaveFor(owner2,channel,lifecycleUid,expectedGeneration){return this.durableBackstop.durableLeaveFor(owner2,channel,lifecycleUid,expectedGeneration)}async catchupCopy(owner2,lifecycleUid,channel,fromSeqExcl,toSeqIncl,generation){if(!this.js||!this.jsm||toSeqIncl<=fromSeqExcl)return 0;const subject=chatSubject(this.space,"*","*",channel);const family=isChannelFamily(channel);const durableClass=new Map;const stored=ch=>{if(!family)return Promise.resolve(true);let cls=durableClass.get(ch);if(cls===void 0)durableClass.set(ch,cls=this.deliveryClassFresh(ch).then(c3=>c3==="durable"));return cls};const cuP=parsePrincipalKey(owner2);const name2=`cu_${cuP?lifecycleNameKey(cuP.owner,cuP.actor,lifecycleUid):`${token(owner2)}-${lifecycleUid}`}_${generation}`;await this.deleteConsumerIfPresent(chatStream(this.space),name2);await this.jsm.consumers.add(chatStream(this.space),{name:name2,filter_subject:subject,ack_policy:import_jetstream21.AckPolicy.None,mem_storage:true,inactive_threshold:(0,import_transport_node22.nanos)(3e4),deliver_policy:import_jetstream21.DeliverPolicy.StartSequence,opt_start_seq:fromSeqExcl+1});let copied=0;try{const consumer=await this.js.consumers.get(chatStream(this.space),name2);let pending=(await consumer.info()).num_pending;while(pending>0){const want=Math.min(pending,256);const iter=await consumer.fetch({max_messages:want,expires:5e3});let got=0;for await(const m2 of iter){got++;if(m2.seq>toSeqIncl)return copied;let msg;try{msg=m2.json()}catch{continue}const parsed=parseSubject(m2.subject);if(!parsed||!isFromSubjectSender(msg,parsed)||msg.from.id===owner2)continue;if(!await stored(parsed.rest))continue;await this.publishDinbox(owner2,lifecycleUid,{msg,channel:parsed.rest,seq:m2.seq,reason:"durable-channel",generation,...family?{row:channel}:{}});copied++}if(got<want)break;pending-=got}}finally{await this.deleteConsumerIfPresent(chatStream(this.space),name2)}return copied}async startPlane3(aclFor,opts={}){return this.deliveryPlane.startPlane3(aclFor,opts)}async quiescePlane3(){return this.deliveryPlane.quiescePlane3()}plane3IsQuiesced(){return this.deliveryPlane.plane3IsQuiesced()}async rearmPlane3(){return this.deliveryPlane.rearmPlane3()}plane3MayAct(){return this.deliveryPlane.plane3MayAct()}async armPlane3(){return this.deliveryPlane.armPlane3()}async pumpDlv(){return this.deliveryPlane.pumpDlv()}async armAnycastRequests(){if(!this.nc||!this.jsm)return;this.dropAnycastRequests();const definition=anycastStoreDefinition(this.space);let kv;try{kv=await new import_kv10.Kvm(this.nc).create(definition.bucket,definition.createOptions)}catch(e3){if(!isPermissionDenied(e3))throw e3;this.anycastUnavailable=ANYCAST_RECORDS_CREDENTIAL_OUTDATED;this.emitRecoverable(new Error(`delivery: ${ANYCAST_RECORDS_CREDENTIAL_OUTDATED}`));return}this.anycastUnavailable=void 0;const authority=new AnycastRequestAuthority({jsm:this.jsm,kv,stream:taskStream(this.space),send:(to,event)=>this.sendAnycastNotice(to,event),mayAct:()=>this.plane3MayAct(),onError:e3=>this.emitRecoverable(e3)});this.anycastAuthority=authority;this.takeServeSub=this.serveTakes(authority);const sweep=()=>void authority.sweep().catch(e3=>this.emitRecoverable(e3));this.anycastSweep=setInterval(sweep,ANYCAST_SWEEP_MS);this.anycastSweep.unref?.();sweep()}dropAnycastRequests(){if(this.takeServeSub){try{this.takeServeSub.unsubscribe()}catch{}const i2=this.subs.indexOf(this.takeServeSub);if(i2>=0)this.subs.splice(i2,1);this.takeServeSub=void 0}clearInterval(this.anycastSweep);this.anycastSweep=void 0;this.anycastAuthority=void 0}serveTakes(authority){const sub=this.nc.subscribe(takeServeFilter(this.space),{queue:TAKE_ROUTE});this.subs.push(sub);void(async()=>{for await(const m2 of sub){if(!m2.reply||!m2.reply.startsWith(`${m2.subject}.reply.`)){this.emitRecoverable(new Error(`rejected take on ${m2.subject}: reply target "${m2.reply??"(none)"}" is not under the sender's own reply subtree`));continue}void this.answerTake(authority,m2).catch(e3=>this.emitRecoverable(e3))}})().catch(e3=>this.emitRecoverable(e3));return sub}async answerTake(authority,m2){let reply;if(this.takesInFlight>=MAX_TAKES_IN_FLIGHT)reply={ok:false,code:"busy",error:"the delivery daemon is answering too many takes; retry"};else{this.takesInFlight++;try{reply=await this.takeFor(authority,m2)}catch(e3){reply={ok:false,code:"busy",error:`the take could not be recorded: ${e3.message}`}}finally{this.takesInFlight--}}m2.respond(JSON.stringify(reply))}async takeFor(authority,m2){if(!this.plane3MayAct())return{ok:false,code:"busy",error:"delivery: this daemon is not serving this shard (it is re-checking ownership); retry"};const parsed=parseTakeSubject(m2.subject);let req;try{req=m2.json()}catch{req=void 0}if(!parsed||!isPrincipalOwnerToken(parsed.owner)||req?.from?.id!==parsed.sender||typeof req.from.name!=="string")return{ok:false,code:"mismatch",error:"sender mismatch - take rejected"};if(!isAnycastSeq(req.seq)||!isAnycastSeq(req.count)||typeof req.id!=="string"||req.id.length>256||typeof req.epoch!=="string"||req.epoch.length>64)return{ok:false,code:"mismatch",error:"a take names a seq, the request id, a delivery count and the stream's creation time"};try{assertValidName(req.from.name)}catch(e3){return{ok:false,code:"mismatch",error:`a take names its holder by a valid display name: ${e3.message}`}}return authority.take(parsed.role,{from:{id:parsed.sender,name:req.from.name},seq:req.seq,id:req.id,count:req.count,epoch:req.epoch})}async sendAnycastNotice(to,event){if(!this.js)throw new Error(this.notLiveMsg());const recipient=parsePrincipalKey(to);if(!recipient)throw new Error(`anycast notice: "${to}" is not a principal`);const msg={id:event.key,ts:Date.now(),space:this.space,from:this.ref(),to,parts:[{kind:"text",text:event.text},{kind:"data",data:{[ANYCAST_NOTICE_KEY]:event.notice}}]};await this.js.publish(unicastSubject(this.space,recipient.owner,recipient.actor,this.owner,this.actor),JSON.stringify(msg),{msgID:msg.id})}async sendMentionNotice(msg,channel,seq,names){if(!this.js)throw new Error(this.notLiveMsg());const recipient=parsePrincipalKey(msg.from.id);if(!recipient)throw new Error(`mention notice: "${msg.from.id}" is not a principal`);const named=names.map(n2=>`@${n2}`).join(", ");const notice={id:`mention.${seq}.${msg.id}`,ts:Date.now(),space:this.space,from:this.ref(),to:msg.from.id,parts:[{kind:"text",text:`Your post on #${channel} mentioned ${named}, who may not read #${channel} and ${names.length===1?"was":"were"} not given it. Reach ${names.length===1?"them":"each"} another way, such as cotal_dm.`},{kind:"data",data:{[MENTION_NOTICE_KEY]:{channel,message:msg.id,names:[...names]}}}]};await this.js.publish(unicastSubject(this.space,recipient.owner,recipient.actor,this.owner,this.actor),JSON.stringify(notice),{msgID:notice.id})}async deliveryAnycast(op,caller,args){const authority=this.anycastAuthority;if(!authority)return{ok:false,error:`delivery: ${this.anycastUnavailable??"the anycast request records are not open on this daemon; retry"}`};if(!isAnycastSeq(args.seq))return{ok:false,error:`${op}: seq must be a whole number of at least 1`};if(args.id!==void 0&&(typeof args.id!=="string"||args.id.length>256))return{ok:false,error:`${op}: id must be a request id`};const q2={seq:args.seq,...typeof args.id==="string"?{id:args.id}:{}};try{const status2=op===ANYCAST_CANCEL_OP?await authority.cancel(caller,q2):await authority.status(caller,q2);if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon stopped serving this shard while the request was in flight; retry"};return{ok:true,data:status2}}catch(e3){return{ok:false,error:e3.message}}}liveness=new EndpointLiveness({nc:()=>this.nc,space:()=>this.space,owner:()=>this.owner,actor:()=>this.actor,subs:()=>this.subs,livenessResponders:()=>this.livenessResponders,notLiveMsg:()=>this.notLiveMsg(),requestBoundReply:(nc,subject,body,reply,timeoutMs)=>this.requestBoundReply(nc,subject,body,reply,timeoutMs),isNoResponders:e3=>this.isNoResponders(e3),emitRecoverable:err3=>this.emitRecoverable(err3),emit:(event,...args)=>this.emit(event,...args)});serveLiveness(plane,readState){return this.liveness.serveLiveness(plane,readState)}bindLiveness(plane){return this.liveness.bindLiveness(plane)}serveDeliveryLiveness(shardIndex=0){this.serveLiveness("delivery",async()=>responderFromLease(await this.readDeliveryLease(shardIndex),this.card.id))}async probeLiveness(plane,timeoutMs=2e3){return this.liveness.probeLiveness(plane,timeoutMs)}servePrincipal(spec){if("endpoint"in spec||"cluster"in spec)throw new Error(`servePrincipal serves only the "${AGENT_ENDPOINT}" endpoint with AGENT_CLUSTER and takes handlers alone; an endpoint or cluster is refused, never ignored (SPEC 13.22)`);const serve={endpoint:AGENT_ENDPOINT,cluster:AGENT_CLUSTER,handlers:spec.handlers};if(!this.authed)throw new Error("the principal route is served only on an authenticated mesh: on an open mesh no row says who may call (SPEC 13.21)");if(!this.userMode)throw new Error("the principal route is served only under a user-auth credential: a static credential names no one who may call (SPEC 13.21)");const uid2=this.ownLifecycleUid;if(uid2===void 0)throw new Error("serving the principal route needs this endpoint's lifecycleUid: the subject names it (SPEC 13.21)");const nc=this.nc;if(!nc)throw new Error(this.notLiveMsg());endpointToken(serve.endpoint);if(this.principalServes.has(serve.endpoint))throw new Error(`this endpoint already serves "${serve.endpoint}" on the principal route`);const self2={owner:this.owner,actor:this.actor,uid:uid2,runtimeId:assertRuntimeToken(processRuntime(uid2).id)};const serverKey=`${this.space}
|
|
51
|
+
${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.errors.push(new errors.YAMLParseError(getErrorPos(token2),"UNEXPECTED_TOKEN",`Unsupported token ${token2.type}`))}}*end(forceDoc=false,endOffset=-1){if(this.doc){this.decorate(this.doc,true);yield this.doc;this.doc=null}else if(forceDoc){const opts=Object.assign({_directives:this.directives},this.options);const doc=new Document.Document(void 0,opts);if(this.atDirectives)this.onError(endOffset,"MISSING_CHAR","Missing directives-end indicator line");doc.range=[0,endOffset,endOffset];this.decorate(doc,false);yield doc}}};exports.Composer=Composer}});var require_cst_scalar=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-scalar.js"(exports){"use strict";var resolveBlockScalar=require_resolve_block_scalar();var resolveFlowScalar=require_resolve_flow_scalar();var errors=require_errors3();var stringifyString=require_stringifyString();function resolveAsScalar(token2,strict=true,onError){if(token2){const _onError=(pos,code2,message)=>{const offset=typeof pos==="number"?pos:Array.isArray(pos)?pos[0]:pos.offset;if(onError)onError(offset,code2,message);else throw new errors.YAMLParseError([offset,offset+1],code2,message)};switch(token2.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return resolveFlowScalar.resolveFlowScalar(token2,strict,_onError);case"block-scalar":return resolveBlockScalar.resolveBlockScalar({options:{strict}},token2,_onError)}}return null}function createScalarToken(value,context){const{implicitKey=false,indent,inFlow=false,offset=-1,type="PLAIN"}=context;const source=stringifyString.stringifyString({type,value},{implicitKey,indent:indent>0?" ".repeat(indent):"",inFlow,options:{blockQuote:true,lineWidth:-1}});const end=context.end??[{type:"newline",offset:-1,indent,source:"\n"}];switch(source[0]){case"|":case">":{const he2=source.indexOf("\n");const head=source.substring(0,he2);const body=source.substring(he2+1)+"\n";const props=[{type:"block-scalar-header",offset,indent,source:head}];if(!addEndtoBlockProps(props,end))props.push({type:"newline",offset:-1,indent,source:"\n"});return{type:"block-scalar",offset,indent,props,source:body}}case'"':return{type:"double-quoted-scalar",offset,indent,source,end};case"'":return{type:"single-quoted-scalar",offset,indent,source,end};default:return{type:"scalar",offset,indent,source,end}}}function setScalarValue(token2,value,context={}){let{afterKey=false,implicitKey=false,inFlow=false,type}=context;let indent="indent"in token2?token2.indent:null;if(afterKey&&typeof indent==="number")indent+=2;if(!type)switch(token2.type){case"single-quoted-scalar":type="QUOTE_SINGLE";break;case"double-quoted-scalar":type="QUOTE_DOUBLE";break;case"block-scalar":{const header=token2.props[0];if(header.type!=="block-scalar-header")throw new Error("Invalid block scalar header");type=header.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:type="PLAIN"}const source=stringifyString.stringifyString({type,value},{implicitKey:implicitKey||indent===null,indent:indent!==null&&indent>0?" ".repeat(indent):"",inFlow,options:{blockQuote:true,lineWidth:-1}});switch(source[0]){case"|":case">":setBlockScalarValue(token2,source);break;case'"':setFlowScalarValue(token2,source,"double-quoted-scalar");break;case"'":setFlowScalarValue(token2,source,"single-quoted-scalar");break;default:setFlowScalarValue(token2,source,"scalar")}}function setBlockScalarValue(token2,source){const he2=source.indexOf("\n");const head=source.substring(0,he2);const body=source.substring(he2+1)+"\n";if(token2.type==="block-scalar"){const header=token2.props[0];if(header.type!=="block-scalar-header")throw new Error("Invalid block scalar header");header.source=head;token2.source=body}else{const{offset}=token2;const indent="indent"in token2?token2.indent:-1;const props=[{type:"block-scalar-header",offset,indent,source:head}];if(!addEndtoBlockProps(props,"end"in token2?token2.end:void 0))props.push({type:"newline",offset:-1,indent,source:"\n"});for(const key of Object.keys(token2))if(key!=="type"&&key!=="offset")delete token2[key];Object.assign(token2,{type:"block-scalar",indent,props,source:body})}}function addEndtoBlockProps(props,end){if(end)for(const st2 of end)switch(st2.type){case"space":case"comment":props.push(st2);break;case"newline":props.push(st2);return true}return false}function setFlowScalarValue(token2,source,type){switch(token2.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":token2.type=type;token2.source=source;break;case"block-scalar":{const end=token2.props.slice(1);let oa2=source.length;if(token2.props[0].type==="block-scalar-header")oa2-=token2.props[0].source.length;for(const tok of end)tok.offset+=oa2;delete token2.props;Object.assign(token2,{type,source,end});break}case"block-map":case"block-seq":{const offset=token2.offset+source.length;const nl={type:"newline",offset,indent:token2.indent,source:"\n"};delete token2.items;Object.assign(token2,{type,source,end:[nl]});break}default:{const indent="indent"in token2?token2.indent:-1;const end="end"in token2&&Array.isArray(token2.end)?token2.end.filter(st2=>st2.type==="space"||st2.type==="comment"||st2.type==="newline"):[];for(const key of Object.keys(token2))if(key!=="type"&&key!=="offset")delete token2[key];Object.assign(token2,{type,indent,source,end})}}}exports.createScalarToken=createScalarToken;exports.resolveAsScalar=resolveAsScalar;exports.setScalarValue=setScalarValue}});var require_cst_stringify=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-stringify.js"(exports){"use strict";var stringify=cst=>"type"in cst?stringifyToken(cst):stringifyItem(cst);function stringifyToken(token2){switch(token2.type){case"block-scalar":{let res="";for(const tok of token2.props)res+=stringifyToken(tok);return res+token2.source}case"block-map":case"block-seq":{let res="";for(const item of token2.items)res+=stringifyItem(item);return res}case"flow-collection":{let res=token2.start.source;for(const item of token2.items)res+=stringifyItem(item);for(const st2 of token2.end)res+=st2.source;return res}case"document":{let res=stringifyItem(token2);if(token2.end)for(const st2 of token2.end)res+=st2.source;return res}default:{let res=token2.source;if("end"in token2&&token2.end)for(const st2 of token2.end)res+=st2.source;return res}}}function stringifyItem({start,key,sep:sep4,value}){let res="";for(const st2 of start)res+=st2.source;if(key)res+=stringifyToken(key);if(sep4)for(const st2 of sep4)res+=st2.source;if(value)res+=stringifyToken(value);return res}exports.stringify=stringify}});var require_cst_visit=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-visit.js"(exports){"use strict";var BREAK=Symbol("break visit");var SKIP=Symbol("skip children");var REMOVE=Symbol("remove item");function visit(cst,visitor){if("type"in cst&&cst.type==="document")cst={start:cst.start,value:cst.value};_visit(Object.freeze([]),cst,visitor)}visit.BREAK=BREAK;visit.SKIP=SKIP;visit.REMOVE=REMOVE;visit.itemAtPath=(cst,path4)=>{let item=cst;for(const[field,index2]of path4){const tok=item?.[field];if(tok&&"items"in tok){item=tok.items[index2]}else return void 0}return item};visit.parentCollection=(cst,path4)=>{const parent=visit.itemAtPath(cst,path4.slice(0,-1));const field=path4[path4.length-1][0];const coll=parent?.[field];if(coll&&"items"in coll)return coll;throw new Error("Parent collection not found")};function _visit(path4,item,visitor){let ctrl=visitor(item,path4);if(typeof ctrl==="symbol")return ctrl;for(const field of["key","value"]){const token2=item[field];if(token2&&"items"in token2){for(let i2=0;i2<token2.items.length;++i2){const ci2=_visit(Object.freeze(path4.concat([[field,i2]])),token2.items[i2],visitor);if(typeof ci2==="number")i2=ci2-1;else if(ci2===BREAK)return BREAK;else if(ci2===REMOVE){token2.items.splice(i2,1);i2-=1}}if(typeof ctrl==="function"&&field==="key")ctrl=ctrl(item,path4)}}return typeof ctrl==="function"?ctrl(item,path4):ctrl}exports.visit=visit}});var require_cst=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst.js"(exports){"use strict";var cstScalar=require_cst_scalar();var cstStringify=require_cst_stringify();var cstVisit=require_cst_visit();var BOM="\uFEFF";var DOCUMENT="";var FLOW_END="";var SCALAR="";var isCollection=token2=>!!token2&&"items"in token2;var isScalar=token2=>!!token2&&(token2.type==="scalar"||token2.type==="single-quoted-scalar"||token2.type==="double-quoted-scalar"||token2.type==="block-scalar");function prettyToken(token2){switch(token2){case BOM:return"<BOM>";case DOCUMENT:return"<DOC>";case FLOW_END:return"<FLOW_END>";case SCALAR:return"<SCALAR>";default:return JSON.stringify(token2)}}function tokenType(source){switch(source){case BOM:return"byte-order-mark";case DOCUMENT:return"doc-mode";case FLOW_END:return"flow-error-end";case SCALAR:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case"\n":case"\r\n":return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(source[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}exports.createScalarToken=cstScalar.createScalarToken;exports.resolveAsScalar=cstScalar.resolveAsScalar;exports.setScalarValue=cstScalar.setScalarValue;exports.stringify=cstStringify.stringify;exports.visit=cstVisit.visit;exports.BOM=BOM;exports.DOCUMENT=DOCUMENT;exports.FLOW_END=FLOW_END;exports.SCALAR=SCALAR;exports.isCollection=isCollection;exports.isScalar=isScalar;exports.prettyToken=prettyToken;exports.tokenType=tokenType}});var require_lexer=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/lexer.js"(exports){"use strict";var cst=require_cst();function isEmpty(ch){switch(ch){case void 0:case" ":case"\n":case"\r":case" ":return true;default:return false}}var hexDigits=new Set("0123456789ABCDEFabcdef");var tagChars=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");var flowIndicatorChars=new Set(",[]{}");var invalidAnchorChars=new Set(" ,[]{}\n\r ");var isNotAnchorChar=ch=>!ch||invalidAnchorChars.has(ch);var Lexer=class{constructor(){this.atEnd=false;this.blockScalarIndent=-1;this.blockScalarKeep=false;this.buffer="";this.flowKey=false;this.flowLevel=0;this.indentNext=0;this.indentValue=0;this.lineEndPos=null;this.next=null;this.pos=0}*lex(source,incomplete=false){if(source){if(typeof source!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+source:source;this.lineEndPos=null}this.atEnd=!incomplete;let next=this.next??"stream";while(next&&(incomplete||this.hasChars(1)))next=yield*this.parseNext(next)}atLineEnd(){let i2=this.pos;let ch=this.buffer[i2];while(ch===" "||ch===" ")ch=this.buffer[++i2];if(!ch||ch==="#"||ch==="\n")return true;if(ch==="\r")return this.buffer[i2+1]==="\n";return false}charAt(n2){return this.buffer[this.pos+n2]}continueScalar(offset){let ch=this.buffer[offset];if(this.indentNext>0){let indent=0;while(ch===" ")ch=this.buffer[++indent+offset];if(ch==="\r"){const next=this.buffer[indent+offset+1];if(next==="\n"||!next&&!this.atEnd)return offset+indent+1}return ch==="\n"||indent>=this.indentNext||!ch&&!this.atEnd?offset+indent:-1}if(ch==="-"||ch==="."){const dt2=this.buffer.substr(offset,3);if((dt2==="---"||dt2==="...")&&isEmpty(this.buffer[offset+3]))return-1}return offset}getLine(){let end=this.lineEndPos;if(typeof end!=="number"||end!==-1&&end<this.pos){end=this.buffer.indexOf("\n",this.pos);this.lineEndPos=end}if(end===-1)return this.atEnd?this.buffer.substring(this.pos):null;if(this.buffer[end-1]==="\r")end-=1;return this.buffer.substring(this.pos,end)}hasChars(n2){return this.pos+n2<=this.buffer.length}setNext(state){this.buffer=this.buffer.substring(this.pos);this.pos=0;this.lineEndPos=null;this.next=state;return null}peek(n2){return this.buffer.substr(this.pos,n2)}*parseNext(next){switch(next){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let line=this.getLine();if(line===null)return this.setNext("stream");if(line[0]===cst.BOM){yield*this.pushCount(1);line=line.substring(1)}if(line[0]==="%"){let dirEnd=line.length;let cs=line.indexOf("#");while(cs!==-1){const ch=line[cs-1];if(ch===" "||ch===" "){dirEnd=cs-1;break}else{cs=line.indexOf("#",cs+1)}}while(true){const ch=line[dirEnd-1];if(ch===" "||ch===" ")dirEnd-=1;else break}const n2=(yield*this.pushCount(dirEnd))+(yield*this.pushSpaces(true));yield*this.pushCount(line.length-n2);this.pushNewline();return"stream"}if(this.atLineEnd()){const sp=yield*this.pushSpaces(true);yield*this.pushCount(line.length-sp);yield*this.pushNewline();return"stream"}yield cst.DOCUMENT;return yield*this.parseLineStart()}*parseLineStart(){const ch=this.charAt(0);if(!ch&&!this.atEnd)return this.setNext("line-start");if(ch==="-"||ch==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const s3=this.peek(3);if((s3==="---"||s3==="...")&&isEmpty(this.charAt(3))){yield*this.pushCount(3);this.indentValue=0;this.indentNext=0;return s3==="---"?"doc":"stream"}}this.indentValue=yield*this.pushSpaces(false);if(this.indentNext>this.indentValue&&!isEmpty(this.charAt(1)))this.indentNext=this.indentValue;return yield*this.parseBlockStart()}*parseBlockStart(){const[ch0,ch1]=this.peek(2);if(!ch1&&!this.atEnd)return this.setNext("block-start");if((ch0==="-"||ch0==="?"||ch0===":")&&isEmpty(ch1)){const n2=(yield*this.pushCount(1))+(yield*this.pushSpaces(true));this.indentNext=this.indentValue+1;this.indentValue+=n2;return"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(true);const line=this.getLine();if(line===null)return this.setNext("doc");let n2=yield*this.pushIndicators();switch(line[n2]){case"#":yield*this.pushCount(line.length-n2);case void 0:yield*this.pushNewline();return yield*this.parseLineStart();case"{":case"[":yield*this.pushCount(1);this.flowKey=false;this.flowLevel=1;return"flow";case"}":case"]":yield*this.pushCount(1);return"doc";case"*":yield*this.pushUntil(isNotAnchorChar);return"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":n2+=yield*this.parseBlockScalarHeader();n2+=yield*this.pushSpaces(true);yield*this.pushCount(line.length-n2);yield*this.pushNewline();return yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let nl,sp;let indent=-1;do{nl=yield*this.pushNewline();if(nl>0){sp=yield*this.pushSpaces(false);this.indentValue=indent=sp}else{sp=0}sp+=yield*this.pushSpaces(true)}while(nl+sp>0);const line=this.getLine();if(line===null)return this.setNext("flow");if(indent!==-1&&indent<this.indentNext&&line[0]!=="#"||indent===0&&(line.startsWith("---")||line.startsWith("..."))&&isEmpty(line[3])){const atFlowEndMarker=indent===this.indentNext-1&&this.flowLevel===1&&(line[0]==="]"||line[0]==="}");if(!atFlowEndMarker){this.flowLevel=0;yield cst.FLOW_END;return yield*this.parseLineStart()}}let n2=0;while(line[n2]===","){n2+=yield*this.pushCount(1);n2+=yield*this.pushSpaces(true);this.flowKey=false}n2+=yield*this.pushIndicators();switch(line[n2]){case void 0:return"flow";case"#":yield*this.pushCount(line.length-n2);return"flow";case"{":case"[":yield*this.pushCount(1);this.flowKey=false;this.flowLevel+=1;return"flow";case"}":case"]":yield*this.pushCount(1);this.flowKey=true;this.flowLevel-=1;return this.flowLevel?"flow":"doc";case"*":yield*this.pushUntil(isNotAnchorChar);return"flow";case'"':case"'":this.flowKey=true;return yield*this.parseQuotedScalar();case":":{const next=this.charAt(1);if(this.flowKey||isEmpty(next)||next===","){this.flowKey=false;yield*this.pushCount(1);yield*this.pushSpaces(true);return"flow"}}default:this.flowKey=false;return yield*this.parsePlainScalar()}}*parseQuotedScalar(){const quote=this.charAt(0);let end=this.buffer.indexOf(quote,this.pos+1);if(quote==="'"){while(end!==-1&&this.buffer[end+1]==="'")end=this.buffer.indexOf("'",end+2)}else{while(end!==-1){let n2=0;while(this.buffer[end-1-n2]==="\\")n2+=1;if(n2%2===0)break;end=this.buffer.indexOf('"',end+1)}}const qb=this.buffer.substring(0,end);let nl=qb.indexOf("\n",this.pos);if(nl!==-1){while(nl!==-1){const cs=this.continueScalar(nl+1);if(cs===-1)break;nl=qb.indexOf("\n",cs)}if(nl!==-1){end=nl-(qb[nl-1]==="\r"?2:1)}}if(end===-1){if(!this.atEnd)return this.setNext("quoted-scalar");end=this.buffer.length}yield*this.pushToIndex(end+1,false);return this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1;this.blockScalarKeep=false;let i2=this.pos;while(true){const ch=this.buffer[++i2];if(ch==="+")this.blockScalarKeep=true;else if(ch>"0"&&ch<="9")this.blockScalarIndent=Number(ch)-1;else if(ch!=="-")break}return yield*this.pushUntil(ch=>isEmpty(ch)||ch==="#")}*parseBlockScalar(){let nl=this.pos-1;let indent=0;let ch;loop:for(let i3=this.pos;ch=this.buffer[i3];++i3){switch(ch){case" ":indent+=1;break;case"\n":nl=i3;indent=0;break;case"\r":{const next=this.buffer[i3+1];if(!next&&!this.atEnd)return this.setNext("block-scalar");if(next==="\n")break}default:break loop}}if(!ch&&!this.atEnd)return this.setNext("block-scalar");if(indent>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=indent;else{this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext)}do{const cs=this.continueScalar(nl+1);if(cs===-1)break;nl=this.buffer.indexOf("\n",cs)}while(nl!==-1);if(nl===-1){if(!this.atEnd)return this.setNext("block-scalar");nl=this.buffer.length}}let i2=nl+1;ch=this.buffer[i2];while(ch===" ")ch=this.buffer[++i2];if(ch===" "){while(ch===" "||ch===" "||ch==="\r"||ch==="\n")ch=this.buffer[++i2];nl=i2-1}else if(!this.blockScalarKeep){do{let i3=nl-1;let ch2=this.buffer[i3];if(ch2==="\r")ch2=this.buffer[--i3];const lastChar=i3;while(ch2===" ")ch2=this.buffer[--i3];if(ch2==="\n"&&i3>=this.pos&&i3+1+indent>lastChar)nl=i3;else break}while(true)}yield cst.SCALAR;yield*this.pushToIndex(nl+1,true);return yield*this.parseLineStart()}*parsePlainScalar(){const inFlow=this.flowLevel>0;let end=this.pos-1;let i2=this.pos-1;let ch;while(ch=this.buffer[++i2]){if(ch===":"){const next=this.buffer[i2+1];if(isEmpty(next)||inFlow&&flowIndicatorChars.has(next))break;end=i2}else if(isEmpty(ch)){let next=this.buffer[i2+1];if(ch==="\r"){if(next==="\n"){i2+=1;ch="\n";next=this.buffer[i2+1]}else end=i2}if(next==="#"||inFlow&&flowIndicatorChars.has(next))break;if(ch==="\n"){const cs=this.continueScalar(i2+1);if(cs===-1)break;i2=Math.max(i2,cs-2)}}else{if(inFlow&&flowIndicatorChars.has(ch))break;end=i2}}if(!ch&&!this.atEnd)return this.setNext("plain-scalar");yield cst.SCALAR;yield*this.pushToIndex(end+1,true);return inFlow?"flow":"doc"}*pushCount(n2){if(n2>0){yield this.buffer.substr(this.pos,n2);this.pos+=n2;return n2}return 0}*pushToIndex(i2,allowEmpty){const s3=this.buffer.slice(this.pos,i2);if(s3){yield s3;this.pos+=s3.length;return s3.length}else if(allowEmpty)yield"";return 0}*pushIndicators(){let n2=0;loop:while(true){switch(this.charAt(0)){case"!":n2+=yield*this.pushTag();n2+=yield*this.pushSpaces(true);continue loop;case"&":n2+=yield*this.pushUntil(isNotAnchorChar);n2+=yield*this.pushSpaces(true);continue loop;case"-":case"?":case":":{const inFlow=this.flowLevel>0;const ch1=this.charAt(1);if(isEmpty(ch1)||inFlow&&flowIndicatorChars.has(ch1)){if(!inFlow)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=false;n2+=yield*this.pushCount(1);n2+=yield*this.pushSpaces(true);continue loop}}}break loop}return n2}*pushTag(){if(this.charAt(1)==="<"){let i2=this.pos+2;let ch=this.buffer[i2];while(!isEmpty(ch)&&ch!==">")ch=this.buffer[++i2];return yield*this.pushToIndex(ch===">"?i2+1:i2,false)}else{let i2=this.pos+1;let ch=this.buffer[i2];while(ch){if(tagChars.has(ch))ch=this.buffer[++i2];else if(ch==="%"&&hexDigits.has(this.buffer[i2+1])&&hexDigits.has(this.buffer[i2+2])){ch=this.buffer[i2+=3]}else break}return yield*this.pushToIndex(i2,false)}}*pushNewline(){const ch=this.buffer[this.pos];if(ch==="\n")return yield*this.pushCount(1);else if(ch==="\r"&&this.charAt(1)==="\n")return yield*this.pushCount(2);else return 0}*pushSpaces(allowTabs){let i2=this.pos-1;let ch;do{ch=this.buffer[++i2]}while(ch===" "||allowTabs&&ch===" ");const n2=i2-this.pos;if(n2>0){yield this.buffer.substr(this.pos,n2);this.pos=i2}return n2}*pushUntil(test){let i2=this.pos;let ch=this.buffer[i2];while(!test(ch))ch=this.buffer[++i2];return yield*this.pushToIndex(i2,false)}};exports.Lexer=Lexer}});var require_line_counter=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/line-counter.js"(exports){"use strict";var LineCounter=class{constructor(){this.lineStarts=[];this.addNewLine=offset=>this.lineStarts.push(offset);this.linePos=offset=>{let low=0;let high=this.lineStarts.length;while(low<high){const mid=low+high>>1;if(this.lineStarts[mid]<offset)low=mid+1;else high=mid}if(this.lineStarts[low]===offset)return{line:low+1,col:1};if(low===0)return{line:0,col:offset};const start=this.lineStarts[low-1];return{line:low,col:offset-start+1}}}};exports.LineCounter=LineCounter}});var require_parser2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/parser.js"(exports){"use strict";var node_process=__require("process");var cst=require_cst();var lexer=require_lexer();function includesToken(list,type){for(let i2=0;i2<list.length;++i2)if(list[i2].type===type)return true;return false}function findNonEmptyIndex(list){for(let i2=0;i2<list.length;++i2){switch(list[i2].type){case"space":case"comment":case"newline":break;default:return i2}}return-1}function isFlowToken(token2){switch(token2?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return true;default:return false}}function getPrevProps(parent){switch(parent.type){case"document":return parent.start;case"block-map":{const it2=parent.items[parent.items.length-1];return it2.sep??it2.start}case"block-seq":return parent.items[parent.items.length-1].start;default:return[]}}function getFirstKeyStartProps(prev){if(prev.length===0)return[];let i2=prev.length;loop:while(--i2>=0){switch(prev[i2].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break loop}}while(prev[++i2]?.type==="space"){}return prev.splice(i2,prev.length)}function arrayPushArray(target2,source){if(source.length<1e5)Array.prototype.push.apply(target2,source);else for(let i2=0;i2<source.length;++i2)target2.push(source[i2])}function fixFlowSeqItems(fc){if(fc.start.type==="flow-seq-start"){for(const it2 of fc.items){if(it2.sep&&!it2.value&&!includesToken(it2.start,"explicit-key-ind")&&!includesToken(it2.sep,"map-value-ind")){if(it2.key)it2.value=it2.key;delete it2.key;if(isFlowToken(it2.value)){if(it2.value.end)arrayPushArray(it2.value.end,it2.sep);else it2.value.end=it2.sep}else arrayPushArray(it2.start,it2.sep);delete it2.sep}}}}var Parser2=class{constructor(onNewLine){this.atNewLine=true;this.atScalar=false;this.indent=0;this.offset=0;this.onKeyLine=false;this.stack=[];this.source="";this.type="";this.lexer=new lexer.Lexer;this.onNewLine=onNewLine}*parse(source,incomplete=false){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(const lexeme of this.lexer.lex(source,incomplete))yield*this.next(lexeme);if(!incomplete)yield*this.end()}*next(source){this.source=source;if(node_process.env.LOG_TOKENS)console.log("|",cst.prettyToken(source));if(this.atScalar){this.atScalar=false;yield*this.step();this.offset+=source.length;return}const type=cst.tokenType(source);if(!type){const message=`Not a YAML token: ${source}`;yield*this.pop({type:"error",offset:this.offset,message,source});this.offset+=source.length}else if(type==="scalar"){this.atNewLine=false;this.atScalar=true;this.type="scalar"}else{this.type=type;yield*this.step();switch(type){case"newline":this.atNewLine=true;this.indent=0;if(this.onNewLine)this.onNewLine(this.offset+source.length);break;case"space":if(this.atNewLine&&source[0]===" ")this.indent+=source.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=source.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=false}this.offset+=source.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){const st2={type:this.type,offset:this.offset,indent:this.indent,source:this.source};return st2}*step(){const top=this.peek(1);if(this.type==="doc-end"&&top?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!top)return yield*this.stream();switch(top.type){case"document":return yield*this.document(top);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(top);case"block-scalar":return yield*this.blockScalar(top);case"block-map":return yield*this.blockMap(top);case"block-seq":return yield*this.blockSequence(top);case"flow-collection":return yield*this.flowCollection(top);case"doc-end":return yield*this.documentEnd(top)}yield*this.pop()}peek(n2){return this.stack[this.stack.length-n2]}*pop(error51){const token2=error51??this.stack.pop();if(!token2){const message="Tried to pop an empty stack";yield{type:"error",offset:this.offset,source:"",message}}else if(this.stack.length===0){yield token2}else{const top=this.peek(1);if(token2.type==="block-scalar"){token2.indent="indent"in top?top.indent:0}else if(token2.type==="flow-collection"&&top.type==="document"){token2.indent=0}if(token2.type==="flow-collection")fixFlowSeqItems(token2);switch(top.type){case"document":top.value=token2;break;case"block-scalar":top.props.push(token2);break;case"block-map":{const it2=top.items[top.items.length-1];if(it2.value){top.items.push({start:[],key:token2,sep:[]});this.onKeyLine=true;return}else if(it2.sep){it2.value=token2}else{Object.assign(it2,{key:token2,sep:[]});this.onKeyLine=!it2.explicitKey;return}break}case"block-seq":{const it2=top.items[top.items.length-1];if(it2.value)top.items.push({start:[],value:token2});else it2.value=token2;break}case"flow-collection":{const it2=top.items[top.items.length-1];if(!it2||it2.value)top.items.push({start:[],key:token2,sep:[]});else if(it2.sep)it2.value=token2;else Object.assign(it2,{key:token2,sep:[]});return}default:yield*this.pop();yield*this.pop(token2)}if((top.type==="document"||top.type==="block-map"||top.type==="block-seq")&&(token2.type==="block-map"||token2.type==="block-seq")){const last=token2.items[token2.items.length-1];if(last&&!last.sep&&!last.value&&last.start.length>0&&findNonEmptyIndex(last.start)===-1&&(token2.indent===0||last.start.every(st2=>st2.type!=="comment"||st2.indent<token2.indent))){if(top.type==="document")top.end=last.start;else top.items.push({start:last.start});token2.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{const doc={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")doc.start.push(this.sourceToken);this.stack.push(doc);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(doc){if(doc.value)return yield*this.lineEnd(doc);switch(this.type){case"doc-start":{if(findNonEmptyIndex(doc.start)!==-1){yield*this.pop();yield*this.step()}else doc.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":doc.start.push(this.sourceToken);return}const bv=this.startBlockValue(doc);if(bv)this.stack.push(bv);else{yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}}*scalar(scalar){if(this.type==="map-value-ind"){const prev=getPrevProps(this.peek(2));const start=getFirstKeyStartProps(prev);let sep4;if(scalar.end){sep4=scalar.end;sep4.push(this.sourceToken);delete scalar.end}else sep4=[this.sourceToken];const map2={type:"block-map",offset:scalar.offset,indent:scalar.indent,items:[{start,key:scalar,sep:sep4}]};this.onKeyLine=true;this.stack[this.stack.length-1]=map2}else yield*this.lineEnd(scalar)}*blockScalar(scalar){switch(this.type){case"space":case"comment":case"newline":scalar.props.push(this.sourceToken);return;case"scalar":scalar.source=this.source;this.atNewLine=true;this.indent=0;if(this.onNewLine){let nl=this.source.indexOf("\n")+1;while(nl!==0){this.onNewLine(this.offset+nl);nl=this.source.indexOf("\n",nl)+1}}yield*this.pop();break;default:yield*this.pop();yield*this.step()}}*blockMap(map2){const it2=map2.items[map2.items.length-1];switch(this.type){case"newline":this.onKeyLine=false;if(it2.value){const end="end"in it2.value?it2.value.end:void 0;const last=Array.isArray(end)?end[end.length-1]:void 0;if(last?.type==="comment")end?.push(this.sourceToken);else map2.items.push({start:[this.sourceToken]})}else if(it2.sep){it2.sep.push(this.sourceToken)}else{it2.start.push(this.sourceToken)}return;case"space":case"comment":if(it2.value){map2.items.push({start:[this.sourceToken]})}else if(it2.sep){it2.sep.push(this.sourceToken)}else{if(this.atIndentedComment(it2.start,map2.indent)){const prev=map2.items[map2.items.length-2];const end=prev?.value?.end;if(Array.isArray(end)){arrayPushArray(end,it2.start);end.push(this.sourceToken);map2.items.pop();return}}it2.start.push(this.sourceToken)}return}if(this.indent>=map2.indent){const atMapIndent=!this.onKeyLine&&this.indent===map2.indent;const atNextItem=atMapIndent&&(it2.sep||it2.explicitKey)&&this.type!=="seq-item-ind";let start=[];if(atNextItem&&it2.sep&&!it2.value){const nl=[];for(let i2=0;i2<it2.sep.length;++i2){const st2=it2.sep[i2];switch(st2.type){case"newline":nl.push(i2);break;case"space":break;case"comment":if(st2.indent>map2.indent)nl.length=0;break;default:nl.length=0}}if(nl.length>=2)start=it2.sep.splice(nl[1])}switch(this.type){case"anchor":case"tag":if(atNextItem||it2.value){start.push(this.sourceToken);map2.items.push({start});this.onKeyLine=true}else if(it2.sep){it2.sep.push(this.sourceToken)}else{it2.start.push(this.sourceToken)}return;case"explicit-key-ind":if(!it2.sep&&!it2.explicitKey){it2.start.push(this.sourceToken);it2.explicitKey=true}else if(atNextItem||it2.value){start.push(this.sourceToken);map2.items.push({start,explicitKey:true})}else{this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:true}]})}this.onKeyLine=true;return;case"map-value-ind":if(it2.explicitKey){if(!it2.sep){if(includesToken(it2.start,"newline")){Object.assign(it2,{key:null,sep:[this.sourceToken]})}else{const start2=getFirstKeyStartProps(it2.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key:null,sep:[this.sourceToken]}]})}}else if(it2.value){map2.items.push({start:[],key:null,sep:[this.sourceToken]})}else if(includesToken(it2.sep,"map-value-ind")){this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]})}else if(isFlowToken(it2.key)&&!includesToken(it2.sep,"newline")){const start2=getFirstKeyStartProps(it2.start);const key=it2.key;const sep4=it2.sep;sep4.push(this.sourceToken);delete it2.key;delete it2.sep;this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key,sep:sep4}]})}else if(start.length>0){it2.sep=it2.sep.concat(start,this.sourceToken)}else{it2.sep.push(this.sourceToken)}}else{if(!it2.sep){Object.assign(it2,{key:null,sep:[this.sourceToken]})}else if(it2.value||atNextItem){map2.items.push({start,key:null,sep:[this.sourceToken]})}else if(includesToken(it2.sep,"map-value-ind")){this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]})}else{it2.sep.push(this.sourceToken)}}this.onKeyLine=true;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const fs2=this.flowScalar(this.type);if(atNextItem||it2.value){map2.items.push({start,key:fs2,sep:[]});this.onKeyLine=true}else if(it2.sep){this.stack.push(fs2)}else{Object.assign(it2,{key:fs2,sep:[]});this.onKeyLine=true}return}default:{const bv=this.startBlockValue(map2);if(bv){if(bv.type==="block-seq"){if(!it2.explicitKey&&it2.sep&&!includesToken(it2.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(atMapIndent){map2.items.push({start})}this.stack.push(bv);return}}}}yield*this.pop();yield*this.step()}*blockSequence(seq){const it2=seq.items[seq.items.length-1];switch(this.type){case"newline":if(it2.value){const end="end"in it2.value?it2.value.end:void 0;const last=Array.isArray(end)?end[end.length-1]:void 0;if(last?.type==="comment")end?.push(this.sourceToken);else seq.items.push({start:[this.sourceToken]})}else it2.start.push(this.sourceToken);return;case"space":case"comment":if(it2.value)seq.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(it2.start,seq.indent)){const prev=seq.items[seq.items.length-2];const end=prev?.value?.end;if(Array.isArray(end)){arrayPushArray(end,it2.start);end.push(this.sourceToken);seq.items.pop();return}}it2.start.push(this.sourceToken)}return;case"anchor":case"tag":if(it2.value||this.indent<=seq.indent)break;it2.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==seq.indent)break;if(it2.value||includesToken(it2.start,"seq-item-ind"))seq.items.push({start:[this.sourceToken]});else it2.start.push(this.sourceToken);return}if(this.indent>seq.indent){const bv=this.startBlockValue(seq);if(bv){this.stack.push(bv);return}}yield*this.pop();yield*this.step()}*flowCollection(fc){const it2=fc.items[fc.items.length-1];if(this.type==="flow-error-end"){let top;do{yield*this.pop();top=this.peek(1)}while(top?.type==="flow-collection")}else if(fc.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!it2||it2.sep)fc.items.push({start:[this.sourceToken]});else it2.start.push(this.sourceToken);return;case"map-value-ind":if(!it2||it2.value)fc.items.push({start:[],key:null,sep:[this.sourceToken]});else if(it2.sep)it2.sep.push(this.sourceToken);else Object.assign(it2,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!it2||it2.value)fc.items.push({start:[this.sourceToken]});else if(it2.sep)it2.sep.push(this.sourceToken);else it2.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const fs2=this.flowScalar(this.type);if(!it2||it2.value)fc.items.push({start:[],key:fs2,sep:[]});else if(it2.sep)this.stack.push(fs2);else Object.assign(it2,{key:fs2,sep:[]});return}case"flow-map-end":case"flow-seq-end":fc.end.push(this.sourceToken);return}const bv=this.startBlockValue(fc);if(bv)this.stack.push(bv);else{yield*this.pop();yield*this.step()}}else{const parent=this.peek(2);if(parent.type==="block-map"&&(this.type==="map-value-ind"&&parent.indent===fc.indent||this.type==="newline"&&!parent.items[parent.items.length-1].sep)){yield*this.pop();yield*this.step()}else if(this.type==="map-value-ind"&&parent.type!=="flow-collection"){const prev=getPrevProps(parent);const start=getFirstKeyStartProps(prev);fixFlowSeqItems(fc);const sep4=fc.end.splice(1,fc.end.length);sep4.push(this.sourceToken);const map2={type:"block-map",offset:fc.offset,indent:fc.indent,items:[{start,key:fc,sep:sep4}]};this.onKeyLine=true;this.stack[this.stack.length-1]=map2}else{yield*this.lineEnd(fc)}}}flowScalar(type){if(this.onNewLine){let nl=this.source.indexOf("\n")+1;while(nl!==0){this.onNewLine(this.offset+nl);nl=this.source.indexOf("\n",nl)+1}}return{type,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(parent){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=true;const prev=getPrevProps(parent);const start=getFirstKeyStartProps(prev);start.push(this.sourceToken);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,explicitKey:true}]}}case"map-value-ind":{this.onKeyLine=true;const prev=getPrevProps(parent);const start=getFirstKeyStartProps(prev);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(start,indent){if(this.type!=="comment")return false;if(this.indent<=indent)return false;return start.every(st2=>st2.type==="newline"||st2.type==="space")}*documentEnd(docEnd){if(this.type!=="doc-mode"){if(docEnd.end)docEnd.end.push(this.sourceToken);else docEnd.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(token2){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop();yield*this.step();break;case"newline":this.onKeyLine=false;case"space":case"comment":default:if(token2.end)token2.end.push(this.sourceToken);else token2.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}};exports.Parser=Parser2}});var require_public_api=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/public-api.js"(exports){"use strict";var composer=require_composer();var Document=require_Document();var errors=require_errors3();var log=require_log();var identity=require_identity();var lineCounter=require_line_counter();var parser=require_parser2();function parseOptions(options){const prettyErrors=options.prettyErrors!==false;const lineCounter$1=options.lineCounter||prettyErrors&&new lineCounter.LineCounter||null;return{lineCounter:lineCounter$1,prettyErrors}}function parseAllDocuments(source,options={}){const{lineCounter:lineCounter2,prettyErrors}=parseOptions(options);const parser$1=new parser.Parser(lineCounter2?.addNewLine);const composer$1=new composer.Composer(options);const docs=Array.from(composer$1.compose(parser$1.parse(source)));if(prettyErrors&&lineCounter2)for(const doc of docs){doc.errors.forEach(errors.prettifyError(source,lineCounter2));doc.warnings.forEach(errors.prettifyError(source,lineCounter2))}if(docs.length>0)return docs;return Object.assign([],{empty:true},composer$1.streamInfo())}function parseDocument(source,options={}){const{lineCounter:lineCounter2,prettyErrors}=parseOptions(options);const parser$1=new parser.Parser(lineCounter2?.addNewLine);const composer$1=new composer.Composer(options);let doc=null;for(const _doc of composer$1.compose(parser$1.parse(source),true,source.length)){if(!doc)doc=_doc;else if(doc.options.logLevel!=="silent"){doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}}if(prettyErrors&&lineCounter2){doc.errors.forEach(errors.prettifyError(source,lineCounter2));doc.warnings.forEach(errors.prettifyError(source,lineCounter2))}return doc}function parse3(src,reviver,options){let _reviver=void 0;if(typeof reviver==="function"){_reviver=reviver}else if(options===void 0&&reviver&&typeof reviver==="object"){options=reviver}const doc=parseDocument(src,options);if(!doc)return null;doc.warnings.forEach(warning=>log.warn(doc.options.logLevel,warning));if(doc.errors.length>0){if(doc.options.logLevel!=="silent")throw doc.errors[0];else doc.errors=[]}return doc.toJS(Object.assign({reviver:_reviver},options))}function stringify(value,replacer,options){let _replacer=null;if(typeof replacer==="function"||Array.isArray(replacer)){_replacer=replacer}else if(options===void 0&&replacer){options=replacer}if(typeof options==="string")options=options.length;if(typeof options==="number"){const indent=Math.round(options);options=indent<1?void 0:indent>8?{indent:8}:{indent}}if(value===void 0){const{keepUndefined}=options??replacer??{};if(!keepUndefined)return void 0}if(identity.isDocument(value)&&!_replacer)return value.toString(options);return new Document.Document(value,_replacer,options).toString(options)}exports.parse=parse3;exports.parseAllDocuments=parseAllDocuments;exports.parseDocument=parseDocument;exports.stringify=stringify}});var require_dist=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js"(exports){"use strict";var composer=require_composer();var Document=require_Document();var Schema=require_Schema();var errors=require_errors3();var Alias=require_Alias();var identity=require_identity();var Pair=require_Pair();var Scalar=require_Scalar();var YAMLMap=require_YAMLMap();var YAMLSeq=require_YAMLSeq();var cst=require_cst();var lexer=require_lexer();var lineCounter=require_line_counter();var parser=require_parser2();var publicApi=require_public_api();var visit=require_visit();exports.Composer=composer.Composer;exports.Document=Document.Document;exports.Schema=Schema.Schema;exports.YAMLError=errors.YAMLError;exports.YAMLParseError=errors.YAMLParseError;exports.YAMLWarning=errors.YAMLWarning;exports.Alias=Alias.Alias;exports.isAlias=identity.isAlias;exports.isCollection=identity.isCollection;exports.isDocument=identity.isDocument;exports.isMap=identity.isMap;exports.isNode=identity.isNode;exports.isPair=identity.isPair;exports.isScalar=identity.isScalar;exports.isSeq=identity.isSeq;exports.Pair=Pair.Pair;exports.Scalar=Scalar.Scalar;exports.YAMLMap=YAMLMap.YAMLMap;exports.YAMLSeq=YAMLSeq.YAMLSeq;exports.CST=cst;exports.Lexer=lexer.Lexer;exports.LineCounter=lineCounter.LineCounter;exports.Parser=parser.Parser;exports.parse=publicApi.parse;exports.parseAllDocuments=publicApi.parseAllDocuments;exports.parseDocument=publicApi.parseDocument;exports.stringify=publicApi.stringify;exports.visit=visit.visit;exports.visitAsync=visit.visitAsync}});function peerLabel(card){return(card.role?`${card.name}/${card.role}`:card.name).replace(/[\p{Cc}\p{Zl}\p{Zp}[\]"]+/gu," ")}function shownPeerName(name2,id2){return name2.trim()?peerLabel({name:name2}):id2}var LINE_BREAK;var init_peer_label=__esm({"../../packages/core/dist/peer-label.js"(){"use strict";LINE_BREAK=/\r\n?|[\n\v\f\u0085\u2028\u2029]/}});function candidate(p2){return{id:p2.card.id,name:p2.card.name,role:p2.card.role,status:p2.status,ts:p2.ts}}function resolvePeer(roster,target2,opts={}){const peers=opts.selfId?roster.filter(p2=>p2.card.id!==opts.selfId):roster;const byId=peers.find(p2=>p2.card.id===target2);if(byId)return byId;const want=target2.trim().toLowerCase();if(!want)return void 0;const matches=peers.filter(p2=>p2.card.name.toLowerCase()===want);if(matches.length===0){const labelled=peers.find(p2=>p2.card.role&&peerLabel(p2.card).trim().toLowerCase()===want);if(labelled)throw new Error(`"${target2}" is the roster label of ${labelled.card.name} (role ${labelled.card.role}), not an address: use the name "${labelled.card.name}" or its instance id`);return void 0}const live=matches.filter(p2=>p2.status!=="offline");const pool=live.length>0?live:matches;if(pool.length===1)return pool[0];throw new AmbiguousPeerError(target2,pool.map(candidate))}function sharedNameIds(roster,opts={}){const peers=opts.selfId?roster.filter(p2=>p2.card.id!==opts.selfId):roster;const groups=new Map;for(const p2 of peers){const key=p2.card.name.trim().toLowerCase();const group=groups.get(key);if(group)group.push(p2);else groups.set(key,[p2])}const ids=new Set;for(const group of groups.values()){const live=group.filter(p2=>p2.status!=="offline");const pool=live.length>0?live:group;if(pool.length>1)for(const p2 of pool)ids.add(p2.card.id)}return ids}function assertValidName(name2){if(name2.length===0||name2!==name2.trim())throw new Error(`invalid name ${JSON.stringify(name2)}: must be non-empty with no surrounding whitespace`);if(name2.length>MAX_NAME_LENGTH)throw new Error(`invalid name ${JSON.stringify(name2.slice(0,32))}\u2026: ${name2.length} characters exceeds the ${MAX_NAME_LENGTH}-character limit (the CONNECT line budget that carries it)`);if(LINE_BREAK.test(name2))throw new Error(`invalid name ${JSON.stringify(name2)}: must be a single line`);if(name2.includes("/"))throw new Error(`invalid name ${JSON.stringify(name2)}: "/" is reserved (the owner/name separator)`);if(name2.includes("\\"))throw new Error(`invalid name ${JSON.stringify(name2)}: "\\" is reserved (a Windows path separator)`);if(!isWellFormedUnicode(name2))throw new Error(`invalid name ${JSON.stringify(name2)}: contains an unpaired UTF-16 surrogate. Such a name cannot survive UTF-8 encoding \u2014 it is replaced with U+FFFD \u2014 so distinct names would silently become one identity.`)}var AmbiguousPeerError,MAX_NAME_LENGTH;var init_resolve=__esm({"../../packages/core/dist/resolve.js"(){"use strict";init_peer_label();init_peer_label();init_canonical_json();init_peer_label();AmbiguousPeerError=class extends Error{target;candidates;constructor(target2,candidates){super(`"${target2}" is ambiguous - ${candidates.length} peers share that name: `+candidates.map(c3=>`${shownPeerName(c3.name,c3.id)} (${c3.id}, ${c3.status})`).join("; ")+`. Re-send to the exact instance id.`);this.target=target2;this.candidates=candidates;this.name="AmbiguousPeerError"}};MAX_NAME_LENGTH=128}});function utf16Problem(text3){return text3.startsWith("\uFFFD\uFFFD")||text3.includes("\0")?"it is saved as UTF-16, and Cotal reads only UTF-8":void 0}var init_text_encoding=__esm({"../../packages/core/dist/text-encoding.js"(){"use strict"}});function parsePersonaEndpoints(raw,where){if(raw===void 0||raw===null)return void 0;const fail2=detail=>{throw new Error(`${where}: "endpoints" ${detail}`)};if(!Array.isArray(raw))fail2("must be a list of { endpoint, commands, instanceId? } entries");const merged=new Map;let total=0;for(const item of raw){if(item===null||typeof item!=="object"||Array.isArray(item))fail2("entries must be mappings of endpoint, commands and an optional instanceId");const proto=Object.getPrototypeOf(item);if(proto!==Object.prototype&&proto!==null)fail2("entries must be plain mappings");const rec=item;const extra=Reflect.ownKeys(rec).find(k2=>typeof k2!=="string"||!ENTRY_KEYS.includes(k2));if(extra!==void 0)fail2(`entry has unknown key ${String(extra)}; an entry takes endpoint, commands and instanceId`);const endpoint=rec.endpoint;if(typeof endpoint!=="string")fail2("entry needs an endpoint name");try{endpointToken(endpoint)}catch(e3){fail2(`entry: ${e3.message}`)}if(!endpoint.includes("."))fail2(`entry names "${endpoint}", a single-label endpoint; those are the reference endpoints, reached through the baseline and the spawn, run and admin capabilities. A persona hands on a reverse-DNS endpoint such as com.example.orders`);let instanceId;if(rec.instanceId!==void 0){if(typeof rec.instanceId!=="string")fail2(`entry for ${endpoint}: instanceId must be a string`);try{instanceId=assertLifecycleToken(rec.instanceId,"instanceId")}catch(e3){fail2(`entry for ${endpoint}: ${e3.message}`)}}const commands=rec.commands;if(!Array.isArray(commands)||commands.length===0)fail2(`entry for ${endpoint} needs a non-empty commands list`);const key=`${endpoint}\0${instanceId??""}`;const into=merged.get(key)??{endpoint,commands:[],...instanceId!==void 0?{instanceId}:{}};for(const c3 of commands){if(typeof c3!=="string")fail2(`entry for ${endpoint}: commands must be strings`);try{assertCommandToken(c3)}catch(e3){fail2(`entry for ${endpoint}: ${e3.message}`)}if(RESERVED_COMMANDS.includes(c3))fail2(`entry for ${endpoint} names the reserved command "${c3}"; describe is granted on every endpoint and cancel is not handed on`);if(!into.commands.includes(c3)){into.commands.push(c3);total++}}merged.set(key,into)}if(total>PERSONA_ENDPOINT_MAX_COMMANDS)fail2(`names ${total} commands; a persona may name at most ${PERSONA_ENDPOINT_MAX_COMMANDS}`);return[...merged.values()].map(e3=>({...e3,commands:[...e3.commands].sort()})).sort((a3,b3)=>a3.endpoint<b3.endpoint?-1:a3.endpoint>b3.endpoint?1:(a3.instanceId??"")<(b3.instanceId??"")?-1:1)}var PERSONA_ENDPOINT_MAX_COMMANDS,ENTRY_KEYS;var init_persona_endpoints=__esm({"../../packages/core/dist/persona-endpoints.js"(){"use strict";init_endpoint_subjects();PERSONA_ENDPOINT_MAX_COMMANDS=256;ENTRY_KEYS=["endpoint","commands","instanceId"]}});import{accessSync,constants as constants2,lstatSync as lstatSync3,mkdirSync as mkdirSync4,readdirSync,readFileSync as readFileSync2,readlinkSync,realpathSync,statSync as statSync2}from"node:fs";function parseFrontmatter(src,path4){let doc;try{doc=(0,import_yaml.parse)(src)}catch(e3){throw new Error(`agent file ${path4}: invalid YAML frontmatter; ${e3.message}`)}if(doc===null||doc===void 0)return{};if(typeof doc!=="object"||Array.isArray(doc))throw new Error(`agent file ${path4}: frontmatter must be a YAML mapping (key: value pairs)`);return doc}function assertLaunchSelectors(def,where){for(const k2 of["model","variant"]){const v3=def[k2];if(v3!==void 0&&!v3.trim())throw new Error(`${where}: "${k2}" must not be empty`)}}function assertValidKind(kind,where){if(kind==="agent"||kind==="endpoint")return kind;throw new Error(`${where?`${where}: `:`invalid kind ${JSON.stringify(kind)}: `}"kind" must be "agent" or "endpoint"`)}function loadAgentFile(path4,options){return parseAgentFileSource(readFileSync2(path4,"utf8"),path4,options)}function parseAgentFileSource(src,path4,options){const encoding=utf16Problem(src);if(encoding)throw new Error(`agent file ${path4}: ${encoding}; save it as UTF-8`);const m2=AGENT_FILE_FENCE.exec(src.replace(/^\uFEFF/,"").replace(/\r\n/g,"\n"));if(!m2)throw new Error(`agent file ${path4}: missing "---" frontmatter block`);const fm=parseFrontmatter(m2[1],path4);const persona=m2[2].trim();const yamlType=v3=>v3===null?"null":Array.isArray(v3)?"array":typeof v3==="object"?"mapping":typeof v3;const str2=k2=>{const v3=fm[k2];if(v3===void 0)return void 0;if(typeof v3!=="string")throw new Error(`agent file ${path4}: "${k2}" must be a string; got ${yamlType(v3)}`);return v3};const list=k2=>{const v3=fm[k2];if(v3===void 0)return void 0;if(!Array.isArray(v3))throw new Error(`agent file ${path4}: "${k2}" must be an array of strings; got ${yamlType(v3)}`);return v3.map((x2,index2)=>{if(typeof x2!=="string")throw new Error(`agent file ${path4}: "${k2}" must be an array of strings; item ${index2} got ${yamlType(x2)}`);return x2})};const name2=str2("name");if(!name2)throw new Error(`agent file ${path4}: "name" is required`);assertValidName(name2);const model=str2("model");const variant=str2("variant");assertLaunchSelectors({model,variant},`agent file ${path4}`);const rawKind=str2("kind");const kind=rawKind!==void 0?assertValidKind(rawKind,`agent file ${path4}`):void 0;for(const old of RENAMED_KEYS)if(old in fm)throw new Error(`agent file ${path4}: "${old}" was renamed - use "subscribe"/"allowSubscribe" (read) and "allowPublish" (post)`);for(const key of["cwd","worktree"])if(key in fm)throw new Error(`agent file ${path4}: "${key}" is not supported in frontmatter; the working directory comes from the spawn request (use --cwd)`);const subscribe=list("subscribe");const allowSubscribe=list("allowSubscribe");const allowPublish=list("allowPublish");const quiet=list("quiet");const muted=list("muted");for(const ch of[...subscribe??[],...allowSubscribe??[],...allowPublish??[]])try{assertValidChannel(ch)}catch(e3){throw new Error(`agent file ${path4}: ${e3.message}`)}let effAllow;try{effAllow=resolveReadAcl(subscribe??[],allowSubscribe)}catch(e3){throw new Error(`agent file ${path4}: ${e3.message}`)}const both=(quiet??[]).filter(c3=>(muted??[]).includes(c3));if(both.length)throw new Error(`agent file ${path4}: channel(s) [${both.join(", ")}] are in both quiet and muted - pick one`);for(const[field,chans]of[["quiet",quiet],["muted",muted]])for(const ch of chans??[]){try{assertValidChannel(ch)}catch(e3){throw new Error(`agent file ${path4}: ${e3.message}`)}if(!isConcreteChannel(ch))throw new Error(`agent file ${path4}: ${field} channel "${ch}" must be a concrete channel (no wildcard)`);if(!channelInAllow(effAllow,ch))throw new Error(`agent file ${path4}: ${field} channel "${ch}" is not within your read ACL / allowSubscribe [${effAllow.join(", ")}]`)}if(fm.eventPayloads!==void 0&&typeof fm.eventPayloads!=="boolean")throw new Error(`agent file ${path4}: "eventPayloads" must be a boolean`);const launchOptionsRaw=fm["launchOptions"];let launchOptions;if(launchOptionsRaw!==void 0){if(launchOptionsRaw===null||typeof launchOptionsRaw!=="object"||Array.isArray(launchOptionsRaw))throw new Error(`agent file ${path4}: "launchOptions" must be a mapping of key: value pairs`);launchOptions=launchOptionsRaw}const role=str2("role");if(role!==void 0&&!options?.deferRoleValidation){try{assertValidRole(role)}catch{throw new Error(`agent file ${path4}: "role" must be a single token using letters, digits, underscores or hyphens`)}}const meta3={};for(const[k2,v3]of Object.entries(fm))if(!MODELED_KEYS.has(k2)&&v3!==null&&typeof v3!=="object")meta3[k2]=String(v3);return{name:name2,role,kind,description:str2("description"),tags:list("tags"),agent:str2("agent"),subscribe,allowSubscribe,allowPublish,quiet,muted,model,variant,launchOptions,eventPayloads:fm.eventPayloads,capabilities:list("capabilities"),endpoints:parsePersonaEndpoints(fm["endpoints"],`agent file ${path4}`),owner:str2("owner"),meta:Object.keys(meta3).length?meta3:void 0,persona:persona||void 0}}var import_yaml,AGENT_FILE_FENCE,MODELED_KEYS,RENAMED_KEYS;var init_agent_file=__esm({"../../packages/core/dist/agent-file.js"(){"use strict";import_yaml=__toESM(require_dist(),1);init_resolve();init_secret_fs();init_text_encoding();init_subjects();init_endpoint_subjects();init_persona_endpoints();AGENT_FILE_FENCE=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;MODELED_KEYS=new Set(["name","role","kind","description","tags","subscribe","allowSubscribe","allowPublish","quiet","muted","agent","model","variant","launchOptions","eventPayloads","capabilities","endpoints","owner"]);RENAMED_KEYS=["channels","publish"]}});function nextHeartbeat(phaseMs,intervalMs,lastBeat,nowMs){const beat=Math.max(lastBeat+1,Math.ceil((nowMs-phaseMs)/intervalMs));return{beat,delayMs:Math.max(0,phaseMs+beat*intervalMs-nowMs)}}var init_presence_heartbeat=__esm({"../../packages/core/dist/presence-heartbeat.js"(){"use strict"}});async function openDeliveryRegistry(nc,space2){return new import_kv5.Kvm(nc).open(deliveryBucket(space2))}var import_kv5,import_transport_node11;var init_lease=__esm({"../../packages/core/dist/lease.js"(){"use strict";init_connection_cleanup();import_kv5=__toESM(require_mod6(),1);import_transport_node11=__toESM(require_transport_node(),1);init_endpoint();init_subjects();init_identity();init_streams()}});import{randomUUID as randomUUID4}from"node:crypto";var EndpointDeliveryLease;var init_endpoint_delivery_lease=__esm({"../../packages/core/dist/endpoint-delivery-lease.js"(){"use strict";init_lease();init_subjects();EndpointDeliveryLease=class{deps;deliveryKv;leaseIncarnation=randomUUID4();leaseAcquiredAt=new Map;leaseWatchIntent;leaseWatchIter;leaseWatchDeletes=new Set;leaseWatchBinds=new Set;constructor(deps){this.deps=deps}get card(){return this.deps.card()}get space(){return this.deps.space()}get nc(){return this.deps.connection()}get presenceEpoch(){return this.deps.epoch()}notLiveMsg(){return this.deps.notLiveMsg()}emitRecoverable(error51){this.deps.recoverable(error51)}emit(event,error51){return this.deps.emit(event,error51)}get hasWatchIntent(){return this.leaseWatchIntent!==void 0}resetConnection(){this.deliveryKv=void 0}async deliveryRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.deliveryKv??=await openDeliveryRegistry(this.nc,this.space);return this.deliveryKv}encodeLease(shardIndex,ready,acquiredAt=this.leaseAcquiredAt.get(shardIndex)){return new TextEncoder().encode(JSON.stringify({holder:this.card.id,incarnation:this.leaseIncarnation,acquiredAt,since:Date.now(),ready}))}ownsDeliveryLease(info){return info.holder===this.card.id&&info.incarnation!==void 0&&info.incarnation===this.leaseIncarnation}async acquireDeliveryLease(shardIndex){const acquiredAt=Date.now();const revision=await(await this.deliveryRegistry()).create(leaseKey(shardIndex),this.encodeLease(shardIndex,false,acquiredAt));this.leaseAcquiredAt.set(shardIndex,acquiredAt);return revision}async markDeliveryLeaseReady(shardIndex,revision){return(await this.deliveryRegistry()).update(leaseKey(shardIndex),this.encodeLease(shardIndex,true),revision)}async markDeliveryLeaseNotReady(shardIndex,revision){return(await this.deliveryRegistry()).update(leaseKey(shardIndex),this.encodeLease(shardIndex,false),revision)}async renewDeliveryLease(shardIndex,revision){return(await this.deliveryRegistry()).update(leaseKey(shardIndex),this.encodeLease(shardIndex,true),revision)}async releaseDeliveryLease(shardIndex,revision){if(revision===void 0)return;await(await this.deliveryRegistry()).delete(leaseKey(shardIndex),{previousSeq:revision})}async readDeliveryLease(shardIndex){return(await this.readDeliveryLeaseEntry(shardIndex))?.info}async watchDeliveryLease(shardIndex,onEvent){this.leaseWatchIntent={shardIndex,onEvent};await this.bindDeliveryLeaseWatch();return()=>{if(this.leaseWatchIntent?.onEvent!==onEvent)return;this.leaseWatchIntent=void 0;this.stopDeliveryLeaseWatch()}}stopDeliveryLeaseWatch(){if(this.leaseWatchIter)this.retireDeliveryLeaseWatch(this.leaseWatchIter);this.leaseWatchIter=void 0}retireDeliveryLeaseWatch(iter){try{iter.stop()}catch{}if(!this.nc||this.nc.isClosed())return;const deleting=this.deps.deleteWatchConsumer(iter).catch(e3=>this.emitRecoverable(new Error(`a retired delivery lease watch consumer was not deleted (${e3.message}); the broker reaps it at its inactive threshold`)));this.leaseWatchDeletes.add(deleting);void deleting.then(()=>this.leaseWatchDeletes.delete(deleting))}async settleDeliveryLeaseWatches(){await Promise.allSettled(this.leaseWatchBinds);await Promise.all(this.leaseWatchDeletes)}bindDeliveryLeaseWatch(){const binding=this.bindDeliveryLeaseWatchOnce();const settled=()=>{this.leaseWatchBinds.delete(binding)};this.leaseWatchBinds.add(binding);void binding.then(settled,settled);return binding}async bindDeliveryLeaseWatchOnce(){const intent=this.leaseWatchIntent;const epoch=this.presenceEpoch;const iter=await(await this.deliveryRegistry()).watch({key:leaseKey(intent.shardIndex)});if(this.leaseWatchIntent!==intent||epoch!==this.presenceEpoch){this.retireDeliveryLeaseWatch(iter);return}this.leaseWatchIter=iter;void(async()=>{for await(const e3 of iter){if(this.leaseWatchIter!==iter)break;if(e3.operation==="DEL"||e3.operation==="PURGE"){intent.onEvent(void 0);continue}try{intent.onEvent(e3.json())}catch{intent.onEvent(void 0)}}})().catch(e3=>this.emit("error",e3))}async deliveryLeaseHolder(shardIndex){try{return(await this.readDeliveryLeaseEntry(shardIndex))?.info.holder}catch{return void 0}}async readDeliveryLeaseEntry(shardIndex){const e3=await(await this.deliveryRegistry()).get(leaseKey(shardIndex));if(!e3||e3.operation==="DEL"||e3.operation==="PURGE")return void 0;try{return{info:e3.json(),revision:e3.revision}}catch(err3){throw new Error(`delivery lease row "${leaseKey(shardIndex)}" exists but does not parse as a lease record (${err3.message}) - it is unreadable, not absent`)}}}}});function anycastRecordKey(epoch,seq){return`r.${epoch.replace(/[^0-9A-Za-z]/g,"")}.${seq}`}function isAnycastSeq(seq){return typeof seq==="number"&&Number.isSafeInteger(seq)&&seq>0}function holderOf(t2){return{id:t2.id,name:t2.name}}function shownHolderName(name2,id2){const ident=id2.trim()?id2:"(unnamed)";return name2.trim()?name2:ident}function holderText(h3){const ident=h3.id.trim()?h3.id:"(unnamed)";return h3.name.trim()?`${h3.name} (${ident})`:ident}function noticeEvent(row,notice){const{taker,previous,role,seq}=notice;const text3=notice.event==="taken"?`${holderText(taker)} took your @${role} request (seq ${seq}).`:`${holderText(previous)} did not confirm your @${role} request (seq ${seq}) before its ack wait ran out, and ${holderText(taker)} took it. ${shownHolderName(previous.name,previous.id)} may already have started it.`;return{key:`anycast.${anycastRecordKey(row.epoch,row.seq).slice(2)}.${row.rev}`,text:text3,notice}}function decideTake(row,stored,t2){const taker={...holderOf(t2.holder),count:t2.count,at:t2.now};if(!row){const next={v:1,epoch:t2.epoch,seq:t2.seq,id:stored.id,role:stored.role,sender:stored.sender,rev:1,state:"taken",taker,outbox:[]};next.outbox.push(noticeEvent(next,{seq:t2.seq,role:stored.role,event:"taken",taker:holderOf(taker)}));return{reply:{ok:true},next}}if(row.state==="cancelled")return{reply:{ok:false,code:"cancelled",error:`request seq ${t2.seq} was cancelled by its sender`}};const current=row.taker;if(current.id===t2.holder.id&¤t.count===t2.count)return{reply:{ok:true}};if(t2.count>current.count){const moved=current.id!==t2.holder.id;const next={...row,rev:row.rev+1,taker,previous:moved?{...holderOf(current),count:current.count}:row.previous,outbox:[...row.outbox]};if(moved)next.outbox.push(noticeEvent(next,{seq:t2.seq,role:row.role,event:"redelivered",taker:holderOf(taker),previous:holderOf(current)}));return{reply:{ok:true},next}}return{reply:{ok:false,code:"taken",error:`request seq ${t2.seq} was taken by ${holderText(current)} on delivery ${current.count}`}}}function statusFor(row,stored,q2){if(row){if(row.sender!==q2.caller||q2.id!==void 0&&row.id!==q2.id)return{state:"unknown",seq:q2.seq};if(row.state==="cancelled")return{state:"cancelled",seq:q2.seq,role:row.role,removal:row.removal??"pending"};const taker=row.taker;return{state:"taken",seq:q2.seq,role:row.role,taker:holderOf(taker),at:taker.at,...row.previous?{previous:holderOf(row.previous)}:{}}}if(!stored||stored.sender!==q2.caller||q2.id!==void 0&&stored.id!==q2.id)return{state:"unknown",seq:q2.seq};return{state:"waiting",seq:q2.seq,role:stored.role}}function decideCancel(row,stored,q2){const status2=statusFor(row,stored,q2);if(status2.state!=="waiting")return{status:status2};const s3=stored;return{status:{state:"cancelled",seq:q2.seq,role:s3.role,removal:"pending"},next:{v:1,epoch:q2.epoch,seq:q2.seq,id:s3.id,role:s3.role,sender:s3.sender,rev:1,state:"cancelled",removal:"pending",outbox:[]}}}function storedRequest(subject,data){const parsed=parseSubject(subject);if(!parsed||parsed.kind!=="svc")return void 0;let id2;try{id2=JSON.parse(new TextDecoder().decode(data)).id}catch{return void 0}if(typeof id2!=="string")return void 0;return{role:parsed.rest,sender:parsed.sender,id:id2}}function isNoMessageFound(e3){return e3?.code===10043||/no message found/i.test(String(e3?.message??""))}function readRow(e3){if(!e3||e3.operation!=="PUT")return void 0;const row=e3.json();if(row?.v!==1||typeof row.epoch!=="string"||!isAnycastSeq(row.seq)||!Array.isArray(row.outbox))throw new Error(`anycast record ${e3.key} is not a version-1 record`);return row}var ANYCAST_RECORD_RETENTION_MS,ANYCAST_STATUS_OP,ANYCAST_CANCEL_OP,ANYCAST_TAKES_OP,ANYCAST_RECORDS_CREDENTIAL_OUTDATED,ANYCAST_NOTICE_KEY,encoder,AnycastRequestAuthority;var init_anycast_requests=__esm({"../../packages/core/dist/anycast-requests.js"(){"use strict";init_endpoint_records();init_subjects();ANYCAST_RECORD_RETENTION_MS=24*60*60*1e3;ANYCAST_STATUS_OP="anycastStatus";ANYCAST_CANCEL_OP="anycastCancel";ANYCAST_TAKES_OP="anycastTakes";ANYCAST_RECORDS_CREDENTIAL_OUTDATED="this delivery daemon's credential was minted before anycast request records existed, so it records no takes and answers no status or cancel; restart the daemon on a credential minted at this version (`cotal up` mints one)";ANYCAST_NOTICE_KEY="cotalAnycastNotice";encoder=new TextEncoder;AnycastRequestAuthority=class{deps;flushing=new Map;constructor(deps){this.deps=deps}now(){return this.deps.now?.()??Date.now()}async queued(seq){for(let attempt=0;attempt<3;attempt++){const before=(await this.deps.jsm.streams.info(this.deps.stream)).created;const sm=await this.deps.jsm.streams.getMessage(this.deps.stream,{seq});const after=(await this.deps.jsm.streams.info(this.deps.stream)).created;if(before!==after)continue;return{epoch:before,stored:sm?storedRequest(sm.subject,sm.data):void 0}}throw new Error(`the ${this.deps.stream} stream was recreated during the read; retry`)}async take(role,req){for(let attempt=0;attempt<5;attempt++){const{epoch,stored}=await this.queued(req.seq);if(req.epoch!==epoch)return{ok:false,code:"mismatch",error:`the copy of seq ${req.seq} came from a ${this.deps.stream} stream that has since been recreated`};if(!stored){const row=readRow(await this.deps.kv.get(anycastRecordKey(epoch,req.seq)));if(row?.state==="cancelled"&&row.id===req.id)return{ok:false,code:"cancelled",error:`request seq ${req.seq} was cancelled by its sender`};return{ok:false,code:"gone",error:`request seq ${req.seq} is no longer on the queue`}}if(stored.role!==role||stored.id!==req.id)return{ok:false,code:"mismatch",error:`seq ${req.seq} on the queue is not the @${role} request ${req.id}`};const key=anycastRecordKey(epoch,req.seq);const entry=await this.deps.kv.get(key);const{reply,next}=decideTake(readRow(entry),stored,{epoch,seq:req.seq,holder:req.from,count:req.count,now:this.now()});if(!next)return reply;if(!this.deps.mayAct())return{ok:false,code:"busy",error:"the delivery daemon stopped serving while the take was in flight; retry"};if(!await this.write(key,next,entry))continue;if(next.outbox.length)this.flushSoon(key);return reply}return{ok:false,code:"busy",error:`request seq ${req.seq} changed under five takes in a row; retry`}}async status(caller,q2){const{epoch,stored}=await this.queued(q2.seq);const row=readRow(await this.deps.kv.get(anycastRecordKey(epoch,q2.seq)));return statusFor(row,stored,{...q2,caller})}async cancel(caller,q2){for(let attempt=0;attempt<5;attempt++){const{epoch,stored}=await this.queued(q2.seq);const key=anycastRecordKey(epoch,q2.seq);const entry=await this.deps.kv.get(key);const row=readRow(entry);const{status:status2,next}=decideCancel(row,stored,{...q2,epoch,caller,now:this.now()});if(!next){if(status2.state==="cancelled"&&status2.removal==="pending")return this.remove(key);return status2}if(!this.deps.mayAct())throw new Error("the delivery daemon stopped serving while the cancel was in flight; retry");if(!await this.write(key,next,entry))continue;return this.remove(key)}throw new Error(`request seq ${q2.seq} changed under five cancels in a row; retry`)}async remove(key){let removal;for(let attempt=0;attempt<5;attempt++){const entry=await this.deps.kv.get(key);const row=readRow(entry);if(!row||row.state!=="cancelled")throw new Error(`anycast record ${key} is not a cancelled request`);if(row.removal!=="pending")return{state:"cancelled",seq:row.seq,role:row.role,removal:row.removal??"pending"};if(removal===void 0){const epoch=(await this.deps.jsm.streams.info(this.deps.stream)).created;if(epoch!==row.epoch)removal="already-gone";else{if(!this.deps.mayAct())return{state:"cancelled",seq:row.seq,role:row.role,removal:"pending"};try{await this.deps.jsm.streams.deleteMessage(this.deps.stream,row.seq,false);removal="deleted"}catch(e3){if(!isNoMessageFound(e3))throw e3;removal="already-gone"}}}if(await this.write(key,{...row,removal},entry))return{state:"cancelled",seq:row.seq,role:row.role,removal}}throw new Error(`anycast record ${key} changed under five writes in a row; retry`)}async write(key,row,entry){try{const bytes=encoder.encode(JSON.stringify(row));if(entry&&entry.operation==="PUT")await this.deps.kv.update(key,bytes,entry.revision);else await this.deps.kv.create(key,bytes);return true}catch(e3){if(isCasLoss(e3))return false;throw e3}}flushSoon(key){void this.flush(key).catch(e3=>this.deps.onError(e3))}flush(key){const prior=this.flushing.get(key)??Promise.resolve();const run=prior.then(async()=>{for(let attempt=0;attempt<16;attempt++){if(!this.deps.mayAct())return;const entry=await this.deps.kv.get(key);const row=readRow(entry);const event=row?.outbox[0];if(!row||!event)return;await this.deps.send(row.sender,event);await this.write(key,{...row,outbox:row.outbox.filter(e3=>e3.key!==event.key)},entry)}});const settled=run.finally(()=>{if(this.flushing.get(key)===settled)this.flushing.delete(key)});this.flushing.set(key,settled);return settled}async sweep(){if((await this.deps.kv.status()).values===0)return;const keys=[];for await(const k2 of await this.deps.kv.keys("r.>"))keys.push(k2);for(const key of keys){if(!this.deps.mayAct())return;try{await this.maintain(key)}catch(e3){this.deps.onError(e3)}}}async maintain(key){let row=readRow(await this.deps.kv.get(key));if(!row)return;if(row.outbox.length)await this.flush(key);if(row.state==="cancelled"&&row.removal==="pending")await this.remove(key);const entry=await this.deps.kv.get(key);row=readRow(entry);if(!row||!this.deps.mayAct())return;if(row.leftAt===void 0){const{epoch,stored}=await this.queued(row.seq);if(epoch===row.epoch&&stored?.id===row.id)return;await this.write(key,{...row,leftAt:this.now()},entry)}else if(this.now()-row.leftAt>ANYCAST_RECORD_RETENTION_MS&&!row.outbox.length){try{await this.deps.kv.delete(key,{previousSeq:entry.revision})}catch(e3){if(!isCasLoss(e3))throw e3}}}}}});function isArtifactPart(value){if(!value||typeof value!=="object")return false;const p2=value;return p2.kind===ARTIFACT_PART_KIND&&typeof p2.name==="string"&&p2.name.length>0&&typeof p2.mediaType==="string"&&p2.mediaType.length>0&&typeof p2.digest==="string"&&isContractDigest(p2.digest)&&typeof p2.size==="number"&&Number.isSafeInteger(p2.size)&&p2.size>=0}var ARTIFACT_PART_KIND;var init_artifact=__esm({"../../packages/core/dist/artifact.js"(){"use strict";init_canonical();ARTIFACT_PART_KIND="artifact"}});function principalFromDurable(name2,prefix){if(!name2.startsWith(prefix))return void 0;const match=/^([A-Za-z0-9_]+)-([A-Za-z0-9_]+)-([a-z0-9]+)$/.exec(name2.slice(prefix.length));return match?{owner:match[1],actor:match[2],lifecycleUid:match[3]}:void 0}function expectedConsumerConfig(space2,stream,name2){if(stream===chatStream(space2)&&name2===FANOUT_DURABLE)return fanoutDurableConfig(space2);if(stream===inboxStream(space2)&&name2===INBOX_READER_DURABLE)return inboxReaderConfig(space2);if(stream===dmStream(space2)){const principal=principalFromDurable(name2,"dm_");if(principal)return dmDurableConfig(space2,principal.owner,principal.actor,principal.lifecycleUid)}if(stream===dlvStream(space2)){const principal=principalFromDurable(name2,"dlv_");if(principal)return dlvDurableConfig(space2,principal.owner,principal.actor,principal.lifecycleUid)}if(stream===taskStream(space2)&&/^svc_[A-Za-z0-9_-]+$/.test(name2))return{...taskDurableConfig(space2,name2.slice("svc_".length)),deliver_policy:import_jetstream12.DeliverPolicy.All};throw new Error(`unsupported persistent consumer ${stream}/${name2}`)}function validatePersistentConsumer(space2,stream,info){validatePullConsumerReadConfig(stream,info,expectedConsumerConfig(space2,stream,info.name),{allowStartSequence:stream!==taskStream(space2),allowImplicitAll:stream===taskStream(space2)})}function validatePullConsumerReadConfig(stream,info,expected,options={}){if(expected.durable_name!==info.name)throw new Error(`${stream}/${info.name} is not the expected durable`);const config2=info.config;const unknown2=Object.keys(config2).filter(key=>!CONSUMER_KEYS.has(key));if(unknown2.length)throw new Error(`${stream}/${info.name} has unsupported consumer fields: ${unknown2.sort().join(", ")}`);if(config2.name!==void 0&&config2.name!==info.name)throw new Error(`${stream}/${info.name} has a mismatched name`);if(config2.durable_name!==info.name)throw new Error(`${stream}/${info.name} is not a canonical durable`);if(config2.deliver_subject||config2.deliver_group)throw new Error(`${stream}/${info.name} is a push consumer`);if(config2.filter_subject!==expected.filter_subject||(config2.filter_subjects?.length??0)!==0)throw new Error(`${stream}/${info.name} has a noncanonical filter`);if(config2.ack_policy!==import_jetstream12.AckPolicy.Explicit||config2.ack_wait!==expected.ack_wait)throw new Error(`${stream}/${info.name} has noncanonical ACK settings`);const migrated=options.allowStartSequence===true&&config2.deliver_policy===import_jetstream12.DeliverPolicy.StartSequence;const implicitTaskAll=options.allowImplicitAll===true&&expected.deliver_policy===import_jetstream12.DeliverPolicy.All&&config2.deliver_policy===void 0;if(config2.deliver_policy!==expected.deliver_policy&&!migrated&&!implicitTaskAll)throw new Error(`${stream}/${info.name} has a noncanonical delivery policy`);if(migrated){if(!Number.isSafeInteger(config2.opt_start_seq)||(config2.opt_start_seq??0)<1)throw new Error(`${stream}/${info.name} has an invalid creation lower bound`)}else if(config2.opt_start_seq!==void 0||config2.opt_start_time!==void 0){throw new Error(`${stream}/${info.name} has an unexpected start bound`)}const expectedMaxAck=expected.max_ack_pending??1e3;if((config2.max_ack_pending??1e3)!==expectedMaxAck)throw new Error(`${stream}/${info.name} has noncanonical max_ack_pending`);if((config2.max_deliver??-1)!==-1||(config2.max_waiting??512)!==512)throw new Error(`${stream}/${info.name} has noncanonical delivery limits`);if((config2.replay_policy??import_jetstream12.ReplayPolicy.Instant)!==import_jetstream12.ReplayPolicy.Instant||(config2.num_replicas??0)!==0)throw new Error(`${stream}/${info.name} has noncanonical replay/replica settings`);for(const key of["backoff","description","flow_control","headers_only","idle_heartbeat","inactive_threshold","max_batch","max_bytes","max_expires","mem_storage","metadata","pause_until","priority_groups","priority_policy","priority_timeout","rate_limit_bps","sample_freq"]){const value=config2[key];if(key==="metadata"&&value&&typeof value==="object"&&!Array.isArray(value)&&Object.entries(value).every(([metadataKey,metadataValue])=>metadataKey.startsWith("_nats.")&&typeof metadataValue==="string"))continue;if(value!==void 0&&value!==false&&value!==0&&value!==""&&!(Array.isArray(value)&&value.length===0)&&!(typeof value==="object"&&value!==null&&Object.keys(value).length===0))throw new Error(`${stream}/${info.name} has active unsupported setting ${key}`)}}function isRestoredConsumer(space2,stream,info,wanted){if(info.name!==wanted.durable_name||info.config.deliver_policy!==import_jetstream12.DeliverPolicy.StartSequence||info.config.ack_wait!==wanted.ack_wait)return false;try{validatePersistentConsumer(space2,stream,info)}catch{return false}return true}var import_jetstream12,import_transport_node12,DEFAULT_TRANSFER_TIMEOUT_MS,CONSUMER_KEYS;var init_backup=__esm({"../../packages/core/dist/backup.js"(){"use strict";import_jetstream12=__toESM(require_mod4(),1);import_transport_node12=__toESM(require_transport_node(),1);init_backup_config();init_deadline();init_endpoint_binding();init_streams();init_subjects();DEFAULT_TRANSFER_TIMEOUT_MS=5*60*1e3;CONSUMER_KEYS=new Set(["ack_policy","ack_wait","backoff","deliver_group","deliver_policy","deliver_subject","description","durable_name","filter_subject","filter_subjects","flow_control","headers_only","idle_heartbeat","inactive_threshold","max_ack_pending","max_batch","max_bytes","max_deliver","max_expires","max_waiting","mem_storage","metadata","name","num_replicas","opt_start_seq","opt_start_time","pause_until","priority_groups","priority_policy","priority_timeout","rate_limit_bps","replay_policy","sample_freq"])}});function authenticatedChannelMessage(msg,channel){if(msg.channel===channel&&msg.to===void 0&&msg.toService===void 0)return msg;const{to:_to,toService:_toService,...base}=msg;return{...base,channel}}async function ackWaitOf(consumer){const{config:config2}=await consumer.info(true);if(config2.ack_wait===void 0)throw new Error(`consumer ${config2.durable_name} reports no ack wait`);return(0,import_transport_node13.millis)(config2.ack_wait)}function durableDelivery(m2,ackWaitMs){return{ack:()=>m2.ack(),nak:()=>m2.nak(),durable:true,redelivery:{deliveryCount:m2.info.deliveryCount,ackWaitMs,working:()=>m2.working()}}}function isRecord(value){return!!value&&typeof value==="object"&&!Array.isArray(value)}var import_transport_node13;var init_endpoint_inbound=__esm({"../../packages/core/dist/endpoint-inbound.js"(){"use strict";import_transport_node13=__toESM(require_transport_node(),1)}});function isPlane3DeliveryFrame(value){if(!isRecord(value))return false;const keys=Object.keys(value);if(keys.length!==3||!keys.includes("version")||!keys.includes("channel")||!keys.includes("msg"))return false;if(value.version!==1||typeof value.channel!=="string"||!isConcreteChannel(value.channel))return false;return isCotalMessage(value.msg)&&value.msg.channel===value.channel}function isCotalMessage(value){if(!isRecord(value))return false;const routes=["channel","to","toService"].filter(key=>key in value);if(routes.length!==1||typeof value[routes[0]]!=="string")return false;if(typeof value.id!=="string"||typeof value.ts!=="number"||!Number.isFinite(value.ts)||typeof value.space!=="string"||!isEndpointRef(value.from)||!Array.isArray(value.parts)||!value.parts.every(isMessagePart))return false;if(value.mentions!==void 0&&(!Array.isArray(value.mentions)||!value.mentions.every(name2=>typeof name2==="string")))return false;if(value.replyTo!==void 0&&typeof value.replyTo!=="string")return false;if(value.contextId!==void 0&&typeof value.contextId!=="string")return false;return true}function isEndpointRef(value){return isRecord(value)&&typeof value.id==="string"&&typeof value.name==="string"&&(value.role===void 0||typeof value.role==="string")}function isMessagePart(value){if(!isRecord(value)||typeof value.kind!=="string")return false;if(value.kind==="text")return typeof value.text==="string";if(value.kind==="data")return Object.prototype.hasOwnProperty.call(value,"data");if(value.kind===ARTIFACT_PART_KIND)return isArtifactPart(value);return/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/.test(value.kind)}var import_jetstream13,import_transport_node14,PLANE3_FRAME_HEADER,ANYCAST_CONTROL_OPS,DELIVERY_LIMIT_READ_MS,READER_MAX_REDELIVERIES,READ_HISTORY_DEFAULT_LIMIT,READ_HISTORY_MAX_LIMIT,EndpointDeliveryPlane;var init_endpoint_delivery_plane=__esm({"../../packages/core/dist/endpoint-delivery-plane.js"(){"use strict";init_acls();init_anycast_requests();init_artifact();init_backup_config();init_backup();init_endpoint_inbound();init_endpoint();init_evict();init_issued_authority();init_jetstream_missing();init_members();init_secret_store();init_streams();init_subjects();import_jetstream13=__toESM(require_mod4(),1);import_transport_node14=__toESM(require_transport_node(),1);PLANE3_FRAME_HEADER="Cotal-Delivery-Frame";ANYCAST_CONTROL_OPS=new Set([ANYCAST_STATUS_OP,ANYCAST_CANCEL_OP,ANYCAST_TAKES_OP]);DELIVERY_LIMIT_READ_MS=5e3;READER_MAX_REDELIVERIES=10;READ_HISTORY_DEFAULT_LIMIT=100;READ_HISTORY_MAX_LIMIT=200;EndpointDeliveryPlane=class{deps;deliveryServeSub;deliveryAdminServeSub;retiringLifecycles=new Map;membershipWrites=new Map;plane3Quiesced=false;plane3;deliveryLimitRead;aclForAlias;channelHistory;deliveryClassFresh;durableJoinFor;durableLeaveFor;ownerMemberships;ownsDeliveryLease;readDeliveryLease;readDeliveryLeaseEntry;reloadCreds;serveControl;aclRegistry;membersRegistry;armAnycastRequests;deliveryAnycast;dropAnycastRequests;manager;notLiveMsg;plane3MsgId;publishDinbox;resolveOwnerByName;scheduleResidentSwap;sendMentionNotice;emit;constructor(deps){this.deps=deps;this.aclForAlias=deps.aclForAlias;this.channelHistory=deps.channelHistory;this.deliveryClassFresh=deps.deliveryClassFresh;this.durableJoinFor=deps.durableJoinFor;this.durableLeaveFor=deps.durableLeaveFor;this.ownerMemberships=deps.ownerMemberships;this.ownsDeliveryLease=deps.ownsDeliveryLease;this.readDeliveryLease=deps.readDeliveryLease;this.readDeliveryLeaseEntry=deps.readDeliveryLeaseEntry;this.reloadCreds=deps.reloadCreds;this.serveControl=deps.serveControl;this.aclRegistry=deps.aclRegistry;this.membersRegistry=deps.membersRegistry;this.armAnycastRequests=deps.armAnycastRequests;this.deliveryAnycast=deps.deliveryAnycast;this.dropAnycastRequests=deps.dropAnycastRequests;this.manager=deps.manager;this.notLiveMsg=deps.notLiveMsg;this.plane3MsgId=deps.plane3MsgId;this.publishDinbox=deps.publishDinbox;this.resolveOwnerByName=deps.resolveOwnerByName;this.scheduleResidentSwap=deps.scheduleResidentSwap;this.sendMentionNotice=deps.sendMentionNotice;this.emit=deps.emit}get ackWaitMs(){return this.deps.ackWaitMs()}get actor(){return this.deps.actor()}get owner(){return this.deps.owner()}get allowSubscribe(){return this.deps.allowSubscribe()}get anycastUnavailable(){return this.deps.anycastUnavailable()}get card(){return this.deps.card()}get js(){return this.deps.js()}get jsm(){return this.deps.jsm()}get nc(){return this.deps.nc()}get ownLifecycleUid(){return this.deps.ownLifecycleUid()}get residentSwap(){return this.deps.residentSwap()}get space(){return this.deps.space()}get stopped(){return this.deps.stopped()}get streamMsgs(){return this.deps.streamMsgs()}get subs(){return this.deps.subs()}get userMode(){return this.deps.userMode()}get watchDeletePermissions(){return this.deps.watchDeletePermissions()}get maxPayload(){return this.deps.maxPayload()}async startPlane3(aclFor,opts={}){if(!this.js)throw new Error(this.notLiveMsg());this.plane3={aclFor,reloadMembershipCreds:opts.reloadMembershipCreds,evictPrincipal:opts.evictPrincipal,evictPrincipals:opts.evictPrincipals,planeConnLiveness:opts.planeConnLiveness,principalLiveness:opts.principalLiveness,reloadStoreIdentity:opts.reloadStoreIdentity,onDeliveryCredsAdopted:opts.onDeliveryCredsAdopted,startupComplete:opts.startupComplete};await this.armPlane3()}plane3MayAct(){return!this.plane3Quiesced}async handleDeliveryControl(req){if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon is not serving this shard (it is re-checking ownership); retry"};const caller=req.from.id;const args=req.args??{};if(req.op==="durableJoin")return this.deliveryJoin(caller,args);if(req.op==="durableLeave")return this.deliveryLeave(caller,args);if(req.op==="readHistory")return this.deliveryReadHistory(caller,args);if(req.op===ANYCAST_TAKES_OP)return this.anycastUnavailable?{ok:false,error:`delivery: ${this.anycastUnavailable}`}:{ok:true,data:{takes:true}};if(req.op===ANYCAST_STATUS_OP||req.op===ANYCAST_CANCEL_OP)return this.deliveryAnycast(req.op,caller,args);if(req.op==="listMemberships"){if(typeof args.lifecycleUid!=="string")return{ok:false,error:"listMemberships: the caller's lifecycleUid is required (membership rows are lifecycle-keyed, SPEC 13.1)"};let uid2;try{uid2=assertLifecycleToken(args.lifecycleUid)}catch(e3){return{ok:false,error:e3.message}}let memberships;if(args.channel!==void 0){const channel=this.checkDurableChannelArg(args,"listMemberships",{family:true});if(typeof channel!=="string")return channel;memberships=(await listMembers(await this.membersRegistry(),{owner:caller})).filter(r2=>r2.channel===channel&&r2.leaveCursor===void 0).map(r2=>({channel:r2.channel,generation:r2.generation,activated:r2.activated===true,lifecycleUid:r2.lifecycleUid}))}else{memberships=await this.ownerMemberships(caller,uid2)}if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon stopped serving this shard while the request was in flight; retry"};return{ok:true,data:{memberships}}}return{ok:false,error:`op "${req.op}" not supported on the delivery control service`}}checkDurableChannelArg(args,op,opts={}){const channel=typeof args.channel==="string"?args.channel.trim():"";if(!channel)return{ok:false,error:`${op}: channel must be a non-blank string`};try{assertValidChannel(channel)}catch(e3){return{ok:false,error:e3.message}}if(opts.family&&isChannelFamily(channel))return channel;if(!isConcreteChannel(channel))return{ok:false,error:opts.family?`${op}: "${channel}" stays live only: a durable membership takes a concrete channel or a family such as review.>, never the root > or a pattern with *`:`${op}: "${channel}" must be a concrete channel (durable membership is per-concrete-channel, not wildcard)`};return channel}async deliveryJoin(caller,args){const channel=this.checkDurableChannelArg(args,"durableJoin",{family:true});if(typeof channel!=="string")return channel;let acl;try{acl=await this.aclForAlias(caller)}catch(e3){return{ok:false,error:e3.message}}if(acl===void 0)return{ok:false,error:`durableJoin: no read ACL on record for ${caller} (not provisioned for durable delivery)`};if(!membershipInAllow(acl.allowSubscribe,channel))return{ok:false,error:`channel "${channel}" is not within your read ACL [${acl.allowSubscribe.join(", ")}]`};const uid2=acl.lifecycleUid;try{return{ok:true,data:await this.membershipWrite(caller,uid2,()=>this.durableJoinFor(caller,channel,uid2,{aclFence:true}))}}catch(e3){return{ok:false,error:e3.message}}}async lifecycleAclUnfenced(principal,lifecycleUid){try{const row=await readAcl(await this.aclRegistry(),principal,lifecycleUid);return row!==void 0&&row.record.allowSubscribe.length>0}catch{return true}}async membershipWrite(principal,lifecycleUid,write){if(this.retiringLifecycles.get(principal)?.has(lifecycleUid))throw new Error(`lifecycle ${lifecycleUid} of ${principal} is retiring: its membership inventory was requested, so its durable memberships no longer change`);const key=`${principal}/${lifecycleUid}`;const running=write();let writes=this.membershipWrites.get(key);if(writes===void 0)this.membershipWrites.set(key,writes=new Set);writes.add(running);try{return await running}finally{writes.delete(running);if(writes.size===0)this.membershipWrites.delete(key)}}async deliveryLeave(caller,args){const channel=this.checkDurableChannelArg(args,"durableLeave",{family:true});if(typeof channel!=="string")return channel;if(typeof args.generation!=="number"||!Number.isFinite(args.generation))return{ok:false,error:"durableLeave: a finite generation is required (fail-closed stale-leave guard)"};if(typeof args.lifecycleUid!=="string")return{ok:false,error:"durableLeave: the leaving incarnation's lifecycleUid is required (membership rows are lifecycle-keyed, SPEC 13.1)"};let uid2;try{uid2=assertLifecycleToken(args.lifecycleUid)}catch(e3){return{ok:false,error:e3.message}}const existing=await readMember(await this.membersRegistry(),channel,caller,uid2);if(!existing)return{ok:true,data:{channel,alreadyLeft:true}};const generation=args.generation;try{await this.membershipWrite(caller,uid2,()=>this.durableLeaveFor(caller,channel,uid2,generation))}catch(e3){return{ok:false,error:e3.message}}return{ok:true,data:{channel}}}async deliveryReadHistory(caller,args){const channel=this.checkDurableChannelArg(args,"readHistory");if(typeof channel!=="string")return channel;const asked=args.limit===void 0?READ_HISTORY_DEFAULT_LIMIT:args.limit;if(typeof asked!=="number"||!Number.isInteger(asked)||asked<1)return{ok:false,error:`readHistory: limit must be a positive integer (got ${JSON.stringify(args.limit)})`};const limit=Math.min(asked,READ_HISTORY_MAX_LIMIT);let acl;try{acl=await this.aclForAlias(caller)}catch(e3){return{ok:false,error:e3.message}}if(acl===void 0)return{ok:false,error:`readHistory: no read ACL on record for ${caller} - not permitted`};const inLive=channelInAllow(acl.allowSubscribe,channel);const inIssued=channelInAllow(acl.issuedAllowSubscribe,channel);if(!inLive||!inIssued){return{ok:false,error:`readHistory: channel "${channel}" is not within your read ACL [${acl.allowSubscribe.join(", ")}] - refused`}}let page;try{page=await this.channelHistory(channel,{limit:limit+1})}catch(e3){return{ok:false,error:`readHistory: ${e3.message}`}}const reachedStart=page.length<=limit;const wanted=reachedStart?page:page.slice(-limit);const fitted=fitHistoryPage(wanted,this.maxPayload);if(wanted.length>0&&fitted.length===0)return{ok:false,error:`readHistory: the newest message on "${channel}" alone exceeds the broker payload budget (${this.maxPayload} bytes) - refused loudly rather than served as an empty page`};return{ok:true,data:{items:fitted,complete:reachedStart&&fitted.length===wanted.length}}}async quiescePlane3(){this.plane3Quiesced=true;if(this.deliveryServeSub){try{this.deliveryServeSub.unsubscribe()}catch{}this.deliveryServeSub=void 0}if(this.deliveryAdminServeSub){try{this.deliveryAdminServeSub.unsubscribe()}catch{}this.deliveryAdminServeSub=void 0}this.dropAnycastRequests();for(const msgs of this.streamMsgs.splice(0)){try{msgs.stop()}catch{}}}plane3IsQuiesced(){return this.plane3Quiesced}async rearmPlane3(){if(!this.plane3Quiesced)return;this.plane3Quiesced=false;try{await this.armPlane3()}catch(e3){this.plane3Quiesced=true;this.quiescePlane3();throw e3}}async armPlane3(){if(!this.plane3||!this.js)return;if(this.plane3Quiesced)return;await this.manager();this.armDeliveryControl();await this.armAnycastRequests();await this.runFanout();await this.runReader()}armDeliveryControl(){if(this.deliveryServeSub){try{this.deliveryServeSub.unsubscribe()}catch{}const i2=this.subs.indexOf(this.deliveryServeSub);if(i2>=0)this.subs.splice(i2,1)}this.deliveryServeSub=this.serveControl(CONTROL_DELIVERY,req=>this.handleDeliveryControl(req),{boundReply:true,concurrent:req=>ANYCAST_CONTROL_OPS.has(req.op)});if(this.deliveryAdminServeSub){try{this.deliveryAdminServeSub.unsubscribe()}catch{}const i2=this.subs.indexOf(this.deliveryAdminServeSub);if(i2>=0)this.subs.splice(i2,1)}this.deliveryAdminServeSub=this.serveControl(CONTROL_DELIVERY_ADMIN,req=>this.handleDeliveryAdmin(req),{boundReply:true,concurrent:req=>req.op==="lifecycleMemberships"})}async handleDeliveryAdmin(req){await this.residentSwap;if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon is not serving this shard (it is re-checking ownership); retry"};if(req.op==="reloadCreds"){if(this.plane3?.startupComplete?.()===false)return{ok:false,error:"delivery: this daemon has not finished starting; nothing adopted - the next renewal pass or the daemon's 75% re-read adopts the re-signed creds"};const expected=req.args?.expected??{};const[delivery,membership]=await Promise.all([this.reloadCreds(expected.delivery).then(brokerAccepted=>({ok:true,brokerAccepted,residentSwap:"scheduled"}),e3=>({ok:false,error:e3.message})),this.plane3?.reloadMembershipCreds?this.plane3.reloadMembershipCreds(expected.membership).then(result=>({ok:true,...result}),e3=>({ok:false,error:e3.message})):Promise.resolve({ok:true,skipped:"no-membership-hook"})]);const failures=[delivery.ok?void 0:`delivery: ${delivery.error}`,membership.ok?void 0:`membership: ${membership.error}`].filter(m2=>m2!==void 0);if(delivery.ok){this.plane3?.onDeliveryCredsAdopted?.();this.scheduleResidentSwap()}return failures.length?{ok:false,error:failures.join("; "),data:{delivery,membership}}:{ok:true,data:{delivery,membership}}}if(req.op==="evictPrincipal"){if(!this.plane3?.evictPrincipal)return{ok:false,error:"evictPrincipal: no eviction executor wired on this daemon"};const principal=typeof req.args?.principal==="string"?req.args.principal.trim():"";if(!principal)return{ok:false,error:"evictPrincipal: a principal (owner.actor dot-form) is required"};try{return{ok:true,data:await this.plane3.evictPrincipal(principal)}}catch(e3){return{ok:false,error:e3.message}}}if(req.op==="evictPrincipals"){if(!this.plane3?.evictPrincipals)return{ok:false,error:"evictPrincipals: no batch eviction executor wired on this daemon"};const raw=req.args?.principals;const principals=Array.isArray(raw)?raw.map(p2=>typeof p2==="string"?p2.trim():""):[];if(principals.length===0||principals.some(p2=>!p2))return{ok:false,error:"evictPrincipals: principals must be a non-empty array of owner.actor dot-form principals"};if(principals.length>EVICT_PRINCIPALS_MAX||new Set(principals).size!==principals.length)return{ok:false,error:`evictPrincipals: principals must be distinct and at most ${EVICT_PRINCIPALS_MAX}`};try{return{ok:true,data:await this.plane3.evictPrincipals(principals)}}catch(e3){return{ok:false,error:e3.message}}}if(req.op==="planeConnLiveness"){if(!this.plane3?.planeConnLiveness)return{ok:false,error:"planeConnLiveness: no plane-liveness oracle wired on this daemon"};try{return{ok:true,data:await this.plane3.planeConnLiveness(req.args?.query)}}catch(e3){return{ok:false,error:e3.message}}}if(req.op==="lifecycleMemberships"){const principal=typeof req.args?.principal==="string"?req.args.principal.trim():"";const uid2=typeof req.args?.lifecycleUid==="string"?req.args.lifecycleUid:"";if(!parsePrincipalKey(principal))return{ok:false,error:"lifecycleMemberships: a principal (owner.actor dot-form) is required"};try{assertLifecycleToken(uid2)}catch(e3){return{ok:false,error:`lifecycleMemberships: ${e3.message}`}}let marked=this.retiringLifecycles.get(principal);if(marked===void 0)this.retiringLifecycles.set(principal,marked=new Set);for(const earlier of[...marked])if(earlier!==uid2&&await aclRetired(await this.aclRegistry(),principal,earlier).catch(()=>false))marked.delete(earlier);if(await this.lifecycleAclUnfenced(principal,uid2))marked.add(uid2);else if(marked.size===0)this.retiringLifecycles.delete(principal);await Promise.allSettled(this.membershipWrites.get(`${principal}/${uid2}`)??[]);try{const channels=await listLifecycleMemberChannels(await this.membersRegistry(),principal,uid2);return{ok:true,data:{complete:true,channels}}}catch(e3){return{ok:false,error:`lifecycleMemberships: the inventory read did not complete (${e3.message})`}}}if(req.op==="principalLiveness"){if(!this.plane3?.principalLiveness)return{ok:false,error:"principalLiveness: no liveness oracle wired on this daemon"};const principal=typeof req.args?.principal==="string"?req.args.principal.trim():"";if(!principal)return{ok:false,error:"principalLiveness: a principal (owner.actor dot-form) is required"};try{return{ok:true,data:await this.plane3.principalLiveness(principal)}}catch(e3){return{ok:false,error:e3.message}}}if(req.op==="reloadStoreIdentity"){if(!this.plane3?.reloadStoreIdentity)return{ok:false,error:"reloadStoreIdentity: this daemon did not name the SecretStore it reloads from"};try{const identity=this.plane3.reloadStoreIdentity();let holdsDeliveryLease=false;try{const own=await this.readDeliveryLeaseEntry(0);holdsDeliveryLease=own!==void 0&&this.ownsDeliveryLease(own.info)}catch{holdsDeliveryLease=false}return{ok:true,data:{identity:parseSecretStoreIdentity(identity),responder:this.card.id,holdsDeliveryLease}}}catch(e3){return{ok:false,error:e3.message}}}return{ok:false,error:`op "${req.op}" not supported on the delivery admin service`}}async addPlane3Durable(stream,config2){try{await this.jsm.consumers.add(stream,config2)}catch(e3){if(!isConsumerAlreadyExists(e3)||!isRestoredConsumer(this.space,stream,await this.jsm.consumers.info(stream,config2.durable_name),config2))throw e3}}async runFanout(){if(!this.js||!this.jsm)return;await this.addPlane3Durable(chatStream(this.space),fanoutDurableConfig(this.space,{ackWaitMs:this.ackWaitMs}));const consumer=await this.js.consumers.get(chatStream(this.space),FANOUT_DURABLE);const msgs=await consumer.consume();this.streamMsgs.push(msgs);void(async()=>{for await(const m2 of msgs){try{await this.fanOutMessage(m2)}catch(e3){if(!this.stopped)this.emit("error",e3);try{m2.nak()}catch{}}}})().catch(e3=>{if(!this.stopped)this.emit("error",e3)})}async fanOutMessage(m2){if(!this.plane3MayAct())return;const parsed=parseSubject(m2.subject);if(!parsed||parsed.kind!=="chat"){m2.ack();return}const channel=parsed.rest;let msg;try{msg=m2.json()}catch{m2.ack();return}if(!isFromSubjectSender(msg,parsed)){m2.ack();return}const seq=m2.seq;const normalizedMsg=authenticatedChannelMessage(msg,channel);if(!this.plane3MayAct())return;const durable=await this.deliveryClassFresh(channel)==="durable";const mentioned=[];for(const name2 of msg.mentions??[]){const owner2=this.resolveOwnerByName(name2);if(!owner2||owner2===msg.from.id)continue;let row;try{row=await this.aclForAlias(owner2)}catch(e3){this.emit("error",e3);continue}if(row)mentioned.push({name:name2,owner:owner2,row})}if(durable){for(const rec of await listMembers(await this.membersRegistry(),{covering:channel})){if(rec.owner===msg.from.id)continue;if(!durableEligible(rec,seq))continue;if(!this.plane3MayAct())return;await this.publishDinbox(rec.owner,rec.lifecycleUid,{msg:normalizedMsg,channel,seq,reason:"durable-channel",generation:rec.generation,...rec.channel!==channel?{row:rec.channel}:{}})}}else{for(const{owner:owner2,row}of mentioned){if(!channelInAllow(row.allowSubscribe,channel))continue;if(!this.plane3MayAct())return;await this.publishDinbox(owner2,row.lifecycleUid,{msg:normalizedMsg,channel,seq,reason:"live-mention",generation:0})}}const unreadable=mentioned.filter(({row})=>!channelInAllow(row.allowSubscribe,channel)).map(({name:name2})=>name2);if(unreadable.length){if(!this.plane3MayAct())return;await this.sendMentionNotice(msg,channel,seq,unreadable)}if(!this.plane3MayAct())return;m2.ack()}async deliveryLimitStamp(){const at2=Date.now();if(this.deliveryLimitRead&&at2-this.deliveryLimitRead.at<DELIVERY_LIMIT_READ_MS)return this.deliveryLimitRead.stamp;const count=(await this.jsm.streams.info(dlvStream(this.space))).config.max_msgs_per_subject;const stamp2=count===HISTORY_NO_COUNT||count<1?"none":String(count);this.deliveryLimitRead={at:at2,stamp:stamp2};return stamp2}async runReader(){if(!this.js||!this.jsm)return;await this.addPlane3Durable(inboxStream(this.space),inboxReaderConfig(this.space,{ackWaitMs:this.ackWaitMs}));const consumer=await this.js.consumers.get(inboxStream(this.space),INBOX_READER_DURABLE);const msgs=await consumer.consume();this.streamMsgs.push(msgs);void(async()=>{for await(const m2 of msgs){try{await this.readerHandle(m2)}catch(e3){if(!this.stopped)this.emit("error",e3);try{m2.nak()}catch{}}}})().catch(e3=>{if(!this.stopped)this.emit("error",e3)})}async lifecycleCoversPost(owner2,lifecycleUid,channel,seq){const kv=await this.membersRegistry();for(const row of[channel,...familiesCovering(channel).reverse()]){const rec=await readMember(kv,row,owner2,lifecycleUid);if(rec&&durableEligible(rec.record,seq))return true}return false}async removeRetiredMemberRow(channel,owner2,lifecycleUid){try{const kv=await this.membersRegistry();if(await readMember(kv,channel,owner2,lifecycleUid)===void 0)return;await deleteMember(kv,channel,owner2,lifecycleUid)}catch(e3){this.emit("warning",new Error(`plane-3 reader: could not remove retired lifecycle ${owner2}.${lifecycleUid}'s "${channel}" member row: ${e3.message}`))}}async readerHandle(m2){if(!this.plane3MayAct())return;const pr2=parseDinboxPrincipal(m2.subject);if(!pr2){m2.ack();return}const owner2=`${pr2.owner}.${pr2.actor}`;let entry;try{entry=m2.json()}catch{m2.ack();return}if(!isRecord(entry)){m2.ack();return}const redeliveries=m2.info?.deliveryCount??1;const acl=await this.plane3?.aclFor(owner2,pr2.lifecycleUid);if(acl===void 0){if(await aclRetired(await this.aclRegistry(),owner2,pr2.lifecycleUid)){if(!this.plane3MayAct())return;let failure;try{await this.jsm.streams.deleteMessage(inboxStream(this.space),m2.seq,false)}catch(e3){if(!isJetStreamMissing(e3,10043))failure=e3 instanceof Error?e3:new Error(String(e3))}if(!this.plane3MayAct())return;if(failure){if(redeliveries>=READER_MAX_REDELIVERIES){m2.term();this.emit("error",new Error(`plane-3 reader: gave up removing entry ${m2.seq} for retired lifecycle ${owner2}.${pr2.lifecycleUid} after ${redeliveries} redeliveries: ${failure.message}`));return}m2.nak(2e3);return}if(entry.reason==="durable-channel")await this.removeRetiredMemberRow(entry.row??entry.channel,owner2,pr2.lifecycleUid);if(!this.plane3MayAct())return;m2.ack();return}if(redeliveries>=READER_MAX_REDELIVERIES){m2.term();this.emit("error",new Error(`plane-3 reader: gave up on entry for unknown owner ${owner2} after ${redeliveries} redeliveries`));return}m2.nak(2e3);return}if(!channelInAllow(acl,entry.channel)){m2.ack();return}if(entry.reason==="durable-channel"&&!await this.lifecycleCoversPost(owner2,pr2.lifecycleUid,entry.channel,entry.seq)){m2.ack();return}if(!this.plane3MayAct())return;try{const frame={version:1,channel:entry.channel,msg:authenticatedChannelMessage(entry.msg,entry.channel)};const frameHeaders=(0,import_transport_node14.headers)();frameHeaders.set(PLANE3_FRAME_HEADER,"1");frameHeaders.set(DELIVERY_LIMIT_HEADER,await this.deliveryLimitStamp());if(!this.plane3MayAct())return;await this.js.publish(dlvSubject(this.space,pr2.owner,pr2.actor,pr2.lifecycleUid),JSON.stringify(frame),{...this.plane3MsgId(entry,`${owner2}:${pr2.lifecycleUid}`),headers:frameHeaders})}catch{if(redeliveries>=READER_MAX_REDELIVERIES){m2.term();this.emit("error",new Error(`plane-3 reader: gave up transferring ${entry.msg.id} for ${owner2} after ${redeliveries} redeliveries`));return}m2.nak(2e3);return}if(!this.plane3MayAct())return;m2.ack()}async pumpDlv(){if(!this.js)return;if(!this.ownLifecycleUid)return;if(this.allowSubscribe?.length===0)return;const durable=dlvDurable(this.owner,this.actor,this.ownLifecycleUid);if(this.allowSubscribe===void 0&&!this.userMode&&this.nc){const permission2=this.watchDeletePermissions.get(this.nc)?.();if(permission2&&!issuedPermitsSubject({...permission2,deny:[]},`$JS.API.CONSUMER.INFO.${dlvStream(this.space)}.${durable}`))return}let consumer;try{consumer=await this.js.consumers.get(dlvStream(this.space),durable)}catch(e3){if(isJetStreamMissing(e3,import_jetstream13.JetStreamApiCodes.ConsumerNotFound)){const issued=this.nc&&this.watchDeletePermissions.get(this.nc)?.();if((this.allowSubscribe?.length??0)>0&&issued&&!issuedPermitsSubject({...issued,deny:[]},`$JS.API.CONSUMER.MSG.NEXT.${dlvStream(this.space)}.${durable}`))throw new Error(`this connection declared a read list, but its credential cannot fetch delivery durable "${durable}" for space "${this.space}"; the read list and the credential disagree`);return}throw e3}const lease=await this.readDeliveryLease(0);const liveDeliveryPlane=lease?.ready===true;if(!liveDeliveryPlane)this.emit("warning",new Error(`delivery durable "${durable}" for space "${this.space}" bound while the plane this connection reaches has no ready delivery lease, so the durable delivers nothing until a delivery daemon serves this plane. If a daemon serves this space on another plane, reconnect against it, which re-binds the durable there.`));const ackWaitMs=await ackWaitOf(consumer);const msgs=await consumer.consume();this.streamMsgs.push(msgs);void(async()=>{for await(const m2 of msgs){let limit;try{limit=deliveryLimitOf(m2.headers?.get(DELIVERY_LIMIT_HEADER))}catch(e3){this.emit("error",e3);limit=null}if(limit!==null&&m2.info.pending>=limit-1)this.emit("stored-copies-full",{limit});if(m2.headers?.get(PLANE3_FRAME_HEADER)!=="1"){this.emit("error",new Error("plane-3 delivery: unauthenticated or unversioned DLV entry terminated"));try{m2.term()}catch{}continue}let raw;try{raw=m2.json()}catch(e3){this.emit("error",e3);try{m2.term()}catch{}continue}if(!isPlane3DeliveryFrame(raw)){this.emit("error",new Error("plane-3 delivery: malformed versioned DLV entry terminated"));try{m2.term()}catch{}continue}const msg=authenticatedChannelMessage(raw.msg,raw.channel);if(msg.from?.id===this.card.id){m2.ack();continue}this.emit("message",msg,durableDelivery(m2,ackWaitMs),{historical:false,kind:"channel"})}})().catch(e3=>{if(!this.stopped)this.emit("error",e3)})}}}});import{randomUUID as randomUUID5}from"node:crypto";var import_transport_node15,EndpointControlPlane;var init_endpoint_control_plane=__esm({"../../packages/core/dist/endpoint-control-plane.js"(){"use strict";import_transport_node15=__toESM(require_transport_node(),1);init_deadline();init_endpoint();init_endpoint_invoke();init_endpoint_envelope();init_endpoint_grants();init_registry_contract();init_registry_client();init_subjects();EndpointControlPlane=class{deps;constructor(deps){this.deps=deps}get nc(){return this.deps.nc()}get space(){return this.deps.space()}get owner(){return this.deps.owner()}get actor(){return this.deps.actor()}get stopped(){return this.deps.stopped()}get authed(){return this.deps.authed()}get connId(){return this.deps.connId()}get presentedExp(){return this.deps.presentedExp()}get issuedGeneration(){return this.deps.issuedGeneration()}get acceptedToken(){return this.deps.acceptedToken()}get rebuildPromise(){return this.deps.rebuildPromise()}get subs(){return this.deps.subs()}get resolvedServices(){return this.deps.resolvedServices()}get resolvedCommandServices(){return this.deps.resolvedCommandServices()}get serviceInvocations(){return this.deps.serviceInvocations()}get requestsAwaitingReply(){return this.deps.requestsAwaitingReply()}get activeGoalFollowers(){return this.deps.activeGoalFollowers()}get splitsRecovered(){return this.deps.splitsRecovered()}set splitsRecovered(count){this.deps.setSplitsRecovered(count)}notLiveMsg(){return this.deps.notLiveMsg()}requireLifecycleUid(what2){return this.deps.requireLifecycleUid(what2)}reportSubscriptionDenial(error51){return this.deps.reportSubscriptionDenial(error51)}ref(){return this.deps.ref()}reconnect(){return this.deps.reconnect()}emit(event,...args){return this.deps.emit(event,...args)}serveControl(service,handler,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());const sub=this.nc.subscribe(controlServiceSubject(this.space,service,"*","*"),{queue:service});this.subs.push(sub);const inOwnTime=opts.concurrent;let inOrder=Promise.resolve();void(async()=>{for await(const m2 of sub){if(opts.boundReply&&(!m2.reply||!m2.reply.startsWith(`${m2.subject}.reply.`))){this.emit("error",new Error(`rejected ${service} request on ${m2.subject}: reply target "${m2.reply??"(none)"}" is not under the sender's own reply subtree`));continue}const answer=()=>this.answerControl(service,handler,m2);if(inOwnTime===void 0){await answer();continue}let own=false;try{own=inOwnTime(m2.json())}catch{}if(own)void answer().catch(e3=>this.emit("error",e3));else inOrder=inOrder.then(answer).catch(e3=>{this.emit("error",e3)})}})().catch(e3=>{if(!this.reportSubscriptionDenial(e3))this.emit("error",e3)});return sub}async answerControl(service,handler,m2){let body;try{let reply;const req=m2.json();const parsed=parseSubject(m2.subject);if(!parsed||!isFromSubjectSender(req,parsed)){this.emit("error",new Error(`rejected control request on ${m2.subject}: from ${req.from?.id??"(none)"} does not match subject sender ${parsed?.sender??"(unparseable)"}`));reply={ok:false,error:"sender mismatch - request rejected"}}else{reply=await handler(req)}body=JSON.stringify(reply)}catch(e3){body=JSON.stringify({ok:false,error:e3.message})}try{m2.respond(body)}catch(e3){const refused3={ok:false,error:`the ${service} reply is ${Buffer.byteLength(body)} bytes and was not published: ${e3.message}`};try{m2.respond(JSON.stringify(refused3))}catch(err3){this.emit("error",new Error(`could not answer ${service} request on ${m2.subject}: ${refused3.error}, and the refusal failed too: ${err3.message}`))}}}async requestBoundReply(nc,subject,body,reply,timeoutMs){let pending=this.requestsAwaitingReply.get(nc);if(!pending){const waiting=new Set;this.requestsAwaitingReply.set(nc,waiting);void nc.closed().then(error51=>{this.requestsAwaitingReply.delete(nc);const failure=error51??new import_transport_node15.ClosedConnectionError;for(const reject of waiting)reject(failure);waiting.clear()});pending=waiting}let rejectClosed;const closed4=new Promise((_resolve,reject)=>{rejectClosed=reject;pending.add(reject)});try{return await Promise.race([nc.request(subject,body,{timeout:timeoutMs,noMux:true,reply}),closed4])}finally{pending.delete(rejectClosed)}}async requestControl(service,req,timeoutMs=5e3){if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=controlServiceSubject(this.space,service,this.owner,this.actor);const reply=`${reqSubject}.reply.${randomUUID5()}`;const body={...req,from:req.from??this.ref()};const m2=await this.requestBoundReply(this.nc,reqSubject,JSON.stringify(body),reply,timeoutMs);return m2.json()}serviceRailCaller(){return this.serviceCaller()}serviceCaller(){const triple={owner:this.owner,actor:this.actor,uid:this.requireLifecycleUid("invokeService")};if(this.acceptedToken===void 0)return triple;if(this.issuedGeneration===void 0)throw new Error("invokeService: the issued generation is not yet discovered on this connection");return{...triple,generation:this.issuedGeneration}}async followServiceGoal(endpoint,submit,deadlineMs=1e4,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());if(this.stopped)throw new Error("endpoint stopped - cannot follow goal");const abortController=new AbortController;const onAbort=()=>abortController.abort();if(opts.signal?.aborted)onAbort();else opts.signal?.addEventListener("abort",onAbort,{once:true});let reconnectHandler;const entry={cancel:()=>abortController.abort(),reconnected:nc=>reconnectHandler?.(nc)};this.activeGoalFollowers.add(entry);try{const reconcile=opts.reconcile??(async(goalId,_attributed,context)=>{const current=this.serviceCaller();if(current.owner!==context.caller.owner||current.actor!==context.caller.actor||current.uid!==context.caller.uid)throw new Error("the renewed goal reader no longer has the accepting caller's full identity");const q2=await this.invokeService(endpoint,"goal-result",{goalId},{deadlineMs:Math.min(deadlineMs,context.deadlineMs),signal:context.signal});if(q2.reply.ok!==true)throw new Error(q2.reply.error.message);return q2.reply.data});return await submitAndFollowGoal(this.nc,this.space,endpoint,this.serviceCaller(),deadlineMs,submit,{reconcile,currentNc:()=>this.nc,onReconnect:cb=>{reconnectHandler=cb;return()=>{reconnectHandler=void 0}},signal:abortController.signal,prepare:opts.prepare})}finally{opts.signal?.removeEventListener("abort",onAbort);this.activeGoalFollowers.delete(entry)}}clearResolvedService(endpoint){this.resolvedServices.delete(endpoint);this.resolvedCommandServices.delete(endpoint)}beginServiceInvocation(nc){let pending=this.serviceInvocations.get(nc);if(!pending){pending=new Set;this.serviceInvocations.set(nc,pending)}let settle;const request=new Promise(resolve6=>{settle=resolve6});pending.add(request);return()=>{pending.delete(request);settle()}}async waitServiceRecovery(recovery,deadline,signal,timeout){let onAbort;const cancelled=new Promise((_3,reject)=>{onAbort=()=>reject(signal?.reason);if(signal?.aborted)onAbort();else signal?.addEventListener("abort",onAbort,{once:true})});try{await withDeadline(Promise.race([recovery,cancelled]),deadline-Date.now(),timeout)}finally{if(onAbort)signal?.removeEventListener("abort",onAbort)}signal?.throwIfAborted();if(deadline<=Date.now())throw timeout()}async describeService(endpoint,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());if(opts.refresh)this.clearResolvedService(endpoint);const cached2=opts.instanceId===void 0?this.resolvedServices.get(endpoint):void 0;if(cached2)return cached2;const svc=await resolveService(this.nc,this.space,endpoint,this.serviceCaller(),{deadlineMs:opts.deadlineMs??1e4,signal:opts.signal,...opts.instanceId!==void 0?{instanceId:opts.instanceId}:{}});if(opts.instanceId===void 0)this.resolvedServices.set(endpoint,svc);return svc}async listingCaller(){if(!this.nc)throw new Error(this.notLiveMsg());return registryListingCaller(this.nc,this.space,this.serviceCaller(),{connId:this.connId,...this.presentedExp!==void 0?{exp:this.presentedExp}:{}})}async listEndpoints(input,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());const nc=this.nc;const listing=this.authed?await this.listingCaller():void 0;if(this.authed&&listing===void 0)return{unbound:true};return this.listEndpointsOver(nc,listing,input,opts)}async listEndpointsOver(nc,listing,input,opts={}){if(!this.nc)throw new Error(this.notLiveMsg());const own=this.nc;const result=await listRegistryEndpoints(this.space,(deadlineMs,signal)=>resolveService(own,this.space,REGISTRY_ENDPOINT,this.serviceCaller(),{deadlineMs,signal,commands:[REGISTRY_ENDPOINTS_COMMAND]}),{nc,...listing?{caller:listing}:{}},input,opts);if(result.unbound)return result;for(const row of result.page?.rows??[])this.clearResolvedService(row.endpoint);return result}async invokeService(endpoint,command,args,opts={}){const deadline=Date.now()+(opts.deadlineMs??1e4);const rebuilding=this.rebuildPromise;if(rebuilding){await this.waitServiceRecovery(rebuilding,deadline,opts.signal,()=>new EpEnvelopeError("deadline-exceeded","the invocation deadline elapsed waiting for connection recovery",void 0,"not-executed"));opts={...opts,deadlineMs:deadline-Date.now()}}const nc=this.nc;if(!nc)throw new Error(this.notLiveMsg());try{return await this.invokeServiceOnce(endpoint,command,args,opts,rebuilding?deadline:void 0)}catch(e3){if(!(e3 instanceof EpEnvelopeError)||e3.code!=="permission-denied"||e3.outcome!=="not-executed"||deadline<=Date.now())throw e3;opts.signal?.throwIfAborted();const recovery=(async()=>{for(;;){opts.signal?.throwIfAborted();if(deadline<=Date.now())throw e3;const pending=this.serviceInvocations.get(nc);if(!pending?.size)break;await Promise.allSettled([...pending])}if(this.nc===nc)await this.reconnect();else await this.rebuildPromise})();await this.waitServiceRecovery(recovery,deadline,opts.signal,()=>e3);this.clearResolvedService(endpoint);return this.invokeServiceOnce(endpoint,command,args,{...opts,deadlineMs:deadline-Date.now()},deadline)}}async invokeServiceOnce(endpoint,command,args,opts={},retryDeadline){if(!this.nc)throw new Error(this.notLiveMsg());const nc=this.nc;const caller=this.serviceCaller();const resolve6=async(signal=opts.signal,deadlineMs=opts.deadlineMs??1e4)=>{signal?.throwIfAborted();if(retryDeadline!==void 0)deadlineMs=Math.min(deadlineMs,retryDeadline-Date.now());if(deadlineMs<=0)throw new EpEnvelopeError("deadline-exceeded","the invocation deadline elapsed before resolve",void 0,"not-executed");const needed=opts.follow?[command,"goal-result"]:[command];const classSelected=opts.instanceId===void 0&&opts.classInstanceId===void 0;const full=classSelected?this.resolvedServices.get(endpoint):void 0;if(full&&needed.every(name2=>full.commands.has(name2)))return full;const cacheKey=[...needed].sort().join("\0");const commandCache=classSelected?this.resolvedCommandServices.get(endpoint):void 0;const cached2=commandCache?.get(cacheKey);if(cached2)return cached2;const svc=await resolveService(nc,this.space,endpoint,caller,{deadlineMs,signal,commands:needed,...opts.follow&&command!=="goal-result"?{optionalCommands:["goal-result"]}:{},...opts.instanceId!==void 0?{instanceId:opts.instanceId}:{},...opts.classInstanceId!==void 0?{classInstanceId:opts.classInstanceId}:{}});if(classSelected){let byCommand=this.resolvedCommandServices.get(endpoint);if(!byCommand){byCommand=new Map;this.resolvedCommandServices.set(endpoint,byCommand)}byCommand.set(cacheKey,svc)}return svc};const invokeOpts={...opts.target?{target:opts.target}:{},...opts.deadlineMs!==void 0?{deadlineMs:opts.deadlineMs}:{}};const invokeResolved=(service,signal)=>{signal?.throwIfAborted();const unfollowable=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable)return Promise.resolve(unfollowable);const deadlineMs=retryDeadline===void 0?invokeOpts.deadlineMs:retryDeadline-Date.now();if(deadlineMs!==void 0&&deadlineMs<=0)throw new EpEnvelopeError("deadline-exceeded","the invocation deadline elapsed before publish",void 0,"not-executed");return invokeCommand(nc,this.space,service,command,args,{...invokeOpts,deadlineMs,signal})};const resolveFirst=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{try{return await resolve6(signal,deadline-Date.now())}catch(e3){if(!(e3 instanceof EpEnvelopeError)||e3.code!=="failed-precondition")throw e3;const left=deadline-Date.now();if(left<=0)throw e3;return await resolve6(signal,left)}};const doInvoke=async(service,signal=opts.signal)=>{signal?.throwIfAborted();try{let r2=await invokeResolved(service,signal);const unmappedHere=x2=>opts.instanceId===void 0&&replyTargetUnmapped(x2.reply.error);let unmapped=unmappedHere(r2)?r2:void 0;for(let reissues=0;reissues<BIND_SPLIT_REISSUES&&r2.reply.ok===false&&(replyRefusedBeforeEffect(r2.reply.error)||unmappedHere(r2));reissues++){this.splitsRecovered++;this.emit("split-recovered",{endpoint,command,servedBy:r2.responder,splitsRecovered:this.splitsRecovered,boundTo:(r2.reply.error.details??[]).find(d2=>d2.kind===EP_BIND_REFUSED)?.boundTo});this.clearResolvedService(endpoint);const raw=r2.reply.error.code;const refusalCode=raw==="expired"?"expired":raw==="failed-precondition"?"failed-precondition":void 0;if(refusalCode===void 0)throw new EpEnvelopeError("internal",`${endpoint}.${command} came back marked as refused before it ran, but with code ${String(raw)}; the fence produces only failed-precondition or expired (SPEC 13.2)`,r2.reply.error.details);let reissueTarget;try{reissueTarget=await resolve6(signal);const unfollowable=opts.follow?goalFollowRefusal(reissueTarget):void 0;if(unfollowable)throw new Error(unfollowable.reply.error.message)}catch(reissue){throw new EpEnvelopeError(refusalCode,`${endpoint}.${command} WAS NOT RUN - the incarnation that received it refused it before any effect, and the re-issue could not be resolved: ${reissue instanceof Error?reissue.message:String(reissue)}. Re-resolve and re-issue when the endpoint is reachable (SPEC 13.2)`,r2.reply.error.details,"not-executed")}r2=await invokeResolved(reissueTarget,signal);if(unmappedHere(r2))unmapped=r2}return replyRefusedBeforeEffect(r2.reply.error)?unmapped??r2:r2}catch(e3){if(respondedButUnbound(e3)){this.clearResolvedService(endpoint);if(!isRepeatSafeCommand(endpoint,command))throw e3;return await invokeResolved(await resolve6(signal),signal)}throw e3}};const release=this.beginServiceInvocation(nc);try{if(!opts.follow)return await doInvoke(await resolveFirst());let service;return await this.followServiceGoal(endpoint,async signal=>{try{return await doInvoke(service,signal)}finally{release()}},opts.deadlineMs??1e4,{signal:opts.signal,prepare:async(signal,deadline)=>{service=await resolveFirst(signal,deadline)}})}finally{release()}}}}});import{randomUUID as randomUUID6}from"node:crypto";function jsonPathProblem(path4,value,seen){if(value===null)return void 0;const t2=typeof value;if(t2==="boolean"||t2==="string")return void 0;if(t2==="number")return Number.isFinite(value)?void 0:`${path4} is not a finite number`;if(t2==="undefined"||t2==="function"||t2==="symbol"||t2==="bigint")return`${path4} is not a JSON value`;if(typeof value==="object"){if(seen.has(value))return`${path4} is cyclic`;seen.add(value);let problem;if(Array.isArray(value)){for(let i2=0;i2<value.length;i2++){problem=jsonPathProblem(`${path4}[${i2}]`,value[i2],seen);if(problem)return problem}}else{const proto=Object.getPrototypeOf(value);if(proto!==null&&proto!==Object.prototype){seen.delete(value);return`${path4} is not a plain object`}for(const key of Object.keys(value)){if(value[key]===void 0)continue;problem=jsonPathProblem(`${path4}.${key}`,value[key],seen);if(problem)return problem}}seen.delete(value);return void 0}return`${path4} is not a JSON value`}function assertPartsSerializable(parts){for(const p2 of parts){if(p2.kind!=="data")continue;const problem=jsonPathProblem("data",p2.data,new Set);if(problem!==void 0){throw new Error(`cannot publish a data part carrying a non-JSON value (SPEC \xA75) - ${problem}`)}}}var import_transport_node16,import_jetstream14,EndpointMessaging;var init_endpoint_messaging=__esm({"../../packages/core/dist/endpoint-messaging.js"(){"use strict";import_transport_node16=__toESM(require_transport_node(),1);import_jetstream14=__toESM(require_mod4(),1);init_event_payloads();init_endpoint_subjects();init_endpoint_records();init_jetstream_missing();init_subjects();EndpointMessaging=class{deps;constructor(deps){this.deps=deps}get nc(){return this.deps.nc()}get js(){return this.deps.js()}get jsm(){return this.deps.jsm()}get space(){return this.deps.space()}get owner(){return this.deps.owner()}get actor(){return this.deps.actor()}get channels(){return this.deps.channels()}notLiveMsg(){return this.deps.notLiveMsg()}ref(){return this.deps.ref()}publishMsg(subject,msg){return this.deps.publishMsg(subject,msg)}streamHistory(stream,subjects,limit,before,signal){return this.deps.streamHistory(stream,subjects,limit,before,signal)}emitRecoverable(err3){this.deps.emitRecoverable(err3)}async multicast(text3,opts){const channel=opts?.channel??this.channels.find(isConcreteChannel);if(channel===void 0)throw new Error("no default channel: this endpoint is not on any concrete channel, so there is nothing to broadcast to - name a channel explicitly, or join one first");if(!isConcreteChannel(channel))throw new Error(`cannot publish to wildcard channel "${channel}" - pick a concrete sub-channel`);const msg={id:randomUUID6(),ts:Date.now(),space:this.space,from:this.ref(),channel,mentions:normalizeMentions(opts?.mentions),parts:opts?.parts??[{kind:"text",text:text3}],replyTo:opts?.replyTo,contextId:opts?.contextId};await this.publishMsg(chatSubject(this.space,this.owner,this.actor,channel),msg);return msg}get maxPayload(){const max=this.nc?.info?.max_payload;if(typeof max!=="number"||!Number.isFinite(max)||max<=0)throw new Error(`${this.notLiveMsg()} - max_payload is only known while connected`);return max}async assertExpectationSemantics(){if(!this.jsm)throw new Error(this.notLiveMsg());const stream=chatStream(this.space);let replicas;try{replicas=(await this.jsm.streams.info(stream)).config.num_replicas}catch(e3){throw new Error(`cannot verify expectation semantics: stream "${stream}" info unavailable (${e3.message}). Serialized appends are refused rather than run on an unverified stream.`)}if(replicas!==1)throw new Error(`stream "${stream}" reports num_replicas=${String(replicas)}; serialized appends on THIS stream require 1 \u2014 a property of this one stream, not of the broker, so a clustered deployment is fine so long as this stream is R1, which a cluster can host. On a replicated stream the dedup cache is consulted before the subject expectation, so a retry returns a duplicate ack instead of a conflict and a lost message reads as success.`)}casEnvelope(opts){return{id:opts.id,ts:Date.now(),space:this.space,from:this.ref(),channel:opts.channel,mentions:normalizeMentions(opts.mentions),parts:opts.parts,replyTo:opts.replyTo,contextId:opts.contextId}}encodedSize(opts){if(!isConcreteChannel(opts.channel))throw new Error(`cannot publish to wildcard channel "${opts.channel}" - pick a concrete sub-channel`);assertIdToken(opts.id,"publish id");if(!Number.isSafeInteger(opts.expectedLastSubjectSeq)||opts.expectedLastSubjectSeq<0)throw new Error(`expectedLastSubjectSeq must be a non-negative safe integer, got ${JSON.stringify(opts.expectedLastSubjectSeq)}`);if(!Array.isArray(opts.parts)||opts.parts.length===0)throw new Error("encodedSize requires at least one part");const mh=(0,import_transport_node16.headers)();mh.set("Nats-Msg-Id",opts.id);mh.set("Nats-Expected-Last-Subject-Sequence",`${opts.expectedLastSubjectSeq}`);if(opts.expectedLastMsgId!==void 0){assertIdToken(opts.expectedLastMsgId,"expected last msg id");mh.set("Nats-Expected-Last-Msg-Id",opts.expectedLastMsgId)}const headerBytes=mh.encode().length;return headerBytes+Buffer.byteLength(JSON.stringify(this.casEnvelope(opts)),"utf8")}async multicastExpecting(opts){if(!this.js)throw new Error(this.notLiveMsg());if(!isConcreteChannel(opts.channel))throw new Error(`cannot publish to wildcard channel "${opts.channel}" - pick a concrete sub-channel`);assertIdToken(opts.id,"publish id");const expected=opts.expectedLastSubjectSeq;if(!Number.isSafeInteger(expected)||expected<0)throw new Error(`expectedLastSubjectSeq must be a non-negative safe integer, got ${JSON.stringify(expected)}`);if(!Array.isArray(opts.parts)||opts.parts.length===0)throw new Error("multicastExpecting requires at least one part");if(opts.expectedLastMsgId!==void 0)assertIdToken(opts.expectedLastMsgId,"expected last msg id");const message=this.casEnvelope(opts);assertPartsSerializable(message.parts);const ack=await this.js.publish(chatSubject(this.space,this.owner,this.actor,opts.channel),JSON.stringify(message),{msgID:opts.id,expect:{lastSubjectSequence:expected,...opts.expectedLastMsgId!==void 0?{lastMsgID:opts.expectedLastMsgId}:{}}});return{message,ack:{seq:ack.seq,duplicate:ack.duplicate===true}}}async publishEventPayload(opts){if(!this.js)throw new Error(this.notLiveMsg());assertIdToken(opts.id,"publish id");if(!Number.isSafeInteger(opts.expectedLastSubjectSeq)||opts.expectedLastSubjectSeq<0)throw new Error("payload expectation must be a non-negative safe integer");if(!opts.parts.length)throw new Error("payload frame requires parts");const message=this.casEnvelope({...opts,channel:`events.${this.owner}.${this.actor}`});assertPartsSerializable(message.parts);const ack=await this.js.publish(eventPayloadSubject(this.space,this.owner,this.actor),JSON.stringify(message),{msgID:opts.id,expect:{lastSubjectSequence:opts.expectedLastSubjectSeq}});return{ack:{seq:ack.seq,duplicate:ack.duplicate===true}}}async eventPayloadHistory(owner2,actor2,opts){return(await this.streamHistory(eventPayloadStream(this.space),[eventPayloadSubject(this.space,assertValidOwnerToken(owner2),assertValidOwnerToken(actor2))],opts?.limit??100,void 0,opts?.signal)).map(row=>row.msg)}async eventPayloadLimit(){if(!this.jsm)throw new Error(this.notLiveMsg());const stream=eventPayloadStream(this.space);const info=await this.jsm.streams.info(stream).catch(err3=>{const denial=err3 instanceof import_transport_node16.PermissionViolationError?err3:err3?.cause;const infoDenied=denial instanceof import_transport_node16.PermissionViolationError&&denial.operation==="publish"&&denial.subject===`$JS.API.STREAM.INFO.${stream}`;if(!infoDenied&&!isJetStreamMissing(err3,import_jetstream14.JetStreamApiCodes.StreamNotFound))throw err3;const reason=infoDenied?`missing publish permission on $JS.API.STREAM.INFO.${stream}`:`stream ${stream} is absent`;this.emitRecoverable(new Error(`event payloads unavailable: ${reason}; publishing tool names and times only. Upgrade the space's broker setup and credentials to enable payloads`));return null});if(info===null)return null;const{config:config2}=info;if(config2.num_replicas!==1)throw new Error("event payload stream requires one replica for serialized appends");const limits=[this.maxPayload,config2.max_msg_size,config2.max_bytes].filter(n2=>typeof n2==="number"&&n2>0);return Math.min(...limits)}async unicast(instanceId,text3,opts){const{msg}=await this.unicastAttributed(instanceId,text3,opts);return msg}async unicastAttributed(instanceId,text3,opts){if(!this.js)throw new Error(this.notLiveMsg());const msg={id:randomUUID6(),ts:Date.now(),space:this.space,from:this.ref(),to:instanceId,parts:opts?.parts??[{kind:"text",text:text3}],replyTo:opts?.replyTo,contextId:opts?.contextId};const recip=parsePrincipalKey(instanceId);if(!recip)throw new Error(`unicast: "${instanceId}" is not a valid recipient principal <owner>.<actor>`);assertPartsSerializable(msg.parts);const subject=unicastSubject(this.space,recip.owner,recip.actor,this.owner,this.actor);try{const ack=await this.js.publish(subject,JSON.stringify(msg),{msgID:msg.id});return{msg,ack:{seq:ack.seq,duplicate:ack.duplicate===true}}}catch(error51){if(error51 instanceof import_transport_node16.TimeoutError)throw new Error(`${error51.message} publishing to ${JSON.stringify(subject)}. The send outcome is unknown: the broker may have stored the message. Check before resending.`,{cause:error51});throw error51}}async anycast(service,text3,opts){const{msg}=await this.anycastAttributed(service,text3,opts);return msg}async anycastAttributed(service,text3,opts){if(!this.js)throw new Error(this.notLiveMsg());assertValidRole(service);const msg={id:randomUUID6(),ts:Date.now(),space:this.space,from:this.ref(),toService:service,parts:opts?.parts??[{kind:"text",text:text3}],replyTo:opts?.replyTo,contextId:opts?.contextId};assertPartsSerializable(msg.parts);const ack=await this.js.publish(anycastSubject(this.space,service,this.owner,this.actor),JSON.stringify(msg),{msgID:msg.id});return{msg,ack:{seq:ack.seq,duplicate:ack.duplicate===true}}}}}});function validateChannelConfig(cfg){validateChannelDefaults(cfg);validateText("description",cfg.description,MAX_CHANNEL_DESCRIPTION);validateText("instructions",cfg.instructions,MAX_CHANNEL_INSTRUCTIONS)}function validateText(field,text3,max){if(text3===void 0)return;if(typeof text3!=="string")throw new Error(`channel ${field} must be a string`);if(text3.length>max)throw new Error(`channel ${field} too long (${text3.length} > ${max} chars)`)}function validateChannelDefaults(d2){if(d2.replay!==void 0&&typeof d2.replay!=="boolean")throw new Error(`invalid replay "${d2.replay}" - expected true or false`);if(d2.replayWindow!==void 0)parseDuration(d2.replayWindow);if(d2.deliveryClass!==void 0&&d2.deliveryClass!=="live"&&d2.deliveryClass!=="durable")throw new Error(`invalid deliveryClass "${d2.deliveryClass}" - expected "live" or "durable"`)}function decodeChannelEntry(e3){const value=e3.json();if(typeof value!=="object"||value===null||Array.isArray(value))throw new Error("not a JSON object");if(e3.key===CHANNEL_DEFAULTS_KEY)validateChannelDefaults(value);else validateChannelConfig(value);return value}function parseDuration(s3){const m2=/^(\d+)(s|m|h|d)$/.exec(s3.trim());if(!m2)throw new Error(`invalid duration "${s3}" - expected <number><s|m|h|d>, e.g. "24h"`);const n2=Number(m2[1]);const unit={s:1e3,m:6e4,h:36e5,d:864e5}[m2[2]];return n2*unit}function effectiveReplay(cfg,defaults){return cfg?.replay??defaults?.replay??true}function effectiveReplayWindowMs(cfg,defaults){const w2=cfg?.replayWindow??defaults?.replayWindow;return w2===void 0?void 0:parseDuration(w2)}function effectiveDeliveryClass(cfg,defaults){return cfg?.deliveryClass??defaults?.deliveryClass??"durable"}async function openChannelRegistry(nc,space2,opts={}){const kvm=new import_kv6.Kvm(nc);return opts.create?kvm.create(channelBucket(space2)):kvm.open(channelBucket(space2))}async function readChannelConfig(kv,channel){return decode2(kv,channel)}async function readChannelDefaults(kv){return decode2(kv,CHANNEL_DEFAULTS_KEY)}async function decode2(kv,key){return entryValue(await kv.get(key))}function entryValue(e3){return entryDecode(e3).value}function entryDecode(e3){if(!e3||e3.operation==="DEL"||e3.operation==="PURGE")return{};try{return{value:decodeChannelEntry(e3)}}catch(err3){return{error:err3.message}}}var import_kv6,import_transport_node17,MAX_CHANNEL_DESCRIPTION,MAX_CHANNEL_INSTRUCTIONS;var init_channels=__esm({"../../packages/core/dist/channels.js"(){"use strict";import_kv6=__toESM(require_mod6(),1);init_connection_cleanup();import_transport_node17=__toESM(require_transport_node(),1);init_endpoint();init_subjects();init_streams();init_kv_scan();init_endpoint_records();init_jetstream_missing();MAX_CHANNEL_DESCRIPTION=200;MAX_CHANNEL_INSTRUCTIONS=2e3}});var import_jetstream15,import_kv7,EndpointDurableBackstop;var init_endpoint_durable_backstop=__esm({"../../packages/core/dist/endpoint-durable-backstop.js"(){"use strict";import_jetstream15=__toESM(require_mod4(),1);import_kv7=__toESM(require_mod6(),1);init_acls();init_channels();init_endpoint_records();init_members();init_streams();init_subjects();EndpointDurableBackstop=class{deps;constructor(deps){this.deps=deps}get nc(){return this.deps.nc()}get js(){return this.deps.js()}get jsm(){return this.deps.jsm()}set jsm(manager){if(manager)this.deps.setJsm(manager)}get space(){return this.deps.space()}get card(){return this.deps.card()}get authed(){return this.deps.authed()}get channelKv(){return this.deps.channelKv()}get presence(){return this.deps.presence()}get deliveryPlane(){return this.deps.deliveryPlane()}get membersKv(){return this.deps.membersKv()}set membersKv(kv){this.deps.setMembersKv(kv)}get aclKv(){return this.deps.aclKv()}set aclKv(kv){this.deps.setAclKv(kv)}get managerLeaseKv(){return this.deps.managerLeaseKv()}set managerLeaseKv(kv){this.deps.setManagerLeaseKv(kv)}get daemonRenewalLeaseRevision(){return this.deps.daemonRenewalLeaseRevision()}set daemonRenewalLeaseRevision(revision){this.deps.setDaemonRenewalLeaseRevision(revision)}notLiveMsg(){return this.deps.notLiveMsg()}consumerInfo(stream,durable){return this.deps.consumerInfo(stream,durable)}manager(){return this.deps.manager()}chatFrontier(){return this.deps.chatFrontier()}aclAllows(owner2,lifecycleUid,channel){return this.deps.aclAllows(owner2,lifecycleUid,channel)}catchupCopy(owner2,lifecycleUid,channel,fromSeqExcl,toSeqIncl,generation){return this.deps.catchupCopy(owner2,lifecycleUid,channel,fromSeqExcl,toSeqIncl,generation)}async membersRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.membersKv??=await openMembersRegistry(this.nc,this.space);return this.membersKv}async aclRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.aclKv??=await openAclRegistry(this.nc,this.space);return this.aclKv}async commitAcl(targetId,lifecycleUid,allowSubscribe){await commitAcl(await this.aclRegistry(),targetId,lifecycleUid,allowSubscribe)}async reissueAcl(targetId,lifecycleUid,allowSubscribe){await reissueAcl(await this.aclRegistry(),targetId,lifecycleUid,allowSubscribe)}async aclForOwner(owner2,lifecycleUid){return(await readAcl(await this.aclRegistry(),owner2,lifecycleUid))?.record.allowSubscribe}async aclForAlias(principal){const row=await readAclForAlias(await this.aclRegistry(),principal);if(row===void 0)return void 0;const allow=row.record.allowSubscribe;const issued=row.record.issuedAllowSubscribe??allow;return{allowSubscribe:allow,issuedAllowSubscribe:issued,lifecycleUid:row.lifecycleUid}}async managerLeaseRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());if(this.managerLeaseKv)return this.managerLeaseKv;const kvm=new import_kv7.Kvm((0,import_jetstream15.jetstream)(this.nc,{timeout:MANAGER_LEASE_ATTEMPT_MS}));if(this.authed){this.managerLeaseKv=await kvm.open(managerBucket(this.space))}else{try{this.managerLeaseKv=await kvm.create(managerBucket(this.space),{ttl:MANAGER_LEASE_TTL_MS})}catch{this.managerLeaseKv=await kvm.open(managerBucket(this.space))}}return this.managerLeaseKv}async holdDaemonRenewalLease(instanceId){const kv=await this.managerLeaseRegistry();const held2=this.daemonRenewalLeaseRevision;if(held2!==void 0){try{this.daemonRenewalLeaseRevision=await kv.update(MANAGER_RENEWAL_LEASE_KEY,this.encodeDaemonRenewalLease(instanceId),held2);return true}catch{this.daemonRenewalLeaseRevision=void 0}}try{this.daemonRenewalLeaseRevision=await kv.create(MANAGER_RENEWAL_LEASE_KEY,this.encodeDaemonRenewalLease(instanceId));return true}catch{return false}}async releaseDaemonRenewalLease(){const held2=this.daemonRenewalLeaseRevision;this.daemonRenewalLeaseRevision=void 0;if(held2===void 0)return;try{await(await this.managerLeaseRegistry()).delete(MANAGER_RENEWAL_LEASE_KEY,{previousSeq:held2})}catch{}}encodeDaemonRenewalLease(instanceId){return new TextEncoder().encode(JSON.stringify({instanceId,since:Date.now()}))}async readDaemonRenewalLease(){const e3=await(await this.managerLeaseRegistry()).get(MANAGER_RENEWAL_LEASE_KEY);if(!e3||e3.operation!=="PUT")return void 0;return JSON.parse(new TextDecoder().decode(e3.value))}encodeManagerLease(info){return new TextEncoder().encode(JSON.stringify(info))}async acquireManagerLease(info){return(await this.managerLeaseRegistry()).create(managerLeaseKey(info.instanceId),this.encodeManagerLease({...info,since:Date.now()}))}async renewManagerLease(info,revision){return(await this.managerLeaseRegistry()).update(managerLeaseKey(info.instanceId),this.encodeManagerLease({...info,since:Date.now()}),revision)}async readOwnManagerLease(instanceId){const e3=await(await this.managerLeaseRegistry()).get(managerLeaseKey(instanceId));if(!e3||e3.operation!=="PUT")return void 0;return{info:JSON.parse(new TextDecoder().decode(e3.value)),revision:e3.revision,created:e3.created.getTime()}}async releaseManagerLease(instanceId,revision){const kv=await this.managerLeaseRegistry();if(revision===void 0)await kv.delete(managerLeaseKey(instanceId));else await kv.delete(managerLeaseKey(instanceId),{previousSeq:revision})}async readManagerLease(){if(!this.nc)return void 0;try{const jsm=this.jsm??(this.jsm=await(0,import_jetstream15.jetstreamManager)(this.nc));const stream=`KV_${managerBucket(this.space)}`;const prefix=`$KV.${managerBucket(this.space)}.${MANAGER_LEASE_KEY}.`;const info=await jsm.streams.info(stream,{subjects_filter:`${prefix}*`});let newest;for(const subject of Object.keys(info.state.subjects??{})){let m2;try{m2=await jsm.streams.getMessage(stream,{last_by_subj:subject})}catch(e3){if(e3.code===import_jetstream15.JetStreamApiCodes.NoMessageFound)continue;throw e3}if(m2===null)continue;const op=m2.header?.get("KV-Operation");if(op==="DEL"||op==="PURGE"||m2.data.length===0)continue;if(newest===void 0||m2.seq>newest.seq)newest={data:m2.data,seq:m2.seq}}if(newest===void 0)return void 0;return JSON.parse(new TextDecoder().decode(newest.data))}catch(e3){const code2=e3.code;if(code2===10037)return void 0;if(code2===404||/stream not found/i.test(e3?.message??""))return void 0;throw e3}}async ownerMemberships(owner2,lifecycleUid){const recs=await listMembers(await this.membersRegistry(),{owner:owner2});return recs.filter(r2=>r2.lifecycleUid===lifecycleUid&&r2.leaveCursor===void 0).map(r2=>({channel:r2.channel,generation:r2.generation,activated:r2.activated===true}))}async deliveryClassFresh(channel){if(!this.channelKv)return effectiveDeliveryClass(void 0,void 0);const[cfg,defaults]=await Promise.all([isConcreteChannel(channel)?readChannelConfig(this.channelKv,channel):Promise.resolve(void 0),readChannelDefaults(this.channelKv)]);return effectiveDeliveryClass(cfg,defaults)}resolveOwnerByName(name2){const matches=[...this.presence.values()].filter(p2=>p2.card.name.toLowerCase()===name2.toLowerCase());return matches.length===1?matches[0].card.id:void 0}plane3MsgId(entry,keySuffix){return entry.msg.id===""?{}:{msgID:`${entry.msg.id}:${keySuffix}`}}async publishDinbox(principal,lifecycleUid,entry){if(!this.js)return;const p2=parsePrincipalKey(principal);if(!p2)throw new Error(`publishDinbox: "${principal}" is not a valid member principal <owner>.<actor>`);await this.js.publish(dinboxSubject(this.space,p2.owner,p2.actor,lifecycleUid),JSON.stringify(entry),{...this.plane3MsgId(entry,`${principal}:${lifecycleUid}`)})}async fanoutDeliveredSeq(){const info=await this.consumerInfo(chatStream(this.space),FANOUT_DURABLE);return info?.delivered?.stream_seq??0}async durableJoinFor(owner2,channel,lifecycleUid,opts={}){if(!this.js)throw new Error(this.notLiveMsg());await this.manager();const kv=await this.membersRegistry();const existing=await readMember(kv,channel,owner2,lifecycleUid);const open7=existing?.record.state==="durable-active"&&existing.record.leaveCursor===void 0;if(open7&&existing.record.activated)return{durable:true,generation:existing.record.generation};const joinCursor=open7?existing.record.joinCursor:await this.chatFrontier();const generation=open7?existing.record.generation:(existing?.record.generation??0)+1;const base={channel,owner:owner2,lifecycleUid,state:"durable-active",joinCursor,generation,activated:false,writerIdentity:this.card.id,updatedAt:Date.now()};if(!open7){if(opts.aclFence&&!await this.aclAllows(owner2,lifecycleUid,channel))throw new Error(`durableJoin: "${channel}" is no longer within the read ACL of lifecycle ${lifecycleUid} (narrowed or retired); no membership row was written`);const written=await commitMemberRevision(kv,base);if(opts.aclFence)await this.keepRowIfAclAllows(kv,owner2,lifecycleUid,channel,written.revision)}const fence=Math.max(await this.chatFrontier(),await this.fanoutDeliveredSeq());await this.catchupCopy(owner2,lifecycleUid,channel,joinCursor,fence,generation);const activated=await activateMember(kv,channel,owner2,lifecycleUid,generation,joinCursor);if(!activated)return{durable:false,reason:"activation superseded by a concurrent leave or rejoin",generation};return{durable:true,generation}}async keepRowIfAclAllows(kv,owner2,lifecycleUid,channel,revision){let disallowed=false;let why;try{if(await this.aclAllows(owner2,lifecycleUid,channel))return;disallowed=true;why="was narrowed or retired while the row was written"}catch(e3){why=`could not be re-read after the row was written (${e3.message})`}const fail2=(outcome,cause)=>new Error(`durableJoin: the read ACL of lifecycle ${lifecycleUid} ${why}; ${outcome}`,cause===void 0?void 0:{cause});try{if(disallowed)await deleteMember(kv,channel,owner2,lifecycleUid);else await kv.purge(memberKey(channel,owner2,lifecycleUid),{previousSeq:revision})}catch(e3){if(!disallowed&&isCasLoss(e3))throw fail2(`a later write replaced its "${channel}" row, which was left to that write`);throw fail2(`removing its "${channel}" row failed (${e3.message})`,e3)}throw fail2(`its "${channel}" row was removed`)}async durableLeaveFor(owner2,channel,lifecycleUid,expectedGeneration){if(!this.deliveryPlane.plane3)return;const kv=await this.membersRegistry();await tombstoneMember(kv,channel,owner2,lifecycleUid,await this.chatFrontier(),this.card.id,expectedGeneration)}}}});function membershipChange(e3,update){const operation=e3.operation;if(e3.key===MEMBERSHIP_FEED_KEY){let asOf;if(operation==="PUT"){try{asOf=e3.json().observedAt}catch{}}return{type:"heartbeat",revision:e3.revision,update,asOf}}let member;if(operation==="PUT"){try{const rec=e3.json();member={id:e3.key,live:rec.live??[],durable:rec.durable??[],observedAt:rec.observedAt}}catch{}}return{type:"member",id:e3.key,operation,revision:e3.revision,update,member}}function membershipConsumerReleased(err3){return isJetStreamMissing(err3,import_jetstream16.JetStreamApiCodes.ConsumerNotFound,import_jetstream16.JetStreamApiCodes.StreamNotFound)||isPublishPermissionDenied(err3)}var import_transport_node18,import_jetstream16,import_kv8,import_internal2,EndpointSubscriptions;var init_endpoint_subscriptions=__esm({"../../packages/core/dist/endpoint-subscriptions.js"(){"use strict";import_transport_node18=__toESM(require_transport_node(),1);import_jetstream16=__toESM(require_mod4(),1);import_kv8=__toESM(require_mod6(),1);import_internal2=__toESM(require_internal_mod3(),1);init_channels();init_endpoint();init_jetstream_missing();init_kv_scan();init_subjects();EndpointSubscriptions=class{deps;constructor(deps){this.deps=deps}get nc(){return this.deps.nc()}get jsm(){return this.deps.jsm()}get space(){return this.deps.space()}get card(){return this.deps.card()}get stopped(){return this.deps.stopped()}get authed(){return this.deps.authed()}get channels(){return this.deps.channels()}get channelConfigs(){return this.deps.channelConfigs()}get channelDefaults(){return this.deps.channelDefaults()}get chatSubDenied(){return this.deps.chatSubDenied()}get plane3Channels(){return this.deps.plane3Channels()}get readsChannelsOnDemand(){return this.deps.readsChannelsOnDemand()}get membershipFeedKv(){return this.deps.membershipFeedKv()}set membershipFeedKv(kv){this.deps.setMembershipFeedKv(kv)}get membershipFeedWatches(){return this.deps.membershipFeedWatches()}get watchDeletePermissions(){return this.deps.watchDeletePermissions()}notLiveMsg(){return this.deps.notLiveMsg()}readChannels(){return this.deps.readChannels()}armJoin(channels){return this.deps.armJoin(channels)}backfillArmed(frontiers,floorSeq){return this.deps.backfillArmed(frontiers,floorSeq)}subscribeChat(channel){this.deps.subscribeChat(channel)}unsubscribeChat(channel){this.deps.unsubscribeChat(channel)}confirmChatSub(){return this.deps.confirmChatSub()}durableJoinChannel(channel){return this.deps.durableJoinChannel(channel)}durableLeaveChannel(channel,generation,lifecycleUid){return this.deps.durableLeaveChannel(channel,generation,lifecycleUid)}fetchMemberships(channel){return this.deps.fetchMemberships(channel)}recordOwnWatchConsumer(info){return this.deps.recordOwnWatchConsumer(info)}watchConsumerDeleteDenied(stream,name2,owner2){return this.deps.watchConsumerDeleteDenied(stream,name2,owner2)}deleteMembershipConsumer(jsm,stream,name2){return this.deps.deleteMembershipConsumer(jsm,stream,name2)}emit(event,...args){return this.deps.emit(event,...args)}joinedChannels(){return[...this.channels]}async joinChannel(channel){if(!this.jsm)throw new Error(this.notLiveMsg());if(this.channels.includes(channel))return{joined:false,backfilled:0,durable:this.plane3Channels.has(channel)};if(this.readsChannelsOnDemand)await this.readChannels();const armed2=await this.armJoin([channel]);this.subscribeChat(channel);try{await this.confirmChatSub()}catch(e3){this.unsubscribeChat(channel);throw new Error(`cannot join "${channel}": live subscription could not be confirmed (${e3.message})`)}if(this.chatSubDenied.has(channel)){this.unsubscribeChat(channel);throw new Error(`cannot join "${channel}": not within this agent's read ACL (allowSubscribe)`)}this.channels.push(channel);let durable=false;let reason;const family=isChannelFamily(channel);if(!family&&!isConcreteChannel(channel))reason="a pattern with * or the root > has no stored copies; follow a concrete channel or a family such as review.>";else if(family||effectiveDeliveryClass(this.channelConfigs.get(channel),this.channelDefaults)==="durable"){try{const r2=await this.durableJoinChannel(channel);if(r2.durable){this.plane3Channels.set(channel,r2.generation??0);durable=true}else{reason=r2.reason??"durable backstop unavailable"}}catch(e3){reason=`durable backstop unavailable (${e3.message})`}}const backfilled=await this.backfillArmed(armed2);return{joined:true,backfilled,durable,...reason!==void 0?{reason}:{}}}async leaveChannel(channel,legacyDiscoveryMessage){if(!this.jsm)throw new Error(this.notLiveMsg());let left=this.channels.includes(channel);if(this.authed&&(isChannelFamily(channel)||isConcreteChannel(channel))){const memberships=await this.fetchMemberships(channel);if(memberships===void 0&&this.plane3Channels.has(channel))await this.durableLeaveChannel(channel,this.plane3Channels.get(channel));for(const member of memberships??[]){if(member.lifecycleUid===void 0)throw new Error(legacyDiscoveryMessage??"the delivery daemon predates lifecycle-aware membership discovery, so this durable leave was not applied and the channel stays joined; restart the daemon at this version (`cotal up` runs it)");await this.durableLeaveChannel(channel,member.generation,member.lifecycleUid);left=true}if(memberships!==void 0)this.plane3Channels.delete(channel)}this.unsubscribeChat(channel);const i2=this.channels.indexOf(channel);if(i2>=0)this.channels.splice(i2,1);return{left}}async chatRetention(){if(!this.nc)throw new Error(this.notLiveMsg());const mgr=await(0,import_jetstream16.jetstreamManager)(this.nc);let info;try{info=await mgr.streams.info(chatStream(this.space),{subjects_filter:">"})}catch(e3){if(!isJetStreamMissing(e3,import_jetstream16.JetStreamApiCodes.StreamNotFound))throw e3;return{perSender:null,maxAgeMs:null,oldestAt:null,senders:[],stream:false,lastSeq:0}}const senders=[];for(const[subject,messages]of Object.entries(info.state.subjects??{})){const p2=parseSubject(subject);if(p2?.kind==="chat"&&isPrincipalOwnerToken(p2.owner))senders.push({channel:p2.rest,sender:p2.sender,messages})}const cap=info.config.max_msgs_per_subject;const age=info.config.max_age;return{perSender:typeof cap==="number"&&cap>0?cap:null,maxAgeMs:typeof age==="number"&&age>0?Math.round(age/1e6):null,oldestAt:info.state.messages>0?info.state.first_ts:null,senders:senders.sort((a3,b3)=>a3.channel.localeCompare(b3.channel)||a3.sender.localeCompare(b3.sender)),stream:true,lastSeq:info.state.last_seq}}async dmStreamPresent(){if(!this.nc)throw new Error(this.notLiveMsg());try{await(await(0,import_jetstream16.jetstreamManager)(this.nc)).streams.info(dmStream(this.space));return true}catch(e3){if(!isJetStreamMissing(e3,import_jetstream16.JetStreamApiCodes.StreamNotFound))throw e3;return false}}async listChannels(){if(!this.nc)throw new Error(this.notLiveMsg());if(this.readsChannelsOnDemand)await this.readChannels();const mgr=await(0,import_jetstream16.jetstreamManager)(this.nc);const counts=new Map;try{const info=await mgr.streams.info(chatStream(this.space),{subjects_filter:">"});if(info.state.subjects){for(const[subject,count]of Object.entries(info.state.subjects)){const p2=parseSubject(subject);if(p2?.kind==="chat"&&isPrincipalOwnerToken(p2.owner))counts.set(p2.rest,(counts.get(p2.rest)??0)+count)}}}catch(e3){if(!isJetStreamMissing(e3,import_jetstream16.JetStreamApiCodes.StreamNotFound))throw e3}const channels=new Set([...counts.keys(),...this.channelConfigs.keys()]);return[...channels].map(channel=>({channel,messages:counts.get(channel)??0,config:this.channelConfigs.get(channel)})).sort((a3,b3)=>a3.channel.localeCompare(b3.channel))}async membershipFeedRegistry(){if(!this.nc)throw new Error(this.notLiveMsg());this.membershipFeedKv??=await new import_kv8.Kvm(this.nc).open(membershipBucket(this.space));return this.membershipFeedKv}async readMembership(){const kv=await this.membershipFeedRegistry();const members=[];let asOf;let entries;try{entries=await lastKvEntries(kv)}catch(e3){if(!isPublishPermissionDenied(e3))throw e3;throw new Error(`membership read refused for ${this.card.id}: this credential may not publish $JS.API.DIRECT.GET.KV_${membershipBucket(this.space)}, the membership feed read (SPEC Appendix B). A credential minted by an older issuer can lack this grant even when newly minted; upgrade the manager or auth service that issues credentials, then mint a new credential. Reusing credentials or reconnecting does not add the grant.`,{cause:e3})}for(const e3 of entries){if(e3.key===MEMBERSHIP_FEED_KEY){try{asOf=e3.json().observedAt}catch{}continue}try{const rec=e3.json();members.push({id:e3.key,live:rec.live??[],durable:rec.durable??[],observedAt:rec.observedAt})}catch{}}return{asOf,members}}async watchMembership(onChange,onClosed){if(this.stopped)throw new Error("endpoint stopped - cannot watch membership");const watch={onChange,onClosed,stopped:false,arm:Promise.resolve()};this.membershipFeedWatches.add(watch);watch.arm=watch.arm.catch(()=>{}).then(()=>this.armMembershipWatch(watch));try{await watch.arm}catch(err3){watch.stopped=true;this.membershipFeedWatches.delete(watch);await this.disarmMembershipWatch(watch);throw err3}return{stop:async()=>{if(watch.stopPromise)return watch.stopPromise;watch.stopped=true;watch.stopPromise=new Promise((resolve6,reject)=>{watch.resolveStop=resolve6;watch.rejectStop=reject});watch.arm=watch.arm.catch(()=>{}).then(async()=>{await this.disarmMembershipWatch(watch);await this.deleteRetainedMembershipConsumer(watch);this.finishMembershipWatchStop(watch)}).catch(err3=>{watch.rejectStop?.(err3)});return watch.stopPromise}}}async armMembershipWatch(watch){if(watch.stopped)return;const kv=await this.membershipFeedRegistry();await this.deleteRetainedMembershipConsumer(watch);if(!(kv instanceof import_internal2.Bucket))throw new Error("membership watch needs the @nats-io/kv Bucket implementation");const cc=kv._buildCC(">",import_internal2.KvWatchInclude.LastValue,{headers_only:false});const consumer=await kv.js.consumers.getPushConsumer(kv.stream,cc);const info=await consumer.info(true);this.recordOwnWatchConsumer(info);watch.consumer=consumer;const permission2=this.nc&&this.watchDeletePermissions.get(this.nc);if(permission2)this.watchDeletePermissions.set(consumer,permission2);watch.consumerStream=info.stream_name;watch.consumerName=info.name;let replaying=info.num_pending>0;let iter;try{iter=await consumer.consume({callback:jm=>{if(watch.stopped||watch.consumer!==consumer)return;const entry=kv.jmToWatchEntry(jm,!replaying);watch.onChange(membershipChange(entry,!replaying));if(replaying&&jm.info.pending===0){replaying=false;watch.onChange({type:"replayed",revision:entry.revision})}}})}catch(err3){await this.disarmMembershipWatch(watch);throw err3}watch.iter=iter;if(watch.stopped){await this.disarmMembershipWatch(watch);return}if(!replaying)watch.onChange({type:"replayed",revision:0});iter.closed().then(()=>{if(watch.stopped||watch.consumer!==consumer)return;const err3=new Error("membership watch closed");watch.onClosed?.(err3);this.emit("error",err3)}).catch(()=>{})}async deleteRetainedMembershipConsumer(watch){if(!watch.consumerStream||!watch.consumerName)return;if(!this.nc||this.nc.isClosed())return;if(this.watchConsumerDeleteDenied(watch.consumerStream,watch.consumerName,this.nc)){watch.consumerStream=void 0;watch.consumerName=void 0;return}const jsm=await(0,import_jetstream16.jetstreamManager)(this.nc);if(await this.deleteMembershipConsumer(jsm,watch.consumerStream,watch.consumerName)){watch.consumerStream=void 0;watch.consumerName=void 0}}finishMembershipWatchStop(watch){if(!watch.stopped||watch.consumer||watch.iter||watch.consumerStream||watch.consumerName)return;this.membershipFeedWatches.delete(watch);watch.resolveStop?.();watch.resolveStop=void 0;watch.rejectStop=void 0}async disarmMembershipWatch(watch){const iter=watch.iter;const consumer=watch.consumer;watch.iter=void 0;watch.consumer=void 0;try{iter?.stop()}catch{}if(consumer){if(watch.consumerStream&&watch.consumerName&&this.watchConsumerDeleteDenied(watch.consumerStream,watch.consumerName,consumer)){watch.consumerStream=void 0;watch.consumerName=void 0;return}try{const deleted=await consumer.delete();if(deleted){watch.consumerStream=void 0;watch.consumerName=void 0}}catch(err3){if(membershipConsumerReleased(err3)){watch.consumerStream=void 0;watch.consumerName=void 0}else{const closedEpoch=err3 instanceof import_transport_node18.ClosedConnectionError;const timeout=err3 instanceof import_transport_node18.TimeoutError;if(timeout||closedEpoch){this.emit("error",err3)}else{throw err3}}}}}async rearmMembershipWatches(){await Promise.all([...this.membershipFeedWatches].map(async watch=>{watch.arm=watch.arm.catch(()=>{}).then(async()=>{await this.disarmMembershipWatch(watch);await this.deleteRetainedMembershipConsumer(watch);if(!watch.stopped)await this.armMembershipWatch(watch)});try{await watch.arm;this.finishMembershipWatchStop(watch)}catch(err3){this.emit("error",err3)}}))}}}});var import_jetstream17,EndpointChannelDiscovery;var init_endpoint_channel_discovery=__esm({"../../packages/core/dist/endpoint-channel-discovery.js"(){"use strict";import_jetstream17=__toESM(require_mod4(),1);init_channels();init_endpoint();init_jetstream_missing();init_kv_scan();init_subjects();EndpointChannelDiscovery=class{deps;constructor(deps){this.deps=deps}get nc(){return this.deps.nc()}get space(){return this.deps.space()}get card(){return this.deps.card()}get doConsume(){return this.deps.doConsume()}get doWatch(){return this.deps.doWatch()}get doWatchChannels(){return this.deps.doWatchChannels()}get channelKv(){return this.deps.channelKv()}set channelWatchIter(iter){this.deps.setChannelWatchIter(iter)}get channelConfigs(){return this.deps.channelConfigs()}get channelDefaults(){return this.deps.channelDefaults()}set channelDefaults(defaults){this.deps.setChannelDefaults(defaults)}get channelRead(){return this.deps.channelRead()}set channelRead(read){this.deps.setChannelRead(read)}get channelReadGeneration(){return this.deps.channelReadGeneration()}set channelReadGeneration(n2){this.deps.setChannelReadGeneration(n2)}get channelReadApplied(){return this.deps.channelReadApplied()}set channelReadApplied(n2){this.deps.setChannelReadApplied(n2)}notLiveMsg(){return this.deps.notLiveMsg()}bindKvWatch(kv){return this.deps.bindKvWatch(kv)}emitRecoverable(err3){this.deps.emitRecoverable(err3)}emit(event,...args){return this.deps.emit(event,...args)}get readsChannelsOnDemand(){return this.doConsume&&this.doWatchChannels&&!this.doWatch}async readChannels(){if(!this.readsChannelsOnDemand)throw new Error("readChannels is for a consumer that reads presence on demand; this endpoint watches the channel registry or keeps no cache of it");const kv=this.channelKv;if(!kv)throw new Error(this.notLiveMsg());if(this.channelRead)return this.channelRead;const generation=++this.channelReadGeneration;const read=(async()=>{let entries;try{entries=await lastKvEntries(kv)}catch(e3){if(!isPublishPermissionDenied(e3))throw e3;throw new Error(`channel registry read refused for ${this.card.id}: this credential may not publish $JS.API.DIRECT.GET.KV_${channelBucket(this.space)}, the on-demand registry read (SPEC Appendix B). A credential minted by an older issuer can lack this grant even when newly minted; upgrade the manager or auth service that issues credentials, then mint a new credential. Reusing credentials or reconnecting does not add the grant.`,{cause:e3})}if(generation<=this.channelReadApplied)return;this.channelReadApplied=generation;this.channelConfigs.clear();this.channelDefaults={};for(const e3 of entries)this.handleChannelEntry(e3)})();this.channelRead=read;const settled=()=>{if(this.channelRead===read)this.channelRead=void 0};read.then(settled,settled);return read}getChannelConfig(channel){return this.channelConfigs.get(channel)}channelReplay(channel){return effectiveReplay(this.channelConfigs.get(channel),this.channelDefaults)}channelReplayWindow(channel){return this.channelConfigs.get(channel)?.replayWindow??this.channelDefaults.replayWindow}async channelReplayPolicy(channel){if(!this.nc)throw new Error(this.notLiveMsg());const kv=this.channelKv??await openChannelRegistry(this.nc,this.space,{create:false});let cfg;let defaults;try{[cfg,defaults]=await Promise.all([isConcreteChannel(channel)?readChannelConfig(kv,channel):Promise.resolve(void 0),readChannelDefaults(kv)])}catch(e3){if(!isJetStreamMissing(e3,import_jetstream17.JetStreamApiCodes.StreamNotFound))throw e3}return{replay:effectiveReplay(cfg,defaults),window:cfg?.replayWindow??defaults?.replayWindow??null,registered:cfg!==void 0}}channelDeliveryClass(channel){return effectiveDeliveryClass(this.channelConfigs.get(channel),this.channelDefaults)}async startChannelWatch(){if(!this.channelKv)return;const bound=await this.bindKvWatch(this.channelKv);if(!bound)return;const{iter}=bound;this.channelWatchIter=iter;void(async()=>{for await(const e3 of iter)this.handleChannelEntry(e3)})().catch(e3=>this.emit("error",e3))}async readChannelsOnce(){if(!this.channelKv)return;for(const e3 of await lastKvEntries(this.channelKv))this.handleChannelEntry(e3)}handleChannelEntry(e3){const isDefaults=e3.key===CHANNEL_DEFAULTS_KEY;if(isDefaults)this.channelDefaults={};else this.channelConfigs.delete(e3.key);if(e3.operation==="DEL"||e3.operation==="PURGE")return;try{if(isDefaults)this.channelDefaults=decodeChannelEntry(e3);else this.channelConfigs.set(e3.key,decodeChannelEntry(e3))}catch(err3){this.emitRecoverable(new Error(`dropped channel registry entry for key ${JSON.stringify(e3.key)}: ${err3.message}`))}}}}});import{randomUUID as randomUUID7}from"node:crypto";var import_transport_node19,EndpointLiveness;var init_endpoint_liveness=__esm({"../../packages/core/dist/endpoint-liveness.js"(){"use strict";import_transport_node19=__toESM(require_transport_node(),1);init_liveness();init_subjects();EndpointLiveness=class{deps;constructor(deps){this.deps=deps}get nc(){return this.deps.nc()}get space(){return this.deps.space()}get owner(){return this.deps.owner()}get actor(){return this.deps.actor()}get subs(){return this.deps.subs()}get livenessResponders(){return this.deps.livenessResponders()}notLiveMsg(){return this.deps.notLiveMsg()}requestBoundReply(nc,subject,body,reply,timeoutMs){return this.deps.requestBoundReply(nc,subject,body,reply,timeoutMs)}isNoResponders(e3){return this.deps.isNoResponders(e3)}emitRecoverable(err3){this.deps.emitRecoverable(err3)}emit(event,...args){return this.deps.emit(event,...args)}serveLiveness(plane,readState){if(!this.nc)throw new Error(this.notLiveMsg());const held2=this.livenessResponders.get(plane);if(held2)held2.readState=readState;else this.livenessResponders.set(plane,{readState});this.bindLiveness(plane)}bindLiveness(plane){const held2=this.livenessResponders.get(plane);if(!held2||!this.nc)return;if(held2.sub){try{held2.sub.unsubscribe()}catch{}const i2=this.subs.indexOf(held2.sub);if(i2>=0)this.subs.splice(i2,1)}const{readState}=held2;const sub=this.nc.subscribe(livenessServeFilter(this.space,plane),{queue:`live.${plane}`});held2.sub=sub;this.subs.push(sub);const instance=randomUUID7();void(async()=>{for await(const m2 of sub){if(!m2.reply||!m2.reply.startsWith(`${m2.subject}.reply.`)){this.emitRecoverable(new Error(`rejected liveness probe on ${m2.subject}: reply target "${m2.reply??"(none)"}" is not under the sender's own reply subtree`));continue}let responder;try{responder=await readState()}catch{responder="unknown"}const answer={plane,responder,instance};try{m2.respond(JSON.stringify(answer))}catch{}}})().catch(e3=>this.emit("error",e3))}async probeLiveness(plane,timeoutMs=2e3){if(!isLivenessPlane(plane))throw new Error(`liveness: "${plane}" is not a plane this surface answers for (${[...LIVENESS_PLANES].join(", ")})`);if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=livenessSubject(this.space,plane,this.owner,this.actor);const reply=`${reqSubject}.reply.${randomUUID7()}`;let outcome;let answered;let instance;try{const m2=await this.requestBoundReply(this.nc,reqSubject,"",reply,timeoutMs);let body;try{body=m2.json()}catch{body=void 0}const parsed=parseLivenessAnswer(body,plane);outcome=parsed?"replied":"malformed";answered=parsed?.responder;instance=parsed?.instance}catch(e3){outcome=this.isNoResponders(e3)?"noResponders":this.probeFailureOutcome(e3)}const verdict={plane,responder:responderFromProbe(outcome,answered)};return instance===void 0?verdict:{...verdict,instance}}probeFailureOutcome(e3){if(e3 instanceof import_transport_node19.AuthorizationError||e3 instanceof import_transport_node19.PermissionViolationError)return"refused";if(e3 instanceof import_transport_node19.TimeoutError)return"timeout";return"refused"}}}});function pickFree(taken,from,to){const free=[];let lo=from;for(const t2 of[...taken].sort((a3,b3)=>a3-b3)){if(t2-RENEWAL_SPACING_MS>lo)free.push([lo,Math.min(to,t2-RENEWAL_SPACING_MS)]);lo=Math.max(lo,t2+RENEWAL_SPACING_MS);if(lo>=to)break}if(lo<=to)free.push([lo,to]);const total=free.reduce((sum,[a3,b3])=>sum+(b3-a3),0);if(free.length===0)return from+Math.random()*(to-from);let r2=Math.random()*total;for(const[a3,b3]of free){if(r2<=b3-a3)return a3+r2;r2-=b3-a3}return free[free.length-1][1]}function armRenewal(space2,issuedAtMs,expiresAtMs,renew,minDelayMs=0){const now=Date.now();const life=Math.max(0,expiresAtMs-issuedAtMs);const from=Math.max(issuedAtMs+RENEWAL_WINDOW.from*life,now+minDelayMs);const to=Math.max(issuedAtMs+RENEWAL_WINDOW.to*life,from);const taken=armed.get(space2)??new Set;armed.set(space2,taken);const at2=pickFree([...taken],from,to);taken.add(at2);const release=()=>{taken.delete(at2);if(taken.size===0&&armed.get(space2)===taken)armed.delete(space2)};let timer2;const wait=()=>{const left=at2-Date.now();timer2=setTimeout(left>MAX_TIMER_MS2?wait:()=>{release();renew()},Math.min(Math.max(0,left),MAX_TIMER_MS2));timer2.unref?.()};wait();return()=>{clearTimeout(timer2);release()}}function renewalDeadlineMs(issuedAtMs,expiresAtMs){return issuedAtMs+RENEWAL_WINDOW.to*Math.max(0,expiresAtMs-issuedAtMs)}function jitteredBackoffMs(attempt,baseMs,capMs){const step=Math.min(capMs,baseMs*2**attempt);return step/2+Math.random()*(step/2)}var RENEWAL_WINDOW,RENEWAL_SPACING_MS,MAX_TIMER_MS2,armed;var init_renewal=__esm({"../../packages/core/dist/renewal.js"(){"use strict";RENEWAL_WINDOW=Object.freeze({from:.5,to:.8});RENEWAL_SPACING_MS=1e3;MAX_TIMER_MS2=2147483647;armed=new Map}});var import_transport_node20;var init_broker_identity=__esm({"../../packages/core/dist/broker-identity.js"(){"use strict";import_transport_node20=__toESM(require_transport_node(),1);init_identity()}});var init_space_quiescence_resources=__esm({"../../packages/core/dist/space-quiescence-resources.js"(){"use strict";init_subjects();init_endpoint_binding();init_endpoint_records();init_broker_identity()}});var PLACEMENT_COMMANDS,PLACED_LIFECYCLE_COMMANDS;var init_run_driver_grants=__esm({"../../packages/core/dist/run-driver-grants.js"(){"use strict";init_subjects();init_endpoint_subjects();init_endpoint_records();init_run_admission();init_endpoint_binding();init_endpoint_grants();PLACEMENT_COMMANDS=Object.freeze(["describe","resolve-cwd","spawn"]);PLACED_LIFECYCLE_COMMANDS=Object.freeze(["turn"])}});var import_nats_core6,import_jetstream18,import_obj2,TRANSFER_CHUNK_MAX,HEADER_ROOM;var init_transfer=__esm({"../../packages/core/dist/transfer.js"(){"use strict";import_nats_core6=__toESM(require_mod3(),1);import_jetstream18=__toESM(require_mod4(),1);import_obj2=__toESM(require_mod7(),1);init_subjects();init_artifact();init_endpoint_records();TRANSFER_CHUNK_MAX=128*1024;HEADER_ROOM=4*1024}});var import_nkeys7,REMOTE_MANAGER_AUTHORITY_OPERATIONS,REMOTE_MANAGER_MAINTENANCE_OPERATIONS,MANAGED_AGENT_RUNTIME_STATES,MANAGED_AGENT_RUNTIME_READINESS,MANAGED_AGENT_RETIREMENT_PHASES,REMOTE_MANAGER_IDENTITY_NAMES;var init_remote_manager_authority=__esm({"../../packages/core/dist/remote-manager-authority.js"(){"use strict";import_nkeys7=__toESM(require_mod(),1);init_canonical();init_endpoint_error();init_identity();init_subjects();REMOTE_MANAGER_AUTHORITY_OPERATIONS=Object.freeze(["prepare","activate","renew","session","retire","renewStandingBundle","renewRunDriver","transferReader"]);REMOTE_MANAGER_MAINTENANCE_OPERATIONS=Object.freeze(["evict-family-principal","reconcile-registration"]);MANAGED_AGENT_RUNTIME_STATES=Object.freeze(["reserved","creating","bound","create-unknown","closing","closed"]);MANAGED_AGENT_RUNTIME_READINESS=Object.freeze(["ready","bound-not-ready","none"]);MANAGED_AGENT_RETIREMENT_PHASES=Object.freeze(["intent","released","retired","deprovisioned","terminal"]);REMOTE_MANAGER_IDENTITY_NAMES=Object.freeze(["supervisor","executor","serve","goalWriter","sessionLedger"])}});var init_environment_manager_grants=__esm({"../../packages/core/dist/environment-manager-grants.js"(){"use strict";init_endpoint_grants();init_endpoint_binding();init_remote_manager_authority();init_subjects();init_endpoint_subjects()}});var enc5,dec5;var init_run_submission=__esm({"../../packages/core/dist/run-submission.js"(){"use strict";init_canonical();init_endpoint_error();init_run_admission();init_endpoint_subjects();init_endpoint_subjects();enc5=new TextEncoder;dec5=new TextDecoder("utf-8",{fatal:true})}});var init_lifecycle_state=__esm({"../../packages/core/dist/lifecycle-state.js"(){"use strict";init_canonical();init_service_gate();init_endpoint_envelope();init_endpoint_records();init_endpoint_subjects();init_subjects()}});var SPAWN_VIEW_READS;var init_provision_permission_builders=__esm({"../../packages/core/dist/provision-permission-builders.js"(){"use strict";init_event_payloads();init_streams();init_space_deletion_targets();init_broker_identity();init_subjects();init_endpoint_grants();init_endpoint_service();init_endpoint_binding();init_endpoint_subjects();init_issued_authority();init_registry_contract();init_run_admission();init_run_submission();init_endpoint_records();init_lifecycle_state();init_backup();SPAWN_VIEW_READS=Object.freeze(["status","models","resolve-cwd","list-dir","ps"])}});var init_provision_permissions=__esm({"../../packages/core/dist/provision-permissions.js"(){"use strict";init_space_quiescence_resources();init_event_payloads();init_subjects();init_liveness();init_endpoint_grants();init_endpoint_binding();init_endpoint_subjects();init_issued_authority();init_registry_contract();init_run_driver_grants();init_transfer();init_environment_manager_grants();init_backup();init_provision_permission_builders();init_provision_permission_builders()}});function inspectCredHealth(creds,nowSec=Math.floor(Date.now()/1e3)){let claims2;try{claims2=credsClaims(creds)}catch(e3){return{state:"unreadable",error:e3.message}}const{iat,exp}=claims2;if(typeof exp!=="number")return{state:"unbounded",iat};if(typeof iat!=="number")return{state:"unreadable",iat:void 0,exp,error:"user JWT carries exp but no iat - cannot place the renewal point"};const renewAt=Math.floor(iat+.75*(exp-iat));if(nowSec>=exp)return{state:"expired",iat,exp,renewAt};if(nowSec>=renewAt)return{state:"near-expiry",iat,exp,renewAt};return{state:"healthy",iat,exp,renewAt}}var import_nkeys8,FIVE_MINUTES,MAX_CONTROL_LINE_BYTES,CONNECT_ENVELOPE_OVERHEAD_BYTES,MAX_MINTED_JWT_BYTES,STANDING_RENEWABLE_TTL_SEC,ROTATION_RENEWED_TTL_SEC,CREDENTIAL_LIFETIMES,LIFETIME_TTL_SNAP,BASE_LIMITS,DATA_LIMITS,SYS_LIMITS;var init_provision_jwt=__esm({"../../packages/core/dist/provision-jwt.js"(){"use strict";init_nkey_signer();init_jwt();import_nkeys8=__toESM(require_mod(),1);init_subjects();init_endpoint_grants();init_endpoint_service();init_service_gate();init_service_authority_limits();init_issued_authority();init_run_driver_grants();init_lifecycle_state();init_environment_manager_grants();init_identity();init_backup();init_provision_permissions();FIVE_MINUTES=5*60;MAX_CONTROL_LINE_BYTES=65536;CONNECT_ENVELOPE_OVERHEAD_BYTES=512;MAX_MINTED_JWT_BYTES=MAX_CONTROL_LINE_BYTES-CONNECT_ENVELOPE_OVERHEAD_BYTES;STANDING_RENEWABLE_TTL_SEC=24*60*60;ROTATION_RENEWED_TTL_SEC=30*24*60*60;CREDENTIAL_LIFETIMES={agent:{class:"mixed",note:"manager children, foreground spawn/join, and `cotal mint` static outputs all use this profile; split or repair flow required before default exp"},"manager-caller":{class:"mixed",note:"short-lived user-auth view bound to the bearer expiry and one manager instance"},observer:{class:"static-operator-managed",note:"out-of-band dashboard/audit credential from `cotal mint`"},admin:{class:"static-operator-managed",note:"out-of-band elevated dashboard/audit credential from `cotal mint`"},supervisor:{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"manager's always-on endpoint; the manager holds the DATA seed and self-remints via the endpoint creds source"},delivery:{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"server-side Plane-3 daemon; seed-less - the manager re-signs .cotal/delivery.creds for the SAME nkey, requests delivery-admin reloadCreds for explicit adoption, and the endpoint source re-read is only a backstop"},"membership-rw":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"membership feed writer; seed-less - the manager re-signs the membership-rw.creds store key for the SAME nkey, the feed adopts it on a 75% preflight-proven renewal timer (its active self-heal), and delivery-admin reloadCreds is the explicit adoption on top"},provisioner:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"setup/spawn provisioning window only"},deprovisioner:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"target-pinned teardown window only"},"retirement-requester":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one despawn's retirement request window; request+reply only"},"lifecycle-executor":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one static lifecycle operation's 13.1 state-write window (activation / terminal / renewal ledger append)"},"endpoint-serve-executor":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one endpoint registration/serve-mint window (13.1 epgate CAS + epcred stage/revoke + eprepair cursor for one (endpoint, instanceId))"},operator:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"send/dm/join/probe-style operator command"},purger:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"history purge command"},backup:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"offline snapshot phase; exact stream and delivery subject, memory-only"},restore:{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"offline restore initiation or exact-ID upload phase, memory-only"},"space-quiescence-reader":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"host-only idle-work observation; no writes, ACKs, consumer creation or renewal"},probe:{class:"one-shot",defaultTtlSeconds:60,note:"connect-only preflight"},"channel-writer":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"channel registry mutation command"},"channel-purger":{class:"mixed",note:"one-shot for CLI, standing inside web; split or renewal required before default exp"},teardown:{class:"one-shot",note:"space teardown can be long/destructive; needs TTL budget/remint guard before default exp"},"membership-store-recreate":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one stopped-space conversion of the derived membership stream from File to Memory; exact stream info/delete only"},"issued-store-recreate":{class:"one-shot",defaultTtlSeconds:30*60,note:"one `up --recreate-issued-stores` step: snapshot and delete the two pre-retention issued-authority stores of one space; 30 minutes bounds a large store's snapshot"},"control-caller-privileged":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"ps/start control call"},"control-caller-admin":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"stop/attach admin control call"},deployer:{class:"one-shot",note:"manifest deploy spans planning/launch/ledger; needs near-expiry guard or remint before default exp"},"endpoint-serve":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"per-instance endpoint serve credential (SPEC 13.9); the managing authority re-mints on renewal and on takeover (new epoch), and the 13.1 barrier revokes the superseded one"},"goal-writer":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"self-mediated goal-writer for spawn-as-action; the manager re-mints for the SAME nkey on renewal, disjoint from the serve credential"},"session-caller":{class:"one-shot",defaultTtlSeconds:24*60*60,note:"per-session console/CLI caller cred: rails-only for ONE \xA713.6 session; TTL-BOUND to the session (the face mints with expiresAt = the session exp; the 24h default is the SESSION_GRANT_MAX_TTL ceiling, never a standing lifetime); NEVER renewed - a new session mints a new cred"},"dm-reader":{class:"mixed",note:"user-auth own-DM reader view: one dm_ durable's INFO/NEXT/ACK, bound to the bearer expiry (which the IdP proof bounds); renewed by re-exchange, never a standing credential"},"session-serving":{class:"one-shot",defaultTtlSeconds:24*60*60,note:"per-session SERVING cred: rails-only for ONE \xA713.6 session, the mirror of session-caller with the directions swapped; minted at redemption and TTL-BOUND to the session (the 24h default is the SESSION_GRANT_MAX_TTL ceiling, never a standing lifetime); NEVER renewed - a new session mints a new cred, and the session's terminal revokes this one by name"},"session-ledger":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"manager's session LEDGER: the dedicated sessions-bucket `session.<id>` rows and NOTHING else - no session rail of any shape. Standing because SPEC 13.6 makes it the durable revocation authority that must survive the serving endpoint; the manager re-mints for the SAME nkey on the half-TTL loop (the goal-writer precedent)"},"run-driver":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"one workflow run's driver, per takeover attempt (SPEC 14.6): the hosting manager mints it when it takes the run over and re-mints for the SAME nkey on renewal; a new takeover mints a new one"},"run-mediator":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"manager",note:"trusted workflow host operations, bound to one run and attempt; kept on the hosting process's connection"},"run-operator":{class:"one-shot",defaultTtlSeconds:60,note:"one served run-status / run-ps / run-answer call (SPEC 14.3): the hosting manager mints it per call on its own connection, never the serve rails; 60s bounds a copied cred to a minute"},"registry-reader":{class:"standing-renewable",defaultTtlSeconds:60*60,renewalOwner:"registry host",note:"the registry's reads (SPEC 13.20), no write of any shape; the evidence-store read is stream-scoped, so it can read every recorded ceiling in the space (a NAMED RESIDUAL), and one hour bounds a copied credential; the process hosting the registry re-mints it"},issuer:{class:"mixed",defaultTtlSeconds:FIVE_MINUTES,renewalOwner:"auth-service",note:"renewed as the auth plane's held session for connect-time issuance (re-minted before exp, closed with the plane); one-shot for every other issuance window and for a lifecycle terminal's issuance retirement (SPEC 13.15)"},"run-admitter":{class:"one-shot",defaultTtlSeconds:60,note:"one hosted run's admission record create, or its revocation marker (SPEC 14.8); 60s bounds a copied cred to a minute"},"transfer-writer":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one carried resume per CLI call: one object's chunk and meta subjects in one instance's transfer bucket"},"transfer-reader":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one transcript-receive or sweep over the minting instance's own transfer bucket"},"endpoint-evictor":{class:"one-shot",defaultTtlSeconds:60,note:"one re-registration's verify-evict window: a scoped delivery-admin caller that kicks+verifies the SUPERSEDED serve family before the epoch advances; 60s bounds a copied cred to a minute"},"remote-manager":{class:"standing-renewable",defaultTtlSeconds:STANDING_RENEWABLE_TTL_SEC,renewalOwner:"auth-service",note:"the scoped remote manager lifecycle: own lease/presence plus same-owner agent provisioning; issued only by the typed supervise protocol, never by `cotal mint` or a raw view/profile string"},"environment-bootstrap":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"one admitted environment's bootstrap caller; explicit expiry capped by admission and five minutes"},"environment-manager-supervisor":{class:"standing-renewable",renewalOwner:"environment-authority",note:"own lease/presence/liveness; explicit expiry capped by admission, no auth-store access"},"environment-manager-executor":{class:"standing-renewable",renewalOwner:"environment-authority",note:"own admitted authority instance RPC; explicit expiry capped by admission, no direct store access"},"environment-manager-goal-writer":{class:"standing-renewable",renewalOwner:"environment-authority",note:"manager goal rows without the auth-read belt; explicit expiry capped by admission"},"membership-observer":{class:"rotation-renewed",defaultTtlSeconds:ROTATION_RENEWED_TTL_SEC,renewalOwner:"system-account rotation",note:"$SYS-account CONNZ observer; NOT online-renewable ($SYS seed dies at `up`) - bounded exp, renewed only by rotateSystemAccount + broker restart; doctor warns near expiry"},"account-census":{class:"one-shot",defaultTtlSeconds:FIVE_MINUTES,note:"Host-only account CONNZ and account-qualified replies; at most five minutes, no KICK or client-side renewal"},"connection-evictor":{class:"rotation-renewed",defaultTtlSeconds:ROTATION_RENEWED_TTL_SEC,renewalOwner:"system-account rotation",note:"$SYS-account KICK-only live-eviction cred; same rotation-renewed posture as the observer"}};for(const p2 of Object.values(CREDENTIAL_LIFETIMES))Object.freeze(p2);Object.freeze(CREDENTIAL_LIFETIMES);LIFETIME_TTL_SNAP=new Map(Object.entries(CREDENTIAL_LIFETIMES).map(([k2,p2])=>[k2,p2.defaultTtlSeconds]));BASE_LIMITS={subs:-1,conn:-1,leaf:-1,imports:-1,exports:-1,data:-1,payload:-1,wildcards:true};DATA_LIMITS={...BASE_LIMITS,mem_storage:-1,disk_storage:-1};SYS_LIMITS={...BASE_LIMITS,mem_storage:0,disk_storage:0}}});var init_provision_resources=__esm({"../../packages/core/dist/provision-resources.js"(){"use strict";init_subjects();init_identity();init_provision_jwt();init_provision_permissions()}});var init_provision_server_config=__esm({"../../packages/core/dist/provision-server-config.js"(){"use strict";init_provision_jwt()}});var init_provision=__esm({"../../packages/core/dist/provision.js"(){"use strict";init_provision_permissions();init_provision_jwt();init_provision_resources();init_provision_server_config()}});import{createConnection,isIP}from"node:net";function authOpts(a3){const tls=a3.tls?{}:void 0;if(a3.bearer){if(a3.creds||a3.token||a3.user||a3.pass)throw new Error("bearer (user-mode auth) is mutually exclusive with creds/token/user/pass");if(!a3.sentinelCreds)throw new Error("user-mode bearer requires sentinelCreds");return{authenticator:[nativeCredsAuthenticator(a3.sentinelCreds),(0,import_transport_node21.tokenAuthenticator)(a3.bearer)],tls}}if(a3.creds){if(a3.token||a3.user||a3.pass)throw new Error("creds are mutually exclusive with token/user/pass auth");const creds=a3.creds;const authenticator=nonce4=>{const presented=typeof creds==="function"?creds():creds;const authenticated=nativeCredsAuthenticator(presented)(nonce4);a3.onCreds?.(presented);return authenticated};return{authenticator,tls}}return{token:a3.token,user:a3.user,pass:a3.pass,tls}}function bearerExpiryMs(bearer){return bearerLifetimeMs(bearer,0).expiresAtMs}function bearerLifetimeMs(bearer,adoptedAtMs){const payload=bearer.split(".")[1];if(!payload)throw new Error("user-mode bearer is not a JWT (no payload segment)");let claims2;try{claims2=JSON.parse(Buffer.from(payload,"base64url").toString("utf8"))}catch{throw new Error("user-mode bearer payload is not valid base64url JSON")}if(typeof claims2.exp!=="number")throw new Error("user-mode bearer is missing a numeric exp claim");const expiresAtMs=claims2.exp*1e3;return{issuedAtMs:Math.min(typeof claims2.iat==="number"?claims2.iat*1e3:adoptedAtMs,expiresAtMs),expiresAtMs}}function bearerRenewalDeadlineMs(bearer,adoptedAtMs){const{issuedAtMs,expiresAtMs}=bearerLifetimeMs(bearer,adoptedAtMs);return renewalDeadlineMs(issuedAtMs,expiresAtMs)}function decodeBearerPrincipal(bearer){const payload=bearer.split(".")[1];if(!payload)throw new Error("user-mode bearer is not a JWT (no payload segment)");let claims2;try{claims2=JSON.parse(Buffer.from(payload,"base64url").toString("utf8"))}catch{throw new Error("user-mode bearer payload is not valid base64url JSON")}const owner2=claims2.sub,actor2=claims2.act?.actor;if(typeof owner2!=="string"||typeof actor2!=="string")throw new Error("user-mode bearer is missing a string sub (owner) / act.actor claim");return{owner:owner2,actor:actor2}}function describeStatusError(err3){if(err3 instanceof import_transport_node21.PermissionViolationError){return new Error(`NATS permission denied: cannot ${err3.operation} "${err3.subject}" - check this endpoint's ACLs (a denied peer looks "absent" rather than blocked)`,{cause:err3})}return err3}function kvWatchConsumer(iter){const consumer=iter._data;if(!consumer)throw new Error("KV watch carries no consumer - the pinned nats.js changed shape");return consumer}function isPublishPermissionDenied(e3){const typed=e3 instanceof import_transport_node21.PermissionViolationError?e3:e3?.cause instanceof import_transport_node21.PermissionViolationError?e3.cause:void 0;return typed?.operation==="publish"}function wsServers(servers){return/^wss?:\/\//i.test((servers.split(",")[0]??"").trim())}function defaultProbeTimeoutMs(servers){return wsServers(servers)?5e3:1e3}function dialerFor(servers){if(!wsServers(servers))return(opts=>(0,import_transport_node21.connect)(withDialedTlsHost(servers,opts)));return(opts=>{const{tls,...rest}=opts??{};const targets=Array.isArray(rest.servers)?rest.servers:String(rest.servers??servers).split(",");if(tls&&targets.some(target2=>!/^wss:\/\//i.test(String(target2).trim())))return Promise.reject(new Error("TLS-required WebSocket connections must use wss:// for every server"));return(0,import_nats_core7.wsconnect)(rest)})}function withDialedTlsHost(servers,opts){const urls=servers.split(",").map(url2=>url2.trim()).filter(Boolean);const tls=opts?.tls;if(urls.length!==1||tls===null||tls===void 0&&!/^tls:\/\//i.test(urls[0]))return opts;let host;try{({host}=hostPort(urls[0]))}catch{return opts}return isIP(host)?{...opts,tls:{host,...tls}}:opts}function hostPort(server){const raw=(server.split(",")[0]??"").trim();const scheme=raw.match(/^([a-z][a-z0-9+.-]*):\/\//i)?.[1]?.toLowerCase();const first=raw.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"");const u2=new URL(`http://${first}`);const fallback=scheme==="wss"?443:scheme==="ws"?80:4222;return{host:u2.hostname,port:u2.port?Number(u2.port):fallback}}function tcpInfoProbe(server,timeoutMs){return new Promise(resolve6=>{let socket;let done=false;let connected=false;const finish=live=>{if(done)return;done=true;try{socket?.destroy()}catch{}resolve6(live)};let host,port;try{({host,port}=hostPort(server))}catch{return resolve6(false)}socket=createConnection({host,port});socket.setTimeout(timeoutMs);let buf="";socket.on("data",chunk=>{buf+=chunk.toString("utf8");const nl=buf.indexOf("\r\n");if(nl===-1){if(buf.length>4096)finish(false);return}const line=buf.slice(0,nl);const brace=line.indexOf("{");if(!/^INFO\b/.test(line)||brace===-1)return finish(false);try{finish({authRequired:JSON.parse(line.slice(brace))?.auth_required===true})}catch{finish(false)}});socket.on("connect",()=>{connected=true});socket.on("timeout",()=>finish(connected?"silent":false));socket.on("error",()=>finish(false));socket.on("close",()=>finish(false))})}function tcpDialable(server,timeoutMs){return new Promise(resolve6=>{let socket;let done=false;const finish=dialable=>{if(done)return;done=true;try{socket?.destroy()}catch{}resolve6(dialable)};let host,port;try{({host,port}=hostPort(server))}catch{return resolve6(false)}socket=createConnection({host,port});socket.setTimeout(timeoutMs);socket.on("connect",()=>finish(true));socket.on("timeout",()=>finish(false));socket.on("error",()=>finish(false));socket.on("close",()=>finish(false))})}function isAuthRejection(e3){return e3 instanceof import_transport_node21.AuthorizationError||e3 instanceof import_transport_node21.UserAuthenticationExpiredError}function retryAfterMs(e3){const seconds=e3?.retryAfterSeconds;return typeof seconds==="number"&&Number.isFinite(seconds)&&seconds>0?seconds*1e3:0}async function probeConnect(server=DEFAULT_SERVER,opts={}){const timeoutMs=opts.timeoutMs??defaultProbeTimeoutMs(server);const started=Date.now();const gate=opts.tls||wsServers(server)?tcpDialable:tcpInfoProbe;const greeting=await gate(server,timeoutMs);if(!greeting)return classifyProbeFailure(void 0,opts);if(greeting==="silent")return classifyProbeFailure(void 0,opts,false,"timeout");try{const nc=await dialerFor(server)({servers:server,timeout:Math.max(1,timeoutMs-(Date.now()-started)),reconnect:false,maxReconnectAttempts:0,...authOpts(opts)});await nc.close();return{ok:true}}catch(e3){return classifyProbeFailure(e3,opts,greeting!==true&&greeting.authRequired)}}function classifyProbeFailure(e3,opts,authRequired=false,otherwise="unreachable"){if(typeof opts.creds==="string"){try{if(inspectCredHealth(opts.creds).state==="expired")return{ok:false,reason:"stale-auth"}}catch{}}if(e3 instanceof import_transport_node21.UserAuthenticationExpiredError)return{ok:false,reason:"stale-auth"};if(e3 instanceof import_transport_node21.AuthorizationError)return{ok:false,reason:"auth-required"};if(e3 instanceof import_transport_node21.TimeoutError)return{ok:false,reason:"timeout"};if(e3 instanceof import_transport_node21.ConnectionError&&e3.message==="server does not support 'tls'")return{ok:false,reason:"tls-unsupported"};if(authRequired&&e3?.code==="ECONNRESET")return{ok:false,reason:"auth-required",inferred:true};return{ok:false,reason:otherwise}}var import_transport_node21,import_nats_core7,import_jetstream19,import_kv9,DEFAULT_SERVER,RepeatedRefusal;var init_endpoint_dial=__esm({"../../packages/core/dist/endpoint-dial.js"(){"use strict";import_transport_node21=__toESM(require_transport_node(),1);import_nats_core7=__toESM(require_mod3(),1);import_jetstream19=__toESM(require_mod4(),1);import_kv9=__toESM(require_mod6(),1);init_creds_authenticator();init_renewal();init_provision();DEFAULT_SERVER="nats://127.0.0.1:4222";RepeatedRefusal=class extends Error{}}});function deliveryLimitOf(value){if(value===void 0||value==="")return PLANE3_MAX_MSGS_PER_SUBJECT;if(value==="none")return null;if(!/^[1-9]\d*$/.test(value)||!Number.isSafeInteger(Number(value)))throw new Error(`plane-3 delivery: ${DELIVERY_LIMIT_HEADER} ${JSON.stringify(value)} is not a count`);return Number(value)}function fitHistoryPage(items,budget){const enc8=new TextEncoder;let used=enc8.encode(JSON.stringify({ok:true,data:{items:[],complete:false}})).length;let first=items.length;for(let i2=items.length-1;i2>=0;i2--){const size=enc8.encode(JSON.stringify(items[i2])).length+1;if(used+size>budget)break;used+=size;first=i2}return first===items.length?[]:items.slice(first)}var MAX_TAKES_IN_FLIGHT,ANYCAST_SWEEP_MS,ANYCAST_TAKE_TIMEOUT_MS,MAX_TIMER_MS3,DmDurableMissingError,DmBindRefusedError;var init_endpoint_options=__esm({"../../packages/core/dist/endpoint-options.js"(){"use strict";init_backup_config();MAX_TAKES_IN_FLIGHT=64;ANYCAST_SWEEP_MS=10*60*1e3;ANYCAST_TAKE_TIMEOUT_MS=5e3;MAX_TIMER_MS3=2147483647;DmDurableMissingError=class extends Error{stream;durable;code="dm-durable-missing";constructor(stream,durable){super(`dm-durable-missing: durable "${durable}" on stream "${stream}" does not exist; this endpoint binds an existing durable and never creates one`);this.stream=stream;this.durable=durable;this.name="DmDurableMissingError"}};DmBindRefusedError=class extends Error{stream;durable;code="dm-bind-refused";constructor(stream,durable,cause){super(`dm-bind-refused: binding durable "${durable}" on stream "${stream}" was refused (${cause instanceof Error?cause.message:String(cause)})`,{cause});this.stream=stream;this.durable=durable;this.name="DmBindRefusedError"}}}});import{randomUUID as randomUUID8}from"node:crypto";var EndpointCredentials;var init_endpoint_credentials=__esm({"../../packages/core/dist/endpoint-credentials.js"(){"use strict";init_endpoint_dial();init_endpoint_options();init_renewal();init_identity();init_deadline();init_request_safe_reconnect();EndpointCredentials=class _EndpointCredentials{deps;constructor(deps){this.deps=deps}get nc(){return this.deps.nc()}get bearerSource(){return this.deps.bearerSource()}get owner(){return this.deps.owner()}get actor(){return this.deps.actor()}get space(){return this.deps.space()}get currentBearer(){return this.deps.currentBearer()}set currentBearer(value){this.deps.setCurrentBearer(value)}get bearerAdoptedAtMs(){return this.deps.bearerAdoptedAtMs()}set bearerAdoptedAtMs(value){this.deps.setBearerAdoptedAtMs(value)}get bearerRenewalFailures(){return this.deps.bearerRenewalFailures()}set bearerRenewalFailures(value){this.deps.setBearerRenewalFailures(value)}get cancelBearerRenewal(){return this.deps.cancelBearerRenewal()}set cancelBearerRenewal(value){this.deps.setCancelBearerRenewal(value)}get stopped(){return this.deps.stopped()}get presentedExp(){return this.deps.presentedExp()}set presentedExp(value){this.deps.setPresentedExp(value)}get currentCreds(){return this.deps.currentCreds()}set currentCreds(value){this.deps.setCurrentCreds(value)}get credsSource(){return this.deps.credsSource()}get connId(){return this.deps.connId()}get overlapOnConnectionRenewal(){return this.deps.overlapOnConnectionRenewal()}get onConnection(){return this.deps.onConnection()}get servers(){return this.deps.servers()}get card(){return this.deps.card()}get token(){return this.deps.token()}get user(){return this.deps.user()}get pass(){return this.deps.pass()}get userMode(){return this.deps.userMode()}get sentinelCreds(){return this.deps.sentinelCreds()}get tls(){return this.deps.tls()}get ownedConnections(){return this.deps.ownedConnections()}get authExpiryReconnectTimer(){return this.deps.authExpiryReconnectTimer()}set authExpiryReconnectTimer(value){this.deps.setAuthExpiryReconnectTimer(value)}get credsTxnsRunning(){return this.deps.credsTxnsRunning()}set credsTxnsRunning(value){this.deps.setCredsTxnsRunning(value)}get credsTxn(){return this.deps.credsTxn()}set credsTxn(value){this.deps.setCredsTxn(value)}get reconnecting(){return this.deps.reconnecting()}get reestablishing(){return this.deps.reestablishing()}get requestsAwaitingReply(){return this.deps.requestsAwaitingReply()}get residentSwap(){return this.deps.residentSwap()}set residentSwap(value){this.deps.setResidentSwap(value)}emitRecoverable(err3){void this.deps.emitRecoverable(err3)}kickBackoff(){void this.deps.kickBackoff()}armCredsRefresh(delayMs){void this.deps.armCredsRefresh(delayMs)}reconnect(){return this.deps.reconnect()}emit(event,...args){return this.deps.emit(event,...args)}on(event,listener){void this.deps.on(event,listener)}off(event,listener){void this.deps.off(event,listener)}static BEARER_MIN_RENEWAL_MS=5e3;static BEARER_RETRY_MS=5e3;static BEARER_RETRY_CAP_MS=6e4;async refreshBearer(initial=false){try{const bearer=await this.bearerSource();const claims2=decodeBearerPrincipal(bearer);if(claims2.owner!==this.owner||claims2.actor!==this.actor)throw new Error(`bearer source returned principal ${claims2.owner}.${claims2.actor}, expected ${this.owner}.${this.actor}`);const expiryMs=bearerExpiryMs(bearer);const held2=this.currentBearer;if(held2!==void 0){if(expiryMs<=Date.now())throw new Error("the bearer source returned a token that has already expired - nothing adopted");if(bearer===held2&&Date.now()>=bearerRenewalDeadlineMs(held2,this.bearerAdoptedAtMs))throw new Error("the bearer source re-served the token already held and it cannot carry another cycle (the auth service has not issued a fresh one) - nothing adopted")}if(bearer!==held2)this.bearerAdoptedAtMs=Date.now();this.currentBearer=bearer;this.bearerRenewalFailures=0;const{issuedAtMs,expiresAtMs}=bearerLifetimeMs(bearer,this.bearerAdoptedAtMs);this.armBearerTimer(armRenewal(this.space,issuedAtMs,expiresAtMs,()=>void this.renewBearerOnTimer(),_EndpointCredentials.BEARER_MIN_RENEWAL_MS))}catch(e3){if(initial)throw e3;if(this.bearerRenewalFailures===0)this.emitRecoverable(new Error(`bearer refresh failed (${e3 instanceof Error?e3.message:String(e3)}) - retrying with backoff; this connection dies at its current token's expiry if the auth service stays down`));const named=retryAfterMs(e3);const delay3=named>0?named:jitteredBackoffMs(this.bearerRenewalFailures,_EndpointCredentials.BEARER_RETRY_MS,_EndpointCredentials.BEARER_RETRY_CAP_MS);this.bearerRenewalFailures++;const timer2=setTimeout(()=>void this.renewBearerOnTimer(),delay3);timer2.unref?.();this.armBearerTimer(()=>clearTimeout(timer2))}}armBearerTimer(cancel){this.cancelBearerRenewal?.();this.cancelBearerRenewal=cancel;if(this.stopped)cancel()}async renewBearerOnTimer(){const held2=this.currentBearer;await this.refreshBearer();if(this.stopped||this.currentBearer===held2)return;if(this.nc&&!this.nc.isClosed())await this.swapConnectionOntoFreshCreds();else this.kickBackoff()}bearerForWire(){const bearer=this.currentBearer;if(bearer!==void 0&&bearerExpiryMs(bearer)>Date.now())return bearer;throw new Error(this.bearerSource?"this endpoint's user bearer has expired and renewal through the auth exchange is failing - not presenting the expired token to the broker; retrying with backoff":"this endpoint's user bearer has expired and it holds no bearer source to renew it - re-authenticate and rebuild the endpoint (construct it with a bearer FUNCTION for standing renewal)")}static CREDS_RETRY_MS=6e4;static presentableCreds(creds,opts){const{exp}=credsClaims(creds);if(typeof exp==="number"&&exp*1e3<=Date.now())throw new Error(opts.renewable?"this endpoint's creds have expired and renewal is failing - not presenting the expired credential to the broker; retrying with backoff":"this endpoint's creds have expired and it holds no creds source to renew them - replace the credential and rebuild the endpoint (pass a creds FUNCTION for standing renewal)");return creds}presentCreds(){const creds=this.credsForWire();this.presentedExp=credsClaims(creds).exp;return creds}presentBearer(){const bearer=this.bearerForWire();this.presentedExp=bearerExpiryMs(bearer)/1e3;return bearer}credsForWire(){if(!this.currentCreds)throw new Error(this.credsSource?"this endpoint has no credential to present yet (the creds source has not returned one) - not dialing without auth material":"this endpoint was constructed with an empty creds string - not dialing without auth material (an empty credential is not anonymous access)");return _EndpointCredentials.presentableCreds(this.currentCreds,{renewable:Boolean(this.credsSource)})}wireCreds(){return this.credsForWire()}static assertRenewableGeneration(candidate2,current,delayMs){const{exp}=credsClaims(candidate2);if(typeof exp==="number"&&exp*1e3<=Date.now())throw new Error("the creds source returned an already-expired credential (its `exp` is in the past) - nothing adopted; the renewal owner has not re-signed it, or the store is serving a stale generation");if(current!==void 0&&credsFingerprint(candidate2)===credsFingerprint(current)&&delayMs<=0)throw new Error("the creds source still holds the previous generation past its renewal point (the renewal owner has not re-signed it) - nothing adopted")}static PREFLIGHT_MS=4e3;static RESIDENT_SWAP_DEFER_MS=250;static RESIDENT_SWAP_GATE_MS=5e3;static RELOAD_DEADLINE_MS=12e3;async fetchFreshCreds(){const creds=await this.credsSource();const id2=idFromCreds(creds);if(id2!==this.connId)throw new Error(`creds source returned identity ${id2}, expected ${this.connId} - renewal may not swap the connection's nkey`);const delay3=credsRenewalDelayMs(creds);_EndpointCredentials.assertRenewableGeneration(creds,this.currentCreds,delay3);this.currentCreds=creds;this.armCredsRefresh(delay3);const{iat,exp}=credsClaims(creds);return{iat,exp}}async swapConnectionOntoFreshCreds(){const nc=this.nc;if(!(nc&&!this.stopped))return;const overlap=this.overlapOnConnectionRenewal&&this.onConnection?await this.openRenewalOverlap().catch(()=>void 0):void 0;try{await nc.reconnect().catch(()=>{});if(overlap&&!nc.isClosed())await withDeadline(nc.flush(),1e4,()=>new Error("resident renewal flush did not finish")).catch(()=>{});if(this.nc===nc&&!this.stopped)this.armAuthExpiryReconnectFence(nc)}finally{if(overlap&&!overlap.isClosed())await this.closeWithoutLibraryReconnect(overlap).catch(()=>{})}}async openRenewalOverlap(){const overlap=await dialerFor(this.servers)({servers:this.servers,noAsyncTraces:true,name:`cotal:${this.card.name}:renewal`,inboxPrefix:`_INBOX_renew_${randomUUID8()}`,maxReconnectAttempts:0,...authOpts({token:this.token,user:this.user,pass:this.pass,creds:this.currentCreds!==void 0||this.credsSource?()=>this.presentCreds():void 0,bearer:this.userMode?()=>this.presentBearer():void 0,sentinelCreds:this.sentinelCreds,tls:this.tls})});this.ownedConnections.add(overlap);try{this.onConnection?.(overlap);await withDeadline(overlap.flush(),5e3,()=>new Error("renewal overlap flush did not finish"));return overlap}catch(error51){await this.closeWithoutLibraryReconnect(overlap).catch(()=>{});throw error51}}disableLibraryReconnect(nc){const protocol=nc.protocol;if(protocol?.options)protocol.options.reconnect=false}async closeWithoutLibraryReconnect(nc){if(!nc)return;this.disableLibraryReconnect(nc);await nc.close();if(!nc.isClosed())throw new Error("endpoint connection closure is unproved; consumer custody must be retained");this.ownedConnections.delete(nc)}armAuthExpiryReconnectFence(nc){clearTimeout(this.authExpiryReconnectTimer);this.authExpiryReconnectTimer=void 0;const credsExp=this.currentCreds&&credsClaims(this.currentCreds).exp;const expiryMs=this.userMode&&this.currentBearer?bearerExpiryMs(this.currentBearer):typeof credsExp==="number"?credsExp*1e3:void 0;if(expiryMs===void 0||this.stopped)return;const delay3=Math.max(0,expiryMs-Date.now()-500);this.authExpiryReconnectTimer=delay3>MAX_TIMER_MS3?setTimeout(()=>{if(this.nc===nc)this.armAuthExpiryReconnectFence(nc)},MAX_TIMER_MS3):setTimeout(()=>{if(this.nc===nc)this.disableLibraryReconnect(nc)},delay3);this.authExpiryReconnectTimer.unref?.()}async refreshCreds(initial=false){try{await this.fetchFreshCreds()}catch(e3){if(initial)throw e3;this.emitRecoverable(new Error(`creds refresh failed (${e3 instanceof Error?e3.message:String(e3)}) - retrying; this connection dies at its current JWT's expiry if renewal keeps failing`));this.armCredsRefresh(_EndpointCredentials.CREDS_RETRY_MS)}}runCredsTxn(fn2){const counted=async()=>{this.credsTxnsRunning++;try{return await fn2()}finally{this.credsTxnsRunning--}};const next=this.credsTxn.then(counted,counted);this.credsTxn=next.then(()=>void 0,()=>void 0);return next}async adoptFreshCreds(opts={}){const deadline=opts.deadline??Date.now()+_EndpointCredentials.RELOAD_DEADLINE_MS;if(Date.now()>deadline)throw new Error("reloadCreds: the request deadline elapsed while queued behind another credential transaction; nothing adopted");const candidate2=await withDeadline(this.credsSource(),deadline-Date.now(),()=>new Error("reloadCreds: the creds source did not return before the daemon deadline; nothing adopted"));const id2=idFromCreds(candidate2);if(id2!==this.connId)throw new Error(`creds source returned identity ${id2}, expected ${this.connId} - renewal may not swap the connection's nkey`);if(opts.expected!==void 0&&credsFingerprint(candidate2)!==opts.expected)throw new Error("reloadCreds: re-read credential generation did not match the expected re-signed generation (a different store, or a torn/stale read); nothing adopted");const proven=_EndpointCredentials.presentableCreds(candidate2,{renewable:true});const probe=await probeConnect(this.servers,{creds:proven,tls:this.tls,timeoutMs:Math.max(500,Math.min(_EndpointCredentials.PREFLIGHT_MS,deadline-Date.now()))});if(!probe.ok)throw new Error(`reloadCreds: the broker did not accept the re-signed credential (${probe.reason}); nothing adopted`);if(Date.now()>deadline)throw new Error("reloadCreds: the proof exceeded the daemon deadline; nothing adopted");const delay3=credsRenewalDelayMs(candidate2);_EndpointCredentials.assertRenewableGeneration(candidate2,this.currentCreds,delay3);this.currentCreds=candidate2;this.armCredsRefresh(delay3);this.emit("creds-adopted",credsClaims(candidate2));return credsClaims(candidate2)}async renewCredsOnTimer(){const deadline=Date.now()+_EndpointCredentials.RELOAD_DEADLINE_MS;try{await this.runCredsTxn(()=>this.adoptFreshCreds({deadline}));await this.swapConnectionOntoFreshCreds()}catch(e3){this.emitRecoverable(new Error(`creds refresh failed (${e3 instanceof Error?e3.message:String(e3)}) - retrying; this connection dies at its current JWT's expiry if renewal keeps failing`));this.armCredsRefresh(_EndpointCredentials.CREDS_RETRY_MS)}}async refreshCredsRequestSafe(){if(!this.credsSource)throw new Error("credential refresh requires a creds source");const nc=this.nc;if(!nc&&!this.stopped&&(this.reconnecting||this.reestablishing))return await this.reconnect();if(!nc||this.stopped)throw new Error("credential refresh requires a running endpoint");const deadline=Date.now()+_EndpointCredentials.RELOAD_DEADLINE_MS;await this.runCredsTxn(async()=>{await this.adoptFreshCreds({deadline});if(this.nc!==nc||this.stopped)throw new Error("endpoint connection changed during credential refresh");await requestSafeReconnect(nc,()=>this.requestsAwaitingReply.get(nc)?.size??0);if(this.nc===nc&&!this.stopped)this.armAuthExpiryReconnectFence(nc)})}async reloadCreds(expected){if(!this.credsSource)throw new Error("reloadCreds: this endpoint has no creds source (a static cred cannot be renewed in place)");const deadline=Date.now()+_EndpointCredentials.RELOAD_DEADLINE_MS;const{iat,exp}=await this.runCredsTxn(()=>this.adoptFreshCreds({expected,deadline}));return{identity:this.connId,iat,exp}}scheduleResidentSwap(){if(this.stopped)return;const swap=new Promise(resolve6=>{setTimeout(resolve6,_EndpointCredentials.RESIDENT_SWAP_DEFER_MS).unref?.()}).then(async()=>{const back=this.transportBack(_EndpointCredentials.RESIDENT_SWAP_GATE_MS);await this.swapConnectionOntoFreshCreds();await back}).finally(()=>{if(this.residentSwap===swap)this.residentSwap=void 0});this.residentSwap=swap}transportBack(ms){return new Promise(resolve6=>{const done=()=>{clearTimeout(timer2);this.off("transport",seen);resolve6()};const seen=state=>{if(state.connected)done()};const timer2=setTimeout(done,ms);timer2.unref?.();this.on("transport",seen)})}}}});var import_jetstream20,EndpointProvisioning;var init_endpoint_provisioning=__esm({"../../packages/core/dist/endpoint-provisioning.js"(){"use strict";import_jetstream20=__toESM(require_mod4(),1);init_jetstream_missing();init_permission_denied();init_streams();init_subjects();EndpointProvisioning=class{deps;constructor(deps){this.deps=deps}get jsm(){return this.deps.jsm()}get space(){return this.deps.space()}get authed(){return this.deps.authed()}notLiveMsg(){return this.deps.notLiveMsg()}manager(){return this.deps.manager()}async ensureStreams(){if(!this.jsm)throw new Error(this.notLiveMsg());await createSpaceStreams(this.jsm,this.space)}async ensureOpenSpaceStreams(){if(this.authed)throw new Error(`the streams of ${this.space} come from its broker's setup on an authenticated space; a sender does not create them`);await createSpaceStreams(await this.manager(),this.space)}async provisionDmInbox(owner2,actor2,lifecycleUid){await this.ensureDmDurable(owner2,actor2,lifecycleUid,{})}async ensureDmDurable(owner2,actor2,lifecycleUid,opts){const jsm=await this.manager();const stream=dmStream(this.space);const name2=dmDurable(owner2,actor2,lifecycleUid);try{await jsm.consumers.info(stream,name2);return}catch(e3){if(!isJetStreamMissing(e3,import_jetstream20.JetStreamApiCodes.ConsumerNotFound))throw e3}const frontier=(await jsm.streams.info(stream)).state.last_seq;try{await jsm.consumers.add(stream,dmDurableConfig(this.space,owner2,actor2,lifecycleUid,{...opts,activationFrontier:frontier}))}catch(e3){try{await jsm.consumers.info(stream,name2);return}catch(probeError){if(isPermissionDenied(probeError))throw probeError}throw e3}}async provisionDlvInbox(owner2,actor2,lifecycleUid){const jsm=await this.manager();await jsm.consumers.add(dlvStream(this.space),dlvDurableConfig(this.space,owner2,actor2,lifecycleUid))}async provisionTaskQueue(role){const jsm=await this.manager();await jsm.consumers.add(taskStream(this.space),taskDurableConfig(this.space,role))}}}});var EndpointBootMemberships;var init_endpoint_boot_memberships=__esm({"../../packages/core/dist/endpoint-boot-memberships.js"(){"use strict";init_subjects();EndpointBootMemberships=class{deps;constructor(deps){this.deps=deps}get channels(){return this.deps.channels()}get plane3Channels(){return this.deps.plane3Channels()}get pendingBootJoins(){return this.deps.pendingBootJoins()}get stopped(){return this.deps.stopped()}requestDelivery(op,args,timeoutMs){return this.deps.requestDelivery(op,args,timeoutMs)}requireLifecycleUid(what2){return this.deps.requireLifecycleUid(what2)}deliveryClassFresh(channel){return this.deps.deliveryClassFresh(channel)}durableJoinChannel(channel){return this.deps.durableJoinChannel(channel)}membershipPause(attempt){return this.deps.membershipPause(attempt)}isNoResponders(e3){return this.deps.isNoResponders(e3)}emitRecoverable(err3){this.deps.emitRecoverable(err3)}async fetchMemberships(channel){let reply;try{reply=await this.requestDelivery("listMemberships",{lifecycleUid:this.requireLifecycleUid("listing durable memberships"),...channel===void 0?{}:{channel}},5e3)}catch(e3){if(this.isNoResponders(e3))return void 0;throw e3}if(!reply.ok)throw new Error(reply.error??"listMemberships failed");return reply.data?.memberships??[]}async armBootDurableMemberships(){for(const channel of this.channels){if(this.plane3Channels.has(channel))continue;if(!isChannelFamily(channel)){if(!isConcreteChannel(channel))continue;const cls=await this.deliveryClassFresh(channel);if(cls!=="durable")continue}try{const r2=await this.durableJoinChannel(channel);if(r2.durable)this.plane3Channels.set(channel,r2.generation??0);else void this.reconcileBootJoin(channel)}catch(e3){if(!this.isNoResponders(e3))this.emitRecoverable(e3);void this.reconcileBootJoin(channel)}}}async reconcileBootJoin(channel){if(this.pendingBootJoins.has(channel))return;this.pendingBootJoins.add(channel);for(let attempt=0;;attempt++){await this.membershipPause(attempt);if(this.stopped||!this.channels.includes(channel)||this.plane3Channels.has(channel)){this.pendingBootJoins.delete(channel);return}try{const r2=await this.durableJoinChannel(channel);if(r2.durable){this.plane3Channels.set(channel,r2.generation??0);this.pendingBootJoins.delete(channel);return}}catch(e3){if(attempt===0&&!this.isNoResponders(e3))this.emitRecoverable(new Error(`channel "${channel}": boot durable self-join not yet established - retrying until the delivery daemon is reachable (${e3.message})`))}}}hasDurableMembership(channel){return this.plane3Channels.has(channel)}}}});function isUsableMessageId(id2){return typeof id2==="string"}function kindFromParsed(kind){switch(kind){case"chat":return"channel";case"inst":return"dm";case"svc":return"anycast";default:throw new Error(`cannot derive a message kind from subject kind "${kind}"`)}}function isFromSubjectSender(msg,parsed){return isRecord(msg)&&isRecord(msg.from)&&msg.from.id===parsed.sender&&isPrincipalOwnerToken(parsed.owner)}function authenticatedMessage(msg,parsed){if(parsed.kind==="chat"||parsed.kind==="evp")return authenticatedChannelMessage(msg,parsed.rest);if(parsed.kind==="inst")return authenticatedDmMessage(msg,parsed.rest);if(parsed.kind==="svc")return authenticatedAnycastMessage(msg,parsed.rest);return msg}function authenticatedDmMessage(msg,to){if(msg.to===to&&msg.channel===void 0&&msg.toService===void 0)return msg;const{channel:_channel,toService:_toService,...base}=msg;return{...base,to}}function authenticatedAnycastMessage(msg,toService){if(msg.toService===toService&&msg.to===void 0&&msg.channel===void 0)return msg;const{to:_to,channel:_channel,...base}=msg;return{...base,toService}}function dmOnlyDelivery(m2,ackWaitMs,nc){const open7=what2=>{if(!nc||nc.isClosed())throw new Error(`DM-only ${what2} refused: the connection that delivered this copy is closed; the broker will redeliver it`)};return{ack:()=>{open7("ack");m2.ack()},nak:()=>{open7("nak");m2.nak()},durable:true,redelivery:{deliveryCount:m2.info.deliveryCount,ackWaitMs,working:()=>{open7("in-progress signal");m2.working()}}}}function historyMessageFromDelivery(m2){let raw;try{raw=m2.json()}catch{return void 0}if(!isHistoryDrainEnvelope(raw))return void 0;if(!isVerifiedHistoryRow(raw))return void 0;const parsed=parseSubject(m2.subject);if(!parsed||!isFromSubjectSender(raw,parsed))return void 0;return authenticatedMessage(raw,parsed)}function isVerifiedHistoryRow(row){if(typeof row.from.name!=="string")return false;if(row.from.role!==void 0&&typeof row.from.role!=="string")return false;if(typeof row.ts!=="number"||!Number.isFinite(row.ts))return false;if(typeof row.space!=="string")return false;if(!Array.isArray(row.parts)||!row.parts.every(isReadableMessagePart))return false;if(row.mentions!==void 0&&(!Array.isArray(row.mentions)||!row.mentions.every(name2=>typeof name2==="string")))return false;if(row.replyTo!==void 0&&typeof row.replyTo!=="string")return false;if(row.contextId!==void 0&&typeof row.contextId!=="string")return false;return true}function isReadableMessagePart(value){return isRecord(value)&&typeof value.kind==="string"}function isHistoryDrainEnvelope(value){return isRecord(value)&&isUsableMessageId(value.id)&&isRecord(value.from)}var init_endpoint_messages=__esm({"../../packages/core/dist/endpoint-messages.js"(){"use strict";init_subjects();init_endpoint_inbound()}});import{EventEmitter}from"node:events";import{randomUUID as randomUUID9}from"node:crypto";var import_transport_node22,import_jetstream21,import_jetstream22,import_kv10,promptsSeqs,principalServers,CotalEndpoint;var init_endpoint=__esm({"../../packages/core/dist/endpoint.js"(){"use strict";init_endpoint_history();init_endpoint_history();init_native_connection();init_connection_cleanup();import_transport_node22=__toESM(require_transport_node(),1);init_liveness();init_endpoint_presence();init_endpoint_presence();init_identity();init_broker_floor();init_deadline();init_secret_store();init_endpoint_invoke();init_endpoint_envelope();init_endpoint_grants();init_endpoint_subjects();init_endpoint_serve();init_endpoint_call();init_agent_endpoint();init_process_runtime();init_issued_authority();init_registry_client();init_jetstream_missing();init_agent_file();init_resolve();init_presence_heartbeat();init_streams();import_jetstream21=__toESM(require_mod4(),1);import_jetstream22=__toESM(require_mod4(),1);import_kv10=__toESM(require_mod6(),1);init_members();init_acls();init_endpoint_delivery_lease();init_endpoint_delivery_plane();init_endpoint_control_plane();init_endpoint_messaging();init_endpoint_durable_backstop();init_endpoint_subscriptions();init_endpoint_channel_discovery();init_endpoint_liveness();init_endpoint_credentials();init_endpoint_provisioning();init_endpoint_boot_memberships();init_endpoint_inbound();init_channels();init_endpoint_records();init_anycast_requests();init_subjects();init_permission_denied();init_endpoint_dial();init_endpoint_dial();init_endpoint_options();init_endpoint_options();init_endpoint_messages();init_endpoint_messages();promptsSeqs=new Map;principalServers=new Map;CotalEndpoint=class _CotalEndpoint extends EventEmitter{card;space;channels;allowSubscribe;servers;token;user;pass;credsSource;currentCreds;credsTimer;watchDeletePermissions=new WeakMap;userMode=false;bearerSource;currentBearer;presentedExp;cancelBearerRenewal;bearerRenewalFailures=0;bearerRefusalSurfaced=false;bearerAdoptedAtMs=0;authExpiryReconnectTimer;sentinelCreds;tls;transportPingIntervalMs;transportMaxPingOut;transportConnectTimeoutMs;heartbeatMs;ttlMs;doRegister;doWatch;doWatchChannels;readOnce;doConsume;dmOnly;dmOnlyInFlight;ackWaitMs;inactiveThresholdMs;nc;requestsAwaitingReply=new Map;onConnection;overlapOnConnectionRenewal;beforeBind;js;jsm;kv;channelKv;channelWatchIter;kvWatchDeletes=new Set;kvWatchBinds=new Set;membersKv;aclKv;managerLeaseKv;daemonRenewalLeaseRevision;membershipFeedKv;membershipFeedWatches=new Set;deliveryPlane=new EndpointDeliveryPlane({ackWaitMs:()=>this.ackWaitMs,actor:()=>this.actor,owner:()=>this.owner,allowSubscribe:()=>this.allowSubscribe,anycastUnavailable:()=>this.anycastUnavailable,card:()=>this.card,js:()=>this.js,jsm:()=>this.jsm,nc:()=>this.nc,ownLifecycleUid:()=>this.ownLifecycleUid,residentSwap:()=>this.residentSwap,space:()=>this.space,stopped:()=>this.stopped,streamMsgs:()=>this.streamMsgs,subs:()=>this.subs,userMode:()=>this.userMode,watchDeletePermissions:()=>this.watchDeletePermissions,maxPayload:()=>this.maxPayload,aclForAlias:(...args)=>this.aclForAlias(...args),channelHistory:(...args)=>this.channelHistory(...args),deliveryClassFresh:(...args)=>this.deliveryClassFresh(...args),durableJoinFor:(...args)=>this.durableJoinFor(...args),durableLeaveFor:(...args)=>this.durableLeaveFor(...args),ownerMemberships:(...args)=>this.ownerMemberships(...args),ownsDeliveryLease:(...args)=>this.ownsDeliveryLease(...args),readDeliveryLease:(...args)=>this.readDeliveryLease(...args),readDeliveryLeaseEntry:(...args)=>this.readDeliveryLeaseEntry(...args),reloadCreds:(...args)=>this.reloadCreds(...args),serveControl:(...args)=>this.serveControl(...args),aclRegistry:(...args)=>this.aclRegistry(...args),membersRegistry:(...args)=>this.membersRegistry(...args),armAnycastRequests:(...args)=>this.armAnycastRequests(...args),deliveryAnycast:(...args)=>this.deliveryAnycast(...args),dropAnycastRequests:(...args)=>this.dropAnycastRequests(...args),manager:(...args)=>this.manager(...args),notLiveMsg:(...args)=>this.notLiveMsg(...args),plane3MsgId:(...args)=>this.plane3MsgId(...args),publishDinbox:(...args)=>this.publishDinbox(...args),resolveOwnerByName:(...args)=>this.resolveOwnerByName(...args),scheduleResidentSwap:(...args)=>this.scheduleResidentSwap(...args),sendMentionNotice:(...args)=>this.sendMentionNotice(...args),emit:(event,...args)=>this.emit(event,...args)});takeServeSub;anycastAuthority;taskEpoch;anycastUnavailable;anycastSweep;takesInFlight=0;channelConfigs=new Map;channelDefaults={};channelRead;channelReadGeneration=0;channelReadApplied=0;history=new EndpointHistory({connection:()=>this.nc,jetstream:()=>this.js,manager:()=>this.jsm,setManager:manager=>{this.jsm=manager},space:()=>this.space,owner:()=>this.owner,actor:()=>this.actor,userMode:()=>this.userMode,connectionId:()=>this.connId,card:()=>this.card,notLiveMsg:()=>this.notLiveMsg(),requireLifecycleUid:operation=>this.requireLifecycleUid(operation),requestDelivery:(op,args)=>this.requestDelivery(op,args),deleteConsumerIfPresent:(stream,name2)=>this.deleteConsumerIfPresent(stream,name2),joinPolicyFresh:channel=>this.joinPolicyFresh(channel),chatMayHaveLost:(subject,sinceSeq)=>this.chatMayHaveLost(subject,sinceSeq),emit:(event,...args)=>this.emit(event,...args),decodeHistory:historyMessageFromDelivery,isRecord,isUsableMessageId,isFromSubjectSender,authenticatedMessage,isPublishPermissionDenied});subs=[];taps=[];livenessResponders=new Map;principalServes=new Map;promptsPresence;streamMsgs=[];chatSubs=new Map;chatSubDenied=new Set;plane3Channels=new Map;pendingDurableLeave=new Map;pendingBootJoins=new Set;chatSubRefusals=new WeakSet;reportedSubRefusals=new WeakSet;ownWatchDeletePrefixes=new Set;firstConnect=true;heartbeatTimer;sweepTimer;deliveryLease=new EndpointDeliveryLease({card:()=>this.card,space:()=>this.space,connection:()=>this.nc,epoch:()=>this.presenceEpoch,notLiveMsg:()=>this.notLiveMsg(),deleteWatchConsumer:iter=>this.deleteOwnConsumer(kvWatchConsumer(iter)),recoverable:error51=>this.emitRecoverable(error51),emit:(event,error51)=>this.emit(event,error51)});presence=new EndpointPresence({card:()=>this.card,space:()=>this.space,bucket:()=>this.kv,connection:()=>this.nc,lifecycleUid:()=>this.ownLifecycleUid,prompts:()=>this.servedPrompts(),ttlMs:()=>this.ttlMs,registers:()=>this.doRegister,watches:()=>this.doWatch,readsOnce:()=>this.readOnce,stopped:()=>this.stopped,reconnecting:()=>this.reconnecting,epoch:()=>this.presenceEpoch,notLiveMsg:()=>this.notLiveMsg(),bindWatch:kv=>this.bindKvWatch(kv),retireWatch:iter=>this.retireKvWatch(iter),emit:(event,value)=>this.emit(event,value),recoverable:error51=>this.emitRecoverable(error51),isPublishPermissionDenied});presenceEpoch=0;stopped=false;stopPromise;startPromise;ownedConnections=new Set;nativeBound=false;credsTxnsRunning=0;rebuildPromise;reconnecting=false;reestablishing=false;backoffResolve;backoffTimer;membershipPauses=new Set;retryMs=3e3;retryAttempt=0;connId;owner;actor;actorIsEphemeral;ownLifecycleUid;backfillFloor;acceptedToken;issuedGeneration;resolvedServices=new Map;serviceInvocations=new WeakMap;resolvedCommandServices=new Map;activeGoalFollowers=new Set;splitsRecovered=0;get principal(){return{owner:this.owner,actor:this.actor}}get splitRecoveryCount(){return this.splitsRecovered}get presenceBindingDropCount(){return this.presence.bindingDropCount}requireLifecycleUid(what2){if(!this.ownLifecycleUid)throw new Error(`${what2} requires this endpoint's lifecycleUid (EndpointOptions.lifecycleUid): dm/dlv/chathist broker resources are lifecycle-keyed names (SPEC 13.1)`);return this.ownLifecycleUid}constructor(opts){super();this.on("transport",state=>{this.nativeBound=state.connected});let selfMintedConnId=false;this.space=opts.space;assertValidName(opts.card.name);assertValidKind(opts.card.kind);if(opts.card.role!==void 0)assertValidRole(opts.card.role);if(opts.bearer){if(opts.creds||opts.token||opts.user||opts.pass)throw new Error("bearer (user-mode auth) is mutually exclusive with creds/token/user/pass");if(!opts.sentinelCreds)throw new Error("user-mode bearer requires sentinelCreds (the shared auth-account creds presented alongside it)")}if(opts.bearer){this.userMode=true;if(typeof opts.bearer==="function"){if(!opts.card.owner||!opts.card.actor)throw new Error("a bearer source requires explicit card.owner + card.actor (no bearer to derive them from at construction)");this.owner=opts.card.owner;this.actor=opts.card.actor;this.bearerSource=opts.bearer}else{const claims2=decodeBearerPrincipal(opts.bearer);if(opts.card.owner&&opts.card.owner!==claims2.owner)throw new Error(`card.owner ${opts.card.owner} != bearer owner ${claims2.owner}`);if(opts.card.actor&&opts.card.actor!==claims2.actor)throw new Error(`card.actor ${opts.card.actor} != bearer actor ${claims2.actor}`);this.owner=claims2.owner;this.actor=claims2.actor;this.currentBearer=opts.bearer}this.connId=assertInboxConnId(`ibx${randomUUID9().replace(/-/g,"")}`);this.sentinelCreds=opts.sentinelCreds;this.actorIsEphemeral=false}else{if(typeof opts.creds==="function"){if(!opts.card.id)throw new Error("a creds source requires an explicit card.id (no cred to derive the identity from at construction)");this.credsSource=opts.creds;this.connId=opts.card.id;selfMintedConnId=false}else{const credId=opts.creds?idFromCreds(opts.creds):void 0;if(opts.card.id&&credId&&opts.card.id!==credId)throw new Error(`card.id ${opts.card.id} != creds identity ${credId} - they must be the same nkey`);this.currentCreds=opts.creds;selfMintedConnId=opts.card.id===void 0&&credId===void 0;this.connId=opts.card.id??credId??randomUUID9().replace(/-/g,"")}this.owner=opts.card.owner??DEV_OWNER;this.actor=opts.card.actor??this.connId;this.actorIsEphemeral=opts.card.actor===void 0&&selfMintedConnId}this.ownLifecycleUid=opts.lifecycleUid!==void 0?assertLifecycleToken(opts.lifecycleUid):this.authed?void 0:mintLifecycleUid();if(opts.backfillFloor!==void 0){if(!Number.isInteger(opts.backfillFloor)||opts.backfillFloor<0)throw new Error(`EndpointOptions.backfillFloor must be a non-negative integer stream sequence, got ${opts.backfillFloor}`);this.backfillFloor=opts.backfillFloor}if(opts.acceptedToken!==void 0){if(!opts.creds)throw new Error("EndpointOptions.acceptedToken names a static issuance and needs creds beside it (SPEC 13.15)");this.acceptedToken=assertGeneration(opts.acceptedToken,"acceptedToken")}const principal=principalKey(this.owner,this.actor);this.card={...opts.card,id:principal.key,owner:this.owner,actor:this.actor};this.presence.configureEnvironment((opts.environment===void 0?process.env.COTAL_ENVIRONMENT:opts.environment)?.trim()||void 0);this.servers=opts.servers??DEFAULT_SERVER;this.token=opts.token;this.user=opts.user;this.pass=opts.pass;this.tls=opts.tls??false;for(const[label,value]of[["transportPingIntervalMs",opts.transportPingIntervalMs],["transportMaxPingOut",opts.transportMaxPingOut],["transportConnectTimeoutMs",opts.transportConnectTimeoutMs]]){if(value!==void 0&&(!Number.isSafeInteger(value)||value<=0))throw new Error(`EndpointOptions.${label} must be a positive safe integer`)}if(opts.transportPingIntervalMs===void 0!==(opts.transportMaxPingOut===void 0))throw new Error("EndpointOptions transportPingIntervalMs and transportMaxPingOut must be configured together");this.onConnection=opts.onConnection;this.overlapOnConnectionRenewal=opts.overlapOnConnectionRenewal===true;this.beforeBind=opts.beforeBind;this.transportPingIntervalMs=opts.transportPingIntervalMs??1e4;this.transportMaxPingOut=opts.transportMaxPingOut??2;this.transportConnectTimeoutMs=opts.transportConnectTimeoutMs;this.channels=opts.channels??[];this.allowSubscribe=opts.allowSubscribe;this.heartbeatMs=opts.heartbeatMs??2e3;this.ttlMs=opts.ttlMs??6e3;this.doRegister=opts.registerPresence??true;this.doWatch=opts.watchPresence??true;this.doWatchChannels=opts.watchChannels??true;this.doConsume=opts.consume??true;this.readOnce=opts.readOnce??false;if(this.readOnce&&(this.doConsume||this.doRegister))throw new Error("EndpointOptions.readOnce requires consume and registerPresence false: a one-time read cannot keep a consumer's channel cache or its own presence current");if(opts.dmOnly!==void 0){if(typeof opts.dmOnly.handler!=="function")throw new Error("EndpointOptions.dmOnly.handler must be a function");const settle=opts.dmOnly.settleTimeoutMs;if(settle!==void 0&&(!Number.isSafeInteger(settle)||settle<=0))throw new Error("EndpointOptions.dmOnly.settleTimeoutMs must be a positive safe integer");if(!this.authed)throw new Error("EndpointOptions.dmOnly requires creds or a bearer: it binds a provisioned durable and never creates one");if(!this.doConsume||this.doRegister||this.doWatch||this.doWatchChannels||this.readOnce)throw new Error("EndpointOptions.dmOnly requires consume true and registerPresence, watchPresence, watchChannels and readOnce false");if(this.channels.length||opts.card.role||opts.acceptedToken!==void 0)throw new Error("EndpointOptions.dmOnly takes no channels, role or acceptedToken: the endpoint reads only its own DM durable");this.requireLifecycleUid("EndpointOptions.dmOnly");this.dmOnly=opts.dmOnly}this.presence.seedChannelModes(opts.channelModes);this.ackWaitMs=opts.ackWaitMs??6e4;this.inactiveThresholdMs=opts.inactiveThresholdMs??6e5}ref(){return{id:this.card.id,name:this.card.name,role:this.card.role}}get authed(){return Boolean(this.currentCreds||this.credsSource)||this.userMode}start(){if(this.startPromise)return this.startPromise;const flight=this.startOnce().finally(()=>{if(this.startPromise===flight)this.startPromise=void 0});this.startPromise=flight;return flight}async startOnce(){try{await this.connectAndBind()}catch(error51){if(!this.stopped)throw error51}if(await this.tearDownIfStopped())return;this.superviseConnection()}emitRecoverable(err3){this.emit("warning",err3)}residentSwap;credsTxn=Promise.resolve();credentials=new EndpointCredentials({nc:()=>this.nc,bearerSource:()=>this.bearerSource,owner:()=>this.owner,actor:()=>this.actor,space:()=>this.space,currentBearer:()=>this.currentBearer,setCurrentBearer:value=>{this.currentBearer=value},bearerAdoptedAtMs:()=>this.bearerAdoptedAtMs,setBearerAdoptedAtMs:value=>{this.bearerAdoptedAtMs=value},bearerRenewalFailures:()=>this.bearerRenewalFailures,setBearerRenewalFailures:value=>{this.bearerRenewalFailures=value},cancelBearerRenewal:()=>this.cancelBearerRenewal,setCancelBearerRenewal:value=>{this.cancelBearerRenewal=value},stopped:()=>this.stopped,presentedExp:()=>this.presentedExp,setPresentedExp:value=>{this.presentedExp=value},currentCreds:()=>this.currentCreds,setCurrentCreds:value=>{this.currentCreds=value},credsSource:()=>this.credsSource,connId:()=>this.connId,overlapOnConnectionRenewal:()=>this.overlapOnConnectionRenewal,onConnection:()=>this.onConnection,servers:()=>this.servers,card:()=>this.card,token:()=>this.token,user:()=>this.user,pass:()=>this.pass,userMode:()=>this.userMode,sentinelCreds:()=>this.sentinelCreds,tls:()=>this.tls,ownedConnections:()=>this.ownedConnections,authExpiryReconnectTimer:()=>this.authExpiryReconnectTimer,setAuthExpiryReconnectTimer:value=>{this.authExpiryReconnectTimer=value},credsTxnsRunning:()=>this.credsTxnsRunning,setCredsTxnsRunning:value=>{this.credsTxnsRunning=value},credsTxn:()=>this.credsTxn,setCredsTxn:value=>{this.credsTxn=value},reconnecting:()=>this.reconnecting,reestablishing:()=>this.reestablishing,requestsAwaitingReply:()=>this.requestsAwaitingReply,residentSwap:()=>this.residentSwap,setResidentSwap:value=>{this.residentSwap=value},emitRecoverable:err3=>this.emitRecoverable(err3),kickBackoff:()=>this.kickBackoff(),armCredsRefresh:delayMs=>this.armCredsRefresh(delayMs),reconnect:()=>this.reconnect(),emit:(event,...args)=>this.emit(event,...args),on:(event,listener)=>{this.on(event,listener)},off:(event,listener)=>{this.off(event,listener)}});refreshBearer(initial=false){return this.credentials.refreshBearer(initial)}bearerForWire(){return this.credentials.bearerForWire()}presentCreds(){return this.credentials.presentCreds()}presentBearer(){return this.credentials.presentBearer()}wireCreds(){return this.credentials.wireCreds()}disableLibraryReconnect(nc){return this.credentials.disableLibraryReconnect(nc)}closeWithoutLibraryReconnect(nc){return this.credentials.closeWithoutLibraryReconnect(nc)}armAuthExpiryReconnectFence(nc){return this.credentials.armAuthExpiryReconnectFence(nc)}refreshCreds(initial=false){return this.credentials.refreshCreds(initial)}renewCredsOnTimer(){return this.credentials.renewCredsOnTimer()}refreshCredsRequestSafe(){return this.credentials.refreshCredsRequestSafe()}reloadCreds(expected){return this.credentials.reloadCreds(expected)}scheduleResidentSwap(){return this.credentials.scheduleResidentSwap()}armCredsRefresh(delayMs){if(this.stopped)return;clearTimeout(this.credsTimer);this.credsTimer=delayMs>MAX_TIMER_MS3?setTimeout(()=>this.armCredsRefresh(delayMs-MAX_TIMER_MS3),MAX_TIMER_MS3):setTimeout(()=>void this.renewCredsOnTimer(),Math.max(1e3,delayMs));this.credsTimer.unref?.()}async connectAndBind(){try{await this.bindConnection()}catch(error51){await this.closeFailedBind();throw error51}}async bindConnection(){this.clearConnectionScoped();if(this.bearerSource){if(!this.currentBearer)await this.refreshBearer(true);else if(this.bearerRenewalFailures===0&&Date.now()>=bearerRenewalDeadlineMs(this.currentBearer,this.bearerAdoptedAtMs))await this.refreshBearer()}if(this.credsSource){const stale=!this.currentCreds||credsRenewalDelayMs(this.currentCreds)<=0;if(stale)await this.refreshCreds(!this.currentCreds)}if(this.userMode){try{this.bearerForWire();this.bearerRefusalSurfaced=false}catch(e3){if(!this.bearerRefusalSurfaced){this.bearerRefusalSurfaced=true;throw e3}throw new RepeatedRefusal(e3.message)}}let watchDeletePermission;this.nc=await dialerFor(this.servers)({servers:this.servers,noAsyncTraces:true,name:this.userMode?this.connId:`cotal:${this.card.name}`,inboxPrefix:`_INBOX_${this.connId}`,...this.transportPingIntervalMs===void 0?{}:{pingInterval:this.transportPingIntervalMs},...this.transportMaxPingOut===void 0?{}:{maxPingOut:this.transportMaxPingOut},...this.transportConnectTimeoutMs===void 0?{}:{timeout:this.transportConnectTimeoutMs},...authOpts({token:this.token,user:this.user,pass:this.pass,creds:this.currentCreds!==void 0||this.credsSource?()=>this.presentCreds():void 0,bearer:this.userMode?()=>this.presentBearer():void 0,sentinelCreds:this.sentinelCreds,tls:this.tls,onCreds:creds=>{watchDeletePermission=void 0;try{const nats=credsClaims(creds).nats;if(nats?.pub!==void 0)watchDeletePermission=importNativeSubjectPermissions({pub:nats.pub}).publish}catch{}}})});this.watchDeletePermissions.set(this.nc,()=>watchDeletePermission);this.ownedConnections.add(this.nc);const owned=this.nc;void owned.closed().then(()=>this.ownedConnections.delete(owned));this.onConnection?.(this.nc);requireBrokerFloor(this.nc);this.armAuthExpiryReconnectFence(this.nc);this.watchStatus();this.js=(0,import_jetstream21.jetstream)(this.nc);if(this.dmOnly){await this.beforeBind?.();if(this.stopped)return;await this.bindDmOnly(this.dmOnly);if(this.stopped)return;this.emit("connection",{connected:true});return}if(this.acceptedToken!==void 0){const ref=await readAcceptedRow(this.nc,this.space,this.acceptedToken);const uid2=this.requireLifecycleUid("an issued endpoint");if(ref.owner!==this.owner||ref.actor!==this.actor||ref.uid!==uid2)throw new Error(`the accepted row names ${ref.owner}.${ref.actor} (uid ${ref.uid}), not this endpoint ${this.owner}.${this.actor} (uid ${uid2}); refusing to ride a foreign issuance (SPEC 13.15)`);this.issuedGeneration=ref.generation}await this.beforeBind?.();if(this.stopped)return;if(this.doWatch||this.doRegister){const kvm=new import_kv10.Kvm(this.nc);this.kv=this.authed?await kvm.open(presenceBucket(this.space)):await kvm.create(presenceBucket(this.space),{ttl:this.ttlMs,storage:PRESENCE_STORAGE})}if(this.doWatch&&this.readOnce)await this.readPresenceOnce();else if(this.doWatch){await this.startPresenceWatch();this.sweepTimer=setInterval(()=>this.sweep(),Math.max(500,Math.floor(this.ttlMs/3)))}const watchChannels=this.doWatch&&this.doWatchChannels;if(watchChannels||this.doConsume){this.channelKv=await openChannelRegistry(this.nc,this.space,{create:!this.authed});if(watchChannels)await(this.readOnce?this.readChannelsOnce():this.startChannelWatch());else if(this.readsChannelsOnDemand)await this.readChannels()}if(this.deliveryLease.hasWatchIntent)await this.bindDeliveryLeaseWatch();if(this.authed&&(this.doConsume||this.doRegister))this.requireLifecycleUid(this.doConsume?"an authed consuming endpoint":"an authed presence-registering endpoint");if(this.doConsume){this.jsm=await(0,import_jetstream21.jetstreamManager)(this.nc);if(!this.authed)await this.ensureStreams();await this.startConsumers()}if(this.doRegister&&!this.doConsume&&this.authed&&this.card.kind==="agent"){const jsm=this.jsm??(this.jsm=await(0,import_jetstream21.jetstreamManager)(this.nc));const uid2=this.requireLifecycleUid("an authed presence-registering agent");try{await jsm.consumers.info(dmStream(this.space),dmDurable(this.owner,this.actor,uid2))}catch(e3){throw new Error(`lifecycle proof failed for ${this.card.id} (uid ${uid2}): its dm_ durable is not present at the broker, so this incarnation's uid does not match its provisioned resources - refusing to publish presence (SPEC 13.1 fail-before-presence): ${e3?.message??String(e3)}`)}}if(this.doRegister){try{await this.publishPresence()}catch(e3){const detail=e3?.message??String(e3);throw new Error(`presence registration failed for ${this.card.id}: the space's presence KV bucket "${presenceBucket(this.space)}" did not accept this endpoint's first write (${detail}). The bucket can be OPENED and WATCHED while refusing every write, so a healthy-looking connection does not rule this out; a broker whose store has latched refuses until it is restarted, and no client can clear it (#1356).`)}const phase=Date.now();let beat=0;const arm=()=>{const next=nextHeartbeat(phase,this.heartbeatMs,beat,Date.now());beat=next.beat;const handle=setTimeout(()=>{this.publishPresence().catch(e3=>this.emitRecoverable(e3));if(this.heartbeatTimer===handle)arm()},next.delayMs);this.heartbeatTimer=handle};arm()}await this.rearmMembershipWatches();await this.armPlane3();for(const plane of this.livenessResponders.keys())this.bindLiveness(plane);this.rebindPrincipalServes(false);for(const tap of this.taps)this.bindTap(tap);if(this.stopped)return;this.emit("connection",{connected:true});if(this.nc){for(const follower of this.activeGoalFollowers){follower.reconnected(this.nc)}}}clearConnectionScoped(){if(this.authExpiryReconnectTimer){clearTimeout(this.authExpiryReconnectTimer);this.authExpiryReconnectTimer=void 0}if(this.heartbeatTimer){clearInterval(this.heartbeatTimer);this.heartbeatTimer=void 0}if(this.sweepTimer){clearInterval(this.sweepTimer);this.sweepTimer=void 0}for(const msgs of this.streamMsgs){try{msgs.stop()}catch{}}this.streamMsgs.length=0;this.presenceEpoch++;this.presence.cancelRebind();this.presence.retireWatch();if(this.channelWatchIter)this.retireKvWatch(this.channelWatchIter);this.channelWatchIter=void 0;this.stopDeliveryLeaseWatch();for(const sub of this.chatSubs.values()){try{sub.unsubscribe()}catch{}}this.chatSubs.clear();this.chatSubDenied.clear();this.ownWatchDeletePrefixes.clear();this.presence.resetConnection();this.channelConfigs.clear();this.channelDefaults={};this.channelRead=void 0;this.channelReadGeneration++;this.channelReadApplied=this.channelReadGeneration;for(const watch of this.membershipFeedWatches)watch.arm=watch.arm.catch(()=>{}).then(()=>this.disarmMembershipWatch(watch)).catch(err3=>{this.emit("error",err3)})}async closeFailedBind(){const failedNc=this.nc;if(failedNc)this.disableLibraryReconnect(failedNc);this.clearConnectionScoped();this.nc=void 0;this.js=void 0;this.jsm=void 0;this.kv=void 0;this.channelKv=void 0;this.membersKv=void 0;this.aclKv=void 0;this.membershipFeedKv=void 0;this.deliveryLease.resetConnection();this.managerLeaseKv=void 0;this.daemonRenewalLeaseRevision=void 0;if(this.deliveryPlane.deliveryServeSub){try{this.deliveryPlane.deliveryServeSub.unsubscribe()}catch{}this.deliveryPlane.deliveryServeSub=void 0}if(this.deliveryPlane.deliveryAdminServeSub){try{this.deliveryPlane.deliveryAdminServeSub.unsubscribe()}catch{}this.deliveryPlane.deliveryAdminServeSub=void 0}this.dropAnycastRequests();for(const sub of this.subs){try{sub.unsubscribe()}catch{}}this.subs.length=0;if(!failedNc)return;this.emit("transport",{connected:false});this.emit("connection",{connected:false});try{await failedNc.close();return}catch{}if(!failedNc.isClosed?.()){try{await drainAndClose(failedNc);return}catch{}}const proto=failedNc.protocol;const transport=proto?.transport;if(transport&&!transport.isClosed){try{await transport.close?.()}catch{}if(!transport.isClosed){try{transport.disconnect?.()}catch{}}}}async tearDownIfStopped(){if(!this.stopped)return false;const nc=this.nc;if(nc)this.disableLibraryReconnect(nc);this.clearConnectionScoped();await this.closeWithoutLibraryReconnect(nc);this.nc=void 0;return true}superviseConnection(){const nc=this.nc;if(!nc)return;void nc.closed().then(err3=>{if(this.stopped)return;if(this.nc!==nc)return;this.emit("connection",{connected:false});this.emit("error",new Error(`mesh connection closed${err3?`: ${err3.message||err3.name}`:""} - re-establishing`));void this.reestablishLoop()})}rebuild(){if(this.rebuildPromise)return this.rebuildPromise;const p2=this.doRebuild().finally(()=>{if(this.rebuildPromise===p2)this.rebuildPromise=void 0});this.rebuildPromise=p2;return p2}async doRebuild(){const oldNc=this.nc;if(oldNc)this.disableLibraryReconnect(oldNc);this.reconnecting=true;try{this.clearConnectionScoped();if(oldNc&&!oldNc.isClosed())await Promise.all([...[...this.membershipFeedWatches].map(watch=>watch.arm),this.settleDeliveryLeaseWatches(),this.settleKvWatches()]);this.nc=void 0;this.js=void 0;this.jsm=void 0;this.kv=void 0;this.channelKv=void 0;this.membersKv=void 0;this.aclKv=void 0;this.membershipFeedKv=void 0;this.deliveryLease.resetConnection();this.managerLeaseKv=void 0;this.daemonRenewalLeaseRevision=void 0;this.emit("transport",{connected:false});this.emit("connection",{connected:false});await this.closeWithoutLibraryReconnect(oldNc);if(this.stopped)return;try{await this.connectAndBind()}catch(error51){if(!this.stopped)throw error51}if(await this.tearDownIfStopped())return;this.superviseConnection()}finally{this.reconnecting=false}}static RETRY_BACKOFF_CAP_MS=6e4;nextRetryDelayMs(){const delay3=Math.min(this.retryMs*2**this.retryAttempt,_CotalEndpoint.RETRY_BACKOFF_CAP_MS);this.retryAttempt++;return Math.round(delay3/2+Math.random()*(delay3/2))}async reestablishLoop(){if(this.reestablishing)return;this.reestablishing=true;try{while(!this.stopped){try{await this.rebuild();this.retryAttempt=0;return}catch(e3){const delay3=this.nextRetryDelayMs();if(!this.stopped&&!(e3 instanceof RepeatedRefusal))this.emitRecoverable(this.userMode&&isAuthRejection(e3)?new Error(`the broker refused this endpoint's bearer for ${this.owner}.${this.actor} - retrying in ${Math.ceil(delay3/1e3)}s; the space's auth service logs why`,{cause:e3}):e3);if(this.stopped)return;await new Promise(resolve6=>{this.backoffResolve=resolve6;this.backoffTimer=setTimeout(resolve6,delay3)})}}}finally{this.reestablishing=false}}retryNow(){if(!this.stopped&&this.reestablishing&&!this.rebuildPromise)this.kickBackoff()}kickBackoff(){this.backoffResolve?.();if(this.backoffTimer){clearTimeout(this.backoffTimer);this.backoffTimer=void 0}}membershipPause(attempt){if(this.stopped)return Promise.resolve();return new Promise(resolve6=>{const wake=()=>{clearTimeout(timer2);this.membershipPauses.delete(wake);resolve6()};const timer2=setTimeout(wake,Math.min(3e4,1e3*2**attempt));this.membershipPauses.add(wake)})}async reconnect(){if(this.stopped)throw new Error("endpoint stopped - cannot reconnect");this.kickBackoff();try{await this.rebuild()}catch(e3){void this.reestablishLoop();throw e3}}stop(){return this.stopPromise??=this.stopOnce()}async stopOnce(){if(this.nc)this.disableLibraryReconnect(this.nc);this.stopped=true;for(const follower of this.activeGoalFollowers){follower.cancel()}this.activeGoalFollowers.clear();this.presenceEpoch++;const principalStops=[...this.principalServes.values()].map(intent=>this.stopPrincipalServe(intent,false));this.presence.cancelRebind();this.kickBackoff();for(const wake of[...this.membershipPauses])wake();if(this.heartbeatTimer)clearInterval(this.heartbeatTimer);if(this.sweepTimer)clearInterval(this.sweepTimer);this.cancelBearerRenewal?.();if(this.credsTimer)clearTimeout(this.credsTimer);if(this.authExpiryReconnectTimer)clearTimeout(this.authExpiryReconnectTimer);for(const watch of this.membershipFeedWatches){watch.stopped=true;watch.arm=watch.arm.catch(()=>{}).then(async()=>{await this.disarmMembershipWatch(watch);await this.deleteRetainedMembershipConsumer(watch)})}await Promise.all([...this.membershipFeedWatches].map(watch=>watch.arm.catch(err3=>{if(this.nc&&!this.nc.isClosed())throw err3})));for(const watch of this.membershipFeedWatches){watch.resolveStop?.();watch.resolveStop=void 0;watch.rejectStop=void 0}this.membershipFeedWatches.clear();for(const msgs of this.streamMsgs){try{msgs.stop()}catch{}}this.presence.retireWatch();if(this.channelWatchIter)this.retireKvWatch(this.channelWatchIter);this.channelWatchIter=void 0;this.stopDeliveryLeaseWatch();await Promise.all(principalStops);try{if(this.doRegister){await this.presence.publishOffline()}}catch{}await Promise.all([this.settleDeliveryLeaseWatches(),this.settleKvWatches()]);let dmOnlyUnsettled=false;if(this.dmOnly&&this.dmOnlyInFlight){const settleMs=this.dmOnly.settleTimeoutMs??3e4;dmOnlyUnsettled=await withDeadline(this.dmOnlyInFlight.then(()=>false),settleMs,()=>new Error("unsettled")).catch(()=>true)}await this.closeWithoutLibraryReconnect(this.nc);this.clearPresenceWriteFailure();await this.rebuildPromise;await this.startPromise;if([...this.ownedConnections].some(nc=>!nc.isClosed()))throw new Error("endpoint stop could not prove its connection closed; local consumer custody must be retained");if(dmOnlyUnsettled)throw new Error(`endpoint stop closed the connection but the DM-only handler did not settle within ${this.dmOnly?.settleTimeoutMs??3e4}ms; its copy stays unacked and handler custody must be retained`)}nativeConnections(){const unsettled=why=>new Error(`endpoint connection inventory is unsettled: ${why}`);if(this.startPromise!==void 0||this.rebuildPromise!==void 0||this.reconnecting)throw unsettled("a start or rebuild is in flight");const open7=[...this.ownedConnections].filter(nc=>!nc.isClosed());if(this.stopped){if(open7.length>0)throw unsettled("the endpoint stopped but a connection has not closed");return[]}if(this.credsTxnsRunning>0||this.residentSwap!==void 0)throw unsettled("a credential adoption is in flight");if(!this.nc||!this.nativeBound)throw unsettled("the connection is down or redialing");return open7.map(nc=>nativeConnectionBinding(nc,"endpoint connection"))}messaging=new EndpointMessaging({nc:()=>this.nc,js:()=>this.js,jsm:()=>this.jsm,space:()=>this.space,owner:()=>this.owner,actor:()=>this.actor,channels:()=>this.channels,notLiveMsg:()=>this.notLiveMsg(),ref:()=>this.ref(),publishMsg:(subject,msg)=>this.publishMsg(subject,msg),streamHistory:(...args)=>this.streamHistory(...args),emitRecoverable:err3=>this.emitRecoverable(err3)});async multicast(text3,opts){return this.messaging.multicast(text3,opts)}get maxPayload(){return this.messaging.maxPayload}async assertExpectationSemantics(){return this.messaging.assertExpectationSemantics()}encodedSize(opts){return this.messaging.encodedSize(opts)}async multicastExpecting(opts){return this.messaging.multicastExpecting(opts)}async publishEventPayload(opts){return this.messaging.publishEventPayload(opts)}async eventPayloadHistory(owner2,actor2,opts){return this.messaging.eventPayloadHistory(owner2,actor2,opts)}async eventPayloadLimit(){return this.messaging.eventPayloadLimit()}async unicast(instanceId,text3,opts){return this.messaging.unicast(instanceId,text3,opts)}async unicastAttributed(instanceId,text3,opts){return this.messaging.unicastAttributed(instanceId,text3,opts)}async anycast(service,text3,opts){return this.messaging.anycast(service,text3,opts)}async anycastAttributed(service,text3,opts){return this.messaging.anycastAttributed(service,text3,opts)}tap(handler,opts){const tap={handler,subject:opts?.subject??spaceWildcard(this.space)};this.taps.push(tap);this.bindTap(tap)}bindTap(tap){if(!this.nc)return;const sub=this.nc.subscribe(tap.subject);this.subs.push(sub);void(async()=>{for await(const m2 of sub){let decoded;try{decoded=m2.json()}catch{decoded=void 0}const parsed=parseSubject(m2.subject);if(decoded!==void 0&&(parsed?.kind==="chat"||parsed?.kind==="evp"||parsed?.kind==="inst"||parsed?.kind==="svc")){if(!isFromSubjectSender(decoded,parsed))continue;if(parsed.kind!=="evp"&&(!Array.isArray(decoded.parts)||!decoded.parts.every(isReadableMessagePart)))continue;decoded=authenticatedMessage(decoded,parsed)}try{tap.handler(m2.subject,decoded)}catch(e3){this.emit("error",e3)}}})().catch(e3=>this.emit("error",e3))}controlPlane=new EndpointControlPlane({nc:()=>this.nc,space:()=>this.space,owner:()=>this.owner,actor:()=>this.actor,stopped:()=>this.stopped,authed:()=>this.authed,connId:()=>this.connId,presentedExp:()=>this.presentedExp,issuedGeneration:()=>this.issuedGeneration,acceptedToken:()=>this.acceptedToken,rebuildPromise:()=>this.rebuildPromise,subs:()=>this.subs,resolvedServices:()=>this.resolvedServices,resolvedCommandServices:()=>this.resolvedCommandServices,serviceInvocations:()=>this.serviceInvocations,requestsAwaitingReply:()=>this.requestsAwaitingReply,activeGoalFollowers:()=>this.activeGoalFollowers,splitsRecovered:()=>this.splitsRecovered,setSplitsRecovered:count=>{this.splitsRecovered=count},notLiveMsg:()=>this.notLiveMsg(),requireLifecycleUid:what2=>this.requireLifecycleUid(what2),reportSubscriptionDenial:error51=>this.reportSubscriptionDenial(error51),ref:()=>this.ref(),reconnect:()=>this.reconnect(),emit:(event,...args)=>this.emit(event,...args)});serveControl(service,handler,opts={}){return this.controlPlane.serveControl(service,handler,opts)}async requestBoundReply(nc,subject,body,reply,timeoutMs){return this.controlPlane.requestBoundReply(nc,subject,body,reply,timeoutMs)}async requestControl(service,req,timeoutMs=5e3){return this.controlPlane.requestControl(service,req,timeoutMs)}serviceRailCaller(){return this.controlPlane.serviceRailCaller()}async followServiceGoal(endpoint,submit,deadlineMs=1e4,opts={}){return this.controlPlane.followServiceGoal(endpoint,submit,deadlineMs,opts)}async describeService(endpoint,opts={}){return this.controlPlane.describeService(endpoint,opts)}async listingCaller(){return this.controlPlane.listingCaller()}async listEndpoints(input,opts={}){return this.controlPlane.listEndpoints(input,opts)}async listEndpointsOver(nc,listing,input,opts={}){return this.controlPlane.listEndpointsOver(nc,listing,input,opts)}async invokeService(endpoint,command,args,opts={}){return this.controlPlane.invokeService(endpoint,command,args,opts)}async requestDelivery(op,args,timeoutMs=5e3){if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=controlServiceSubject(this.space,CONTROL_DELIVERY,this.owner,this.actor);const reply=`${reqSubject}.reply.${randomUUID9()}`;const body={op,args,from:this.ref()};const m2=await this.requestBoundReply(this.nc,reqSubject,JSON.stringify(body),reply,timeoutMs);return m2.json()}async requestDeliveryAdmin(op,args,timeoutMs=5e3){if(!this.nc)throw new Error(this.notLiveMsg());const reqSubject=controlServiceSubject(this.space,CONTROL_DELIVERY_ADMIN,this.owner,this.actor);const reply=`${reqSubject}.reply.${randomUUID9()}`;const body={op,args,from:this.ref()};const m2=await this.requestBoundReply(this.nc,reqSubject,JSON.stringify(body),reply,timeoutMs);return m2.json()}getRoster(){return this.presence.getRoster()}async readPresence(){return this.presence.readPresence()}presenceView(){return this.presence.presenceView()}async waitForPresenceSnapshot(timeoutMs=1e3){return this.presence.waitForPresenceSnapshot(timeoutMs)}async setActivity(activity){return this.presence.setActivity(activity)}async setStatus(status2,activity){return this.presence.setStatus(status2,activity)}noteActivity(at2=Date.now()){return this.presence.noteActivity(at2)}async setCondition(condition){return this.presence.setCondition(condition)}async setAttention(attention){return this.presence.setAttention(attention)}async setChannelModes(modes){return this.presence.setChannelModes(modes)}async setCardModel(model,variant,provider){return this.presence.setCardModel(model,variant,provider)}async setCardCwd(cwd){return this.presence.setCardCwd(cwd)}channelDiscovery=new EndpointChannelDiscovery({nc:()=>this.nc,space:()=>this.space,card:()=>this.card,doConsume:()=>this.doConsume,doWatch:()=>this.doWatch,doWatchChannels:()=>this.doWatchChannels,channelKv:()=>this.channelKv,setChannelWatchIter:iter=>{this.channelWatchIter=iter},channelConfigs:()=>this.channelConfigs,channelDefaults:()=>this.channelDefaults,setChannelDefaults:defaults=>{this.channelDefaults=defaults},channelRead:()=>this.channelRead,setChannelRead:read=>{this.channelRead=read},channelReadGeneration:()=>this.channelReadGeneration,setChannelReadGeneration:n2=>{this.channelReadGeneration=n2},channelReadApplied:()=>this.channelReadApplied,setChannelReadApplied:n2=>{this.channelReadApplied=n2},notLiveMsg:()=>this.notLiveMsg(),bindKvWatch:kv=>this.bindKvWatch(kv),emitRecoverable:err3=>this.emitRecoverable(err3),emit:(event,...args)=>this.emit(event,...args)});get readsChannelsOnDemand(){return this.channelDiscovery.readsChannelsOnDemand}async readChannels(){return this.channelDiscovery.readChannels()}getChannelConfig(channel){return this.channelDiscovery.getChannelConfig(channel)}channelReplay(channel){return this.channelDiscovery.channelReplay(channel)}channelReplayWindow(channel){return this.channelDiscovery.channelReplayWindow(channel)}async channelReplayPolicy(channel){return this.channelDiscovery.channelReplayPolicy(channel)}channelDeliveryClass(channel){return this.channelDiscovery.channelDeliveryClass(channel)}subscriptions=new EndpointSubscriptions({nc:()=>this.nc,jsm:()=>this.jsm,space:()=>this.space,card:()=>this.card,stopped:()=>this.stopped,authed:()=>this.authed,channels:()=>this.channels,channelConfigs:()=>this.channelConfigs,channelDefaults:()=>this.channelDefaults,chatSubDenied:()=>this.chatSubDenied,plane3Channels:()=>this.plane3Channels,readsChannelsOnDemand:()=>this.readsChannelsOnDemand,membershipFeedKv:()=>this.membershipFeedKv,setMembershipFeedKv:kv=>{this.membershipFeedKv=kv},membershipFeedWatches:()=>this.membershipFeedWatches,watchDeletePermissions:()=>this.watchDeletePermissions,notLiveMsg:()=>this.notLiveMsg(),readChannels:()=>this.readChannels(),armJoin:channels=>this.armJoin(channels),backfillArmed:(frontiers,floorSeq)=>this.backfillArmed(frontiers,floorSeq),subscribeChat:channel=>this.subscribeChat(channel),unsubscribeChat:channel=>this.unsubscribeChat(channel),confirmChatSub:()=>this.confirmChatSub(),durableJoinChannel:channel=>this.durableJoinChannel(channel),durableLeaveChannel:(...args)=>this.durableLeaveChannel(...args),fetchMemberships:channel=>this.fetchMemberships(channel),recordOwnWatchConsumer:info=>this.recordOwnWatchConsumer(info),watchConsumerDeleteDenied:(stream,name2,owner2)=>this.watchConsumerDeleteDenied(stream,name2,owner2),deleteMembershipConsumer:(jsm,stream,name2)=>this.deleteMembershipConsumer(jsm,stream,name2),emit:(event,...args)=>this.emit(event,...args)});joinedChannels(){return this.subscriptions.joinedChannels()}async joinChannel(channel){return this.subscriptions.joinChannel(channel)}async leaveChannel(channel,legacyDiscoveryMessage){return this.subscriptions.leaveChannel(channel,legacyDiscoveryMessage)}async chatRetention(){return this.subscriptions.chatRetention()}async dmStreamPresent(){return this.subscriptions.dmStreamPresent()}async listChannels(){return this.subscriptions.listChannels()}async channelMembers(channel){const members=(await listMembers(await this.membersRegistry())).filter(r2=>r2.leaveCursor===void 0&&r2.activated===true);const byId=new Map;for(const p2 of this.presence.values())byId.set(p2.card.id,p2);const memberForId=id2=>{const p2=byId.get(id2);return p2?{id:p2.card.id,name:p2.card.name,role:p2.card.role,live:p2.status!=="offline"}:{id:id2,name:id2,live:false}};const byName=(a3,b3)=>a3.name.localeCompare(b3.name);if(channel!==void 0){const stored=await this.deliveryClassFresh(channel)==="durable";const ids=new Set(members.filter(r2=>r2.channel===channel||stored&&isChannelFamily(r2.channel)&&subjectMatches(r2.channel,channel)).map(r2=>r2.owner));return[...ids].map(memberForId).sort(byName)}const map2=new Map;for(const r2 of members){const arr=map2.get(r2.channel);const m2=memberForId(r2.owner);if(arr){if(!arr.some(x2=>x2.id===m2.id))arr.push(m2)}else{map2.set(r2.channel,[m2])}}for(const arr of map2.values())arr.sort(byName);return map2}async readMembership(){return this.subscriptions.readMembership()}async watchMembership(onChange,onClosed){return this.subscriptions.watchMembership(onChange,onClosed)}async deleteRetainedMembershipConsumer(watch){return this.subscriptions.deleteRetainedMembershipConsumer(watch)}recordOwnWatchConsumer({stream_name,name:name2}){const prefix=`$JS.API.CONSUMER.DELETE.${stream_name}.${name2.slice(0,name2.lastIndexOf("_")+1)}`;this.ownWatchDeletePrefixes.add(prefix);return prefix}isOwnWatchDelete(subject){const cut2=subject.lastIndexOf("_")+1;return/^\d+$/.test(subject.slice(cut2))&&this.ownWatchDeletePrefixes.has(subject.slice(0,cut2))}watchConsumerDeleteDenied(stream,name2,owner2){const permission2=owner2&&this.watchDeletePermissions.get(owner2)?.();return Boolean(permission2&&!issuedPermitsSubject(permission2,`$JS.API.CONSUMER.DELETE.${stream}.${name2}`))}async deleteOwnConsumer(consumer){const{stream_name,name:name2}=await consumer.info(true);if(this.watchConsumerDeleteDenied(stream_name,name2,consumer))return;try{await consumer.delete()}catch(e3){if(!isJetStreamMissing(e3,import_jetstream21.JetStreamApiCodes.ConsumerNotFound)&&!isPublishPermissionDenied(e3))throw e3}}async deleteMembershipConsumer(jsm,stream,name2){try{return await jsm.consumers.delete(stream,name2)}catch(err3){if(membershipConsumerReleased(err3))return true;throw err3}}async disarmMembershipWatch(watch){return this.subscriptions.disarmMembershipWatch(watch)}async rearmMembershipWatches(){return this.subscriptions.rearmMembershipWatches()}async channelHistory(channel,opts){return this.history.channelHistory(channel,opts)}async channelHistoryPage(channel,opts){return this.history.channelHistoryPage(channel,opts)}async multiChannelHistory(channels,opts){return this.history.multiChannelHistory(channels,opts)}async readHistory(channel,opts){return this.history.readHistory(channel,opts)}async dmHistory(opts){return this.history.dmHistory(opts)}async dmHistoryOf(principals,opts){const keys=[...new Set(principals)].map(p2=>{const key=parsePrincipalKey(p2);if(!key)throw new Error(`dmHistoryOf: "${p2}" is not a principal <owner>.<actor>`);return key});if(!keys.length)return{state:"read",items:[]};const limit=opts?.limit??100;const read=subjects=>this.streamHistory(dmStream(this.space),subjects,limit,void 0,opts?.signal);let rows;try{rows=(await Promise.all([read(keys.map(k2=>unicastRecvFilter(this.space,k2.owner,k2.actor))),read(keys.map(k2=>unicastSubject(this.space,"*","*",k2.owner,k2.actor)))])).flat()}catch(e3){if(isPermissionDenied(e3))return{state:"denied",reason:e3.message};throw e3}const bySeq=new Map(rows.map(r2=>[r2.seq,r2.msg]));return{state:"read",items:[...bySeq].sort(([a3],[b3])=>a3-b3).slice(-limit).map(([,msg])=>msg)}}async streamHistory(stream,subjects,limit,before,signal){return this.history.streamHistory(stream,subjects,limit,before,signal)}watchStatus(){const nc=this.nc;if(!nc)return;const handedToRequest=this.trackRequestDenials(nc);void(async()=>{for await(const s3 of nc.status()){if(this.nc!==nc)continue;if(nativeBindingAfter(s3.type)===false)this.nativeBound=false;if(s3.type==="disconnect"){this.emit("transport",{connected:false,server:s3.server});continue}if(s3.type==="reconnect"){this.armAuthExpiryReconnectFence(nc);this.rebindPrincipalServes(true);this.emit("transport",{connected:true,server:s3.server});for(const follower of this.activeGoalFollowers){follower.reconnected(nc)}continue}if(s3.type==="close"){this.emit("transport",{connected:false});continue}if(s3.type!=="error")continue;if(s3.error instanceof import_transport_node22.PermissionViolationError&&this.chatSubRefusals.has(s3.error))continue;if(s3.error instanceof import_transport_node22.PermissionViolationError&&this.ownedPrincipalRouteRefusal(s3.error))continue;if(s3.error instanceof import_transport_node22.PermissionViolationError&&handedToRequest.has(s3.error))continue;if(s3.error instanceof import_transport_node22.PermissionViolationError&&s3.error.operation==="publish"&&this.isOwnWatchDelete(s3.error.subject))continue;if(!this.reportSubscriptionDenial(s3.error))this.emit("error",describeStatusError(s3.error))}})().catch(e3=>{if(!this.stopped&&this.nc===nc)this.emit("error",e3)});if(this.stopped)return;this.emit("transport",{connected:true,server:nc.getServer()})}reportSubscriptionDenial(error51){if(!(error51 instanceof import_transport_node22.PermissionViolationError)||error51.operation!=="subscription")return false;if(!this.reportedSubRefusals.has(error51)){this.reportedSubRefusals.add(error51);this.emit("error",describeStatusError(error51))}return true}trackRequestDenials(nc){const handed=new WeakSet;const request=nc.request.bind(nc);nc.request=(subject,payload,opts)=>{if(typeof subject==="string"&&this.ungrantedOwnWatchDelete(subject)){const violation=new import_transport_node22.PermissionViolationError(`Permissions Violation for Publish to "${subject}"`,"publish",subject);handed.add(violation);return Promise.reject(new import_transport_node22.RequestError("permissions violation",{cause:violation}))}const reply=request(subject,payload,opts);reply.catch(({cause})=>{if(cause instanceof import_transport_node22.PermissionViolationError&&cause.operation==="publish")handed.add(cause)});return reply};return handed}ungrantedOwnWatchDelete(subject){if(!this.isOwnWatchDelete(subject))return false;const permission2=this.watchDeletePermissions.get(this.nc)?.();return Boolean(permission2&&!issuedPermitsSubject(permission2,subject))}notLiveMsg(){return this.reconnecting||this.reestablishing?"reconnecting - try again shortly":"endpoint not started"}async publishMsg(subject,msg){if(!this.js)throw new Error(this.notLiveMsg());assertPartsSerializable(msg.parts);try{await this.js.publish(subject,JSON.stringify(msg),{msgID:msg.id})}catch(error51){if(error51 instanceof import_transport_node22.TimeoutError)throw new Error(`${error51.message} publishing to ${JSON.stringify(subject)}. The send outcome is unknown: the broker may have stored the message. Check before resending.`,{cause:error51});throw error51}}provisioning=new EndpointProvisioning({jsm:()=>this.jsm,space:()=>this.space,authed:()=>this.authed,notLiveMsg:()=>this.notLiveMsg(),manager:()=>this.manager()});async ensureStreams(){return this.provisioning.ensureStreams()}async ensureOpenSpaceStreams(){return this.provisioning.ensureOpenSpaceStreams()}async provisionDmInbox(owner2,actor2,lifecycleUid){return this.provisioning.provisionDmInbox(owner2,actor2,lifecycleUid)}async ensureDmDurable(owner2,actor2,lifecycleUid,opts){return this.provisioning.ensureDmDurable(owner2,actor2,lifecycleUid,opts)}async provisionDlvInbox(owner2,actor2,lifecycleUid){return this.provisioning.provisionDlvInbox(owner2,actor2,lifecycleUid)}async provisionTaskQueue(role){return this.provisioning.provisionTaskQueue(role)}durableBackstop=new EndpointDurableBackstop({nc:()=>this.nc,js:()=>this.js,jsm:()=>this.jsm,setJsm:manager=>{this.jsm=manager},space:()=>this.space,card:()=>this.card,authed:()=>this.authed,channelKv:()=>this.channelKv,presence:()=>this.presence,deliveryPlane:()=>this.deliveryPlane,membersKv:()=>this.membersKv,setMembersKv:kv=>{this.membersKv=kv},aclKv:()=>this.aclKv,setAclKv:kv=>{this.aclKv=kv},managerLeaseKv:()=>this.managerLeaseKv,setManagerLeaseKv:kv=>{this.managerLeaseKv=kv},daemonRenewalLeaseRevision:()=>this.daemonRenewalLeaseRevision,setDaemonRenewalLeaseRevision:revision=>{this.daemonRenewalLeaseRevision=revision},notLiveMsg:()=>this.notLiveMsg(),consumerInfo:(stream,durable)=>this.consumerInfo(stream,durable),manager:()=>this.manager(),chatFrontier:()=>this.chatFrontier(),aclAllows:(owner2,lifecycleUid,channel)=>this.aclAllows(owner2,lifecycleUid,channel),catchupCopy:(...args)=>this.catchupCopy(...args)});async membersRegistry(){return this.durableBackstop.membersRegistry()}async aclRegistry(){return this.durableBackstop.aclRegistry()}async commitAcl(targetId,lifecycleUid,allowSubscribe){return this.durableBackstop.commitAcl(targetId,lifecycleUid,allowSubscribe)}async reissueAcl(targetId,lifecycleUid,allowSubscribe){return this.durableBackstop.reissueAcl(targetId,lifecycleUid,allowSubscribe)}async aclForOwner(owner2,lifecycleUid){return this.durableBackstop.aclForOwner(owner2,lifecycleUid)}async aclForAlias(principal){return this.durableBackstop.aclForAlias(principal)}ownsDeliveryLease(info){return this.deliveryLease.ownsDeliveryLease(info)}async acquireDeliveryLease(shardIndex){return this.deliveryLease.acquireDeliveryLease(shardIndex)}async markDeliveryLeaseReady(shardIndex,revision){return this.deliveryLease.markDeliveryLeaseReady(shardIndex,revision)}async markDeliveryLeaseNotReady(shardIndex,revision){return this.deliveryLease.markDeliveryLeaseNotReady(shardIndex,revision)}async renewDeliveryLease(shardIndex,revision){return this.deliveryLease.renewDeliveryLease(shardIndex,revision)}async releaseDeliveryLease(shardIndex,revision){return this.deliveryLease.releaseDeliveryLease(shardIndex,revision)}async readDeliveryLease(shardIndex){return this.deliveryLease.readDeliveryLease(shardIndex)}async watchDeliveryLease(shardIndex,onEvent){return this.deliveryLease.watchDeliveryLease(shardIndex,onEvent)}stopDeliveryLeaseWatch(){return this.deliveryLease.stopDeliveryLeaseWatch()}async settleDeliveryLeaseWatches(){return this.deliveryLease.settleDeliveryLeaseWatches()}retireKvWatch(iter){try{iter.stop()}catch{}if(!this.nc||this.nc.isClosed())return;const deleting=this.deleteOwnConsumer(kvWatchConsumer(iter)).catch(e3=>this.emitRecoverable(new Error(`a retired KV watch consumer was not deleted (${e3.message}); the broker reaps it at its inactive threshold`)));this.kvWatchDeletes.add(deleting);void deleting.then(()=>this.kvWatchDeletes.delete(deleting))}async settleKvWatches(){await Promise.allSettled(this.kvWatchBinds);await Promise.all(this.kvWatchDeletes)}bindKvWatch(kv){if(this.stopped)return Promise.resolve(void 0);const epoch=this.presenceEpoch;const binding=(async()=>{const permission2=this.nc&&this.watchDeletePermissions.get(this.nc);const iter=await kv.watch();const info=await kvWatchConsumer(iter).info(true);this.recordOwnWatchConsumer(info);if(permission2)this.watchDeletePermissions.set(kvWatchConsumer(iter),permission2);if(epoch===this.presenceEpoch&&!this.stopped)return{iter,info};this.retireKvWatch(iter);return void 0})();const settled=()=>{this.kvWatchBinds.delete(binding)};this.kvWatchBinds.add(binding);void binding.then(settled,settled);return binding}bindDeliveryLeaseWatch(){return this.deliveryLease.bindDeliveryLeaseWatch()}async deliveryLeaseHolder(shardIndex){return this.deliveryLease.deliveryLeaseHolder(shardIndex)}async readDeliveryLeaseEntry(shardIndex){return this.deliveryLease.readDeliveryLeaseEntry(shardIndex)}async holdDaemonRenewalLease(instanceId){return this.durableBackstop.holdDaemonRenewalLease(instanceId)}async releaseDaemonRenewalLease(){return this.durableBackstop.releaseDaemonRenewalLease()}async readDaemonRenewalLease(){return this.durableBackstop.readDaemonRenewalLease()}async acquireManagerLease(info){return this.durableBackstop.acquireManagerLease(info)}async renewManagerLease(info,revision){return this.durableBackstop.renewManagerLease(info,revision)}async readOwnManagerLease(instanceId){return this.durableBackstop.readOwnManagerLease(instanceId)}async releaseManagerLease(instanceId,revision){return this.durableBackstop.releaseManagerLease(instanceId,revision)}async readManagerLease(){return this.durableBackstop.readManagerLease()}async ownerMemberships(owner2,lifecycleUid){return this.durableBackstop.ownerMemberships(owner2,lifecycleUid)}async deliveryClassFresh(channel){return this.durableBackstop.deliveryClassFresh(channel)}resolveOwnerByName(name2){return this.durableBackstop.resolveOwnerByName(name2)}plane3MsgId(entry,keySuffix){return this.durableBackstop.plane3MsgId(entry,keySuffix)}async publishDinbox(principal,lifecycleUid,entry){return this.durableBackstop.publishDinbox(principal,lifecycleUid,entry)}async durableJoinFor(owner2,channel,lifecycleUid,opts={}){return this.durableBackstop.durableJoinFor(owner2,channel,lifecycleUid,opts)}async aclAllows(owner2,lifecycleUid,channel){const row=await readAcl(await this.aclRegistry(),owner2,lifecycleUid);return row!==void 0&&membershipInAllow(row.record.allowSubscribe,channel)}async durableLeaveFor(owner2,channel,lifecycleUid,expectedGeneration){return this.durableBackstop.durableLeaveFor(owner2,channel,lifecycleUid,expectedGeneration)}async catchupCopy(owner2,lifecycleUid,channel,fromSeqExcl,toSeqIncl,generation){if(!this.js||!this.jsm||toSeqIncl<=fromSeqExcl)return 0;const subject=chatSubject(this.space,"*","*",channel);const family=isChannelFamily(channel);const durableClass=new Map;const stored=ch=>{if(!family)return Promise.resolve(true);let cls=durableClass.get(ch);if(cls===void 0)durableClass.set(ch,cls=this.deliveryClassFresh(ch).then(c3=>c3==="durable"));return cls};const cuP=parsePrincipalKey(owner2);const name2=`cu_${cuP?lifecycleNameKey(cuP.owner,cuP.actor,lifecycleUid):`${token(owner2)}-${lifecycleUid}`}_${generation}`;await this.deleteConsumerIfPresent(chatStream(this.space),name2);await this.jsm.consumers.add(chatStream(this.space),{name:name2,filter_subject:subject,ack_policy:import_jetstream21.AckPolicy.None,mem_storage:true,inactive_threshold:(0,import_transport_node22.nanos)(3e4),deliver_policy:import_jetstream21.DeliverPolicy.StartSequence,opt_start_seq:fromSeqExcl+1});let copied=0;try{const consumer=await this.js.consumers.get(chatStream(this.space),name2);let pending=(await consumer.info()).num_pending;while(pending>0){const want=Math.min(pending,256);const iter=await consumer.fetch({max_messages:want,expires:5e3});let got=0;for await(const m2 of iter){got++;if(m2.seq>toSeqIncl)return copied;let msg;try{msg=m2.json()}catch{continue}const parsed=parseSubject(m2.subject);if(!parsed||!isFromSubjectSender(msg,parsed)||msg.from.id===owner2)continue;if(!await stored(parsed.rest))continue;await this.publishDinbox(owner2,lifecycleUid,{msg,channel:parsed.rest,seq:m2.seq,reason:"durable-channel",generation,...family?{row:channel}:{}});copied++}if(got<want)break;pending-=got}}finally{await this.deleteConsumerIfPresent(chatStream(this.space),name2)}return copied}async startPlane3(aclFor,opts={}){return this.deliveryPlane.startPlane3(aclFor,opts)}async quiescePlane3(){return this.deliveryPlane.quiescePlane3()}plane3IsQuiesced(){return this.deliveryPlane.plane3IsQuiesced()}async rearmPlane3(){return this.deliveryPlane.rearmPlane3()}plane3MayAct(){return this.deliveryPlane.plane3MayAct()}async armPlane3(){return this.deliveryPlane.armPlane3()}async pumpDlv(){return this.deliveryPlane.pumpDlv()}async armAnycastRequests(){if(!this.nc||!this.jsm)return;this.dropAnycastRequests();const definition=anycastStoreDefinition(this.space);let kv;try{kv=await new import_kv10.Kvm(this.nc).create(definition.bucket,definition.createOptions)}catch(e3){if(!isPermissionDenied(e3))throw e3;this.anycastUnavailable=ANYCAST_RECORDS_CREDENTIAL_OUTDATED;this.emitRecoverable(new Error(`delivery: ${ANYCAST_RECORDS_CREDENTIAL_OUTDATED}`));return}this.anycastUnavailable=void 0;const authority=new AnycastRequestAuthority({jsm:this.jsm,kv,stream:taskStream(this.space),send:(to,event)=>this.sendAnycastNotice(to,event),mayAct:()=>this.plane3MayAct(),onError:e3=>this.emitRecoverable(e3)});this.anycastAuthority=authority;this.takeServeSub=this.serveTakes(authority);const sweep=()=>void authority.sweep().catch(e3=>this.emitRecoverable(e3));this.anycastSweep=setInterval(sweep,ANYCAST_SWEEP_MS);this.anycastSweep.unref?.();sweep()}dropAnycastRequests(){if(this.takeServeSub){try{this.takeServeSub.unsubscribe()}catch{}const i2=this.subs.indexOf(this.takeServeSub);if(i2>=0)this.subs.splice(i2,1);this.takeServeSub=void 0}clearInterval(this.anycastSweep);this.anycastSweep=void 0;this.anycastAuthority=void 0}serveTakes(authority){const sub=this.nc.subscribe(takeServeFilter(this.space),{queue:TAKE_ROUTE});this.subs.push(sub);void(async()=>{for await(const m2 of sub){if(!m2.reply||!m2.reply.startsWith(`${m2.subject}.reply.`)){this.emitRecoverable(new Error(`rejected take on ${m2.subject}: reply target "${m2.reply??"(none)"}" is not under the sender's own reply subtree`));continue}void this.answerTake(authority,m2).catch(e3=>this.emitRecoverable(e3))}})().catch(e3=>this.emitRecoverable(e3));return sub}async answerTake(authority,m2){let reply;if(this.takesInFlight>=MAX_TAKES_IN_FLIGHT)reply={ok:false,code:"busy",error:"the delivery daemon is answering too many takes; retry"};else{this.takesInFlight++;try{reply=await this.takeFor(authority,m2)}catch(e3){reply={ok:false,code:"busy",error:`the take could not be recorded: ${e3.message}`}}finally{this.takesInFlight--}}m2.respond(JSON.stringify(reply))}async takeFor(authority,m2){if(!this.plane3MayAct())return{ok:false,code:"busy",error:"delivery: this daemon is not serving this shard (it is re-checking ownership); retry"};const parsed=parseTakeSubject(m2.subject);let req;try{req=m2.json()}catch{req=void 0}if(!parsed||!isPrincipalOwnerToken(parsed.owner)||req?.from?.id!==parsed.sender||typeof req.from.name!=="string")return{ok:false,code:"mismatch",error:"sender mismatch - take rejected"};if(!isAnycastSeq(req.seq)||!isAnycastSeq(req.count)||typeof req.id!=="string"||req.id.length>256||typeof req.epoch!=="string"||req.epoch.length>64)return{ok:false,code:"mismatch",error:"a take names a seq, the request id, a delivery count and the stream's creation time"};try{assertValidName(req.from.name)}catch(e3){return{ok:false,code:"mismatch",error:`a take names its holder by a valid display name: ${e3.message}`}}return authority.take(parsed.role,{from:{id:parsed.sender,name:req.from.name},seq:req.seq,id:req.id,count:req.count,epoch:req.epoch})}async sendAnycastNotice(to,event){if(!this.js)throw new Error(this.notLiveMsg());const recipient=parsePrincipalKey(to);if(!recipient)throw new Error(`anycast notice: "${to}" is not a principal`);const msg={id:event.key,ts:Date.now(),space:this.space,from:this.ref(),to,parts:[{kind:"text",text:event.text},{kind:"data",data:{[ANYCAST_NOTICE_KEY]:event.notice}}]};await this.js.publish(unicastSubject(this.space,recipient.owner,recipient.actor,this.owner,this.actor),JSON.stringify(msg),{msgID:msg.id})}async sendMentionNotice(msg,channel,seq,names){if(!this.js)throw new Error(this.notLiveMsg());const recipient=parsePrincipalKey(msg.from.id);if(!recipient)throw new Error(`mention notice: "${msg.from.id}" is not a principal`);const named=names.map(n2=>`@${n2}`).join(", ");const notice={id:`mention.${seq}.${msg.id}`,ts:Date.now(),space:this.space,from:this.ref(),to:msg.from.id,parts:[{kind:"text",text:`Your post on #${channel} mentioned ${named}, who may not read #${channel} and ${names.length===1?"was":"were"} not given it. Reach ${names.length===1?"them":"each"} another way, such as cotal_dm.`},{kind:"data",data:{[MENTION_NOTICE_KEY]:{channel,message:msg.id,names:[...names]}}}]};await this.js.publish(unicastSubject(this.space,recipient.owner,recipient.actor,this.owner,this.actor),JSON.stringify(notice),{msgID:notice.id})}async deliveryAnycast(op,caller,args){const authority=this.anycastAuthority;if(!authority)return{ok:false,error:`delivery: ${this.anycastUnavailable??"the anycast request records are not open on this daemon; retry"}`};if(!isAnycastSeq(args.seq))return{ok:false,error:`${op}: seq must be a whole number of at least 1`};if(args.id!==void 0&&(typeof args.id!=="string"||args.id.length>256))return{ok:false,error:`${op}: id must be a request id`};const q2={seq:args.seq,...typeof args.id==="string"?{id:args.id}:{}};try{const status2=op===ANYCAST_CANCEL_OP?await authority.cancel(caller,q2):await authority.status(caller,q2);if(!this.plane3MayAct())return{ok:false,error:"delivery: this daemon stopped serving this shard while the request was in flight; retry"};return{ok:true,data:status2}}catch(e3){return{ok:false,error:e3.message}}}liveness=new EndpointLiveness({nc:()=>this.nc,space:()=>this.space,owner:()=>this.owner,actor:()=>this.actor,subs:()=>this.subs,livenessResponders:()=>this.livenessResponders,notLiveMsg:()=>this.notLiveMsg(),requestBoundReply:(nc,subject,body,reply,timeoutMs)=>this.requestBoundReply(nc,subject,body,reply,timeoutMs),isNoResponders:e3=>this.isNoResponders(e3),emitRecoverable:err3=>this.emitRecoverable(err3),emit:(event,...args)=>this.emit(event,...args)});serveLiveness(plane,readState){return this.liveness.serveLiveness(plane,readState)}bindLiveness(plane){return this.liveness.bindLiveness(plane)}serveDeliveryLiveness(shardIndex=0){this.serveLiveness("delivery",async()=>responderFromLease(await this.readDeliveryLease(shardIndex),this.card.id))}async probeLiveness(plane,timeoutMs=2e3){return this.liveness.probeLiveness(plane,timeoutMs)}servePrincipal(spec){if("endpoint"in spec||"cluster"in spec)throw new Error(`servePrincipal serves only the "${AGENT_ENDPOINT}" endpoint with AGENT_CLUSTER and takes handlers alone; an endpoint or cluster is refused, never ignored (SPEC 13.22)`);const serve={endpoint:AGENT_ENDPOINT,cluster:AGENT_CLUSTER,handlers:spec.handlers};if(!this.authed)throw new Error("the principal route is served only on an authenticated mesh: on an open mesh no row says who may call (SPEC 13.21)");if(!this.userMode)throw new Error("the principal route is served only under a user-auth credential: a static credential names no one who may call (SPEC 13.21)");const uid2=this.ownLifecycleUid;if(uid2===void 0)throw new Error("serving the principal route needs this endpoint's lifecycleUid: the subject names it (SPEC 13.21)");const nc=this.nc;if(!nc)throw new Error(this.notLiveMsg());endpointToken(serve.endpoint);if(this.principalServes.has(serve.endpoint))throw new Error(`this endpoint already serves "${serve.endpoint}" on the principal route`);const self2={owner:this.owner,actor:this.actor,uid:uid2,runtimeId:assertRuntimeToken(processRuntime(uid2).id)};const serverKey=`${this.space}
|
|
52
52
|
${self2.runtimeId}
|
|
53
|
-
${serve.endpoint}`;if(principalServers.has(serverKey))throw new Error(`another endpoint in this process already serves "${serve.endpoint}" for lifecycle ${uid2}: both would subscribe the same principal-route subject and answer one request twice (SPEC 13.21); stop that one first`);let resolveReady,rejectReady,resolveFailed;const ready=new Promise((resolve6,reject)=>{resolveReady=resolve6;rejectReady=reject});ready.catch(()=>{});const failed=new Promise(resolve6=>{resolveFailed=resolve6});const intent={serve,self:self2,serverKey,handles:[],ended:false,readySettled:false,resolveReady,rejectReady,resolveFailed};const handle=this.bindPrincipalHandle(intent,nc);this.principalServes.set(serve.endpoint,intent);principalServers.set(serverKey,intent);if(serve.endpoint===AGENT_ENDPOINT)this.promptsPresence={open:0,seq:this.nextPromptsSeq()};void this.armPrincipalServe(intent,nc,handle);return{ready,failed,stop:()=>this.stopPrincipalServe(intent)}}bindPrincipalHandle(intent,nc){return servePrincipalRoute(nc,this.space,intent.self,intent.serve)}ownedPrincipalRouteRefusal(err3){const p2=`${spacePrefix(this.space)}.ep.`;if(err3.operation==="publish")return err3.subject.startsWith(`${p2}prin.`);return err3.subject.startsWith(`${p2}prin.`)||err3.subject.startsWith(`${p2}prin-reply.`)}async armPrincipalServe(intent,nc,handle){intent.binding={nc,handle};for(const old of intent.handles)void old.stop().finally(()=>{const i2=intent.handles.indexOf(old);if(i2>=0)intent.handles.splice(i2,1)});intent.handles.push(handle);intent.readyOn=void 0;void handle.refused.then(err3=>{if(!intent.ended&&intent.binding?.handle===handle)this.endPrincipalServe(intent,err3)});try{await handle.ready}catch{return}this.principalServeConfirmed(intent,nc,handle)}principalServeConfirmed(intent,nc,handle){if(intent.ended||intent.binding?.handle!==handle||this.nc!==nc)return;intent.readyOn=nc;if(!intent.readySettled){intent.readySettled=true;intent.resolveReady()}if(intent.serve.endpoint===AGENT_ENDPOINT)this.publishPresence().catch(e3=>this.emitRecoverable(e3))}rebindPrincipalServes(reconnected){const nc=this.nc;if(!nc)return;for(const intent of this.principalServes.values()){if(intent.ended)continue;const bound=intent.binding;if(bound&&bound.nc===nc){if(!reconnected)continue;intent.readyOn=void 0;void bound.handle.check().then(()=>this.principalServeConfirmed(intent,nc,bound.handle),()=>{});continue}let handle;try{handle=this.bindPrincipalHandle(intent,nc)}catch(e3){this.endPrincipalServe(intent,e3);continue}void this.armPrincipalServe(intent,nc,handle)}}endPrincipalServe(intent,err3){if(intent.ended)return;this.forgetPrincipalServe(intent);const wasReady=intent.readySettled;if(!intent.readySettled){intent.readySettled=true;intent.rejectReady(err3)}intent.resolveFailed(err3);for(const handle of intent.handles)void handle.stop();if(intent.serve.endpoint===AGENT_ENDPOINT){this.promptsPresence=void 0;this.publishPresence().catch(e3=>this.emitRecoverable(e3))}if(wasReady)this.emitRecoverable(new Error(`stopped serving "${intent.serve.endpoint}" on the principal route: ${err3.message}`,{cause:err3}))}forgetPrincipalServe(intent){intent.ended=true;intent.readyOn=void 0;if(this.principalServes.get(intent.serve.endpoint)===intent)this.principalServes.delete(intent.serve.endpoint);if(principalServers.get(intent.serverKey)===intent)principalServers.delete(intent.serverKey)}async stopPrincipalServe(intent,republish=true){if(!intent.ended){this.forgetPrincipalServe(intent);if(!intent.readySettled){intent.readySettled=true;intent.rejectReady(new Error(`stopped serving "${intent.serve.endpoint}" before the broker confirmed the subscription`))}if(intent.serve.endpoint===AGENT_ENDPOINT){this.promptsPresence=void 0;if(republish)this.publishPresence().catch(e3=>this.emitRecoverable(e3))}}await Promise.all(intent.handles.map(handle=>handle.stop()))}async setPromptsPresence(prompts){for(const k2 of["open","seq"])if(!Number.isSafeInteger(prompts?.[k2])||prompts[k2]<0)throw new TypeError(`prompts.${k2} must be a non-negative safe integer`);const intent=this.principalServes.get(AGENT_ENDPOINT);if(!intent)throw new Error(`the prompts presence field belongs to a served "${AGENT_ENDPOINT}" endpoint: call servePrincipal first (SPEC \xA76)`);const used=promptsSeqs.get(intent.self.runtimeId)??0;if(prompts.seq<used)throw new RangeError(`prompts.seq ${prompts.seq} is below ${used}, which this process already used under runtime ${intent.self.runtimeId}: seq never goes back under one runtime id (SPEC \xA76)`);promptsSeqs.set(intent.self.runtimeId,prompts.seq);this.promptsPresence={open:prompts.open,seq:prompts.seq};await this.publishPresence()}nextPromptsSeq(){const runtimeId=processRuntime(this.requireLifecycleUid("nextPromptsSeq")).id;const used=promptsSeqs.get(runtimeId);const next=used===void 0?0:used+1;promptsSeqs.set(runtimeId,next);return next}servedPrompts(){const intent=this.principalServes.get(AGENT_ENDPOINT);if(!intent||intent.ended||!this.nc||intent.readyOn!==this.nc)return void 0;return this.promptsPresence}async callPrincipal(call){const nc=this.nc;if(!nc)throw new Error(this.notLiveMsg());const contract=call.contract??(call.command==="describe"?describeContracts():call.endpoint===AGENT_ENDPOINT?AGENT_CONTRACTS[call.command]:void 0);if(contract===void 0)throw new EpEnvelopeError("bad-request",`no contract is built in for ${call.endpoint}.${call.command}; pass one`,void 0,"not-executed");const caller={owner:this.owner,actor:this.actor,uid:this.requireLifecycleUid("callPrincipal")};return epPrincipalCall(nc,this.space,{principal:call.principal,authority:call.authority},{endpoint:call.endpoint,command:call.command,contract,caller,name:this.card.name,...call.args!==void 0?{args:call.args}:{}},{deadlineMs:call.deadlineMs,...call.signal?{signal:call.signal}:{}})}async durableJoinChannel(channel){const reply=await this.requestDelivery("durableJoin",{channel},3e4);if(!reply.ok)throw new Error(reply.error??"durable join rejected");return reply.data??{durable:false}}async durableLeaveChannel(channel,generation,lifecycleUid=this.requireLifecycleUid("leaving a durable channel")){const reply=await this.requestDelivery("durableLeave",{channel,generation,lifecycleUid});if(!reply.ok)throw new Error(reply.error??"durable leave rejected")}async closeRefusedMembership(channel,generation){this.pendingDurableLeave.set(channel,generation);for(let attempt=0;;attempt++){if(this.stopped)return;try{await this.durableLeaveChannel(channel,generation);this.plane3Channels.delete(channel);this.pendingDurableLeave.delete(channel);return}catch(e3){if(attempt===0)this.emitRecoverable(new Error(`channel "${channel}": Plane-3 durable membership (generation ${generation}) not yet tombstoned after a refused live sub - retrying; \xA77 boundary may be open until it succeeds (${e3.message})`));await this.membershipPause(attempt)}}}pendingDurableLeaves(){return[...this.pendingDurableLeave.keys()]}isNoResponders(e3){return e3 instanceof import_transport_node22.NoRespondersError||e3 instanceof import_transport_node22.RequestError&&e3.isNoResponders()}async takeAnycast(role,seq,id2,count,epoch,nak){const nc=this.nc;if(!nc)return{taken:false,drop:false,reason:"daemon-down",detail:this.notLiveMsg()};const held2=(reason,detail)=>({taken:false,drop:false,reason,detail});const subject=takeSubject(this.space,role,this.owner,this.actor);const body={from:{id:this.card.id,name:this.card.name},seq,id:id2,count,epoch};let reply;try{const m2=await this.requestBoundReply(nc,subject,JSON.stringify(body),`${subject}.reply.${randomUUID8()}`,ANYCAST_TAKE_TIMEOUT_MS);reply=m2.json()}catch(e3){if(isPermissionDenied(e3))return held2("credential-outdated","this seat's credential was minted before anycast takes existed, so it cannot take role requests; respawn the seat to get a current credential");if(this.isNoResponders(e3))return this.takeResponderMissing();return held2("daemon-down",`the delivery daemon did not answer the take: ${e3.message}`)}if(reply.ok)return{taken:true};if(reply.code==="mismatch"){const current=await this.readTaskEpoch().catch(()=>void 0);if(current!==void 0&¤t!==epoch)nak()}if(reply.code==="cancelled"||reply.code==="taken"||reply.code==="gone"||reply.code==="mismatch")return{taken:false,drop:true,reason:reply.code,detail:reply.error};return held2("daemon-busy",reply.error)}async takeResponderMissing(){const held2=(reason,detail)=>({taken:false,drop:false,reason,detail});let reply;try{reply=await this.requestDelivery(ANYCAST_TAKES_OP,{},ANYCAST_TAKE_TIMEOUT_MS)}catch{return held2("daemon-down","no delivery daemon is answering on this mesh, so role requests wait on the queue until one does")}if(!reply.ok&&/not supported on the delivery control service/.test(reply.error??""))return held2("daemon-outdated","the delivery daemon predates anycast takes, so this seat holds role requests until the daemon is restarted at this version (`cotal up` runs it)");if(!reply.ok&&reply.error?.includes(ANYCAST_RECORDS_CREDENTIAL_OUTDATED))return held2("daemon-outdated",`this seat holds role requests until the delivery daemon can record takes: ${ANYCAST_RECORDS_CREDENTIAL_OUTDATED}`);return held2("daemon-down","the delivery daemon is not answering takes, so role requests wait on the queue until it does")}async anycastStatus(seq,id2){return this.anycastRequest(ANYCAST_STATUS_OP,seq,id2)}async cancelAnycast(seq,id2){return this.anycastRequest(ANYCAST_CANCEL_OP,seq,id2)}async anycastRequest(op,seq,id2){if(!this.authed)throw new Error("an open mesh runs no delivery daemon, so it keeps no record of anycast requests");if(!isAnycastSeq(seq))throw new Error(`seq must be a whole number of at least 1, got ${seq}`);let reply;try{reply=await this.requestDelivery(op,{seq,...id2!==void 0?{id:id2}:{}},1e4)}catch(e3){if(this.isNoResponders(e3))throw new Error("no delivery daemon is answering on this mesh, so the request's record cannot be read");throw e3}if(!reply.ok){if(/not supported on the delivery control service/.test(reply.error??""))throw new Error("the delivery daemon predates anycast request status; restart it at this version (`cotal up` runs it)");throw new Error(reply.error??`${op} failed`)}return reply.data}bootMemberships=new EndpointBootMemberships({channels:()=>this.channels,plane3Channels:()=>this.plane3Channels,pendingBootJoins:()=>this.pendingBootJoins,stopped:()=>this.stopped,requestDelivery:(op,args,timeoutMs)=>this.requestDelivery(op,args,timeoutMs),requireLifecycleUid:what2=>this.requireLifecycleUid(what2),deliveryClassFresh:channel=>this.deliveryClassFresh(channel),durableJoinChannel:channel=>this.durableJoinChannel(channel),membershipPause:attempt=>this.membershipPause(attempt),isNoResponders:e3=>this.isNoResponders(e3),emitRecoverable:err3=>this.emitRecoverable(err3)});async fetchMemberships(channel){return this.bootMemberships.fetchMemberships(channel)}async armBootDurableMemberships(){return this.bootMemberships.armBootDurableMemberships()}hasDurableMembership(channel){return this.bootMemberships.hasDurableMembership(channel)}async manager(){if(!this.nc)throw new Error(this.notLiveMsg());this.jsm??=await(0,import_jetstream21.jetstreamManager)(this.nc);return this.jsm}async startConsumers(){if(!this.jsm)throw new Error(this.notLiveMsg());const ownUid=this.requireLifecycleUid("consuming the DM inbox");if(!this.authed){await this.ensureDmDurable(this.owner,this.actor,ownUid,{ackWaitMs:this.ackWaitMs,inactiveThresholdMs:this.inactiveThresholdMs})}const dm=dmDurable(this.owner,this.actor,ownUid);try{await this.pump(dmStream(this.space),dm,{inbox:true})}catch(e3){if(this.authed&&isConsumerNotFound(e3))throw new DmDurableMissingError(dmStream(this.space),dm);throw e3}await this.pumpDlv();if(this.channels.length){const armed2=this.firstConnect?await this.armJoin(this.channels):void 0;for(const ch of this.channels)this.subscribeChat(ch);await this.confirmChatSub();if(armed2)await this.backfillArmed(armed2,this.backfillFloor)}if(this.firstConnect&&this.authed&&this.channels.length)await this.armBootDurableMemberships();this.firstConnect=false;if(this.card.role){if(!this.authed){await this.jsm.consumers.add(taskStream(this.space),taskDurableConfig(this.space,this.card.role,{ackWaitMs:this.ackWaitMs}))}await this.pump(taskStream(this.space),taskDurable(this.card.role),this.authed?{takeRole:this.card.role}:{})}}async pump(stream,durable,opts={}){if(!this.js)throw new Error(this.notLiveMsg());const consumer=opts.takeRole===void 0?await this.js.consumers.get(stream,durable):await this.bindTaskConsumer(stream,durable);const ackWaitMs=await ackWaitOf(consumer);const msgs=await consumer.consume();this.streamMsgs.push(msgs);if(opts.inbox)this.watchInbox(msgs,stream,durable);void(async()=>{for await(const m2 of msgs){const authed=this.authenticateStreamMsg(m2);if(!authed)continue;const{msg,parsed}=authed;const delivery=durableDelivery(m2,ackWaitMs);const role=opts.takeRole;if(role!==void 0){const epoch=this.taskEpoch;delivery.take=()=>this.takeAnycast(role,m2.seq,msg.id,m2.info.deliveryCount,epoch,()=>m2.nak())}this.emit("message",authenticatedMessage(msg,parsed),delivery,{historical:false,kind:kindFromParsed(parsed.kind)})}})().catch(e3=>{if(!this.stopped)this.emit("error",e3)})}async bindTaskConsumer(stream,durable){for(let attempt=0;attempt<3;attempt++){const before=await this.readTaskEpoch();const consumer=await this.js.consumers.get(stream,durable);if(before===await this.readTaskEpoch())return consumer}throw new Error(`the ${stream} stream was recreated while its role consumer was binding; reconnect to bind it again`)}async readTaskEpoch(){const epoch=(await(await this.manager()).streams.info(taskStream(this.space))).created;this.taskEpoch=epoch;return epoch}watchInbox(msgs,stream,durable){const boundNc=this.nc;void(async()=>{let absences=0;let deleted=false;for await(const s3 of msgs.status()){if(this.stopped||this.nc!==boundNc)break;if(s3.type==="next"){absences=0;deleted=false;continue}if(s3.type==="consumer_deleted"){if(deleted)continue;deleted=true;absences=1}else if(s3.type!=="consumer_not_found"&&s3.type!=="stream_not_found")continue;if(++absences===2)this.emitRecoverable(new Error(`DM inbox missing: the broker reports consumer "${durable}" on stream "${stream}" missing, so direct messages to this endpoint are not delivered. The endpoint keeps checking; if the inbox does not come back, end this session and start a new one`))}})().catch(e3=>{if(!this.stopped)this.emit("error",e3)})}authenticateStreamMsg(m2){let msg;try{msg=m2.json()}catch(e3){m2.term();this.emit("error",e3);return void 0}if(!isRecord(msg)||!isUsableMessageId(msg.id)){m2.term();this.emit("error",new Error(`dropped message on ${m2.subject}: absent or non-string id`));return void 0}const parsed=parseSubject(m2.subject);if(!parsed||!isFromSubjectSender(msg,parsed)){m2.term();this.emit("error",new Error(`dropped message on ${m2.subject}: payload from ${msg.from?.id??"(none)"} does not match subject sender ${parsed?.sender??"(unparseable)"}`));return void 0}return{msg,parsed}}async bindDmOnly(mode){if(!this.js)throw new Error(this.notLiveMsg());const stream=dmStream(this.space);const durable=dmDurable(this.owner,this.actor,this.requireLifecycleUid("consuming the DM inbox"));let consumer;try{consumer=await this.js.consumers.get(stream,durable)}catch(e3){if(isJetStreamMissing(e3,import_jetstream21.JetStreamApiCodes.ConsumerNotFound))throw new DmDurableMissingError(stream,durable);throw new DmBindRefusedError(stream,durable,e3)}const ackWaitMs=await ackWaitOf(consumer);if(this.dmOnlyInFlight){const settleMs=mode.settleTimeoutMs??3e4;await withDeadline(this.dmOnlyInFlight,settleMs,()=>new Error(`DM-only rebind waited ${settleMs}ms for the previous handler to settle; not reading the next DM yet`))}const msgs=await consumer.consume({max_messages:1});this.streamMsgs.push(msgs);const boundNc=this.nc;const retired=()=>this.stopped||this.nc!==boundNc||!boundNc||boundNc.isClosed();void(async()=>{for await(const m2 of msgs){if(retired())break;const authed=this.authenticateStreamMsg(m2);if(!authed)continue;if(authed.parsed.kind!=="inst"){m2.term();continue}const run=Promise.resolve().then(()=>mode.handler(authenticatedMessage(authed.msg,authed.parsed),dmOnlyDelivery(m2,ackWaitMs,boundNc),{historical:false,kind:"dm"}));const flight=run.then(()=>{},()=>{});this.dmOnlyInFlight=flight;try{await run}catch(e3){this.emit("error",e3 instanceof Error?e3:new Error(String(e3)))}finally{if(this.dmOnlyInFlight===flight)this.dmOnlyInFlight=void 0}}})().catch(e3=>{if(!this.stopped)this.emit("error",e3)})}subscribeChat(channel){if(!this.nc||this.chatSubs.has(channel))return;this.chatSubDenied.delete(channel);const subject=chatSubject(this.space,"*","*",channel);const sub=this.nc.subscribe(subject,{callback:(err3,m2)=>{if(err3){if(err3 instanceof import_transport_node22.PermissionViolationError)this.chatSubRefusals.add(err3);this.chatSubDenied.add(channel);this.chatSubs.delete(channel);const i2=this.channels.indexOf(channel);if(i2>=0){this.channels.splice(i2,1);const gen=this.plane3Channels.get(channel);if(gen!==void 0)void this.closeRefusedMembership(channel,gen);this.emit("error",new Error(`left channel "${channel}": its live subscription was refused by the broker`,{cause:err3}))}return}const parsed=parseSubject(m2.subject);if(!parsed||parsed.kind!=="chat")return;let msg;try{msg=m2.json()}catch(e3){this.emit("error",e3);return}if(!isRecord(msg)||!isUsableMessageId(msg.id))return;if(!isFromSubjectSender(msg,parsed))return;if(msg.from.id===this.card.id)return;const delivery={ack:()=>{},nak:()=>{},durable:false};this.emit("message",authenticatedMessage(msg,parsed),delivery,{historical:false,kind:kindFromParsed(parsed.kind)})}});this.chatSubs.set(channel,sub)}unsubscribeChat(channel){const sub=this.chatSubs.get(channel);if(sub){try{sub.unsubscribe()}catch{}this.chatSubs.delete(channel)}this.chatSubDenied.delete(channel)}async confirmChatSub(){if(!this.nc)throw new Error("connection not established");await this.nc.flush();await new Promise(r2=>setTimeout(r2,50))}async consumerInfo(stream,durable){if(!this.jsm)throw new Error(this.notLiveMsg());try{return await this.jsm.consumers.info(stream,durable)}catch(e3){if(isJetStreamMissing(e3,import_jetstream21.JetStreamApiCodes.ConsumerNotFound))return null;throw e3}}async deleteConsumerIfPresent(stream,durable){if(!this.jsm)throw new Error(this.notLiveMsg());try{await this.jsm.consumers.delete(stream,durable)}catch(e3){if(!isJetStreamMissing(e3,import_jetstream21.JetStreamApiCodes.ConsumerNotFound,import_jetstream21.JetStreamApiCodes.StreamNotFound))throw e3}}async chatFrontier(){const jsm=await this.manager();return(await jsm.streams.info(chatStream(this.space))).state.last_seq}async streamRecorded(name2){try{await(await this.manager()).streams.info(name2);return true}catch(e3){if(isStreamNotFound(e3))return false;throw e3}}async storedBytes(){return(await(await this.manager()).getAccountInfo()).storage}async armJoin(channels){const frontiers=new Map;for(const ch of channels){frontiers.set(ch,await this.chatFrontier())}return frontiers}async backfillArmed(frontiers,floorSeq){let total=0;for(const[ch,frontier]of frontiers){const policy=await this.joinPolicyFresh(ch);if(policy.replay)total+=await this.backfillChannel(ch,frontier,policy.windowMs,floorSeq)}return total}async joinPolicyFresh(channel){if(!this.channelKv)return{replay:effectiveReplay(void 0,void 0)};const[cfg,defaults]=await Promise.all([isConcreteChannel(channel)?readChannelConfig(this.channelKv,channel):Promise.resolve(void 0),readChannelDefaults(this.channelKv)]);return{replay:effectiveReplay(cfg,defaults),windowMs:effectiveReplayWindowMs(cfg,defaults)}}async collectHistory(subject,start,opts={}){return this.history.collectHistory(subject,start,opts)}async backfillChannel(channel,upToSeq,sinceMs,floorSeq){return this.history.backfillChannel(channel,upToSeq,sinceMs,floorSeq)}async recallChannel(channel,sinceSeq){return this.history.recallChannel(channel,sinceSeq)}async chatMayHaveLost(subject,sinceSeq){if(!this.jsm)throw new Error(this.notLiveMsg());const info=await this.jsm.streams.info(chatStream(this.space),{subjects_filter:subject});if(info.state.first_seq>sinceSeq+1)return true;const cap=info.config.max_msgs_per_subject;let maxPerSubject=0;for(const count of Object.values(info.state.subjects??{}))maxPerSubject=Math.max(maxPerSubject,count);if(cap<1||maxPerSubject<cap)return false;const oldest=(await this.collectHistory(subject,{seq:1},{limit:1}))[0]?.seq;return oldest!==void 0&&oldest>sinceSeq+1}async publishPresence(){return this.presence.publishPresence()}clearPresenceWriteFailure(){return this.presence.clearPresenceWriteFailure()}presenceWriteFailure(){return this.presence.presenceWriteFailure()}async startPresenceWatch(){return this.presence.startPresenceWatch()}async readPresenceOnce(){return this.presence.readPresenceOnce()}async startChannelWatch(){return this.channelDiscovery.startChannelWatch()}async readChannelsOnce(){return this.channelDiscovery.readChannelsOnce()}sweep(){return this.presence.sweep()}}}});var import_nkeys9,import_transport_node23,EVICT_PRINCIPALS_MAX;var init_evict=__esm({"../../packages/core/dist/evict.js"(){"use strict";init_connection_cleanup();import_nkeys9=__toESM(require_mod(),1);import_transport_node23=__toESM(require_transport_node(),1);init_endpoint();init_identity();init_subjects();EVICT_PRINCIPALS_MAX=256}});var SOURCE_CHAIN_ID,SOURCE_CHAIN_ELEMENT;var init_endpoint_service=__esm({"../../packages/core/dist/endpoint-service.js"(){"use strict";init_service_authority_limits();init_service_gate();init_subjects();init_canonical();init_endpoint_subjects();init_endpoint_envelope();init_endpoint_records();init_endpoint_cluster();init_canonical();init_remote_service_authority();init_endpoint_supervisor();init_evict();init_lifecycle_state();SOURCE_CHAIN_ID="[A-Za-z0-9_-]{1,64}";SOURCE_CHAIN_ELEMENT=new RegExp(`^(root|handle\\.${SOURCE_CHAIN_ID}\\.${SOURCE_CHAIN_ID}|session\\.${SOURCE_CHAIN_ID})$`)}});var init_endpoint_verbs=__esm({"../../packages/core/dist/endpoint-verbs.js"(){"use strict";init_subjects();init_endpoint_subjects();init_endpoint_envelope();init_endpoint_service();init_endpoint_call();init_endpoint_call()}});async function fetchClusterDocument(store,closureDigest,walk){const{manifest,artifacts}=await fetchContractClosure(store,closureDigest,()=>[],walk);const rootBytes=artifacts.get(contractRefToHex(manifest.root));if(rootBytes===void 0)throw new EpEnvelopeError("failed-precondition",`the cluster manifest ${closureDigest} names root ${manifest.root} but the root artifact is absent from the fetched closure (SPEC 13.7)`);return parseClusterDocument(JSON.parse(dec3.decode(rootBytes)))}async function recompileClosure(store,closureDigest,walk){const{manifest,artifacts}=await fetchContractClosure(store,closureDigest,bytes=>extractSchemaRefs(bytes),walk);const members={};for(const[hex3,bytes]of artifacts)members[`sha256:${hex3}`]=JSON.parse(dec3.decode(bytes));const rootRef=manifest.root;const root=members[rootRef];if(root===void 0)throw new EpEnvelopeError("failed-precondition",`schema closure ${closureDigest} is missing its root ${rootRef} (SPEC 13.7)`);const bundleMembers={};for(const[ref,value]of Object.entries(members))if(ref!==rootRef)bundleMembers[ref]=value;const compiled=compileContract({root,members:bundleMembers});if(compiled.closureDigest!==closureDigest)throw new EpEnvelopeError("internal",`the recompiled schema closure hashes to ${compiled.closureDigest}, not the fetched ${closureDigest}; a store that served the wrong bytes never authorizes (SPEC 13.7)`);return compiled}function extractSchemaRefs(bytes){const refs=[];const walk=v3=>{if(typeof v3==="string"){const m2=/^cotal:(sha256:[0-9a-f]{64})$/.exec(v3);if(m2)refs.push(m2[1])}else if(Array.isArray(v3)){for(const c3 of v3)walk(c3)}else if(v3!==null&&typeof v3==="object"){for(const c3 of Object.values(v3))walk(c3)}};walk(JSON.parse(dec3.decode(bytes)));return refs}async function pooled(items,limit,work){const out=new Array(items.length);let next=0;const worker=async()=>{for(;;){const i2=next++;if(i2>=items.length)return;try{out[i2]=await work(items[i2])}catch(e3){next=items.length;throw e3}}};await Promise.all(Array.from({length:Math.min(limit,items.length)},worker));return out}async function resolveService(nc,space2,endpoint,caller,opts={}){if(opts.commands!==void 0){if(!Array.isArray(opts.commands)||opts.commands.length===0)throw new EpEnvelopeError("failed-precondition","commands must be a non-empty array when a resolve is narrowed");for(const command of opts.commands){try{assertCommandToken(command)}catch(e3){throw new EpEnvelopeError("failed-precondition",`invalid requested command: ${e3.message}`)}}}if(opts.optionalCommands!==void 0){if(!Array.isArray(opts.optionalCommands)||opts.optionalCommands.length===0)throw new EpEnvelopeError("failed-precondition","optionalCommands must be a non-empty array when supplied");for(const command of opts.optionalCommands){try{assertCommandToken(command)}catch(e3){throw new EpEnvelopeError("failed-precondition",`invalid optional command: ${e3.message}`)}}}const startedAt2=performance.now();const deadlineMs=opts.deadlineMs??1e4;const{answer,responder}=await describeEndpoint(nc,space2,endpoint,caller,{...opts,deadlineMs});const store=await contractStoreContext(nc,space2);const visible=new Set(answer.descriptor.clusters.flatMap(cl=>cl.commands));const requested=opts.commands===void 0?visible:new Set(opts.commands);const optional3=new Set(opts.optionalCommands);for(const command of requested){if(visible.has(command))continue;if(optional3.has(command)){requested.delete(command);continue}throw new EpEnvelopeError("not-found",`command "${command}" is not in ${endpoint}'s visible surface; describe lists ${[...visible].sort().join(", ")||"(none)"}`)}const artifactMemo=new Map;const walk=()=>{const walkBudgetMs=Math.floor(deadlineMs-(performance.now()-startedAt2));if(walkBudgetMs<=0)throw new EpEnvelopeError("deadline-exceeded",`resolving ${endpoint} exhausted its ${deadlineMs}ms deadline before a contract-store read`);return{artifactMemo,walkBudgetMs,...opts.signal?{signal:opts.signal}:{}}};const clusters=answer.descriptor.clusters.filter(cl=>cl.commands.some(command=>requested.has(command)));const docs=await pooled(clusters,RESOLVE_MAX_INFLIGHT_READS,cl=>{opts.signal?.throwIfAborted();return fetchClusterDocument(store,cl.digest,walk())});const declared=docs.flatMap(doc=>doc.commands).filter(cmd=>requested.has(cmd.name));const resolved=await pooled(declared,Math.max(1,RESOLVE_MAX_INFLIGHT_READS>>1),async cmd=>{opts.signal?.throwIfAborted();const[input,output]=await Promise.all([recompileClosure(store,cmd.inputDigest,walk()),recompileClosure(store,cmd.outputDigest,walk())]);return{command:cmd.name,contract:{input,output},class:cmd.class,targeted:cmd.targeted,modes:cmd.modes??[],capability:cmd.capability,...cmd.action?{action:true}:{}}});opts.signal?.throwIfAborted();const commands=new Map;for(const rc of resolved)commands.set(rc.command,rc);return{endpoint:answer.descriptor.endpoint,owner:answer.descriptor.owner,caller,responder,commands,...opts.instanceId!==void 0?{pinnedInstanceId:opts.instanceId}:{}}}function submitAndFollowGoal(nc,space2,endpoint,caller,deadlineMs,submit,opts){return submitAndFollowGoalWith(parseGoalResultFact,nc,space2,endpoint,caller,deadlineMs,submit,opts)}var import_jetstream23,RESOLVE_MAX_INFLIGHT_READS;var init_endpoint_invoke=__esm({"../../packages/core/dist/endpoint-invoke.js"(){"use strict";import_jetstream23=__toESM(require_mod4(),1);init_endpoint_envelope();init_schema_profile();init_endpoint_action();init_endpoint_goal_follow();init_endpoint_contract_store();init_endpoint_cluster();init_endpoint_verbs();init_endpoint_subjects();init_endpoint_caller();init_endpoint_caller();RESOLVE_MAX_INFLIGHT_READS=32}});async function registryListingCaller(nc,space2,caller,credential){if(isIssuedCaller(caller))return caller;if(credential.exp===void 0)return void 0;try{return await issuedCallerOfToken(nc,space2,listingAcceptedToken(credential.connId,credential.exp),caller)}catch(e3){if(isPermissionDenied(e3))return void 0;throw e3}}async function listRegistryEndpoints(space2,describe4,ask,input,opts={}){const deadline=Date.now()+(opts.deadlineMs??1e4);const ours=REGISTRY_CONTRACTS[REGISTRY_ENDPOINTS_COMMAND];let reply;for(let attempt=0;attempt<=BIND_SPLIT_REISSUES&&Date.now()<deadline;attempt++){const service=await describe4(deadline-Date.now(),opts.signal);const theirs=service.commands.get(REGISTRY_ENDPOINTS_COMMAND).contract;if(theirs.input.closureDigest!==ours.input.closureDigest||theirs.output.closureDigest!==ours.output.closureDigest)throw new EpEnvelopeError("contract-mismatch",`the registry serves a version of "${REGISTRY_ENDPOINTS_COMMAND}" this client does not implement; upgrade the client (SPEC 13.20)`);try{reply=await invokeCommand(ask.nc,space2,service,REGISTRY_ENDPOINTS_COMMAND,{...input},{deadlineMs:deadline-Date.now(),signal:opts.signal,...ask.caller?{caller:ask.caller}:{}})}catch(e3){if(ask.caller!==void 0&&e3 instanceof EpEnvelopeError&&e3.code==="permission-denied"&&e3.outcome==="not-executed")return{unbound:true};throw e3}if(reply.reply.ok!==false||!replyRefusedBeforeEffect(reply.reply.error))break}if(reply===void 0)throw new EpEnvelopeError("deadline-exceeded","the registry was not reached before the deadline");return{reply,...reply.reply.ok===true?{page:reply.reply.data}:{}}}var init_registry_client=__esm({"../../packages/core/dist/registry-client.js"(){"use strict";init_endpoint_invoke();init_endpoint_error();init_endpoint_subjects();init_issued_authority();init_permission_denied();init_registry_contract()}});var import_jetstream24,import_kv11,import_transport_node24;var init_space_resource_definitions=__esm({"../../packages/core/dist/space-resource-definitions.js"(){"use strict";import_jetstream24=__toESM(require_mod4(),1);import_kv11=__toESM(require_mod6(),1);import_transport_node24=__toESM(require_transport_node(),1);init_backup_config();init_subjects();init_channels();init_endpoint_binding();init_issued_authority();init_run_admission();init_streams()}});function $constructor(name2,initializer3,params){function init(inst,def){if(!inst._zod){Object.defineProperty(inst,"_zod",{value:{def,constr:_3,traits:new Set},enumerable:false})}if(inst._zod.traits.has(name2)){return}inst._zod.traits.add(name2);initializer3(inst,def);const proto=_3.prototype;const keys=Object.keys(proto);for(let i2=0;i2<keys.length;i2++){const k2=keys[i2];if(!(k2 in inst)){inst[k2]=proto[k2].bind(inst)}}}const Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name2});function _3(def){var _a3;const inst=params?.Parent?new Definition:this;init(inst,def);(_a3=inst._zod).deferred??(_a3.deferred=[]);for(const fn2 of inst._zod.deferred){fn2()}return inst}Object.defineProperty(_3,"init",{value:init});Object.defineProperty(_3,Symbol.hasInstance,{value:inst=>{if(params?.Parent&&inst instanceof params.Parent)return true;return inst?._zod?.traits?.has(name2)}});Object.defineProperty(_3,"name",{value:name2});return _3}function config(newConfig){if(newConfig)Object.assign(globalConfig,newConfig);return globalConfig}var _a,NEVER,$brand,$ZodAsyncError,$ZodEncodeError,globalConfig;var init_core=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js"(){NEVER=Object.freeze({status:"aborted"});$brand=Symbol("zod_brand");$ZodAsyncError=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}};$ZodEncodeError=class extends Error{constructor(name2){super(`Encountered unidirectional transform during encode: ${name2}`);this.name="ZodEncodeError"}};(_a=globalThis).__zod_globalConfig??(_a.__zod_globalConfig={});globalConfig=globalThis.__zod_globalConfig}});var util_exports={};__export(util_exports,{BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES,Class:()=>Class,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,aborted:()=>aborted,allowsEval:()=>allowsEval,assert:()=>assert,assertEqual:()=>assertEqual,assertIs:()=>assertIs,assertNever:()=>assertNever,assertNotEqual:()=>assertNotEqual,assignProp:()=>assignProp,base64ToUint8Array:()=>base64ToUint8Array,base64urlToUint8Array:()=>base64urlToUint8Array,cached:()=>cached,captureStackTrace:()=>captureStackTrace,cleanEnum:()=>cleanEnum,cleanRegex:()=>cleanRegex,clone:()=>clone,cloneDef:()=>cloneDef,createTransparentProxy:()=>createTransparentProxy,defineLazy:()=>defineLazy,esc:()=>esc,escapeRegex:()=>escapeRegex,explicitlyAborted:()=>explicitlyAborted,extend:()=>extend,finalizeIssue:()=>finalizeIssue,floatSafeRemainder:()=>floatSafeRemainder,getElementAtPath:()=>getElementAtPath,getEnumValues:()=>getEnumValues,getLengthableOrigin:()=>getLengthableOrigin,getParsedType:()=>getParsedType,getSizableOrigin:()=>getSizableOrigin,hexToUint8Array:()=>hexToUint8Array,isObject:()=>isObject,isPlainObject:()=>isPlainObject,issue:()=>issue,joinValues:()=>joinValues,jsonStringifyReplacer:()=>jsonStringifyReplacer,merge:()=>merge,mergeDefs:()=>mergeDefs,normalizeParams:()=>normalizeParams,nullish:()=>nullish,numKeys:()=>numKeys,objectClone:()=>objectClone,omit:()=>omit,optionalKeys:()=>optionalKeys,parsedType:()=>parsedType,partial:()=>partial,pick:()=>pick,prefixIssues:()=>prefixIssues,primitiveTypes:()=>primitiveTypes,promiseAllObject:()=>promiseAllObject,propertyKeyTypes:()=>propertyKeyTypes,randomString:()=>randomString,required:()=>required,safeExtend:()=>safeExtend,shallowClone:()=>shallowClone,slugify:()=>slugify,stringifyPrimitive:()=>stringifyPrimitive,uint8ArrayToBase64:()=>uint8ArrayToBase64,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToHex:()=>uint8ArrayToHex,unwrapMessage:()=>unwrapMessage});function assertEqual(val){return val}function assertNotEqual(val){return val}function assertIs(_arg){}function assertNever(_x){throw new Error("Unexpected value in exhaustive check")}function assert(_3){}function getEnumValues(entries){const numericValues=Object.values(entries).filter(v3=>typeof v3==="number");const values=Object.entries(entries).filter(([k2,_3])=>numericValues.indexOf(+k2)===-1).map(([_3,v3])=>v3);return values}function joinValues(array2,separator="|"){return array2.map(val=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_3,value){if(typeof value==="bigint")return value.toString();return value}function cached(getter){const set3=false;return{get value(){if(!set3){const value=getter();Object.defineProperty(this,"value",{value});return value}throw new Error("cached value already set")}}}function nullish(input){return input===null||input===void 0}function cleanRegex(source){const start=source.startsWith("^")?1:0;const end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder(val,step){const ratio=val/step;const roundedRatio=Math.round(ratio);const tolerance=Number.EPSILON*Math.max(Math.abs(ratio),1);if(Math.abs(ratio-roundedRatio)<tolerance)return 0;return ratio-roundedRatio}function defineLazy(object2,key,getter){let value=void 0;Object.defineProperty(object2,key,{get(){if(value===EVALUATING){return void 0}if(value===void 0){value=EVALUATING;value=getter()}return value},set(v3){Object.defineProperty(object2,key,{value:v3})},configurable:true})}function objectClone(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp(target2,prop,value){Object.defineProperty(target2,prop,{value,writable:true,enumerable:true,configurable:true})}function mergeDefs(...defs){const mergedDescriptors={};for(const def of defs){const descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef(schema){return mergeDefs(schema._zod.def)}function getElementAtPath(obj,path4){if(!path4)return obj;return path4.reduce((acc,key)=>acc?.[key],obj)}function promiseAllObject(promisesObj){const keys=Object.keys(promisesObj);const promises=keys.map(key=>promisesObj[key]);return Promise.all(promises).then(results=>{const resolvedObj={};for(let i2=0;i2<keys.length;i2++){resolvedObj[keys[i2]]=results[i2]}return resolvedObj})}function randomString(length=10){const chars="abcdefghijklmnopqrstuvwxyz";let str2="";for(let i2=0;i2<length;i2++){str2+=chars[Math.floor(Math.random()*chars.length)]}return str2}function esc(str2){return JSON.stringify(str2)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function isObject(data){return typeof data==="object"&&data!==null&&!Array.isArray(data)}function isPlainObject(o3){if(isObject(o3)===false)return false;const ctor=o3.constructor;if(ctor===void 0)return true;if(typeof ctor!=="function")return true;const prot=ctor.prototype;if(isObject(prot)===false)return false;if(Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===false){return false}return true}function shallowClone(o3){if(isPlainObject(o3))return{...o3};if(Array.isArray(o3))return[...o3];if(o3 instanceof Map)return new Map(o3);if(o3 instanceof Set)return new Set(o3);return o3}function numKeys(data){let keyCount=0;for(const key in data){if(Object.prototype.hasOwnProperty.call(data,key)){keyCount++}}return keyCount}function escapeRegex(str2){return str2.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){const cl=new inst._zod.constr(def??inst._zod.def);if(!def||params?.parent)cl._zod.parent=inst;return cl}function normalizeParams(_params){const params=_params;if(!params)return{};if(typeof params==="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");params.error=params.message}delete params.message;if(typeof params.error==="string")return{...params,error:()=>params.error};return params}function createTransparentProxy(getter){let target2;return new Proxy({},{get(_3,prop,receiver){target2??(target2=getter());return Reflect.get(target2,prop,receiver)},set(_3,prop,value,receiver){target2??(target2=getter());return Reflect.set(target2,prop,value,receiver)},has(_3,prop){target2??(target2=getter());return Reflect.has(target2,prop)},deleteProperty(_3,prop){target2??(target2=getter());return Reflect.deleteProperty(target2,prop)},ownKeys(_3){target2??(target2=getter());return Reflect.ownKeys(target2)},getOwnPropertyDescriptor(_3,prop){target2??(target2=getter());return Reflect.getOwnPropertyDescriptor(target2,prop)},defineProperty(_3,prop,descriptor){target2??(target2=getter());return Reflect.defineProperty(target2,prop,descriptor)}})}function stringifyPrimitive(value){if(typeof value==="bigint")return value.toString()+"n";if(typeof value==="string")return`"${value}"`;return`${value}`}function optionalKeys(shape){return Object.keys(shape).filter(k2=>{return shape[k2]._zod.optin==="optional"&&shape[k2]._zod.optout==="optional"})}function pick(schema,mask){const currDef=schema._zod.def;const checks=currDef.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){throw new Error(".pick() cannot be used on object schemas containing refinements")}const def=mergeDefs(schema._zod.def,{get shape(){const newShape={};for(const key in mask){if(!(key in currDef.shape)){throw new Error(`Unrecognized key: "${key}"`)}if(!mask[key])continue;newShape[key]=currDef.shape[key]}assignProp(this,"shape",newShape);return newShape},checks:[]});return clone(schema,def)}function omit(schema,mask){const currDef=schema._zod.def;const checks=currDef.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){throw new Error(".omit() cannot be used on object schemas containing refinements")}const def=mergeDefs(schema._zod.def,{get shape(){const newShape={...schema._zod.def.shape};for(const key in mask){if(!(key in currDef.shape)){throw new Error(`Unrecognized key: "${key}"`)}if(!mask[key])continue;delete newShape[key]}assignProp(this,"shape",newShape);return newShape},checks:[]});return clone(schema,def)}function extend(schema,shape){if(!isPlainObject(shape)){throw new Error("Invalid input to extend: expected a plain object")}const checks=schema._zod.def.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){const existingShape=schema._zod.def.shape;for(const key in shape){if(Object.getOwnPropertyDescriptor(existingShape,key)!==void 0){throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}}}const def=mergeDefs(schema._zod.def,{get shape(){const _shape={...schema._zod.def.shape,...shape};assignProp(this,"shape",_shape);return _shape}});return clone(schema,def)}function safeExtend(schema,shape){if(!isPlainObject(shape)){throw new Error("Invalid input to safeExtend: expected a plain object")}const def=mergeDefs(schema._zod.def,{get shape(){const _shape={...schema._zod.def.shape,...shape};assignProp(this,"shape",_shape);return _shape}});return clone(schema,def)}function merge(a3,b3){if(a3._zod.def.checks?.length){throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.")}const def=mergeDefs(a3._zod.def,{get shape(){const _shape={...a3._zod.def.shape,...b3._zod.def.shape};assignProp(this,"shape",_shape);return _shape},get catchall(){return b3._zod.def.catchall},checks:b3._zod.def.checks??[]});return clone(a3,def)}function partial(Class2,schema,mask){const currDef=schema._zod.def;const checks=currDef.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){throw new Error(".partial() cannot be used on object schemas containing refinements")}const def=mergeDefs(schema._zod.def,{get shape(){const oldShape=schema._zod.def.shape;const shape={...oldShape};if(mask){for(const key in mask){if(!(key in oldShape)){throw new Error(`Unrecognized key: "${key}"`)}if(!mask[key])continue;shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key]}}else{for(const key in oldShape){shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key]}}assignProp(this,"shape",shape);return shape},checks:[]});return clone(schema,def)}function required(Class2,schema,mask){const def=mergeDefs(schema._zod.def,{get shape(){const oldShape=schema._zod.def.shape;const shape={...oldShape};if(mask){for(const key in mask){if(!(key in shape)){throw new Error(`Unrecognized key: "${key}"`)}if(!mask[key])continue;shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]})}}else{for(const key in oldShape){shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]})}}assignProp(this,"shape",shape);return shape}});return clone(schema,def)}function aborted(x2,startIndex=0){if(x2.aborted===true)return true;for(let i2=startIndex;i2<x2.issues.length;i2++){if(x2.issues[i2]?.continue!==true){return true}}return false}function explicitlyAborted(x2,startIndex=0){if(x2.aborted===true)return true;for(let i2=startIndex;i2<x2.issues.length;i2++){if(x2.issues[i2]?.continue===false){return true}}return false}function prefixIssues(path4,issues){return issues.map(iss=>{var _a3;(_a3=iss).path??(_a3.path=[]);iss.path.unshift(path4);return iss})}function unwrapMessage(message){return typeof message==="string"?message:message?.message}function finalizeIssue(iss,ctx,config2){const message=iss.message?iss.message:unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config2.customError?.(iss))??unwrapMessage(config2.localeError?.(iss))??"Invalid input";const{inst:_inst,continue:_continue,input:_input,...rest}=iss;rest.path??(rest.path=[]);rest.message=message;if(ctx?.reportInput){rest.input=_input}return rest}function getSizableOrigin(input){if(input instanceof Set)return"set";if(input instanceof Map)return"map";if(input instanceof File)return"file";return"unknown"}function getLengthableOrigin(input){if(Array.isArray(input))return"array";if(typeof input==="string")return"string";return"unknown"}function parsedType(data){const t2=typeof data;switch(t2){case"number":{return Number.isNaN(data)?"nan":"number"}case"object":{if(data===null){return"null"}if(Array.isArray(data)){return"array"}const obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor){return obj.constructor.name}}}return t2}function issue(...args){const[iss,input,inst]=args;if(typeof iss==="string"){return{message:iss,code:"custom",input,inst}}return{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k2,_3])=>{return Number.isNaN(Number.parseInt(k2,10))}).map(el=>el[1])}function base64ToUint8Array(base643){const binaryString=atob(base643);const bytes=new Uint8Array(binaryString.length);for(let i2=0;i2<binaryString.length;i2++){bytes[i2]=binaryString.charCodeAt(i2)}return bytes}function uint8ArrayToBase64(bytes){let binaryString="";for(let i2=0;i2<bytes.length;i2++){binaryString+=String.fromCharCode(bytes[i2])}return btoa(binaryString)}function base64urlToUint8Array(base64url4){const base643=base64url4.replace(/-/g,"+").replace(/_/g,"/");const padding="=".repeat((4-base643.length%4)%4);return base64ToUint8Array(base643+padding)}function uint8ArrayToBase64url(bytes){return uint8ArrayToBase64(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array(hex3){const cleanHex=hex3.replace(/^0x/,"");if(cleanHex.length%2!==0){throw new Error("Invalid hex string length")}const bytes=new Uint8Array(cleanHex.length/2);for(let i2=0;i2<cleanHex.length;i2+=2){bytes[i2/2]=Number.parseInt(cleanHex.slice(i2,i2+2),16)}return bytes}function uint8ArrayToHex(bytes){return Array.from(bytes).map(b3=>b3.toString(16).padStart(2,"0")).join("")}var EVALUATING,captureStackTrace,allowsEval,getParsedType,propertyKeyTypes,primitiveTypes,NUMBER_FORMAT_RANGES,BIGINT_FORMAT_RANGES,Class;var init_util=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js"(){init_core();EVALUATING=Symbol("evaluating");captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};allowsEval=cached(()=>{if(globalConfig.jitless){return false}if(typeof navigator!=="undefined"&&navigator?.userAgent?.includes("Cloudflare")){return false}try{const F2=Function;new F2("");return true}catch(_3){return false}});getParsedType=data=>{const t2=typeof data;switch(t2){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(data)){return"array"}if(data===null){return"null"}if(data.then&&typeof data.then==="function"&&data.catch&&typeof data.catch==="function"){return"promise"}if(typeof Map!=="undefined"&&data instanceof Map){return"map"}if(typeof Set!=="undefined"&&data instanceof Set){return"set"}if(typeof Date!=="undefined"&&data instanceof Date){return"date"}if(typeof File!=="undefined"&&data instanceof File){return"file"}return"object";default:throw new Error(`Unknown data type: ${t2}`)}};propertyKeyTypes=new Set(["string","number","symbol"]);primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Class=class{constructor(..._args){}}}});function flattenError(error51,mapper=issue2=>issue2.message){const fieldErrors={};const formErrors=[];for(const sub of error51.issues){if(sub.path.length>0){fieldErrors[sub.path[0]]=fieldErrors[sub.path[0]]||[];fieldErrors[sub.path[0]].push(mapper(sub))}else{formErrors.push(mapper(sub))}}return{formErrors,fieldErrors}}function formatError(error51,mapper=issue2=>issue2.message){const fieldErrors={_errors:[]};const processError=(error52,path4=[])=>{for(const issue2 of error52.issues){if(issue2.code==="invalid_union"&&issue2.errors.length){issue2.errors.map(issues=>processError({issues},[...path4,...issue2.path]))}else if(issue2.code==="invalid_key"){processError({issues:issue2.issues},[...path4,...issue2.path])}else if(issue2.code==="invalid_element"){processError({issues:issue2.issues},[...path4,...issue2.path])}else{const fullpath=[...path4,...issue2.path];if(fullpath.length===0){fieldErrors._errors.push(mapper(issue2))}else{let curr=fieldErrors;let i2=0;while(i2<fullpath.length){const el=fullpath[i2];const terminal=i2===fullpath.length-1;if(!terminal){curr[el]=curr[el]||{_errors:[]}}else{curr[el]=curr[el]||{_errors:[]};curr[el]._errors.push(mapper(issue2))}curr=curr[el];i2++}}}}};processError(error51);return fieldErrors}function treeifyError(error51,mapper=issue2=>issue2.message){const result={errors:[]};const processError=(error52,path4=[])=>{var _a3,_b;for(const issue2 of error52.issues){if(issue2.code==="invalid_union"&&issue2.errors.length){issue2.errors.map(issues=>processError({issues},[...path4,...issue2.path]))}else if(issue2.code==="invalid_key"){processError({issues:issue2.issues},[...path4,...issue2.path])}else if(issue2.code==="invalid_element"){processError({issues:issue2.issues},[...path4,...issue2.path])}else{const fullpath=[...path4,...issue2.path];if(fullpath.length===0){result.errors.push(mapper(issue2));continue}let curr=result;let i2=0;while(i2<fullpath.length){const el=fullpath[i2];const terminal=i2===fullpath.length-1;if(typeof el==="string"){curr.properties??(curr.properties={});(_a3=curr.properties)[el]??(_a3[el]={errors:[]});curr=curr.properties[el]}else{curr.items??(curr.items=[]);(_b=curr.items)[el]??(_b[el]={errors:[]});curr=curr.items[el]}if(terminal){curr.errors.push(mapper(issue2))}i2++}}}};processError(error51);return result}function toDotPath(_path){const segs=[];const path4=_path.map(seg=>typeof seg==="object"?seg.key:seg);for(const seg of path4){if(typeof seg==="number")segs.push(`[${seg}]`);else if(typeof seg==="symbol")segs.push(`[${JSON.stringify(String(seg))}]`);else if(/[^\w$]/.test(seg))segs.push(`[${JSON.stringify(seg)}]`);else{if(segs.length)segs.push(".");segs.push(seg)}}return segs.join("")}function prettifyError(error51){const lines=[];const issues=[...error51.issues].sort((a3,b3)=>(a3.path??[]).length-(b3.path??[]).length);for(const issue2 of issues){lines.push(`\u2716 ${issue2.message}`);if(issue2.path?.length)lines.push(` \u2192 at ${toDotPath(issue2.path)}`)}return lines.join("\n")}var initializer,$ZodError,$ZodRealError;var init_errors=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js"(){init_core();init_util();initializer=(inst,def)=>{inst.name="$ZodError";Object.defineProperty(inst,"_zod",{value:inst._zod,enumerable:false});Object.defineProperty(inst,"issues",{value:def,enumerable:false});inst.message=JSON.stringify(def,jsonStringifyReplacer,2);Object.defineProperty(inst,"toString",{value:()=>inst.message,enumerable:false})};$ZodError=$constructor("$ZodError",initializer);$ZodRealError=$constructor("$ZodError",initializer,{Parent:Error})}});var _parse,parse,_parseAsync,parseAsync,_safeParse,safeParse,_safeParseAsync,safeParseAsync,_encode,encode2,_decode,decode3,_encodeAsync,encodeAsync,_decodeAsync,decodeAsync,_safeEncode,safeEncode,_safeDecode,safeDecode,_safeEncodeAsync,safeEncodeAsync,_safeDecodeAsync,safeDecodeAsync;var init_parse=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js"(){init_core();init_errors();init_util();_parse=_Err=>(schema,value,_ctx,_params)=>{const ctx=_ctx?{..._ctx,async:false}:{async:false};const result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise){throw new $ZodAsyncError}if(result.issues.length){const e3=new(_params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));captureStackTrace(e3,_params?.callee);throw e3}return result.value};parse=_parse($ZodRealError);_parseAsync=_Err=>async(schema,value,_ctx,params)=>{const ctx=_ctx?{..._ctx,async:true}:{async:true};let result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;if(result.issues.length){const e3=new(params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));captureStackTrace(e3,params?.callee);throw e3}return result.value};parseAsync=_parseAsync($ZodRealError);_safeParse=_Err=>(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,async:false}:{async:false};const result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise){throw new $ZodAsyncError}return result.issues.length?{success:false,error:new(_Err??$ZodError)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:true,data:result.value}};safeParse=_safeParse($ZodRealError);_safeParseAsync=_Err=>async(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,async:true}:{async:true};let result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;return result.issues.length?{success:false,error:new _Err(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:true,data:result.value}};safeParseAsync=_safeParseAsync($ZodRealError);_encode=_Err=>(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _parse(_Err)(schema,value,ctx)};encode2=_encode($ZodRealError);_decode=_Err=>(schema,value,_ctx)=>{return _parse(_Err)(schema,value,_ctx)};decode3=_decode($ZodRealError);_encodeAsync=_Err=>async(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _parseAsync(_Err)(schema,value,ctx)};encodeAsync=_encodeAsync($ZodRealError);_decodeAsync=_Err=>async(schema,value,_ctx)=>{return _parseAsync(_Err)(schema,value,_ctx)};decodeAsync=_decodeAsync($ZodRealError);_safeEncode=_Err=>(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParse(_Err)(schema,value,ctx)};safeEncode=_safeEncode($ZodRealError);_safeDecode=_Err=>(schema,value,_ctx)=>{return _safeParse(_Err)(schema,value,_ctx)};safeDecode=_safeDecode($ZodRealError);_safeEncodeAsync=_Err=>async(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParseAsync(_Err)(schema,value,ctx)};safeEncodeAsync=_safeEncodeAsync($ZodRealError);_safeDecodeAsync=_Err=>async(schema,value,_ctx)=>{return _safeParseAsync(_Err)(schema,value,_ctx)};safeDecodeAsync=_safeDecodeAsync($ZodRealError)}});var regexes_exports={};__export(regexes_exports,{base64:()=>base64,base64url:()=>base64url2,bigint:()=>bigint,boolean:()=>boolean,browserEmail:()=>browserEmail,cidrv4:()=>cidrv4,cidrv6:()=>cidrv6,cuid:()=>cuid,cuid2:()=>cuid2,date:()=>date,datetime:()=>datetime,domain:()=>domain,duration:()=>duration,e164:()=>e164,email:()=>email,emoji:()=>emoji,extendedDuration:()=>extendedDuration,guid:()=>guid,hex:()=>hex,hostname:()=>hostname3,html5Email:()=>html5Email,httpProtocol:()=>httpProtocol,idnEmail:()=>idnEmail,integer:()=>integer,ipv4:()=>ipv4,ipv6:()=>ipv6,ksuid:()=>ksuid,lowercase:()=>lowercase,mac:()=>mac,md5_base64:()=>md5_base64,md5_base64url:()=>md5_base64url,md5_hex:()=>md5_hex,nanoid:()=>nanoid,null:()=>_null,number:()=>number,rfc5322Email:()=>rfc5322Email,sha1_base64:()=>sha1_base64,sha1_base64url:()=>sha1_base64url,sha1_hex:()=>sha1_hex,sha256_base64:()=>sha256_base64,sha256_base64url:()=>sha256_base64url,sha256_hex:()=>sha256_hex,sha384_base64:()=>sha384_base64,sha384_base64url:()=>sha384_base64url,sha384_hex:()=>sha384_hex,sha512_base64:()=>sha512_base64,sha512_base64url:()=>sha512_base64url,sha512_hex:()=>sha512_hex,string:()=>string,time:()=>time,ulid:()=>ulid,undefined:()=>_undefined,unicodeEmail:()=>unicodeEmail,uppercase:()=>uppercase,uuid:()=>uuid,uuid4:()=>uuid4,uuid6:()=>uuid6,uuid7:()=>uuid7,xid:()=>xid});function emoji(){return new RegExp(_emoji,"u")}function timeSource(args){const hhmm=`(?:[01]\\d|2[0-3]):[0-5]\\d`;const regex=typeof args.precision==="number"?args.precision===-1?`${hhmm}`:args.precision===0?`${hhmm}:[0-5]\\d`:`${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`:`${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;return regex}function time(args){return new RegExp(`^${timeSource(args)}$`)}function datetime(args){const time3=timeSource({precision:args.precision});const opts=["Z"];if(args.local)opts.push("");if(args.offset)opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);const timeRegex=`${time3}(?:${opts.join("|")})`;return new RegExp(`^${dateSource}T(?:${timeRegex})$`)}function fixedBase64(bodyLength,padding){return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`)}function fixedBase64url(length){return new RegExp(`^[A-Za-z0-9_-]{${length}}$`)}var cuid,cuid2,ulid,xid,ksuid,nanoid,duration,extendedDuration,guid,uuid,uuid4,uuid6,uuid7,email,html5Email,rfc5322Email,unicodeEmail,idnEmail,browserEmail,_emoji,ipv4,ipv6,mac,cidrv4,cidrv6,base64,base64url2,hostname3,domain,httpProtocol,e164,dateSource,date,string,bigint,integer,number,boolean,_null,_undefined,lowercase,uppercase,hex,md5_hex,md5_base64,md5_base64url,sha1_hex,sha1_base64,sha1_base64url,sha256_hex,sha256_base64,sha256_base64url,sha384_hex,sha384_base64,sha384_base64url,sha512_hex,sha512_base64,sha512_base64url;var init_regexes=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js"(){init_util();cuid=/^[cC][0-9a-z]{6,}$/;cuid2=/^[0-9a-z]+$/;ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;xid=/^[0-9a-vA-V]{20}$/;ksuid=/^[A-Za-z0-9]{27}$/;nanoid=/^[a-zA-Z0-9_-]{21}$/;duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;extendedDuration=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;uuid=version2=>{if(!version2)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};uuid4=uuid(4);uuid6=uuid(6);uuid7=uuid(7);email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;html5Email=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;rfc5322Email=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;unicodeEmail=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u;idnEmail=unicodeEmail;browserEmail=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;_emoji=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;mac=delimiter=>{const escapedDelim=escapeRegex(delimiter??":");return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`)};cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;base64url2=/^[A-Za-z0-9_-]*$/;hostname3=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;domain=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;httpProtocol=/^https?$/;e164=/^\+[1-9]\d{6,14}$/;dateSource=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;date=new RegExp(`^${dateSource}$`);string=params=>{const regex=params?`[\\s\\S]{${params?.minimum??0},${params?.maximum??""}}`:`[\\s\\S]*`;return new RegExp(`^${regex}$`)};bigint=/^-?\d+n?$/;integer=/^-?\d+$/;number=/^-?\d+(?:\.\d+)?$/;boolean=/^(?:true|false)$/i;_null=/^null$/i;_undefined=/^undefined$/i;lowercase=/^[^A-Z]*$/;uppercase=/^[^a-z]*$/;hex=/^[0-9a-fA-F]*$/;md5_hex=/^[0-9a-fA-F]{32}$/;md5_base64=fixedBase64(22,"==");md5_base64url=fixedBase64url(22);sha1_hex=/^[0-9a-fA-F]{40}$/;sha1_base64=fixedBase64(27,"=");sha1_base64url=fixedBase64url(27);sha256_hex=/^[0-9a-fA-F]{64}$/;sha256_base64=fixedBase64(43,"=");sha256_base64url=fixedBase64url(43);sha384_hex=/^[0-9a-fA-F]{96}$/;sha384_base64=fixedBase64(64,"");sha384_base64url=fixedBase64url(64);sha512_hex=/^[0-9a-fA-F]{128}$/;sha512_base64=fixedBase64(86,"==");sha512_base64url=fixedBase64url(86)}});function handleCheckPropertyResult(result,payload,property){if(result.issues.length){payload.issues.push(...prefixIssues(property,result.issues))}}var $ZodCheck,numericOriginMap,$ZodCheckLessThan,$ZodCheckGreaterThan,$ZodCheckMultipleOf,$ZodCheckNumberFormat,$ZodCheckBigIntFormat,$ZodCheckMaxSize,$ZodCheckMinSize,$ZodCheckSizeEquals,$ZodCheckMaxLength,$ZodCheckMinLength,$ZodCheckLengthEquals,$ZodCheckStringFormat,$ZodCheckRegex,$ZodCheckLowerCase,$ZodCheckUpperCase,$ZodCheckIncludes,$ZodCheckStartsWith,$ZodCheckEndsWith,$ZodCheckProperty,$ZodCheckMimeType,$ZodCheckOverwrite;var init_checks=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js"(){init_core();init_regexes();init_util();$ZodCheck=$constructor("$ZodCheck",(inst,def)=>{var _a3;inst._zod??(inst._zod={});inst._zod.def=def;(_a3=inst._zod).onattach??(_a3.onattach=[])});numericOriginMap={number:"number",bigint:"bigint",object:"date"};$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(inst,def)=>{$ZodCheck.init(inst,def);const origin=numericOriginMap[typeof def.value];inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;const curr=(def.inclusive?bag.maximum:bag.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(def.value<curr){if(def.inclusive)bag.maximum=def.value;else bag.exclusiveMaximum=def.value}});inst._zod.check=payload=>{if(def.inclusive?payload.value<=def.value:payload.value<def.value){return}payload.issues.push({origin,code:"too_big",maximum:typeof def.value==="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}});$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck.init(inst,def);const origin=numericOriginMap[typeof def.value];inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;const curr=(def.inclusive?bag.minimum:bag.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(def.value>curr){if(def.inclusive)bag.minimum=def.value;else bag.exclusiveMinimum=def.value}});inst._zod.check=payload=>{if(def.inclusive?payload.value>=def.value:payload.value>def.value){return}payload.issues.push({origin,code:"too_small",minimum:typeof def.value==="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}});$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck.init(inst,def);inst._zod.onattach.push(inst2=>{var _a3;(_a3=inst2._zod.bag).multipleOf??(_a3.multipleOf=def.value)});inst._zod.check=payload=>{if(typeof payload.value!==typeof def.value)throw new Error("Cannot mix number and bigint in multiple_of check.");const isMultiple=typeof payload.value==="bigint"?payload.value%def.value===BigInt(0):floatSafeRemainder(payload.value,def.value)===0;if(isMultiple)return;payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}});$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck.init(inst,def);def.format=def.format||"float64";const isInt=def.format?.includes("int");const origin=isInt?"int":"number";const[minimum,maximum]=NUMBER_FORMAT_RANGES[def.format];inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.format=def.format;bag.minimum=minimum;bag.maximum=maximum;if(isInt)bag.pattern=integer});inst._zod.check=payload=>{const input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:false,input,inst});return}if(!Number.isSafeInteger(input)){if(input>0){payload.issues.push({input,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:true,continue:!def.abort})}else{payload.issues.push({input,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:true,continue:!def.abort})}return}}if(input<minimum){payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:true,inst,continue:!def.abort})}if(input>maximum){payload.issues.push({origin:"number",input,code:"too_big",maximum,inclusive:true,inst,continue:!def.abort})}}});$ZodCheckBigIntFormat=$constructor("$ZodCheckBigIntFormat",(inst,def)=>{$ZodCheck.init(inst,def);const[minimum,maximum]=BIGINT_FORMAT_RANGES[def.format];inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.format=def.format;bag.minimum=minimum;bag.maximum=maximum});inst._zod.check=payload=>{const input=payload.value;if(input<minimum){payload.issues.push({origin:"bigint",input,code:"too_small",minimum,inclusive:true,inst,continue:!def.abort})}if(input>maximum){payload.issues.push({origin:"bigint",input,code:"too_big",maximum,inclusive:true,inst,continue:!def.abort})}}});$ZodCheckMaxSize=$constructor("$ZodCheckMaxSize",(inst,def)=>{var _a3;$ZodCheck.init(inst,def);(_a3=inst._zod.def).when??(_a3.when=payload=>{const val=payload.value;return!nullish(val)&&val.size!==void 0});inst._zod.onattach.push(inst2=>{const curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;if(def.maximum<curr)inst2._zod.bag.maximum=def.maximum});inst._zod.check=payload=>{const input=payload.value;const size=input.size;if(size<=def.maximum)return;payload.issues.push({origin:getSizableOrigin(input),code:"too_big",maximum:def.maximum,inclusive:true,input,inst,continue:!def.abort})}});$ZodCheckMinSize=$constructor("$ZodCheckMinSize",(inst,def)=>{var _a3;$ZodCheck.init(inst,def);(_a3=inst._zod.def).when??(_a3.when=payload=>{const val=payload.value;return!nullish(val)&&val.size!==void 0});inst._zod.onattach.push(inst2=>{const curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(def.minimum>curr)inst2._zod.bag.minimum=def.minimum});inst._zod.check=payload=>{const input=payload.value;const size=input.size;if(size>=def.minimum)return;payload.issues.push({origin:getSizableOrigin(input),code:"too_small",minimum:def.minimum,inclusive:true,input,inst,continue:!def.abort})}});$ZodCheckSizeEquals=$constructor("$ZodCheckSizeEquals",(inst,def)=>{var _a3;$ZodCheck.init(inst,def);(_a3=inst._zod.def).when??(_a3.when=payload=>{const val=payload.value;return!nullish(val)&&val.size!==void 0});inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.minimum=def.size;bag.maximum=def.size;bag.size=def.size});inst._zod.check=payload=>{const input=payload.value;const size=input.size;if(size===def.size)return;const tooBig=size>def.size;payload.issues.push({origin:getSizableOrigin(input),...tooBig?{code:"too_big",maximum:def.size}:{code:"too_small",minimum:def.size},inclusive:true,exact:true,input:payload.value,inst,continue:!def.abort})}});$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(inst,def)=>{var _a3;$ZodCheck.init(inst,def);(_a3=inst._zod.def).when??(_a3.when=payload=>{const val=payload.value;return!nullish(val)&&val.length!==void 0});inst._zod.onattach.push(inst2=>{const curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;if(def.maximum<curr)inst2._zod.bag.maximum=def.maximum});inst._zod.check=payload=>{const input=payload.value;const length=input.length;if(length<=def.maximum)return;const origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:true,input,inst,continue:!def.abort})}});$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(inst,def)=>{var _a3;$ZodCheck.init(inst,def);(_a3=inst._zod.def).when??(_a3.when=payload=>{const val=payload.value;return!nullish(val)&&val.length!==void 0});inst._zod.onattach.push(inst2=>{const curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(def.minimum>curr)inst2._zod.bag.minimum=def.minimum});inst._zod.check=payload=>{const input=payload.value;const length=input.length;if(length>=def.minimum)return;const origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:true,input,inst,continue:!def.abort})}});$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(inst,def)=>{var _a3;$ZodCheck.init(inst,def);(_a3=inst._zod.def).when??(_a3.when=payload=>{const val=payload.value;return!nullish(val)&&val.length!==void 0});inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.minimum=def.length;bag.maximum=def.length;bag.length=def.length});inst._zod.check=payload=>{const input=payload.value;const length=input.length;if(length===def.length)return;const origin=getLengthableOrigin(input);const tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:true,exact:true,input:payload.value,inst,continue:!def.abort})}});$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(inst,def)=>{var _a3,_b;$ZodCheck.init(inst,def);inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.format=def.format;if(def.pattern){bag.patterns??(bag.patterns=new Set);bag.patterns.add(def.pattern)}});if(def.pattern)(_a3=inst._zod).check??(_a3.check=payload=>{def.pattern.lastIndex=0;if(def.pattern.test(payload.value))return;payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})});else(_b=inst._zod).check??(_b.check=()=>{})});$ZodCheckRegex=$constructor("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat.init(inst,def);inst._zod.check=payload=>{def.pattern.lastIndex=0;if(def.pattern.test(payload.value))return;payload.issues.push({origin:"string",code:"invalid_format",format:"regex",input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}});$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase);$ZodCheckStringFormat.init(inst,def)});$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase);$ZodCheckStringFormat.init(inst,def)});$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(inst,def)=>{$ZodCheck.init(inst,def);const escapedRegex=escapeRegex(def.includes);const pattern=new RegExp(typeof def.position==="number"?`^.{${def.position}}${escapedRegex}`:escapedRegex);def.pattern=pattern;inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set);bag.patterns.add(pattern)});inst._zod.check=payload=>{if(payload.value.includes(def.includes,def.position))return;payload.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:def.includes,input:payload.value,inst,continue:!def.abort})}});$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck.init(inst,def);const pattern=new RegExp(`^${escapeRegex(def.prefix)}.*`);def.pattern??(def.pattern=pattern);inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set);bag.patterns.add(pattern)});inst._zod.check=payload=>{if(payload.value.startsWith(def.prefix))return;payload.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}});$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck.init(inst,def);const pattern=new RegExp(`.*${escapeRegex(def.suffix)}$`);def.pattern??(def.pattern=pattern);inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set);bag.patterns.add(pattern)});inst._zod.check=payload=>{if(payload.value.endsWith(def.suffix))return;payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}});$ZodCheckProperty=$constructor("$ZodCheckProperty",(inst,def)=>{$ZodCheck.init(inst,def);inst._zod.check=payload=>{const result=def.schema._zod.run({value:payload.value[def.property],issues:[]},{});if(result instanceof Promise){return result.then(result2=>handleCheckPropertyResult(result2,payload,def.property))}handleCheckPropertyResult(result,payload,def.property);return}});$ZodCheckMimeType=$constructor("$ZodCheckMimeType",(inst,def)=>{$ZodCheck.init(inst,def);const mimeSet=new Set(def.mime);inst._zod.onattach.push(inst2=>{inst2._zod.bag.mime=def.mime});inst._zod.check=payload=>{if(mimeSet.has(payload.value.type))return;payload.issues.push({code:"invalid_value",values:def.mime,input:payload.value.type,inst,continue:!def.abort})}});$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck.init(inst,def);inst._zod.check=payload=>{payload.value=def.tx(payload.value)}})}});var Doc;var init_doc=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js"(){Doc=class{constructor(args=[]){this.content=[];this.indent=0;if(this)this.args=args}indented(fn2){this.indent+=1;fn2(this);this.indent-=1}write(arg){if(typeof arg==="function"){arg(this,{execution:"sync"});arg(this,{execution:"async"});return}const content=arg;const lines=content.split("\n").filter(x2=>x2);const minIndent=Math.min(...lines.map(x2=>x2.length-x2.trimStart().length));const dedented=lines.map(x2=>x2.slice(minIndent)).map(x2=>" ".repeat(this.indent*2)+x2);for(const line of dedented){this.content.push(line)}}compile(){const F2=Function;const args=this?.args;const content=this?.content??[``];const lines=[...content.map(x2=>` ${x2}`)];return new F2(...args,lines.join("\n"))}}}});var version;var init_versions=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js"(){version={major:4,minor:4,patch:3}}});function isValidBase64(data){if(data==="")return true;if(/\s/.test(data))return false;if(data.length%4!==0)return false;try{atob(data);return true}catch{return false}}function isValidBase64URL(data){if(!base64url2.test(data))return false;const base643=data.replace(/[-_]/g,c3=>c3==="-"?"+":"/");const padded=base643.padEnd(Math.ceil(base643.length/4)*4,"=");return isValidBase64(padded)}function isValidJWT(token2,algorithm=null){try{const tokensParts=token2.split(".");if(tokensParts.length!==3)return false;const[header]=tokensParts;if(!header)return false;const parsedHeader=JSON.parse(atob(header));if("typ"in parsedHeader&&parsedHeader?.typ!=="JWT")return false;if(!parsedHeader.alg)return false;if(algorithm&&(!("alg"in parsedHeader)||parsedHeader.alg!==algorithm))return false;return true}catch{return false}}function handleArrayResult(result,final,index2){if(result.issues.length){final.issues.push(...prefixIssues(index2,result.issues))}final.value[index2]=result.value}function handlePropertyResult(result,final,key,input,isOptionalIn,isOptionalOut){const isPresent=key in input;if(result.issues.length){if(isOptionalIn&&isOptionalOut&&!isPresent){return}final.issues.push(...prefixIssues(key,result.issues))}if(!isPresent&&!isOptionalIn){if(!result.issues.length){final.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[key]})}return}if(result.value===void 0){if(isPresent){final.value[key]=void 0}}else{final.value[key]=result.value}}function normalizeDef(def){const keys=Object.keys(def.shape);for(const k2 of keys){if(!def.shape?.[k2]?._zod?.traits?.has("$ZodType")){throw new Error(`Invalid element at key "${k2}": expected a Zod schema`)}}const okeys=optionalKeys(def.shape);return{...def,keys,keySet:new Set(keys),numKeys:keys.length,optionalKeys:new Set(okeys)}}function handleCatchall(proms,input,payload,ctx,def,inst){const unrecognized=[];const keySet=def.keySet;const _catchall=def.catchall._zod;const t2=_catchall.def.type;const isOptionalIn=_catchall.optin==="optional";const isOptionalOut=_catchall.optout==="optional";for(const key in input){if(key==="__proto__")continue;if(keySet.has(key))continue;if(t2==="never"){unrecognized.push(key);continue}const r2=_catchall.run({value:input[key],issues:[]},ctx);if(r2 instanceof Promise){proms.push(r2.then(r3=>handlePropertyResult(r3,payload,key,input,isOptionalIn,isOptionalOut)))}else{handlePropertyResult(r2,payload,key,input,isOptionalIn,isOptionalOut)}}if(unrecognized.length){payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input,inst})}if(!proms.length)return payload;return Promise.all(proms).then(()=>{return payload})}function handleUnionResults(results,final,inst,ctx){for(const result of results){if(result.issues.length===0){final.value=result.value;return final}}const nonaborted=results.filter(r2=>!aborted(r2));if(nonaborted.length===1){final.value=nonaborted[0].value;return nonaborted[0]}final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))});return final}function handleExclusiveUnionResults(results,final,inst,ctx){const successes=results.filter(r2=>r2.issues.length===0);if(successes.length===1){final.value=successes[0].value;return final}if(successes.length===0){final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))})}else{final.issues.push({code:"invalid_union",input:final.value,inst,errors:[],inclusive:false})}return final}function mergeValues(a3,b3){if(a3===b3){return{valid:true,data:a3}}if(a3 instanceof Date&&b3 instanceof Date&&+a3===+b3){return{valid:true,data:a3}}if(isPlainObject(a3)&&isPlainObject(b3)){const bKeys=Object.keys(b3);const sharedKeys=Object.keys(a3).filter(key=>bKeys.indexOf(key)!==-1);const newObj={...a3,...b3};for(const key of sharedKeys){const sharedValue=mergeValues(a3[key],b3[key]);if(!sharedValue.valid){return{valid:false,mergeErrorPath:[key,...sharedValue.mergeErrorPath]}}newObj[key]=sharedValue.data}return{valid:true,data:newObj}}if(Array.isArray(a3)&&Array.isArray(b3)){if(a3.length!==b3.length){return{valid:false,mergeErrorPath:[]}}const newArray=[];for(let index2=0;index2<a3.length;index2++){const itemA=a3[index2];const itemB=b3[index2];const sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid){return{valid:false,mergeErrorPath:[index2,...sharedValue.mergeErrorPath]}}newArray.push(sharedValue.data)}return{valid:true,data:newArray}}return{valid:false,mergeErrorPath:[]}}function handleIntersectionResults(result,left,right){const unrecKeys=new Map;let unrecIssue;for(const iss of left.issues){if(iss.code==="unrecognized_keys"){unrecIssue??(unrecIssue=iss);for(const k2 of iss.keys){if(!unrecKeys.has(k2))unrecKeys.set(k2,{});unrecKeys.get(k2).l=true}}else{result.issues.push(iss)}}for(const iss of right.issues){if(iss.code==="unrecognized_keys"){for(const k2 of iss.keys){if(!unrecKeys.has(k2))unrecKeys.set(k2,{});unrecKeys.get(k2).r=true}}else{result.issues.push(iss)}}const bothKeys=[...unrecKeys].filter(([,f2])=>f2.l&&f2.r).map(([k2])=>k2);if(bothKeys.length&&unrecIssue){result.issues.push({...unrecIssue,keys:bothKeys})}if(aborted(result))return result;const merged=mergeValues(left.value,right.value);if(!merged.valid){throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`)}result.value=merged.data;return result}function getTupleOptStart(items,key){for(let i2=items.length-1;i2>=0;i2--){if(items[i2]._zod[key]!=="optional")return i2+1}return 0}function handleTupleResult(result,final,index2){if(result.issues.length){final.issues.push(...prefixIssues(index2,result.issues))}final.value[index2]=result.value}function handleTupleResults(itemResults,final,items,input,optoutStart){for(let i2=0;i2<items.length;i2++){const r2=itemResults[i2];const isPresent=i2<input.length;if(r2.issues.length){if(!isPresent&&i2>=optoutStart){final.value.length=i2;break}final.issues.push(...prefixIssues(i2,r2.issues))}final.value[i2]=r2.value}for(let i2=final.value.length-1;i2>=input.length;i2--){if(items[i2]._zod.optout==="optional"&&final.value[i2]===void 0){final.value.length=i2}else{break}}return final}function handleMapResult(keyResult,valueResult,final,key,input,inst,ctx){if(keyResult.issues.length){if(propertyKeyTypes.has(typeof key)){final.issues.push(...prefixIssues(key,keyResult.issues))}else{final.issues.push({code:"invalid_key",origin:"map",input,inst,issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config()))})}}if(valueResult.issues.length){if(propertyKeyTypes.has(typeof key)){final.issues.push(...prefixIssues(key,valueResult.issues))}else{final.issues.push({origin:"map",code:"invalid_element",input,inst,key,issues:valueResult.issues.map(iss=>finalizeIssue(iss,ctx,config()))})}}final.value.set(keyResult.value,valueResult.value)}function handleSetResult(result,final){if(result.issues.length){final.issues.push(...result.issues)}final.value.add(result.value)}function handleOptionalResult(result,input){if(input===void 0&&(result.issues.length||result.fallback)){return{issues:[],value:void 0}}return result}function handleDefaultResult(payload,def){if(payload.value===void 0){payload.value=def.defaultValue}return payload}function handleNonOptionalResult(payload,inst){if(!payload.issues.length&&payload.value===void 0){payload.issues.push({code:"invalid_type",expected:"nonoptional",input:payload.value,inst})}return payload}function handlePipeResult(left,next,ctx){if(left.issues.length){left.aborted=true;return left}return next._zod.run({value:left.value,issues:left.issues,fallback:left.fallback},ctx)}function handleCodecAResult(result,def,ctx){if(result.issues.length){result.aborted=true;return result}const direction=ctx.direction||"forward";if(direction==="forward"){const transformed=def.transform(result.value,result);if(transformed instanceof Promise){return transformed.then(value=>handleCodecTxResult(result,value,def.out,ctx))}return handleCodecTxResult(result,transformed,def.out,ctx)}else{const transformed=def.reverseTransform(result.value,result);if(transformed instanceof Promise){return transformed.then(value=>handleCodecTxResult(result,value,def.in,ctx))}return handleCodecTxResult(result,transformed,def.in,ctx)}}function handleCodecTxResult(left,value,nextSchema,ctx){if(left.issues.length){left.aborted=true;return left}return nextSchema._zod.run({value,issues:left.issues},ctx)}function handleReadonlyResult(payload){payload.value=Object.freeze(payload.value);return payload}function handleRefineResult(result,payload,input,inst){if(!result){const _iss={code:"custom",input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};if(inst._zod.def.params)_iss.params=inst._zod.def.params;payload.issues.push(issue(_iss))}}var $ZodType,$ZodString,$ZodStringFormat,$ZodGUID,$ZodUUID,$ZodEmail,$ZodURL,$ZodEmoji,$ZodNanoID,$ZodCUID,$ZodCUID2,$ZodULID,$ZodXID,$ZodKSUID,$ZodISODateTime,$ZodISODate,$ZodISOTime,$ZodISODuration,$ZodIPv4,$ZodIPv6,$ZodMAC,$ZodCIDRv4,$ZodCIDRv6,$ZodBase64,$ZodBase64URL,$ZodE164,$ZodJWT,$ZodCustomStringFormat,$ZodNumber,$ZodNumberFormat,$ZodBoolean,$ZodBigInt,$ZodBigIntFormat,$ZodSymbol,$ZodUndefined,$ZodNull,$ZodAny,$ZodUnknown,$ZodNever,$ZodVoid,$ZodDate,$ZodArray,$ZodObject,$ZodObjectJIT,$ZodUnion,$ZodXor,$ZodDiscriminatedUnion,$ZodIntersection,$ZodTuple,$ZodRecord,$ZodMap,$ZodSet,$ZodEnum,$ZodLiteral,$ZodFile,$ZodTransform,$ZodOptional,$ZodExactOptional,$ZodNullable,$ZodDefault,$ZodPrefault,$ZodNonOptional,$ZodSuccess,$ZodCatch,$ZodNaN,$ZodPipe,$ZodCodec,$ZodPreprocess,$ZodReadonly,$ZodTemplateLiteral,$ZodFunction,$ZodPromise,$ZodLazy,$ZodCustom;var init_schemas=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js"(){init_checks();init_core();init_doc();init_parse();init_regexes();init_util();init_versions();init_util();$ZodType=$constructor("$ZodType",(inst,def)=>{var _a3;inst??(inst={});inst._zod.def=def;inst._zod.bag=inst._zod.bag||{};inst._zod.version=version;const checks=[...inst._zod.def.checks??[]];if(inst._zod.traits.has("$ZodCheck")){checks.unshift(inst)}for(const ch of checks){for(const fn2 of ch._zod.onattach){fn2(inst)}}if(checks.length===0){(_a3=inst._zod).deferred??(_a3.deferred=[]);inst._zod.deferred?.push(()=>{inst._zod.run=inst._zod.parse})}else{const runChecks=(payload,checks2,ctx)=>{let isAborted=aborted(payload);let asyncResult;for(const ch of checks2){if(ch._zod.def.when){if(explicitlyAborted(payload))continue;const shouldRun=ch._zod.def.when(payload);if(!shouldRun)continue}else if(isAborted){continue}const currLen=payload.issues.length;const _3=ch._zod.check(payload);if(_3 instanceof Promise&&ctx?.async===false){throw new $ZodAsyncError}if(asyncResult||_3 instanceof Promise){asyncResult=(asyncResult??Promise.resolve()).then(async()=>{await _3;const nextLen=payload.issues.length;if(nextLen===currLen)return;if(!isAborted)isAborted=aborted(payload,currLen)})}else{const nextLen=payload.issues.length;if(nextLen===currLen)continue;if(!isAborted)isAborted=aborted(payload,currLen)}}if(asyncResult){return asyncResult.then(()=>{return payload})}return payload};const handleCanaryResult=(canary,payload,ctx)=>{if(aborted(canary)){canary.aborted=true;return canary}const checkResult=runChecks(payload,checks,ctx);if(checkResult instanceof Promise){if(ctx.async===false)throw new $ZodAsyncError;return checkResult.then(checkResult2=>inst._zod.parse(checkResult2,ctx))}return inst._zod.parse(checkResult,ctx)};inst._zod.run=(payload,ctx)=>{if(ctx.skipChecks){return inst._zod.parse(payload,ctx)}if(ctx.direction==="backward"){const canary=inst._zod.parse({value:payload.value,issues:[]},{...ctx,skipChecks:true});if(canary instanceof Promise){return canary.then(canary2=>{return handleCanaryResult(canary2,payload,ctx)})}return handleCanaryResult(canary,payload,ctx)}const result=inst._zod.parse(payload,ctx);if(result instanceof Promise){if(ctx.async===false)throw new $ZodAsyncError;return result.then(result2=>runChecks(result2,checks,ctx))}return runChecks(result,checks,ctx)}}defineLazy(inst,"~standard",()=>({validate:value=>{try{const r2=safeParse(inst,value);return r2.success?{value:r2.data}:{issues:r2.error?.issues}}catch(_3){return safeParseAsync(inst,value).then(r2=>r2.success?{value:r2.data}:{issues:r2.error?.issues})}},vendor:"zod",version:1}))});$ZodString=$constructor("$ZodString",(inst,def)=>{$ZodType.init(inst,def);inst._zod.pattern=[...inst?._zod.bag?.patterns??[]].pop()??string(inst._zod.bag);inst._zod.parse=(payload,_3)=>{if(def.coerce)try{payload.value=String(payload.value)}catch(_4){}if(typeof payload.value==="string")return payload;payload.issues.push({expected:"string",code:"invalid_type",input:payload.value,inst});return payload}});$ZodStringFormat=$constructor("$ZodStringFormat",(inst,def)=>{$ZodCheckStringFormat.init(inst,def);$ZodString.init(inst,def)});$ZodGUID=$constructor("$ZodGUID",(inst,def)=>{def.pattern??(def.pattern=guid);$ZodStringFormat.init(inst,def)});$ZodUUID=$constructor("$ZodUUID",(inst,def)=>{if(def.version){const versionMap={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8};const v3=versionMap[def.version];if(v3===void 0)throw new Error(`Invalid UUID version: "${def.version}"`);def.pattern??(def.pattern=uuid(v3))}else def.pattern??(def.pattern=uuid());$ZodStringFormat.init(inst,def)});$ZodEmail=$constructor("$ZodEmail",(inst,def)=>{def.pattern??(def.pattern=email);$ZodStringFormat.init(inst,def)});$ZodURL=$constructor("$ZodURL",(inst,def)=>{$ZodStringFormat.init(inst,def);inst._zod.check=payload=>{try{const trimmed=payload.value.trim();if(!def.normalize&&def.protocol?.source===httpProtocol.source){if(!/^https?:\/\//i.test(trimmed)){payload.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:payload.value,inst,continue:!def.abort});return}}const url2=new URL(trimmed);if(def.hostname){def.hostname.lastIndex=0;if(!def.hostname.test(url2.hostname)){payload.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:def.hostname.source,input:payload.value,inst,continue:!def.abort})}}if(def.protocol){def.protocol.lastIndex=0;if(!def.protocol.test(url2.protocol.endsWith(":")?url2.protocol.slice(0,-1):url2.protocol)){payload.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:def.protocol.source,input:payload.value,inst,continue:!def.abort})}}if(def.normalize){payload.value=url2.href}else{payload.value=trimmed}return}catch(_3){payload.issues.push({code:"invalid_format",format:"url",input:payload.value,inst,continue:!def.abort})}}});$ZodEmoji=$constructor("$ZodEmoji",(inst,def)=>{def.pattern??(def.pattern=emoji());$ZodStringFormat.init(inst,def)});$ZodNanoID=$constructor("$ZodNanoID",(inst,def)=>{def.pattern??(def.pattern=nanoid);$ZodStringFormat.init(inst,def)});$ZodCUID=$constructor("$ZodCUID",(inst,def)=>{def.pattern??(def.pattern=cuid);$ZodStringFormat.init(inst,def)});$ZodCUID2=$constructor("$ZodCUID2",(inst,def)=>{def.pattern??(def.pattern=cuid2);$ZodStringFormat.init(inst,def)});$ZodULID=$constructor("$ZodULID",(inst,def)=>{def.pattern??(def.pattern=ulid);$ZodStringFormat.init(inst,def)});$ZodXID=$constructor("$ZodXID",(inst,def)=>{def.pattern??(def.pattern=xid);$ZodStringFormat.init(inst,def)});$ZodKSUID=$constructor("$ZodKSUID",(inst,def)=>{def.pattern??(def.pattern=ksuid);$ZodStringFormat.init(inst,def)});$ZodISODateTime=$constructor("$ZodISODateTime",(inst,def)=>{def.pattern??(def.pattern=datetime(def));$ZodStringFormat.init(inst,def)});$ZodISODate=$constructor("$ZodISODate",(inst,def)=>{def.pattern??(def.pattern=date);$ZodStringFormat.init(inst,def)});$ZodISOTime=$constructor("$ZodISOTime",(inst,def)=>{def.pattern??(def.pattern=time(def));$ZodStringFormat.init(inst,def)});$ZodISODuration=$constructor("$ZodISODuration",(inst,def)=>{def.pattern??(def.pattern=duration);$ZodStringFormat.init(inst,def)});$ZodIPv4=$constructor("$ZodIPv4",(inst,def)=>{def.pattern??(def.pattern=ipv4);$ZodStringFormat.init(inst,def);inst._zod.bag.format=`ipv4`});$ZodIPv6=$constructor("$ZodIPv6",(inst,def)=>{def.pattern??(def.pattern=ipv6);$ZodStringFormat.init(inst,def);inst._zod.bag.format=`ipv6`;inst._zod.check=payload=>{try{new URL(`http://[${payload.value}]`)}catch{payload.issues.push({code:"invalid_format",format:"ipv6",input:payload.value,inst,continue:!def.abort})}}});$ZodMAC=$constructor("$ZodMAC",(inst,def)=>{def.pattern??(def.pattern=mac(def.delimiter));$ZodStringFormat.init(inst,def);inst._zod.bag.format=`mac`});$ZodCIDRv4=$constructor("$ZodCIDRv4",(inst,def)=>{def.pattern??(def.pattern=cidrv4);$ZodStringFormat.init(inst,def)});$ZodCIDRv6=$constructor("$ZodCIDRv6",(inst,def)=>{def.pattern??(def.pattern=cidrv6);$ZodStringFormat.init(inst,def);inst._zod.check=payload=>{const parts=payload.value.split("/");try{if(parts.length!==2)throw new Error;const[address,prefix]=parts;if(!prefix)throw new Error;const prefixNum=Number(prefix);if(`${prefixNum}`!==prefix)throw new Error;if(prefixNum<0||prefixNum>128)throw new Error;new URL(`http://[${address}]`)}catch{payload.issues.push({code:"invalid_format",format:"cidrv6",input:payload.value,inst,continue:!def.abort})}}});$ZodBase64=$constructor("$ZodBase64",(inst,def)=>{def.pattern??(def.pattern=base64);$ZodStringFormat.init(inst,def);inst._zod.bag.contentEncoding="base64";inst._zod.check=payload=>{if(isValidBase64(payload.value))return;payload.issues.push({code:"invalid_format",format:"base64",input:payload.value,inst,continue:!def.abort})}});$ZodBase64URL=$constructor("$ZodBase64URL",(inst,def)=>{def.pattern??(def.pattern=base64url2);$ZodStringFormat.init(inst,def);inst._zod.bag.contentEncoding="base64url";inst._zod.check=payload=>{if(isValidBase64URL(payload.value))return;payload.issues.push({code:"invalid_format",format:"base64url",input:payload.value,inst,continue:!def.abort})}});$ZodE164=$constructor("$ZodE164",(inst,def)=>{def.pattern??(def.pattern=e164);$ZodStringFormat.init(inst,def)});$ZodJWT=$constructor("$ZodJWT",(inst,def)=>{$ZodStringFormat.init(inst,def);inst._zod.check=payload=>{if(isValidJWT(payload.value,def.alg))return;payload.issues.push({code:"invalid_format",format:"jwt",input:payload.value,inst,continue:!def.abort})}});$ZodCustomStringFormat=$constructor("$ZodCustomStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def);inst._zod.check=payload=>{if(def.fn(payload.value))return;payload.issues.push({code:"invalid_format",format:def.format,input:payload.value,inst,continue:!def.abort})}});$ZodNumber=$constructor("$ZodNumber",(inst,def)=>{$ZodType.init(inst,def);inst._zod.pattern=inst._zod.bag.pattern??number;inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=Number(payload.value)}catch(_3){}const input=payload.value;if(typeof input==="number"&&!Number.isNaN(input)&&Number.isFinite(input)){return payload}const received=typeof input==="number"?Number.isNaN(input)?"NaN":!Number.isFinite(input)?"Infinity":void 0:void 0;payload.issues.push({expected:"number",code:"invalid_type",input,inst,...received?{received}:{}});return payload}});$ZodNumberFormat=$constructor("$ZodNumberFormat",(inst,def)=>{$ZodCheckNumberFormat.init(inst,def);$ZodNumber.init(inst,def)});$ZodBoolean=$constructor("$ZodBoolean",(inst,def)=>{$ZodType.init(inst,def);inst._zod.pattern=boolean;inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=Boolean(payload.value)}catch(_3){}const input=payload.value;if(typeof input==="boolean")return payload;payload.issues.push({expected:"boolean",code:"invalid_type",input,inst});return payload}});$ZodBigInt=$constructor("$ZodBigInt",(inst,def)=>{$ZodType.init(inst,def);inst._zod.pattern=bigint;inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=BigInt(payload.value)}catch(_3){}if(typeof payload.value==="bigint")return payload;payload.issues.push({expected:"bigint",code:"invalid_type",input:payload.value,inst});return payload}});$ZodBigIntFormat=$constructor("$ZodBigIntFormat",(inst,def)=>{$ZodCheckBigIntFormat.init(inst,def);$ZodBigInt.init(inst,def)});$ZodSymbol=$constructor("$ZodSymbol",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,_ctx)=>{const input=payload.value;if(typeof input==="symbol")return payload;payload.issues.push({expected:"symbol",code:"invalid_type",input,inst});return payload}});$ZodUndefined=$constructor("$ZodUndefined",(inst,def)=>{$ZodType.init(inst,def);inst._zod.pattern=_undefined;inst._zod.values=new Set([void 0]);inst._zod.parse=(payload,_ctx)=>{const input=payload.value;if(typeof input==="undefined")return payload;payload.issues.push({expected:"undefined",code:"invalid_type",input,inst});return payload}});$ZodNull=$constructor("$ZodNull",(inst,def)=>{$ZodType.init(inst,def);inst._zod.pattern=_null;inst._zod.values=new Set([null]);inst._zod.parse=(payload,_ctx)=>{const input=payload.value;if(input===null)return payload;payload.issues.push({expected:"null",code:"invalid_type",input,inst});return payload}});$ZodAny=$constructor("$ZodAny",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=payload=>payload});$ZodUnknown=$constructor("$ZodUnknown",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=payload=>payload});$ZodNever=$constructor("$ZodNever",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,_ctx)=>{payload.issues.push({expected:"never",code:"invalid_type",input:payload.value,inst});return payload}});$ZodVoid=$constructor("$ZodVoid",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,_ctx)=>{const input=payload.value;if(typeof input==="undefined")return payload;payload.issues.push({expected:"void",code:"invalid_type",input,inst});return payload}});$ZodDate=$constructor("$ZodDate",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,_ctx)=>{if(def.coerce){try{payload.value=new Date(payload.value)}catch(_err){}}const input=payload.value;const isDate=input instanceof Date;const isValidDate=isDate&&!Number.isNaN(input.getTime());if(isValidDate)return payload;payload.issues.push({expected:"date",code:"invalid_type",input,...isDate?{received:"Invalid Date"}:{},inst});return payload}});$ZodArray=$constructor("$ZodArray",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,ctx)=>{const input=payload.value;if(!Array.isArray(input)){payload.issues.push({expected:"array",code:"invalid_type",input,inst});return payload}payload.value=Array(input.length);const proms=[];for(let i2=0;i2<input.length;i2++){const item=input[i2];const result=def.element._zod.run({value:item,issues:[]},ctx);if(result instanceof Promise){proms.push(result.then(result2=>handleArrayResult(result2,payload,i2)))}else{handleArrayResult(result,payload,i2)}}if(proms.length){return Promise.all(proms).then(()=>payload)}return payload}});$ZodObject=$constructor("$ZodObject",(inst,def)=>{$ZodType.init(inst,def);const desc=Object.getOwnPropertyDescriptor(def,"shape");if(!desc?.get){const sh=def.shape;Object.defineProperty(def,"shape",{get:()=>{const newSh={...sh};Object.defineProperty(def,"shape",{value:newSh});return newSh}})}const _normalized=cached(()=>normalizeDef(def));defineLazy(inst._zod,"propValues",()=>{const shape=def.shape;const propValues={};for(const key in shape){const field=shape[key]._zod;if(field.values){propValues[key]??(propValues[key]=new Set);for(const v3 of field.values)propValues[key].add(v3)}}return propValues});const isObject2=isObject;const catchall=def.catchall;let value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);const input=payload.value;if(!isObject2(input)){payload.issues.push({expected:"object",code:"invalid_type",input,inst});return payload}payload.value={};const proms=[];const shape=value.shape;for(const key of value.keys){const el=shape[key];const isOptionalIn=el._zod.optin==="optional";const isOptionalOut=el._zod.optout==="optional";const r2=el._zod.run({value:input[key],issues:[]},ctx);if(r2 instanceof Promise){proms.push(r2.then(r3=>handlePropertyResult(r3,payload,key,input,isOptionalIn,isOptionalOut)))}else{handlePropertyResult(r2,payload,key,input,isOptionalIn,isOptionalOut)}}if(!catchall){return proms.length?Promise.all(proms).then(()=>payload):payload}return handleCatchall(proms,input,payload,ctx,_normalized.value,inst)}});$ZodObjectJIT=$constructor("$ZodObjectJIT",(inst,def)=>{$ZodObject.init(inst,def);const superParse=inst._zod.parse;const _normalized=cached(()=>normalizeDef(def));const generateFastpass=shape=>{const doc=new Doc(["shape","payload","ctx"]);const normalized=_normalized.value;const parseStr=key=>{const k2=esc(key);return`shape[${k2}]._zod.run({ value: input[${k2}], issues: [] }, ctx)`};doc.write(`const input = payload.value;`);const ids=Object.create(null);let counter=0;for(const key of normalized.keys){ids[key]=`key_${counter++}`}doc.write(`const newResult = {};`);for(const key of normalized.keys){const id2=ids[key];const k2=esc(key);const schema=shape[key];const isOptionalIn=schema?._zod?.optin==="optional";const isOptionalOut=schema?._zod?.optout==="optional";doc.write(`const ${id2} = ${parseStr(key)};`);if(isOptionalIn&&isOptionalOut){doc.write(`
|
|
53
|
+
${serve.endpoint}`;if(principalServers.has(serverKey))throw new Error(`another endpoint in this process already serves "${serve.endpoint}" for lifecycle ${uid2}: both would subscribe the same principal-route subject and answer one request twice (SPEC 13.21); stop that one first`);let resolveReady,rejectReady,resolveFailed;const ready=new Promise((resolve6,reject)=>{resolveReady=resolve6;rejectReady=reject});ready.catch(()=>{});const failed=new Promise(resolve6=>{resolveFailed=resolve6});const intent={serve,self:self2,serverKey,handles:[],ended:false,readySettled:false,resolveReady,rejectReady,resolveFailed};const handle=this.bindPrincipalHandle(intent,nc);this.principalServes.set(serve.endpoint,intent);principalServers.set(serverKey,intent);if(serve.endpoint===AGENT_ENDPOINT)this.promptsPresence={open:0,seq:this.nextPromptsSeq()};void this.armPrincipalServe(intent,nc,handle);return{ready,failed,stop:()=>this.stopPrincipalServe(intent)}}bindPrincipalHandle(intent,nc){return servePrincipalRoute(nc,this.space,intent.self,intent.serve)}ownedPrincipalRouteRefusal(err3){const p2=`${spacePrefix(this.space)}.ep.`;if(err3.operation==="publish")return err3.subject.startsWith(`${p2}prin.`);return err3.subject.startsWith(`${p2}prin.`)||err3.subject.startsWith(`${p2}prin-reply.`)}async armPrincipalServe(intent,nc,handle){intent.binding={nc,handle};for(const old of intent.handles)void old.stop().finally(()=>{const i2=intent.handles.indexOf(old);if(i2>=0)intent.handles.splice(i2,1)});intent.handles.push(handle);intent.readyOn=void 0;void handle.refused.then(err3=>{if(!intent.ended&&intent.binding?.handle===handle)this.endPrincipalServe(intent,err3)});try{await handle.ready}catch{return}this.principalServeConfirmed(intent,nc,handle)}principalServeConfirmed(intent,nc,handle){if(intent.ended||intent.binding?.handle!==handle||this.nc!==nc)return;intent.readyOn=nc;if(!intent.readySettled){intent.readySettled=true;intent.resolveReady()}if(intent.serve.endpoint===AGENT_ENDPOINT)this.publishPresence().catch(e3=>this.emitRecoverable(e3))}rebindPrincipalServes(reconnected){const nc=this.nc;if(!nc)return;for(const intent of this.principalServes.values()){if(intent.ended)continue;const bound=intent.binding;if(bound&&bound.nc===nc){if(!reconnected)continue;intent.readyOn=void 0;void bound.handle.check().then(()=>this.principalServeConfirmed(intent,nc,bound.handle),()=>{});continue}let handle;try{handle=this.bindPrincipalHandle(intent,nc)}catch(e3){this.endPrincipalServe(intent,e3);continue}void this.armPrincipalServe(intent,nc,handle)}}endPrincipalServe(intent,err3){if(intent.ended)return;this.forgetPrincipalServe(intent);const wasReady=intent.readySettled;if(!intent.readySettled){intent.readySettled=true;intent.rejectReady(err3)}intent.resolveFailed(err3);for(const handle of intent.handles)void handle.stop();if(intent.serve.endpoint===AGENT_ENDPOINT){this.promptsPresence=void 0;this.publishPresence().catch(e3=>this.emitRecoverable(e3))}if(wasReady)this.emitRecoverable(new Error(`stopped serving "${intent.serve.endpoint}" on the principal route: ${err3.message}`,{cause:err3}))}forgetPrincipalServe(intent){intent.ended=true;intent.readyOn=void 0;if(this.principalServes.get(intent.serve.endpoint)===intent)this.principalServes.delete(intent.serve.endpoint);if(principalServers.get(intent.serverKey)===intent)principalServers.delete(intent.serverKey)}async stopPrincipalServe(intent,republish=true){if(!intent.ended){this.forgetPrincipalServe(intent);if(!intent.readySettled){intent.readySettled=true;intent.rejectReady(new Error(`stopped serving "${intent.serve.endpoint}" before the broker confirmed the subscription`))}if(intent.serve.endpoint===AGENT_ENDPOINT){this.promptsPresence=void 0;if(republish)this.publishPresence().catch(e3=>this.emitRecoverable(e3))}}await Promise.all(intent.handles.map(handle=>handle.stop()))}async setPromptsPresence(prompts){for(const k2 of["open","seq"])if(!Number.isSafeInteger(prompts?.[k2])||prompts[k2]<0)throw new TypeError(`prompts.${k2} must be a non-negative safe integer`);const intent=this.principalServes.get(AGENT_ENDPOINT);if(!intent)throw new Error(`the prompts presence field belongs to a served "${AGENT_ENDPOINT}" endpoint: call servePrincipal first (SPEC \xA76)`);const used=promptsSeqs.get(intent.self.runtimeId)??0;if(prompts.seq<used)throw new RangeError(`prompts.seq ${prompts.seq} is below ${used}, which this process already used under runtime ${intent.self.runtimeId}: seq never goes back under one runtime id (SPEC \xA76)`);promptsSeqs.set(intent.self.runtimeId,prompts.seq);this.promptsPresence={open:prompts.open,seq:prompts.seq};await this.publishPresence()}nextPromptsSeq(){const runtimeId=processRuntime(this.requireLifecycleUid("nextPromptsSeq")).id;const used=promptsSeqs.get(runtimeId);const next=used===void 0?0:used+1;promptsSeqs.set(runtimeId,next);return next}servedPrompts(){const intent=this.principalServes.get(AGENT_ENDPOINT);if(!intent||intent.ended||!this.nc||intent.readyOn!==this.nc)return void 0;return this.promptsPresence}async callPrincipal(call){const nc=this.nc;if(!nc)throw new Error(this.notLiveMsg());const contract=call.contract??(call.command==="describe"?describeContracts():call.endpoint===AGENT_ENDPOINT?AGENT_CONTRACTS[call.command]:void 0);if(contract===void 0)throw new EpEnvelopeError("bad-request",`no contract is built in for ${call.endpoint}.${call.command}; pass one`,void 0,"not-executed");const caller={owner:this.owner,actor:this.actor,uid:this.requireLifecycleUid("callPrincipal")};return epPrincipalCall(nc,this.space,{principal:call.principal,authority:call.authority},{endpoint:call.endpoint,command:call.command,contract,caller,name:this.card.name,...call.args!==void 0?{args:call.args}:{}},{deadlineMs:call.deadlineMs,...call.signal?{signal:call.signal}:{}})}async durableJoinChannel(channel){const reply=await this.requestDelivery("durableJoin",{channel},3e4);if(!reply.ok)throw new Error(reply.error??"durable join rejected");return reply.data??{durable:false}}async durableLeaveChannel(channel,generation,lifecycleUid=this.requireLifecycleUid("leaving a durable channel")){const reply=await this.requestDelivery("durableLeave",{channel,generation,lifecycleUid});if(!reply.ok)throw new Error(reply.error??"durable leave rejected")}async closeRefusedMembership(channel,generation){this.pendingDurableLeave.set(channel,generation);for(let attempt=0;;attempt++){if(this.stopped)return;try{await this.durableLeaveChannel(channel,generation);this.plane3Channels.delete(channel);this.pendingDurableLeave.delete(channel);return}catch(e3){if(attempt===0)this.emitRecoverable(new Error(`channel "${channel}": Plane-3 durable membership (generation ${generation}) not yet tombstoned after a refused live sub - retrying; \xA77 boundary may be open until it succeeds (${e3.message})`));await this.membershipPause(attempt)}}}pendingDurableLeaves(){return[...this.pendingDurableLeave.keys()]}isNoResponders(e3){return e3 instanceof import_transport_node22.NoRespondersError||e3 instanceof import_transport_node22.RequestError&&e3.isNoResponders()}async takeAnycast(role,seq,id2,count,epoch,nak){const nc=this.nc;if(!nc)return{taken:false,drop:false,reason:"daemon-down",detail:this.notLiveMsg()};const held2=(reason,detail)=>({taken:false,drop:false,reason,detail});const subject=takeSubject(this.space,role,this.owner,this.actor);const body={from:{id:this.card.id,name:this.card.name},seq,id:id2,count,epoch};let reply;try{const m2=await this.requestBoundReply(nc,subject,JSON.stringify(body),`${subject}.reply.${randomUUID9()}`,ANYCAST_TAKE_TIMEOUT_MS);reply=m2.json()}catch(e3){if(isPermissionDenied(e3))return held2("credential-outdated","this seat's credential was minted before anycast takes existed, so it cannot take role requests; respawn the seat to get a current credential");if(this.isNoResponders(e3))return this.takeResponderMissing();return held2("daemon-down",`the delivery daemon did not answer the take: ${e3.message}`)}if(reply.ok)return{taken:true};if(reply.code==="mismatch"){const current=await this.readTaskEpoch().catch(()=>void 0);if(current!==void 0&¤t!==epoch)nak()}if(reply.code==="cancelled"||reply.code==="taken"||reply.code==="gone"||reply.code==="mismatch")return{taken:false,drop:true,reason:reply.code,detail:reply.error};return held2("daemon-busy",reply.error)}async takeResponderMissing(){const held2=(reason,detail)=>({taken:false,drop:false,reason,detail});let reply;try{reply=await this.requestDelivery(ANYCAST_TAKES_OP,{},ANYCAST_TAKE_TIMEOUT_MS)}catch{return held2("daemon-down","no delivery daemon is answering on this mesh, so role requests wait on the queue until one does")}if(!reply.ok&&/not supported on the delivery control service/.test(reply.error??""))return held2("daemon-outdated","the delivery daemon predates anycast takes, so this seat holds role requests until the daemon is restarted at this version (`cotal up` runs it)");if(!reply.ok&&reply.error?.includes(ANYCAST_RECORDS_CREDENTIAL_OUTDATED))return held2("daemon-outdated",`this seat holds role requests until the delivery daemon can record takes: ${ANYCAST_RECORDS_CREDENTIAL_OUTDATED}`);return held2("daemon-down","the delivery daemon is not answering takes, so role requests wait on the queue until it does")}async anycastStatus(seq,id2){return this.anycastRequest(ANYCAST_STATUS_OP,seq,id2)}async cancelAnycast(seq,id2){return this.anycastRequest(ANYCAST_CANCEL_OP,seq,id2)}async anycastRequest(op,seq,id2){if(!this.authed)throw new Error("an open mesh runs no delivery daemon, so it keeps no record of anycast requests");if(!isAnycastSeq(seq))throw new Error(`seq must be a whole number of at least 1, got ${seq}`);let reply;try{reply=await this.requestDelivery(op,{seq,...id2!==void 0?{id:id2}:{}},1e4)}catch(e3){if(this.isNoResponders(e3))throw new Error("no delivery daemon is answering on this mesh, so the request's record cannot be read");throw e3}if(!reply.ok){if(/not supported on the delivery control service/.test(reply.error??""))throw new Error("the delivery daemon predates anycast request status; restart it at this version (`cotal up` runs it)");throw new Error(reply.error??`${op} failed`)}return reply.data}bootMemberships=new EndpointBootMemberships({channels:()=>this.channels,plane3Channels:()=>this.plane3Channels,pendingBootJoins:()=>this.pendingBootJoins,stopped:()=>this.stopped,requestDelivery:(op,args,timeoutMs)=>this.requestDelivery(op,args,timeoutMs),requireLifecycleUid:what2=>this.requireLifecycleUid(what2),deliveryClassFresh:channel=>this.deliveryClassFresh(channel),durableJoinChannel:channel=>this.durableJoinChannel(channel),membershipPause:attempt=>this.membershipPause(attempt),isNoResponders:e3=>this.isNoResponders(e3),emitRecoverable:err3=>this.emitRecoverable(err3)});async fetchMemberships(channel){return this.bootMemberships.fetchMemberships(channel)}async armBootDurableMemberships(){return this.bootMemberships.armBootDurableMemberships()}hasDurableMembership(channel){return this.bootMemberships.hasDurableMembership(channel)}async manager(){if(!this.nc)throw new Error(this.notLiveMsg());this.jsm??=await(0,import_jetstream21.jetstreamManager)(this.nc);return this.jsm}async startConsumers(){if(!this.jsm)throw new Error(this.notLiveMsg());const ownUid=this.requireLifecycleUid("consuming the DM inbox");if(!this.authed){await this.ensureDmDurable(this.owner,this.actor,ownUid,{ackWaitMs:this.ackWaitMs,inactiveThresholdMs:this.inactiveThresholdMs})}const dm=dmDurable(this.owner,this.actor,ownUid);try{await this.pump(dmStream(this.space),dm,{inbox:true})}catch(e3){if(this.authed&&isConsumerNotFound(e3))throw new DmDurableMissingError(dmStream(this.space),dm);throw e3}await this.pumpDlv();if(this.channels.length){const armed2=this.firstConnect?await this.armJoin(this.channels):void 0;for(const ch of this.channels)this.subscribeChat(ch);await this.confirmChatSub();if(armed2)await this.backfillArmed(armed2,this.backfillFloor)}if(this.firstConnect&&this.authed&&this.channels.length)await this.armBootDurableMemberships();this.firstConnect=false;if(this.card.role){if(!this.authed){await this.jsm.consumers.add(taskStream(this.space),taskDurableConfig(this.space,this.card.role,{ackWaitMs:this.ackWaitMs}))}await this.pump(taskStream(this.space),taskDurable(this.card.role),this.authed?{takeRole:this.card.role}:{})}}async pump(stream,durable,opts={}){if(!this.js)throw new Error(this.notLiveMsg());const consumer=opts.takeRole===void 0?await this.js.consumers.get(stream,durable):await this.bindTaskConsumer(stream,durable);const ackWaitMs=await ackWaitOf(consumer);const msgs=await consumer.consume();this.streamMsgs.push(msgs);if(opts.inbox)this.watchInbox(msgs,stream,durable);void(async()=>{for await(const m2 of msgs){const authed=this.authenticateStreamMsg(m2);if(!authed)continue;const{msg,parsed}=authed;const delivery=durableDelivery(m2,ackWaitMs);const role=opts.takeRole;if(role!==void 0){const epoch=this.taskEpoch;delivery.take=()=>this.takeAnycast(role,m2.seq,msg.id,m2.info.deliveryCount,epoch,()=>m2.nak())}this.emit("message",authenticatedMessage(msg,parsed),delivery,{historical:false,kind:kindFromParsed(parsed.kind)})}})().catch(e3=>{if(!this.stopped)this.emit("error",e3)})}async bindTaskConsumer(stream,durable){for(let attempt=0;attempt<3;attempt++){const before=await this.readTaskEpoch();const consumer=await this.js.consumers.get(stream,durable);if(before===await this.readTaskEpoch())return consumer}throw new Error(`the ${stream} stream was recreated while its role consumer was binding; reconnect to bind it again`)}async readTaskEpoch(){const epoch=(await(await this.manager()).streams.info(taskStream(this.space))).created;this.taskEpoch=epoch;return epoch}watchInbox(msgs,stream,durable){const boundNc=this.nc;void(async()=>{let absences=0;let deleted=false;for await(const s3 of msgs.status()){if(this.stopped||this.nc!==boundNc)break;if(s3.type==="next"){absences=0;deleted=false;continue}if(s3.type==="consumer_deleted"){if(deleted)continue;deleted=true;absences=1}else if(s3.type!=="consumer_not_found"&&s3.type!=="stream_not_found")continue;if(++absences===2)this.emitRecoverable(new Error(`DM inbox missing: the broker reports consumer "${durable}" on stream "${stream}" missing, so direct messages to this endpoint are not delivered. The endpoint keeps checking; if the inbox does not come back, end this session and start a new one`))}})().catch(e3=>{if(!this.stopped)this.emit("error",e3)})}authenticateStreamMsg(m2){let msg;try{msg=m2.json()}catch(e3){m2.term();this.emit("error",e3);return void 0}if(!isRecord(msg)||!isUsableMessageId(msg.id)){m2.term();this.emit("error",new Error(`dropped message on ${m2.subject}: absent or non-string id`));return void 0}const parsed=parseSubject(m2.subject);if(!parsed||!isFromSubjectSender(msg,parsed)){m2.term();this.emit("error",new Error(`dropped message on ${m2.subject}: payload from ${msg.from?.id??"(none)"} does not match subject sender ${parsed?.sender??"(unparseable)"}`));return void 0}return{msg,parsed}}async bindDmOnly(mode){if(!this.js)throw new Error(this.notLiveMsg());const stream=dmStream(this.space);const durable=dmDurable(this.owner,this.actor,this.requireLifecycleUid("consuming the DM inbox"));let consumer;try{consumer=await this.js.consumers.get(stream,durable)}catch(e3){if(isJetStreamMissing(e3,import_jetstream21.JetStreamApiCodes.ConsumerNotFound))throw new DmDurableMissingError(stream,durable);throw new DmBindRefusedError(stream,durable,e3)}const ackWaitMs=await ackWaitOf(consumer);if(this.dmOnlyInFlight){const settleMs=mode.settleTimeoutMs??3e4;await withDeadline(this.dmOnlyInFlight,settleMs,()=>new Error(`DM-only rebind waited ${settleMs}ms for the previous handler to settle; not reading the next DM yet`))}const msgs=await consumer.consume({max_messages:1});this.streamMsgs.push(msgs);const boundNc=this.nc;const retired=()=>this.stopped||this.nc!==boundNc||!boundNc||boundNc.isClosed();void(async()=>{for await(const m2 of msgs){if(retired())break;const authed=this.authenticateStreamMsg(m2);if(!authed)continue;if(authed.parsed.kind!=="inst"){m2.term();continue}const run=Promise.resolve().then(()=>mode.handler(authenticatedMessage(authed.msg,authed.parsed),dmOnlyDelivery(m2,ackWaitMs,boundNc),{historical:false,kind:"dm"}));const flight=run.then(()=>{},()=>{});this.dmOnlyInFlight=flight;try{await run}catch(e3){this.emit("error",e3 instanceof Error?e3:new Error(String(e3)))}finally{if(this.dmOnlyInFlight===flight)this.dmOnlyInFlight=void 0}}})().catch(e3=>{if(!this.stopped)this.emit("error",e3)})}subscribeChat(channel){if(!this.nc||this.chatSubs.has(channel))return;this.chatSubDenied.delete(channel);const subject=chatSubject(this.space,"*","*",channel);const sub=this.nc.subscribe(subject,{callback:(err3,m2)=>{if(err3){if(err3 instanceof import_transport_node22.PermissionViolationError)this.chatSubRefusals.add(err3);this.chatSubDenied.add(channel);this.chatSubs.delete(channel);const i2=this.channels.indexOf(channel);if(i2>=0){this.channels.splice(i2,1);const gen=this.plane3Channels.get(channel);if(gen!==void 0)void this.closeRefusedMembership(channel,gen);this.emit("error",new Error(`left channel "${channel}": its live subscription was refused by the broker`,{cause:err3}))}return}const parsed=parseSubject(m2.subject);if(!parsed||parsed.kind!=="chat")return;let msg;try{msg=m2.json()}catch(e3){this.emit("error",e3);return}if(!isRecord(msg)||!isUsableMessageId(msg.id))return;if(!isFromSubjectSender(msg,parsed))return;if(msg.from.id===this.card.id)return;const delivery={ack:()=>{},nak:()=>{},durable:false};this.emit("message",authenticatedMessage(msg,parsed),delivery,{historical:false,kind:kindFromParsed(parsed.kind)})}});this.chatSubs.set(channel,sub)}unsubscribeChat(channel){const sub=this.chatSubs.get(channel);if(sub){try{sub.unsubscribe()}catch{}this.chatSubs.delete(channel)}this.chatSubDenied.delete(channel)}async confirmChatSub(){if(!this.nc)throw new Error("connection not established");await this.nc.flush();await new Promise(r2=>setTimeout(r2,50))}async consumerInfo(stream,durable){if(!this.jsm)throw new Error(this.notLiveMsg());try{return await this.jsm.consumers.info(stream,durable)}catch(e3){if(isJetStreamMissing(e3,import_jetstream21.JetStreamApiCodes.ConsumerNotFound))return null;throw e3}}async deleteConsumerIfPresent(stream,durable){if(!this.jsm)throw new Error(this.notLiveMsg());try{await this.jsm.consumers.delete(stream,durable)}catch(e3){if(!isJetStreamMissing(e3,import_jetstream21.JetStreamApiCodes.ConsumerNotFound,import_jetstream21.JetStreamApiCodes.StreamNotFound))throw e3}}async chatFrontier(){const jsm=await this.manager();return(await jsm.streams.info(chatStream(this.space))).state.last_seq}async streamRecorded(name2){try{await(await this.manager()).streams.info(name2);return true}catch(e3){if(isStreamNotFound(e3))return false;throw e3}}async storedBytes(){return(await(await this.manager()).getAccountInfo()).storage}async armJoin(channels){const frontiers=new Map;for(const ch of channels){frontiers.set(ch,await this.chatFrontier())}return frontiers}async backfillArmed(frontiers,floorSeq){let total=0;for(const[ch,frontier]of frontiers){const policy=await this.joinPolicyFresh(ch);if(policy.replay)total+=await this.backfillChannel(ch,frontier,policy.windowMs,floorSeq)}return total}async joinPolicyFresh(channel){if(!this.channelKv)return{replay:effectiveReplay(void 0,void 0)};const[cfg,defaults]=await Promise.all([isConcreteChannel(channel)?readChannelConfig(this.channelKv,channel):Promise.resolve(void 0),readChannelDefaults(this.channelKv)]);return{replay:effectiveReplay(cfg,defaults),windowMs:effectiveReplayWindowMs(cfg,defaults)}}async collectHistory(subject,start,opts={}){return this.history.collectHistory(subject,start,opts)}async backfillChannel(channel,upToSeq,sinceMs,floorSeq){return this.history.backfillChannel(channel,upToSeq,sinceMs,floorSeq)}async recallChannel(channel,sinceSeq){return this.history.recallChannel(channel,sinceSeq)}async chatMayHaveLost(subject,sinceSeq){if(!this.jsm)throw new Error(this.notLiveMsg());const info=await this.jsm.streams.info(chatStream(this.space),{subjects_filter:subject});if(info.state.first_seq>sinceSeq+1)return true;const cap=info.config.max_msgs_per_subject;let maxPerSubject=0;for(const count of Object.values(info.state.subjects??{}))maxPerSubject=Math.max(maxPerSubject,count);if(cap<1||maxPerSubject<cap)return false;const oldest=(await this.collectHistory(subject,{seq:1},{limit:1}))[0]?.seq;return oldest!==void 0&&oldest>sinceSeq+1}async publishPresence(){return this.presence.publishPresence()}clearPresenceWriteFailure(){return this.presence.clearPresenceWriteFailure()}presenceWriteFailure(){return this.presence.presenceWriteFailure()}async startPresenceWatch(){return this.presence.startPresenceWatch()}async readPresenceOnce(){return this.presence.readPresenceOnce()}async startChannelWatch(){return this.channelDiscovery.startChannelWatch()}async readChannelsOnce(){return this.channelDiscovery.readChannelsOnce()}sweep(){return this.presence.sweep()}}}});var import_nkeys9,import_transport_node23,EVICT_PRINCIPALS_MAX;var init_evict=__esm({"../../packages/core/dist/evict.js"(){"use strict";init_connection_cleanup();import_nkeys9=__toESM(require_mod(),1);import_transport_node23=__toESM(require_transport_node(),1);init_endpoint();init_identity();init_subjects();EVICT_PRINCIPALS_MAX=256}});var SOURCE_CHAIN_ID,SOURCE_CHAIN_ELEMENT;var init_endpoint_service=__esm({"../../packages/core/dist/endpoint-service.js"(){"use strict";init_service_authority_limits();init_service_gate();init_subjects();init_canonical();init_endpoint_subjects();init_endpoint_envelope();init_endpoint_records();init_endpoint_cluster();init_canonical();init_remote_service_authority();init_endpoint_supervisor();init_evict();init_lifecycle_state();SOURCE_CHAIN_ID="[A-Za-z0-9_-]{1,64}";SOURCE_CHAIN_ELEMENT=new RegExp(`^(root|handle\\.${SOURCE_CHAIN_ID}\\.${SOURCE_CHAIN_ID}|session\\.${SOURCE_CHAIN_ID})$`)}});var init_endpoint_verbs=__esm({"../../packages/core/dist/endpoint-verbs.js"(){"use strict";init_subjects();init_endpoint_subjects();init_endpoint_envelope();init_endpoint_service();init_endpoint_call();init_endpoint_call()}});async function fetchClusterDocument(store,closureDigest,walk){const{manifest,artifacts}=await fetchContractClosure(store,closureDigest,()=>[],walk);const rootBytes=artifacts.get(contractRefToHex(manifest.root));if(rootBytes===void 0)throw new EpEnvelopeError("failed-precondition",`the cluster manifest ${closureDigest} names root ${manifest.root} but the root artifact is absent from the fetched closure (SPEC 13.7)`);return parseClusterDocument(JSON.parse(dec3.decode(rootBytes)))}async function recompileClosure(store,closureDigest,walk){const{manifest,artifacts}=await fetchContractClosure(store,closureDigest,bytes=>extractSchemaRefs(bytes),walk);const members={};for(const[hex3,bytes]of artifacts)members[`sha256:${hex3}`]=JSON.parse(dec3.decode(bytes));const rootRef=manifest.root;const root=members[rootRef];if(root===void 0)throw new EpEnvelopeError("failed-precondition",`schema closure ${closureDigest} is missing its root ${rootRef} (SPEC 13.7)`);const bundleMembers={};for(const[ref,value]of Object.entries(members))if(ref!==rootRef)bundleMembers[ref]=value;const compiled=compileContract({root,members:bundleMembers});if(compiled.closureDigest!==closureDigest)throw new EpEnvelopeError("internal",`the recompiled schema closure hashes to ${compiled.closureDigest}, not the fetched ${closureDigest}; a store that served the wrong bytes never authorizes (SPEC 13.7)`);return compiled}function extractSchemaRefs(bytes){const refs=[];const walk=v3=>{if(typeof v3==="string"){const m2=/^cotal:(sha256:[0-9a-f]{64})$/.exec(v3);if(m2)refs.push(m2[1])}else if(Array.isArray(v3)){for(const c3 of v3)walk(c3)}else if(v3!==null&&typeof v3==="object"){for(const c3 of Object.values(v3))walk(c3)}};walk(JSON.parse(dec3.decode(bytes)));return refs}async function pooled(items,limit,work){const out=new Array(items.length);let next=0;const worker=async()=>{for(;;){const i2=next++;if(i2>=items.length)return;try{out[i2]=await work(items[i2])}catch(e3){next=items.length;throw e3}}};await Promise.all(Array.from({length:Math.min(limit,items.length)},worker));return out}async function resolveService(nc,space2,endpoint,caller,opts={}){if(opts.commands!==void 0){if(!Array.isArray(opts.commands)||opts.commands.length===0)throw new EpEnvelopeError("failed-precondition","commands must be a non-empty array when a resolve is narrowed");for(const command of opts.commands){try{assertCommandToken(command)}catch(e3){throw new EpEnvelopeError("failed-precondition",`invalid requested command: ${e3.message}`)}}}if(opts.optionalCommands!==void 0){if(!Array.isArray(opts.optionalCommands)||opts.optionalCommands.length===0)throw new EpEnvelopeError("failed-precondition","optionalCommands must be a non-empty array when supplied");for(const command of opts.optionalCommands){try{assertCommandToken(command)}catch(e3){throw new EpEnvelopeError("failed-precondition",`invalid optional command: ${e3.message}`)}}}const startedAt2=performance.now();const deadlineMs=opts.deadlineMs??1e4;const{answer,responder}=await describeEndpoint(nc,space2,endpoint,caller,{...opts,deadlineMs});const store=await contractStoreContext(nc,space2);const visible=new Set(answer.descriptor.clusters.flatMap(cl=>cl.commands));const requested=opts.commands===void 0?visible:new Set(opts.commands);const optional3=new Set(opts.optionalCommands);for(const command of requested){if(visible.has(command))continue;if(optional3.has(command)){requested.delete(command);continue}throw new EpEnvelopeError("not-found",`command "${command}" is not in ${endpoint}'s visible surface; describe lists ${[...visible].sort().join(", ")||"(none)"}`)}const artifactMemo=new Map;const walk=()=>{const walkBudgetMs=Math.floor(deadlineMs-(performance.now()-startedAt2));if(walkBudgetMs<=0)throw new EpEnvelopeError("deadline-exceeded",`resolving ${endpoint} exhausted its ${deadlineMs}ms deadline before a contract-store read`);return{artifactMemo,walkBudgetMs,...opts.signal?{signal:opts.signal}:{}}};const clusters=answer.descriptor.clusters.filter(cl=>cl.commands.some(command=>requested.has(command)));const docs=await pooled(clusters,RESOLVE_MAX_INFLIGHT_READS,cl=>{opts.signal?.throwIfAborted();return fetchClusterDocument(store,cl.digest,walk())});const declared=docs.flatMap(doc=>doc.commands).filter(cmd=>requested.has(cmd.name));const resolved=await pooled(declared,Math.max(1,RESOLVE_MAX_INFLIGHT_READS>>1),async cmd=>{opts.signal?.throwIfAborted();const[input,output]=await Promise.all([recompileClosure(store,cmd.inputDigest,walk()),recompileClosure(store,cmd.outputDigest,walk())]);return{command:cmd.name,contract:{input,output},class:cmd.class,targeted:cmd.targeted,modes:cmd.modes??[],capability:cmd.capability,...cmd.action?{action:true}:{}}});opts.signal?.throwIfAborted();const commands=new Map;for(const rc of resolved)commands.set(rc.command,rc);return{endpoint:answer.descriptor.endpoint,owner:answer.descriptor.owner,caller,responder,commands,...opts.instanceId!==void 0?{pinnedInstanceId:opts.instanceId}:{}}}function submitAndFollowGoal(nc,space2,endpoint,caller,deadlineMs,submit,opts){return submitAndFollowGoalWith(parseGoalResultFact,nc,space2,endpoint,caller,deadlineMs,submit,opts)}var import_jetstream23,RESOLVE_MAX_INFLIGHT_READS;var init_endpoint_invoke=__esm({"../../packages/core/dist/endpoint-invoke.js"(){"use strict";import_jetstream23=__toESM(require_mod4(),1);init_endpoint_envelope();init_schema_profile();init_endpoint_action();init_endpoint_goal_follow();init_endpoint_contract_store();init_endpoint_cluster();init_endpoint_verbs();init_endpoint_subjects();init_endpoint_caller();init_endpoint_caller();RESOLVE_MAX_INFLIGHT_READS=32}});async function registryListingCaller(nc,space2,caller,credential){if(isIssuedCaller(caller))return caller;if(credential.exp===void 0)return void 0;try{return await issuedCallerOfToken(nc,space2,listingAcceptedToken(credential.connId,credential.exp),caller)}catch(e3){if(isPermissionDenied(e3))return void 0;throw e3}}async function listRegistryEndpoints(space2,describe4,ask,input,opts={}){const deadline=Date.now()+(opts.deadlineMs??1e4);const ours=REGISTRY_CONTRACTS[REGISTRY_ENDPOINTS_COMMAND];let reply;for(let attempt=0;attempt<=BIND_SPLIT_REISSUES&&Date.now()<deadline;attempt++){const service=await describe4(deadline-Date.now(),opts.signal);const theirs=service.commands.get(REGISTRY_ENDPOINTS_COMMAND).contract;if(theirs.input.closureDigest!==ours.input.closureDigest||theirs.output.closureDigest!==ours.output.closureDigest)throw new EpEnvelopeError("contract-mismatch",`the registry serves a version of "${REGISTRY_ENDPOINTS_COMMAND}" this client does not implement; upgrade the client (SPEC 13.20)`);try{reply=await invokeCommand(ask.nc,space2,service,REGISTRY_ENDPOINTS_COMMAND,{...input},{deadlineMs:deadline-Date.now(),signal:opts.signal,...ask.caller?{caller:ask.caller}:{}})}catch(e3){if(ask.caller!==void 0&&e3 instanceof EpEnvelopeError&&e3.code==="permission-denied"&&e3.outcome==="not-executed")return{unbound:true};throw e3}if(reply.reply.ok!==false||!replyRefusedBeforeEffect(reply.reply.error))break}if(reply===void 0)throw new EpEnvelopeError("deadline-exceeded","the registry was not reached before the deadline");return{reply,...reply.reply.ok===true?{page:reply.reply.data}:{}}}var init_registry_client=__esm({"../../packages/core/dist/registry-client.js"(){"use strict";init_endpoint_invoke();init_endpoint_error();init_endpoint_subjects();init_issued_authority();init_permission_denied();init_registry_contract()}});var import_jetstream24,import_kv11,import_transport_node24;var init_space_resource_definitions=__esm({"../../packages/core/dist/space-resource-definitions.js"(){"use strict";import_jetstream24=__toESM(require_mod4(),1);import_kv11=__toESM(require_mod6(),1);import_transport_node24=__toESM(require_transport_node(),1);init_backup_config();init_subjects();init_channels();init_endpoint_binding();init_issued_authority();init_run_admission();init_streams()}});function $constructor(name2,initializer3,params){function init(inst,def){if(!inst._zod){Object.defineProperty(inst,"_zod",{value:{def,constr:_3,traits:new Set},enumerable:false})}if(inst._zod.traits.has(name2)){return}inst._zod.traits.add(name2);initializer3(inst,def);const proto=_3.prototype;const keys=Object.keys(proto);for(let i2=0;i2<keys.length;i2++){const k2=keys[i2];if(!(k2 in inst)){inst[k2]=proto[k2].bind(inst)}}}const Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name2});function _3(def){var _a3;const inst=params?.Parent?new Definition:this;init(inst,def);(_a3=inst._zod).deferred??(_a3.deferred=[]);for(const fn2 of inst._zod.deferred){fn2()}return inst}Object.defineProperty(_3,"init",{value:init});Object.defineProperty(_3,Symbol.hasInstance,{value:inst=>{if(params?.Parent&&inst instanceof params.Parent)return true;return inst?._zod?.traits?.has(name2)}});Object.defineProperty(_3,"name",{value:name2});return _3}function config(newConfig){if(newConfig)Object.assign(globalConfig,newConfig);return globalConfig}var _a,NEVER,$brand,$ZodAsyncError,$ZodEncodeError,globalConfig;var init_core=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js"(){NEVER=Object.freeze({status:"aborted"});$brand=Symbol("zod_brand");$ZodAsyncError=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}};$ZodEncodeError=class extends Error{constructor(name2){super(`Encountered unidirectional transform during encode: ${name2}`);this.name="ZodEncodeError"}};(_a=globalThis).__zod_globalConfig??(_a.__zod_globalConfig={});globalConfig=globalThis.__zod_globalConfig}});var util_exports={};__export(util_exports,{BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES,Class:()=>Class,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,aborted:()=>aborted,allowsEval:()=>allowsEval,assert:()=>assert,assertEqual:()=>assertEqual,assertIs:()=>assertIs,assertNever:()=>assertNever,assertNotEqual:()=>assertNotEqual,assignProp:()=>assignProp,base64ToUint8Array:()=>base64ToUint8Array,base64urlToUint8Array:()=>base64urlToUint8Array,cached:()=>cached,captureStackTrace:()=>captureStackTrace,cleanEnum:()=>cleanEnum,cleanRegex:()=>cleanRegex,clone:()=>clone,cloneDef:()=>cloneDef,createTransparentProxy:()=>createTransparentProxy,defineLazy:()=>defineLazy,esc:()=>esc,escapeRegex:()=>escapeRegex,explicitlyAborted:()=>explicitlyAborted,extend:()=>extend,finalizeIssue:()=>finalizeIssue,floatSafeRemainder:()=>floatSafeRemainder,getElementAtPath:()=>getElementAtPath,getEnumValues:()=>getEnumValues,getLengthableOrigin:()=>getLengthableOrigin,getParsedType:()=>getParsedType,getSizableOrigin:()=>getSizableOrigin,hexToUint8Array:()=>hexToUint8Array,isObject:()=>isObject,isPlainObject:()=>isPlainObject,issue:()=>issue,joinValues:()=>joinValues,jsonStringifyReplacer:()=>jsonStringifyReplacer,merge:()=>merge,mergeDefs:()=>mergeDefs,normalizeParams:()=>normalizeParams,nullish:()=>nullish,numKeys:()=>numKeys,objectClone:()=>objectClone,omit:()=>omit,optionalKeys:()=>optionalKeys,parsedType:()=>parsedType,partial:()=>partial,pick:()=>pick,prefixIssues:()=>prefixIssues,primitiveTypes:()=>primitiveTypes,promiseAllObject:()=>promiseAllObject,propertyKeyTypes:()=>propertyKeyTypes,randomString:()=>randomString,required:()=>required,safeExtend:()=>safeExtend,shallowClone:()=>shallowClone,slugify:()=>slugify,stringifyPrimitive:()=>stringifyPrimitive,uint8ArrayToBase64:()=>uint8ArrayToBase64,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToHex:()=>uint8ArrayToHex,unwrapMessage:()=>unwrapMessage});function assertEqual(val){return val}function assertNotEqual(val){return val}function assertIs(_arg){}function assertNever(_x){throw new Error("Unexpected value in exhaustive check")}function assert(_3){}function getEnumValues(entries){const numericValues=Object.values(entries).filter(v3=>typeof v3==="number");const values=Object.entries(entries).filter(([k2,_3])=>numericValues.indexOf(+k2)===-1).map(([_3,v3])=>v3);return values}function joinValues(array2,separator="|"){return array2.map(val=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_3,value){if(typeof value==="bigint")return value.toString();return value}function cached(getter){const set3=false;return{get value(){if(!set3){const value=getter();Object.defineProperty(this,"value",{value});return value}throw new Error("cached value already set")}}}function nullish(input){return input===null||input===void 0}function cleanRegex(source){const start=source.startsWith("^")?1:0;const end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder(val,step){const ratio=val/step;const roundedRatio=Math.round(ratio);const tolerance=Number.EPSILON*Math.max(Math.abs(ratio),1);if(Math.abs(ratio-roundedRatio)<tolerance)return 0;return ratio-roundedRatio}function defineLazy(object2,key,getter){let value=void 0;Object.defineProperty(object2,key,{get(){if(value===EVALUATING){return void 0}if(value===void 0){value=EVALUATING;value=getter()}return value},set(v3){Object.defineProperty(object2,key,{value:v3})},configurable:true})}function objectClone(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp(target2,prop,value){Object.defineProperty(target2,prop,{value,writable:true,enumerable:true,configurable:true})}function mergeDefs(...defs){const mergedDescriptors={};for(const def of defs){const descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef(schema){return mergeDefs(schema._zod.def)}function getElementAtPath(obj,path4){if(!path4)return obj;return path4.reduce((acc,key)=>acc?.[key],obj)}function promiseAllObject(promisesObj){const keys=Object.keys(promisesObj);const promises=keys.map(key=>promisesObj[key]);return Promise.all(promises).then(results=>{const resolvedObj={};for(let i2=0;i2<keys.length;i2++){resolvedObj[keys[i2]]=results[i2]}return resolvedObj})}function randomString(length=10){const chars="abcdefghijklmnopqrstuvwxyz";let str2="";for(let i2=0;i2<length;i2++){str2+=chars[Math.floor(Math.random()*chars.length)]}return str2}function esc(str2){return JSON.stringify(str2)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function isObject(data){return typeof data==="object"&&data!==null&&!Array.isArray(data)}function isPlainObject(o3){if(isObject(o3)===false)return false;const ctor=o3.constructor;if(ctor===void 0)return true;if(typeof ctor!=="function")return true;const prot=ctor.prototype;if(isObject(prot)===false)return false;if(Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===false){return false}return true}function shallowClone(o3){if(isPlainObject(o3))return{...o3};if(Array.isArray(o3))return[...o3];if(o3 instanceof Map)return new Map(o3);if(o3 instanceof Set)return new Set(o3);return o3}function numKeys(data){let keyCount=0;for(const key in data){if(Object.prototype.hasOwnProperty.call(data,key)){keyCount++}}return keyCount}function escapeRegex(str2){return str2.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){const cl=new inst._zod.constr(def??inst._zod.def);if(!def||params?.parent)cl._zod.parent=inst;return cl}function normalizeParams(_params){const params=_params;if(!params)return{};if(typeof params==="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");params.error=params.message}delete params.message;if(typeof params.error==="string")return{...params,error:()=>params.error};return params}function createTransparentProxy(getter){let target2;return new Proxy({},{get(_3,prop,receiver){target2??(target2=getter());return Reflect.get(target2,prop,receiver)},set(_3,prop,value,receiver){target2??(target2=getter());return Reflect.set(target2,prop,value,receiver)},has(_3,prop){target2??(target2=getter());return Reflect.has(target2,prop)},deleteProperty(_3,prop){target2??(target2=getter());return Reflect.deleteProperty(target2,prop)},ownKeys(_3){target2??(target2=getter());return Reflect.ownKeys(target2)},getOwnPropertyDescriptor(_3,prop){target2??(target2=getter());return Reflect.getOwnPropertyDescriptor(target2,prop)},defineProperty(_3,prop,descriptor){target2??(target2=getter());return Reflect.defineProperty(target2,prop,descriptor)}})}function stringifyPrimitive(value){if(typeof value==="bigint")return value.toString()+"n";if(typeof value==="string")return`"${value}"`;return`${value}`}function optionalKeys(shape){return Object.keys(shape).filter(k2=>{return shape[k2]._zod.optin==="optional"&&shape[k2]._zod.optout==="optional"})}function pick(schema,mask){const currDef=schema._zod.def;const checks=currDef.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){throw new Error(".pick() cannot be used on object schemas containing refinements")}const def=mergeDefs(schema._zod.def,{get shape(){const newShape={};for(const key in mask){if(!(key in currDef.shape)){throw new Error(`Unrecognized key: "${key}"`)}if(!mask[key])continue;newShape[key]=currDef.shape[key]}assignProp(this,"shape",newShape);return newShape},checks:[]});return clone(schema,def)}function omit(schema,mask){const currDef=schema._zod.def;const checks=currDef.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){throw new Error(".omit() cannot be used on object schemas containing refinements")}const def=mergeDefs(schema._zod.def,{get shape(){const newShape={...schema._zod.def.shape};for(const key in mask){if(!(key in currDef.shape)){throw new Error(`Unrecognized key: "${key}"`)}if(!mask[key])continue;delete newShape[key]}assignProp(this,"shape",newShape);return newShape},checks:[]});return clone(schema,def)}function extend(schema,shape){if(!isPlainObject(shape)){throw new Error("Invalid input to extend: expected a plain object")}const checks=schema._zod.def.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){const existingShape=schema._zod.def.shape;for(const key in shape){if(Object.getOwnPropertyDescriptor(existingShape,key)!==void 0){throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}}}const def=mergeDefs(schema._zod.def,{get shape(){const _shape={...schema._zod.def.shape,...shape};assignProp(this,"shape",_shape);return _shape}});return clone(schema,def)}function safeExtend(schema,shape){if(!isPlainObject(shape)){throw new Error("Invalid input to safeExtend: expected a plain object")}const def=mergeDefs(schema._zod.def,{get shape(){const _shape={...schema._zod.def.shape,...shape};assignProp(this,"shape",_shape);return _shape}});return clone(schema,def)}function merge(a3,b3){if(a3._zod.def.checks?.length){throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.")}const def=mergeDefs(a3._zod.def,{get shape(){const _shape={...a3._zod.def.shape,...b3._zod.def.shape};assignProp(this,"shape",_shape);return _shape},get catchall(){return b3._zod.def.catchall},checks:b3._zod.def.checks??[]});return clone(a3,def)}function partial(Class2,schema,mask){const currDef=schema._zod.def;const checks=currDef.checks;const hasChecks=checks&&checks.length>0;if(hasChecks){throw new Error(".partial() cannot be used on object schemas containing refinements")}const def=mergeDefs(schema._zod.def,{get shape(){const oldShape=schema._zod.def.shape;const shape={...oldShape};if(mask){for(const key in mask){if(!(key in oldShape)){throw new Error(`Unrecognized key: "${key}"`)}if(!mask[key])continue;shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key]}}else{for(const key in oldShape){shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key]}}assignProp(this,"shape",shape);return shape},checks:[]});return clone(schema,def)}function required(Class2,schema,mask){const def=mergeDefs(schema._zod.def,{get shape(){const oldShape=schema._zod.def.shape;const shape={...oldShape};if(mask){for(const key in mask){if(!(key in shape)){throw new Error(`Unrecognized key: "${key}"`)}if(!mask[key])continue;shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]})}}else{for(const key in oldShape){shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]})}}assignProp(this,"shape",shape);return shape}});return clone(schema,def)}function aborted(x2,startIndex=0){if(x2.aborted===true)return true;for(let i2=startIndex;i2<x2.issues.length;i2++){if(x2.issues[i2]?.continue!==true){return true}}return false}function explicitlyAborted(x2,startIndex=0){if(x2.aborted===true)return true;for(let i2=startIndex;i2<x2.issues.length;i2++){if(x2.issues[i2]?.continue===false){return true}}return false}function prefixIssues(path4,issues){return issues.map(iss=>{var _a3;(_a3=iss).path??(_a3.path=[]);iss.path.unshift(path4);return iss})}function unwrapMessage(message){return typeof message==="string"?message:message?.message}function finalizeIssue(iss,ctx,config2){const message=iss.message?iss.message:unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config2.customError?.(iss))??unwrapMessage(config2.localeError?.(iss))??"Invalid input";const{inst:_inst,continue:_continue,input:_input,...rest}=iss;rest.path??(rest.path=[]);rest.message=message;if(ctx?.reportInput){rest.input=_input}return rest}function getSizableOrigin(input){if(input instanceof Set)return"set";if(input instanceof Map)return"map";if(input instanceof File)return"file";return"unknown"}function getLengthableOrigin(input){if(Array.isArray(input))return"array";if(typeof input==="string")return"string";return"unknown"}function parsedType(data){const t2=typeof data;switch(t2){case"number":{return Number.isNaN(data)?"nan":"number"}case"object":{if(data===null){return"null"}if(Array.isArray(data)){return"array"}const obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor){return obj.constructor.name}}}return t2}function issue(...args){const[iss,input,inst]=args;if(typeof iss==="string"){return{message:iss,code:"custom",input,inst}}return{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k2,_3])=>{return Number.isNaN(Number.parseInt(k2,10))}).map(el=>el[1])}function base64ToUint8Array(base643){const binaryString=atob(base643);const bytes=new Uint8Array(binaryString.length);for(let i2=0;i2<binaryString.length;i2++){bytes[i2]=binaryString.charCodeAt(i2)}return bytes}function uint8ArrayToBase64(bytes){let binaryString="";for(let i2=0;i2<bytes.length;i2++){binaryString+=String.fromCharCode(bytes[i2])}return btoa(binaryString)}function base64urlToUint8Array(base64url4){const base643=base64url4.replace(/-/g,"+").replace(/_/g,"/");const padding="=".repeat((4-base643.length%4)%4);return base64ToUint8Array(base643+padding)}function uint8ArrayToBase64url(bytes){return uint8ArrayToBase64(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array(hex3){const cleanHex=hex3.replace(/^0x/,"");if(cleanHex.length%2!==0){throw new Error("Invalid hex string length")}const bytes=new Uint8Array(cleanHex.length/2);for(let i2=0;i2<cleanHex.length;i2+=2){bytes[i2/2]=Number.parseInt(cleanHex.slice(i2,i2+2),16)}return bytes}function uint8ArrayToHex(bytes){return Array.from(bytes).map(b3=>b3.toString(16).padStart(2,"0")).join("")}var EVALUATING,captureStackTrace,allowsEval,getParsedType,propertyKeyTypes,primitiveTypes,NUMBER_FORMAT_RANGES,BIGINT_FORMAT_RANGES,Class;var init_util=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js"(){init_core();EVALUATING=Symbol("evaluating");captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};allowsEval=cached(()=>{if(globalConfig.jitless){return false}if(typeof navigator!=="undefined"&&navigator?.userAgent?.includes("Cloudflare")){return false}try{const F2=Function;new F2("");return true}catch(_3){return false}});getParsedType=data=>{const t2=typeof data;switch(t2){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(data)){return"array"}if(data===null){return"null"}if(data.then&&typeof data.then==="function"&&data.catch&&typeof data.catch==="function"){return"promise"}if(typeof Map!=="undefined"&&data instanceof Map){return"map"}if(typeof Set!=="undefined"&&data instanceof Set){return"set"}if(typeof Date!=="undefined"&&data instanceof Date){return"date"}if(typeof File!=="undefined"&&data instanceof File){return"file"}return"object";default:throw new Error(`Unknown data type: ${t2}`)}};propertyKeyTypes=new Set(["string","number","symbol"]);primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Class=class{constructor(..._args){}}}});function flattenError(error51,mapper=issue2=>issue2.message){const fieldErrors={};const formErrors=[];for(const sub of error51.issues){if(sub.path.length>0){fieldErrors[sub.path[0]]=fieldErrors[sub.path[0]]||[];fieldErrors[sub.path[0]].push(mapper(sub))}else{formErrors.push(mapper(sub))}}return{formErrors,fieldErrors}}function formatError(error51,mapper=issue2=>issue2.message){const fieldErrors={_errors:[]};const processError=(error52,path4=[])=>{for(const issue2 of error52.issues){if(issue2.code==="invalid_union"&&issue2.errors.length){issue2.errors.map(issues=>processError({issues},[...path4,...issue2.path]))}else if(issue2.code==="invalid_key"){processError({issues:issue2.issues},[...path4,...issue2.path])}else if(issue2.code==="invalid_element"){processError({issues:issue2.issues},[...path4,...issue2.path])}else{const fullpath=[...path4,...issue2.path];if(fullpath.length===0){fieldErrors._errors.push(mapper(issue2))}else{let curr=fieldErrors;let i2=0;while(i2<fullpath.length){const el=fullpath[i2];const terminal=i2===fullpath.length-1;if(!terminal){curr[el]=curr[el]||{_errors:[]}}else{curr[el]=curr[el]||{_errors:[]};curr[el]._errors.push(mapper(issue2))}curr=curr[el];i2++}}}}};processError(error51);return fieldErrors}function treeifyError(error51,mapper=issue2=>issue2.message){const result={errors:[]};const processError=(error52,path4=[])=>{var _a3,_b;for(const issue2 of error52.issues){if(issue2.code==="invalid_union"&&issue2.errors.length){issue2.errors.map(issues=>processError({issues},[...path4,...issue2.path]))}else if(issue2.code==="invalid_key"){processError({issues:issue2.issues},[...path4,...issue2.path])}else if(issue2.code==="invalid_element"){processError({issues:issue2.issues},[...path4,...issue2.path])}else{const fullpath=[...path4,...issue2.path];if(fullpath.length===0){result.errors.push(mapper(issue2));continue}let curr=result;let i2=0;while(i2<fullpath.length){const el=fullpath[i2];const terminal=i2===fullpath.length-1;if(typeof el==="string"){curr.properties??(curr.properties={});(_a3=curr.properties)[el]??(_a3[el]={errors:[]});curr=curr.properties[el]}else{curr.items??(curr.items=[]);(_b=curr.items)[el]??(_b[el]={errors:[]});curr=curr.items[el]}if(terminal){curr.errors.push(mapper(issue2))}i2++}}}};processError(error51);return result}function toDotPath(_path){const segs=[];const path4=_path.map(seg=>typeof seg==="object"?seg.key:seg);for(const seg of path4){if(typeof seg==="number")segs.push(`[${seg}]`);else if(typeof seg==="symbol")segs.push(`[${JSON.stringify(String(seg))}]`);else if(/[^\w$]/.test(seg))segs.push(`[${JSON.stringify(seg)}]`);else{if(segs.length)segs.push(".");segs.push(seg)}}return segs.join("")}function prettifyError(error51){const lines=[];const issues=[...error51.issues].sort((a3,b3)=>(a3.path??[]).length-(b3.path??[]).length);for(const issue2 of issues){lines.push(`\u2716 ${issue2.message}`);if(issue2.path?.length)lines.push(` \u2192 at ${toDotPath(issue2.path)}`)}return lines.join("\n")}var initializer,$ZodError,$ZodRealError;var init_errors=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js"(){init_core();init_util();initializer=(inst,def)=>{inst.name="$ZodError";Object.defineProperty(inst,"_zod",{value:inst._zod,enumerable:false});Object.defineProperty(inst,"issues",{value:def,enumerable:false});inst.message=JSON.stringify(def,jsonStringifyReplacer,2);Object.defineProperty(inst,"toString",{value:()=>inst.message,enumerable:false})};$ZodError=$constructor("$ZodError",initializer);$ZodRealError=$constructor("$ZodError",initializer,{Parent:Error})}});var _parse,parse,_parseAsync,parseAsync,_safeParse,safeParse,_safeParseAsync,safeParseAsync,_encode,encode2,_decode,decode3,_encodeAsync,encodeAsync,_decodeAsync,decodeAsync,_safeEncode,safeEncode,_safeDecode,safeDecode,_safeEncodeAsync,safeEncodeAsync,_safeDecodeAsync,safeDecodeAsync;var init_parse=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js"(){init_core();init_errors();init_util();_parse=_Err=>(schema,value,_ctx,_params)=>{const ctx=_ctx?{..._ctx,async:false}:{async:false};const result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise){throw new $ZodAsyncError}if(result.issues.length){const e3=new(_params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));captureStackTrace(e3,_params?.callee);throw e3}return result.value};parse=_parse($ZodRealError);_parseAsync=_Err=>async(schema,value,_ctx,params)=>{const ctx=_ctx?{..._ctx,async:true}:{async:true};let result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;if(result.issues.length){const e3=new(params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));captureStackTrace(e3,params?.callee);throw e3}return result.value};parseAsync=_parseAsync($ZodRealError);_safeParse=_Err=>(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,async:false}:{async:false};const result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise){throw new $ZodAsyncError}return result.issues.length?{success:false,error:new(_Err??$ZodError)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:true,data:result.value}};safeParse=_safeParse($ZodRealError);_safeParseAsync=_Err=>async(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,async:true}:{async:true};let result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;return result.issues.length?{success:false,error:new _Err(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:true,data:result.value}};safeParseAsync=_safeParseAsync($ZodRealError);_encode=_Err=>(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _parse(_Err)(schema,value,ctx)};encode2=_encode($ZodRealError);_decode=_Err=>(schema,value,_ctx)=>{return _parse(_Err)(schema,value,_ctx)};decode3=_decode($ZodRealError);_encodeAsync=_Err=>async(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _parseAsync(_Err)(schema,value,ctx)};encodeAsync=_encodeAsync($ZodRealError);_decodeAsync=_Err=>async(schema,value,_ctx)=>{return _parseAsync(_Err)(schema,value,_ctx)};decodeAsync=_decodeAsync($ZodRealError);_safeEncode=_Err=>(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParse(_Err)(schema,value,ctx)};safeEncode=_safeEncode($ZodRealError);_safeDecode=_Err=>(schema,value,_ctx)=>{return _safeParse(_Err)(schema,value,_ctx)};safeDecode=_safeDecode($ZodRealError);_safeEncodeAsync=_Err=>async(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParseAsync(_Err)(schema,value,ctx)};safeEncodeAsync=_safeEncodeAsync($ZodRealError);_safeDecodeAsync=_Err=>async(schema,value,_ctx)=>{return _safeParseAsync(_Err)(schema,value,_ctx)};safeDecodeAsync=_safeDecodeAsync($ZodRealError)}});var regexes_exports={};__export(regexes_exports,{base64:()=>base64,base64url:()=>base64url2,bigint:()=>bigint,boolean:()=>boolean,browserEmail:()=>browserEmail,cidrv4:()=>cidrv4,cidrv6:()=>cidrv6,cuid:()=>cuid,cuid2:()=>cuid2,date:()=>date,datetime:()=>datetime,domain:()=>domain,duration:()=>duration,e164:()=>e164,email:()=>email,emoji:()=>emoji,extendedDuration:()=>extendedDuration,guid:()=>guid,hex:()=>hex,hostname:()=>hostname3,html5Email:()=>html5Email,httpProtocol:()=>httpProtocol,idnEmail:()=>idnEmail,integer:()=>integer,ipv4:()=>ipv4,ipv6:()=>ipv6,ksuid:()=>ksuid,lowercase:()=>lowercase,mac:()=>mac,md5_base64:()=>md5_base64,md5_base64url:()=>md5_base64url,md5_hex:()=>md5_hex,nanoid:()=>nanoid,null:()=>_null,number:()=>number,rfc5322Email:()=>rfc5322Email,sha1_base64:()=>sha1_base64,sha1_base64url:()=>sha1_base64url,sha1_hex:()=>sha1_hex,sha256_base64:()=>sha256_base64,sha256_base64url:()=>sha256_base64url,sha256_hex:()=>sha256_hex,sha384_base64:()=>sha384_base64,sha384_base64url:()=>sha384_base64url,sha384_hex:()=>sha384_hex,sha512_base64:()=>sha512_base64,sha512_base64url:()=>sha512_base64url,sha512_hex:()=>sha512_hex,string:()=>string,time:()=>time,ulid:()=>ulid,undefined:()=>_undefined,unicodeEmail:()=>unicodeEmail,uppercase:()=>uppercase,uuid:()=>uuid,uuid4:()=>uuid4,uuid6:()=>uuid6,uuid7:()=>uuid7,xid:()=>xid});function emoji(){return new RegExp(_emoji,"u")}function timeSource(args){const hhmm=`(?:[01]\\d|2[0-3]):[0-5]\\d`;const regex=typeof args.precision==="number"?args.precision===-1?`${hhmm}`:args.precision===0?`${hhmm}:[0-5]\\d`:`${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`:`${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;return regex}function time(args){return new RegExp(`^${timeSource(args)}$`)}function datetime(args){const time3=timeSource({precision:args.precision});const opts=["Z"];if(args.local)opts.push("");if(args.offset)opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);const timeRegex=`${time3}(?:${opts.join("|")})`;return new RegExp(`^${dateSource}T(?:${timeRegex})$`)}function fixedBase64(bodyLength,padding){return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`)}function fixedBase64url(length){return new RegExp(`^[A-Za-z0-9_-]{${length}}$`)}var cuid,cuid2,ulid,xid,ksuid,nanoid,duration,extendedDuration,guid,uuid,uuid4,uuid6,uuid7,email,html5Email,rfc5322Email,unicodeEmail,idnEmail,browserEmail,_emoji,ipv4,ipv6,mac,cidrv4,cidrv6,base64,base64url2,hostname3,domain,httpProtocol,e164,dateSource,date,string,bigint,integer,number,boolean,_null,_undefined,lowercase,uppercase,hex,md5_hex,md5_base64,md5_base64url,sha1_hex,sha1_base64,sha1_base64url,sha256_hex,sha256_base64,sha256_base64url,sha384_hex,sha384_base64,sha384_base64url,sha512_hex,sha512_base64,sha512_base64url;var init_regexes=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js"(){init_util();cuid=/^[cC][0-9a-z]{6,}$/;cuid2=/^[0-9a-z]+$/;ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;xid=/^[0-9a-vA-V]{20}$/;ksuid=/^[A-Za-z0-9]{27}$/;nanoid=/^[a-zA-Z0-9_-]{21}$/;duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;extendedDuration=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;uuid=version2=>{if(!version2)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};uuid4=uuid(4);uuid6=uuid(6);uuid7=uuid(7);email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;html5Email=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;rfc5322Email=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;unicodeEmail=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u;idnEmail=unicodeEmail;browserEmail=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;_emoji=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;mac=delimiter=>{const escapedDelim=escapeRegex(delimiter??":");return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`)};cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;base64url2=/^[A-Za-z0-9_-]*$/;hostname3=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;domain=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;httpProtocol=/^https?$/;e164=/^\+[1-9]\d{6,14}$/;dateSource=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;date=new RegExp(`^${dateSource}$`);string=params=>{const regex=params?`[\\s\\S]{${params?.minimum??0},${params?.maximum??""}}`:`[\\s\\S]*`;return new RegExp(`^${regex}$`)};bigint=/^-?\d+n?$/;integer=/^-?\d+$/;number=/^-?\d+(?:\.\d+)?$/;boolean=/^(?:true|false)$/i;_null=/^null$/i;_undefined=/^undefined$/i;lowercase=/^[^A-Z]*$/;uppercase=/^[^a-z]*$/;hex=/^[0-9a-fA-F]*$/;md5_hex=/^[0-9a-fA-F]{32}$/;md5_base64=fixedBase64(22,"==");md5_base64url=fixedBase64url(22);sha1_hex=/^[0-9a-fA-F]{40}$/;sha1_base64=fixedBase64(27,"=");sha1_base64url=fixedBase64url(27);sha256_hex=/^[0-9a-fA-F]{64}$/;sha256_base64=fixedBase64(43,"=");sha256_base64url=fixedBase64url(43);sha384_hex=/^[0-9a-fA-F]{96}$/;sha384_base64=fixedBase64(64,"");sha384_base64url=fixedBase64url(64);sha512_hex=/^[0-9a-fA-F]{128}$/;sha512_base64=fixedBase64(86,"==");sha512_base64url=fixedBase64url(86)}});function handleCheckPropertyResult(result,payload,property){if(result.issues.length){payload.issues.push(...prefixIssues(property,result.issues))}}var $ZodCheck,numericOriginMap,$ZodCheckLessThan,$ZodCheckGreaterThan,$ZodCheckMultipleOf,$ZodCheckNumberFormat,$ZodCheckBigIntFormat,$ZodCheckMaxSize,$ZodCheckMinSize,$ZodCheckSizeEquals,$ZodCheckMaxLength,$ZodCheckMinLength,$ZodCheckLengthEquals,$ZodCheckStringFormat,$ZodCheckRegex,$ZodCheckLowerCase,$ZodCheckUpperCase,$ZodCheckIncludes,$ZodCheckStartsWith,$ZodCheckEndsWith,$ZodCheckProperty,$ZodCheckMimeType,$ZodCheckOverwrite;var init_checks=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js"(){init_core();init_regexes();init_util();$ZodCheck=$constructor("$ZodCheck",(inst,def)=>{var _a3;inst._zod??(inst._zod={});inst._zod.def=def;(_a3=inst._zod).onattach??(_a3.onattach=[])});numericOriginMap={number:"number",bigint:"bigint",object:"date"};$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(inst,def)=>{$ZodCheck.init(inst,def);const origin=numericOriginMap[typeof def.value];inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;const curr=(def.inclusive?bag.maximum:bag.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(def.value<curr){if(def.inclusive)bag.maximum=def.value;else bag.exclusiveMaximum=def.value}});inst._zod.check=payload=>{if(def.inclusive?payload.value<=def.value:payload.value<def.value){return}payload.issues.push({origin,code:"too_big",maximum:typeof def.value==="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}});$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck.init(inst,def);const origin=numericOriginMap[typeof def.value];inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;const curr=(def.inclusive?bag.minimum:bag.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(def.value>curr){if(def.inclusive)bag.minimum=def.value;else bag.exclusiveMinimum=def.value}});inst._zod.check=payload=>{if(def.inclusive?payload.value>=def.value:payload.value>def.value){return}payload.issues.push({origin,code:"too_small",minimum:typeof def.value==="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}});$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck.init(inst,def);inst._zod.onattach.push(inst2=>{var _a3;(_a3=inst2._zod.bag).multipleOf??(_a3.multipleOf=def.value)});inst._zod.check=payload=>{if(typeof payload.value!==typeof def.value)throw new Error("Cannot mix number and bigint in multiple_of check.");const isMultiple=typeof payload.value==="bigint"?payload.value%def.value===BigInt(0):floatSafeRemainder(payload.value,def.value)===0;if(isMultiple)return;payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}});$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck.init(inst,def);def.format=def.format||"float64";const isInt=def.format?.includes("int");const origin=isInt?"int":"number";const[minimum,maximum]=NUMBER_FORMAT_RANGES[def.format];inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.format=def.format;bag.minimum=minimum;bag.maximum=maximum;if(isInt)bag.pattern=integer});inst._zod.check=payload=>{const input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:false,input,inst});return}if(!Number.isSafeInteger(input)){if(input>0){payload.issues.push({input,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:true,continue:!def.abort})}else{payload.issues.push({input,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:true,continue:!def.abort})}return}}if(input<minimum){payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:true,inst,continue:!def.abort})}if(input>maximum){payload.issues.push({origin:"number",input,code:"too_big",maximum,inclusive:true,inst,continue:!def.abort})}}});$ZodCheckBigIntFormat=$constructor("$ZodCheckBigIntFormat",(inst,def)=>{$ZodCheck.init(inst,def);const[minimum,maximum]=BIGINT_FORMAT_RANGES[def.format];inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.format=def.format;bag.minimum=minimum;bag.maximum=maximum});inst._zod.check=payload=>{const input=payload.value;if(input<minimum){payload.issues.push({origin:"bigint",input,code:"too_small",minimum,inclusive:true,inst,continue:!def.abort})}if(input>maximum){payload.issues.push({origin:"bigint",input,code:"too_big",maximum,inclusive:true,inst,continue:!def.abort})}}});$ZodCheckMaxSize=$constructor("$ZodCheckMaxSize",(inst,def)=>{var _a3;$ZodCheck.init(inst,def);(_a3=inst._zod.def).when??(_a3.when=payload=>{const val=payload.value;return!nullish(val)&&val.size!==void 0});inst._zod.onattach.push(inst2=>{const curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;if(def.maximum<curr)inst2._zod.bag.maximum=def.maximum});inst._zod.check=payload=>{const input=payload.value;const size=input.size;if(size<=def.maximum)return;payload.issues.push({origin:getSizableOrigin(input),code:"too_big",maximum:def.maximum,inclusive:true,input,inst,continue:!def.abort})}});$ZodCheckMinSize=$constructor("$ZodCheckMinSize",(inst,def)=>{var _a3;$ZodCheck.init(inst,def);(_a3=inst._zod.def).when??(_a3.when=payload=>{const val=payload.value;return!nullish(val)&&val.size!==void 0});inst._zod.onattach.push(inst2=>{const curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(def.minimum>curr)inst2._zod.bag.minimum=def.minimum});inst._zod.check=payload=>{const input=payload.value;const size=input.size;if(size>=def.minimum)return;payload.issues.push({origin:getSizableOrigin(input),code:"too_small",minimum:def.minimum,inclusive:true,input,inst,continue:!def.abort})}});$ZodCheckSizeEquals=$constructor("$ZodCheckSizeEquals",(inst,def)=>{var _a3;$ZodCheck.init(inst,def);(_a3=inst._zod.def).when??(_a3.when=payload=>{const val=payload.value;return!nullish(val)&&val.size!==void 0});inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.minimum=def.size;bag.maximum=def.size;bag.size=def.size});inst._zod.check=payload=>{const input=payload.value;const size=input.size;if(size===def.size)return;const tooBig=size>def.size;payload.issues.push({origin:getSizableOrigin(input),...tooBig?{code:"too_big",maximum:def.size}:{code:"too_small",minimum:def.size},inclusive:true,exact:true,input:payload.value,inst,continue:!def.abort})}});$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(inst,def)=>{var _a3;$ZodCheck.init(inst,def);(_a3=inst._zod.def).when??(_a3.when=payload=>{const val=payload.value;return!nullish(val)&&val.length!==void 0});inst._zod.onattach.push(inst2=>{const curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;if(def.maximum<curr)inst2._zod.bag.maximum=def.maximum});inst._zod.check=payload=>{const input=payload.value;const length=input.length;if(length<=def.maximum)return;const origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:true,input,inst,continue:!def.abort})}});$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(inst,def)=>{var _a3;$ZodCheck.init(inst,def);(_a3=inst._zod.def).when??(_a3.when=payload=>{const val=payload.value;return!nullish(val)&&val.length!==void 0});inst._zod.onattach.push(inst2=>{const curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(def.minimum>curr)inst2._zod.bag.minimum=def.minimum});inst._zod.check=payload=>{const input=payload.value;const length=input.length;if(length>=def.minimum)return;const origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:true,input,inst,continue:!def.abort})}});$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(inst,def)=>{var _a3;$ZodCheck.init(inst,def);(_a3=inst._zod.def).when??(_a3.when=payload=>{const val=payload.value;return!nullish(val)&&val.length!==void 0});inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.minimum=def.length;bag.maximum=def.length;bag.length=def.length});inst._zod.check=payload=>{const input=payload.value;const length=input.length;if(length===def.length)return;const origin=getLengthableOrigin(input);const tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:true,exact:true,input:payload.value,inst,continue:!def.abort})}});$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(inst,def)=>{var _a3,_b;$ZodCheck.init(inst,def);inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.format=def.format;if(def.pattern){bag.patterns??(bag.patterns=new Set);bag.patterns.add(def.pattern)}});if(def.pattern)(_a3=inst._zod).check??(_a3.check=payload=>{def.pattern.lastIndex=0;if(def.pattern.test(payload.value))return;payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})});else(_b=inst._zod).check??(_b.check=()=>{})});$ZodCheckRegex=$constructor("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat.init(inst,def);inst._zod.check=payload=>{def.pattern.lastIndex=0;if(def.pattern.test(payload.value))return;payload.issues.push({origin:"string",code:"invalid_format",format:"regex",input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}});$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase);$ZodCheckStringFormat.init(inst,def)});$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase);$ZodCheckStringFormat.init(inst,def)});$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(inst,def)=>{$ZodCheck.init(inst,def);const escapedRegex=escapeRegex(def.includes);const pattern=new RegExp(typeof def.position==="number"?`^.{${def.position}}${escapedRegex}`:escapedRegex);def.pattern=pattern;inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set);bag.patterns.add(pattern)});inst._zod.check=payload=>{if(payload.value.includes(def.includes,def.position))return;payload.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:def.includes,input:payload.value,inst,continue:!def.abort})}});$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck.init(inst,def);const pattern=new RegExp(`^${escapeRegex(def.prefix)}.*`);def.pattern??(def.pattern=pattern);inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set);bag.patterns.add(pattern)});inst._zod.check=payload=>{if(payload.value.startsWith(def.prefix))return;payload.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}});$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck.init(inst,def);const pattern=new RegExp(`.*${escapeRegex(def.suffix)}$`);def.pattern??(def.pattern=pattern);inst._zod.onattach.push(inst2=>{const bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set);bag.patterns.add(pattern)});inst._zod.check=payload=>{if(payload.value.endsWith(def.suffix))return;payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}});$ZodCheckProperty=$constructor("$ZodCheckProperty",(inst,def)=>{$ZodCheck.init(inst,def);inst._zod.check=payload=>{const result=def.schema._zod.run({value:payload.value[def.property],issues:[]},{});if(result instanceof Promise){return result.then(result2=>handleCheckPropertyResult(result2,payload,def.property))}handleCheckPropertyResult(result,payload,def.property);return}});$ZodCheckMimeType=$constructor("$ZodCheckMimeType",(inst,def)=>{$ZodCheck.init(inst,def);const mimeSet=new Set(def.mime);inst._zod.onattach.push(inst2=>{inst2._zod.bag.mime=def.mime});inst._zod.check=payload=>{if(mimeSet.has(payload.value.type))return;payload.issues.push({code:"invalid_value",values:def.mime,input:payload.value.type,inst,continue:!def.abort})}});$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck.init(inst,def);inst._zod.check=payload=>{payload.value=def.tx(payload.value)}})}});var Doc;var init_doc=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js"(){Doc=class{constructor(args=[]){this.content=[];this.indent=0;if(this)this.args=args}indented(fn2){this.indent+=1;fn2(this);this.indent-=1}write(arg){if(typeof arg==="function"){arg(this,{execution:"sync"});arg(this,{execution:"async"});return}const content=arg;const lines=content.split("\n").filter(x2=>x2);const minIndent=Math.min(...lines.map(x2=>x2.length-x2.trimStart().length));const dedented=lines.map(x2=>x2.slice(minIndent)).map(x2=>" ".repeat(this.indent*2)+x2);for(const line of dedented){this.content.push(line)}}compile(){const F2=Function;const args=this?.args;const content=this?.content??[``];const lines=[...content.map(x2=>` ${x2}`)];return new F2(...args,lines.join("\n"))}}}});var version;var init_versions=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js"(){version={major:4,minor:4,patch:3}}});function isValidBase64(data){if(data==="")return true;if(/\s/.test(data))return false;if(data.length%4!==0)return false;try{atob(data);return true}catch{return false}}function isValidBase64URL(data){if(!base64url2.test(data))return false;const base643=data.replace(/[-_]/g,c3=>c3==="-"?"+":"/");const padded=base643.padEnd(Math.ceil(base643.length/4)*4,"=");return isValidBase64(padded)}function isValidJWT(token2,algorithm=null){try{const tokensParts=token2.split(".");if(tokensParts.length!==3)return false;const[header]=tokensParts;if(!header)return false;const parsedHeader=JSON.parse(atob(header));if("typ"in parsedHeader&&parsedHeader?.typ!=="JWT")return false;if(!parsedHeader.alg)return false;if(algorithm&&(!("alg"in parsedHeader)||parsedHeader.alg!==algorithm))return false;return true}catch{return false}}function handleArrayResult(result,final,index2){if(result.issues.length){final.issues.push(...prefixIssues(index2,result.issues))}final.value[index2]=result.value}function handlePropertyResult(result,final,key,input,isOptionalIn,isOptionalOut){const isPresent=key in input;if(result.issues.length){if(isOptionalIn&&isOptionalOut&&!isPresent){return}final.issues.push(...prefixIssues(key,result.issues))}if(!isPresent&&!isOptionalIn){if(!result.issues.length){final.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[key]})}return}if(result.value===void 0){if(isPresent){final.value[key]=void 0}}else{final.value[key]=result.value}}function normalizeDef(def){const keys=Object.keys(def.shape);for(const k2 of keys){if(!def.shape?.[k2]?._zod?.traits?.has("$ZodType")){throw new Error(`Invalid element at key "${k2}": expected a Zod schema`)}}const okeys=optionalKeys(def.shape);return{...def,keys,keySet:new Set(keys),numKeys:keys.length,optionalKeys:new Set(okeys)}}function handleCatchall(proms,input,payload,ctx,def,inst){const unrecognized=[];const keySet=def.keySet;const _catchall=def.catchall._zod;const t2=_catchall.def.type;const isOptionalIn=_catchall.optin==="optional";const isOptionalOut=_catchall.optout==="optional";for(const key in input){if(key==="__proto__")continue;if(keySet.has(key))continue;if(t2==="never"){unrecognized.push(key);continue}const r2=_catchall.run({value:input[key],issues:[]},ctx);if(r2 instanceof Promise){proms.push(r2.then(r3=>handlePropertyResult(r3,payload,key,input,isOptionalIn,isOptionalOut)))}else{handlePropertyResult(r2,payload,key,input,isOptionalIn,isOptionalOut)}}if(unrecognized.length){payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input,inst})}if(!proms.length)return payload;return Promise.all(proms).then(()=>{return payload})}function handleUnionResults(results,final,inst,ctx){for(const result of results){if(result.issues.length===0){final.value=result.value;return final}}const nonaborted=results.filter(r2=>!aborted(r2));if(nonaborted.length===1){final.value=nonaborted[0].value;return nonaborted[0]}final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))});return final}function handleExclusiveUnionResults(results,final,inst,ctx){const successes=results.filter(r2=>r2.issues.length===0);if(successes.length===1){final.value=successes[0].value;return final}if(successes.length===0){final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))})}else{final.issues.push({code:"invalid_union",input:final.value,inst,errors:[],inclusive:false})}return final}function mergeValues(a3,b3){if(a3===b3){return{valid:true,data:a3}}if(a3 instanceof Date&&b3 instanceof Date&&+a3===+b3){return{valid:true,data:a3}}if(isPlainObject(a3)&&isPlainObject(b3)){const bKeys=Object.keys(b3);const sharedKeys=Object.keys(a3).filter(key=>bKeys.indexOf(key)!==-1);const newObj={...a3,...b3};for(const key of sharedKeys){const sharedValue=mergeValues(a3[key],b3[key]);if(!sharedValue.valid){return{valid:false,mergeErrorPath:[key,...sharedValue.mergeErrorPath]}}newObj[key]=sharedValue.data}return{valid:true,data:newObj}}if(Array.isArray(a3)&&Array.isArray(b3)){if(a3.length!==b3.length){return{valid:false,mergeErrorPath:[]}}const newArray=[];for(let index2=0;index2<a3.length;index2++){const itemA=a3[index2];const itemB=b3[index2];const sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid){return{valid:false,mergeErrorPath:[index2,...sharedValue.mergeErrorPath]}}newArray.push(sharedValue.data)}return{valid:true,data:newArray}}return{valid:false,mergeErrorPath:[]}}function handleIntersectionResults(result,left,right){const unrecKeys=new Map;let unrecIssue;for(const iss of left.issues){if(iss.code==="unrecognized_keys"){unrecIssue??(unrecIssue=iss);for(const k2 of iss.keys){if(!unrecKeys.has(k2))unrecKeys.set(k2,{});unrecKeys.get(k2).l=true}}else{result.issues.push(iss)}}for(const iss of right.issues){if(iss.code==="unrecognized_keys"){for(const k2 of iss.keys){if(!unrecKeys.has(k2))unrecKeys.set(k2,{});unrecKeys.get(k2).r=true}}else{result.issues.push(iss)}}const bothKeys=[...unrecKeys].filter(([,f2])=>f2.l&&f2.r).map(([k2])=>k2);if(bothKeys.length&&unrecIssue){result.issues.push({...unrecIssue,keys:bothKeys})}if(aborted(result))return result;const merged=mergeValues(left.value,right.value);if(!merged.valid){throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`)}result.value=merged.data;return result}function getTupleOptStart(items,key){for(let i2=items.length-1;i2>=0;i2--){if(items[i2]._zod[key]!=="optional")return i2+1}return 0}function handleTupleResult(result,final,index2){if(result.issues.length){final.issues.push(...prefixIssues(index2,result.issues))}final.value[index2]=result.value}function handleTupleResults(itemResults,final,items,input,optoutStart){for(let i2=0;i2<items.length;i2++){const r2=itemResults[i2];const isPresent=i2<input.length;if(r2.issues.length){if(!isPresent&&i2>=optoutStart){final.value.length=i2;break}final.issues.push(...prefixIssues(i2,r2.issues))}final.value[i2]=r2.value}for(let i2=final.value.length-1;i2>=input.length;i2--){if(items[i2]._zod.optout==="optional"&&final.value[i2]===void 0){final.value.length=i2}else{break}}return final}function handleMapResult(keyResult,valueResult,final,key,input,inst,ctx){if(keyResult.issues.length){if(propertyKeyTypes.has(typeof key)){final.issues.push(...prefixIssues(key,keyResult.issues))}else{final.issues.push({code:"invalid_key",origin:"map",input,inst,issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config()))})}}if(valueResult.issues.length){if(propertyKeyTypes.has(typeof key)){final.issues.push(...prefixIssues(key,valueResult.issues))}else{final.issues.push({origin:"map",code:"invalid_element",input,inst,key,issues:valueResult.issues.map(iss=>finalizeIssue(iss,ctx,config()))})}}final.value.set(keyResult.value,valueResult.value)}function handleSetResult(result,final){if(result.issues.length){final.issues.push(...result.issues)}final.value.add(result.value)}function handleOptionalResult(result,input){if(input===void 0&&(result.issues.length||result.fallback)){return{issues:[],value:void 0}}return result}function handleDefaultResult(payload,def){if(payload.value===void 0){payload.value=def.defaultValue}return payload}function handleNonOptionalResult(payload,inst){if(!payload.issues.length&&payload.value===void 0){payload.issues.push({code:"invalid_type",expected:"nonoptional",input:payload.value,inst})}return payload}function handlePipeResult(left,next,ctx){if(left.issues.length){left.aborted=true;return left}return next._zod.run({value:left.value,issues:left.issues,fallback:left.fallback},ctx)}function handleCodecAResult(result,def,ctx){if(result.issues.length){result.aborted=true;return result}const direction=ctx.direction||"forward";if(direction==="forward"){const transformed=def.transform(result.value,result);if(transformed instanceof Promise){return transformed.then(value=>handleCodecTxResult(result,value,def.out,ctx))}return handleCodecTxResult(result,transformed,def.out,ctx)}else{const transformed=def.reverseTransform(result.value,result);if(transformed instanceof Promise){return transformed.then(value=>handleCodecTxResult(result,value,def.in,ctx))}return handleCodecTxResult(result,transformed,def.in,ctx)}}function handleCodecTxResult(left,value,nextSchema,ctx){if(left.issues.length){left.aborted=true;return left}return nextSchema._zod.run({value,issues:left.issues},ctx)}function handleReadonlyResult(payload){payload.value=Object.freeze(payload.value);return payload}function handleRefineResult(result,payload,input,inst){if(!result){const _iss={code:"custom",input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};if(inst._zod.def.params)_iss.params=inst._zod.def.params;payload.issues.push(issue(_iss))}}var $ZodType,$ZodString,$ZodStringFormat,$ZodGUID,$ZodUUID,$ZodEmail,$ZodURL,$ZodEmoji,$ZodNanoID,$ZodCUID,$ZodCUID2,$ZodULID,$ZodXID,$ZodKSUID,$ZodISODateTime,$ZodISODate,$ZodISOTime,$ZodISODuration,$ZodIPv4,$ZodIPv6,$ZodMAC,$ZodCIDRv4,$ZodCIDRv6,$ZodBase64,$ZodBase64URL,$ZodE164,$ZodJWT,$ZodCustomStringFormat,$ZodNumber,$ZodNumberFormat,$ZodBoolean,$ZodBigInt,$ZodBigIntFormat,$ZodSymbol,$ZodUndefined,$ZodNull,$ZodAny,$ZodUnknown,$ZodNever,$ZodVoid,$ZodDate,$ZodArray,$ZodObject,$ZodObjectJIT,$ZodUnion,$ZodXor,$ZodDiscriminatedUnion,$ZodIntersection,$ZodTuple,$ZodRecord,$ZodMap,$ZodSet,$ZodEnum,$ZodLiteral,$ZodFile,$ZodTransform,$ZodOptional,$ZodExactOptional,$ZodNullable,$ZodDefault,$ZodPrefault,$ZodNonOptional,$ZodSuccess,$ZodCatch,$ZodNaN,$ZodPipe,$ZodCodec,$ZodPreprocess,$ZodReadonly,$ZodTemplateLiteral,$ZodFunction,$ZodPromise,$ZodLazy,$ZodCustom;var init_schemas=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js"(){init_checks();init_core();init_doc();init_parse();init_regexes();init_util();init_versions();init_util();$ZodType=$constructor("$ZodType",(inst,def)=>{var _a3;inst??(inst={});inst._zod.def=def;inst._zod.bag=inst._zod.bag||{};inst._zod.version=version;const checks=[...inst._zod.def.checks??[]];if(inst._zod.traits.has("$ZodCheck")){checks.unshift(inst)}for(const ch of checks){for(const fn2 of ch._zod.onattach){fn2(inst)}}if(checks.length===0){(_a3=inst._zod).deferred??(_a3.deferred=[]);inst._zod.deferred?.push(()=>{inst._zod.run=inst._zod.parse})}else{const runChecks=(payload,checks2,ctx)=>{let isAborted=aborted(payload);let asyncResult;for(const ch of checks2){if(ch._zod.def.when){if(explicitlyAborted(payload))continue;const shouldRun=ch._zod.def.when(payload);if(!shouldRun)continue}else if(isAborted){continue}const currLen=payload.issues.length;const _3=ch._zod.check(payload);if(_3 instanceof Promise&&ctx?.async===false){throw new $ZodAsyncError}if(asyncResult||_3 instanceof Promise){asyncResult=(asyncResult??Promise.resolve()).then(async()=>{await _3;const nextLen=payload.issues.length;if(nextLen===currLen)return;if(!isAborted)isAborted=aborted(payload,currLen)})}else{const nextLen=payload.issues.length;if(nextLen===currLen)continue;if(!isAborted)isAborted=aborted(payload,currLen)}}if(asyncResult){return asyncResult.then(()=>{return payload})}return payload};const handleCanaryResult=(canary,payload,ctx)=>{if(aborted(canary)){canary.aborted=true;return canary}const checkResult=runChecks(payload,checks,ctx);if(checkResult instanceof Promise){if(ctx.async===false)throw new $ZodAsyncError;return checkResult.then(checkResult2=>inst._zod.parse(checkResult2,ctx))}return inst._zod.parse(checkResult,ctx)};inst._zod.run=(payload,ctx)=>{if(ctx.skipChecks){return inst._zod.parse(payload,ctx)}if(ctx.direction==="backward"){const canary=inst._zod.parse({value:payload.value,issues:[]},{...ctx,skipChecks:true});if(canary instanceof Promise){return canary.then(canary2=>{return handleCanaryResult(canary2,payload,ctx)})}return handleCanaryResult(canary,payload,ctx)}const result=inst._zod.parse(payload,ctx);if(result instanceof Promise){if(ctx.async===false)throw new $ZodAsyncError;return result.then(result2=>runChecks(result2,checks,ctx))}return runChecks(result,checks,ctx)}}defineLazy(inst,"~standard",()=>({validate:value=>{try{const r2=safeParse(inst,value);return r2.success?{value:r2.data}:{issues:r2.error?.issues}}catch(_3){return safeParseAsync(inst,value).then(r2=>r2.success?{value:r2.data}:{issues:r2.error?.issues})}},vendor:"zod",version:1}))});$ZodString=$constructor("$ZodString",(inst,def)=>{$ZodType.init(inst,def);inst._zod.pattern=[...inst?._zod.bag?.patterns??[]].pop()??string(inst._zod.bag);inst._zod.parse=(payload,_3)=>{if(def.coerce)try{payload.value=String(payload.value)}catch(_4){}if(typeof payload.value==="string")return payload;payload.issues.push({expected:"string",code:"invalid_type",input:payload.value,inst});return payload}});$ZodStringFormat=$constructor("$ZodStringFormat",(inst,def)=>{$ZodCheckStringFormat.init(inst,def);$ZodString.init(inst,def)});$ZodGUID=$constructor("$ZodGUID",(inst,def)=>{def.pattern??(def.pattern=guid);$ZodStringFormat.init(inst,def)});$ZodUUID=$constructor("$ZodUUID",(inst,def)=>{if(def.version){const versionMap={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8};const v3=versionMap[def.version];if(v3===void 0)throw new Error(`Invalid UUID version: "${def.version}"`);def.pattern??(def.pattern=uuid(v3))}else def.pattern??(def.pattern=uuid());$ZodStringFormat.init(inst,def)});$ZodEmail=$constructor("$ZodEmail",(inst,def)=>{def.pattern??(def.pattern=email);$ZodStringFormat.init(inst,def)});$ZodURL=$constructor("$ZodURL",(inst,def)=>{$ZodStringFormat.init(inst,def);inst._zod.check=payload=>{try{const trimmed=payload.value.trim();if(!def.normalize&&def.protocol?.source===httpProtocol.source){if(!/^https?:\/\//i.test(trimmed)){payload.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:payload.value,inst,continue:!def.abort});return}}const url2=new URL(trimmed);if(def.hostname){def.hostname.lastIndex=0;if(!def.hostname.test(url2.hostname)){payload.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:def.hostname.source,input:payload.value,inst,continue:!def.abort})}}if(def.protocol){def.protocol.lastIndex=0;if(!def.protocol.test(url2.protocol.endsWith(":")?url2.protocol.slice(0,-1):url2.protocol)){payload.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:def.protocol.source,input:payload.value,inst,continue:!def.abort})}}if(def.normalize){payload.value=url2.href}else{payload.value=trimmed}return}catch(_3){payload.issues.push({code:"invalid_format",format:"url",input:payload.value,inst,continue:!def.abort})}}});$ZodEmoji=$constructor("$ZodEmoji",(inst,def)=>{def.pattern??(def.pattern=emoji());$ZodStringFormat.init(inst,def)});$ZodNanoID=$constructor("$ZodNanoID",(inst,def)=>{def.pattern??(def.pattern=nanoid);$ZodStringFormat.init(inst,def)});$ZodCUID=$constructor("$ZodCUID",(inst,def)=>{def.pattern??(def.pattern=cuid);$ZodStringFormat.init(inst,def)});$ZodCUID2=$constructor("$ZodCUID2",(inst,def)=>{def.pattern??(def.pattern=cuid2);$ZodStringFormat.init(inst,def)});$ZodULID=$constructor("$ZodULID",(inst,def)=>{def.pattern??(def.pattern=ulid);$ZodStringFormat.init(inst,def)});$ZodXID=$constructor("$ZodXID",(inst,def)=>{def.pattern??(def.pattern=xid);$ZodStringFormat.init(inst,def)});$ZodKSUID=$constructor("$ZodKSUID",(inst,def)=>{def.pattern??(def.pattern=ksuid);$ZodStringFormat.init(inst,def)});$ZodISODateTime=$constructor("$ZodISODateTime",(inst,def)=>{def.pattern??(def.pattern=datetime(def));$ZodStringFormat.init(inst,def)});$ZodISODate=$constructor("$ZodISODate",(inst,def)=>{def.pattern??(def.pattern=date);$ZodStringFormat.init(inst,def)});$ZodISOTime=$constructor("$ZodISOTime",(inst,def)=>{def.pattern??(def.pattern=time(def));$ZodStringFormat.init(inst,def)});$ZodISODuration=$constructor("$ZodISODuration",(inst,def)=>{def.pattern??(def.pattern=duration);$ZodStringFormat.init(inst,def)});$ZodIPv4=$constructor("$ZodIPv4",(inst,def)=>{def.pattern??(def.pattern=ipv4);$ZodStringFormat.init(inst,def);inst._zod.bag.format=`ipv4`});$ZodIPv6=$constructor("$ZodIPv6",(inst,def)=>{def.pattern??(def.pattern=ipv6);$ZodStringFormat.init(inst,def);inst._zod.bag.format=`ipv6`;inst._zod.check=payload=>{try{new URL(`http://[${payload.value}]`)}catch{payload.issues.push({code:"invalid_format",format:"ipv6",input:payload.value,inst,continue:!def.abort})}}});$ZodMAC=$constructor("$ZodMAC",(inst,def)=>{def.pattern??(def.pattern=mac(def.delimiter));$ZodStringFormat.init(inst,def);inst._zod.bag.format=`mac`});$ZodCIDRv4=$constructor("$ZodCIDRv4",(inst,def)=>{def.pattern??(def.pattern=cidrv4);$ZodStringFormat.init(inst,def)});$ZodCIDRv6=$constructor("$ZodCIDRv6",(inst,def)=>{def.pattern??(def.pattern=cidrv6);$ZodStringFormat.init(inst,def);inst._zod.check=payload=>{const parts=payload.value.split("/");try{if(parts.length!==2)throw new Error;const[address,prefix]=parts;if(!prefix)throw new Error;const prefixNum=Number(prefix);if(`${prefixNum}`!==prefix)throw new Error;if(prefixNum<0||prefixNum>128)throw new Error;new URL(`http://[${address}]`)}catch{payload.issues.push({code:"invalid_format",format:"cidrv6",input:payload.value,inst,continue:!def.abort})}}});$ZodBase64=$constructor("$ZodBase64",(inst,def)=>{def.pattern??(def.pattern=base64);$ZodStringFormat.init(inst,def);inst._zod.bag.contentEncoding="base64";inst._zod.check=payload=>{if(isValidBase64(payload.value))return;payload.issues.push({code:"invalid_format",format:"base64",input:payload.value,inst,continue:!def.abort})}});$ZodBase64URL=$constructor("$ZodBase64URL",(inst,def)=>{def.pattern??(def.pattern=base64url2);$ZodStringFormat.init(inst,def);inst._zod.bag.contentEncoding="base64url";inst._zod.check=payload=>{if(isValidBase64URL(payload.value))return;payload.issues.push({code:"invalid_format",format:"base64url",input:payload.value,inst,continue:!def.abort})}});$ZodE164=$constructor("$ZodE164",(inst,def)=>{def.pattern??(def.pattern=e164);$ZodStringFormat.init(inst,def)});$ZodJWT=$constructor("$ZodJWT",(inst,def)=>{$ZodStringFormat.init(inst,def);inst._zod.check=payload=>{if(isValidJWT(payload.value,def.alg))return;payload.issues.push({code:"invalid_format",format:"jwt",input:payload.value,inst,continue:!def.abort})}});$ZodCustomStringFormat=$constructor("$ZodCustomStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def);inst._zod.check=payload=>{if(def.fn(payload.value))return;payload.issues.push({code:"invalid_format",format:def.format,input:payload.value,inst,continue:!def.abort})}});$ZodNumber=$constructor("$ZodNumber",(inst,def)=>{$ZodType.init(inst,def);inst._zod.pattern=inst._zod.bag.pattern??number;inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=Number(payload.value)}catch(_3){}const input=payload.value;if(typeof input==="number"&&!Number.isNaN(input)&&Number.isFinite(input)){return payload}const received=typeof input==="number"?Number.isNaN(input)?"NaN":!Number.isFinite(input)?"Infinity":void 0:void 0;payload.issues.push({expected:"number",code:"invalid_type",input,inst,...received?{received}:{}});return payload}});$ZodNumberFormat=$constructor("$ZodNumberFormat",(inst,def)=>{$ZodCheckNumberFormat.init(inst,def);$ZodNumber.init(inst,def)});$ZodBoolean=$constructor("$ZodBoolean",(inst,def)=>{$ZodType.init(inst,def);inst._zod.pattern=boolean;inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=Boolean(payload.value)}catch(_3){}const input=payload.value;if(typeof input==="boolean")return payload;payload.issues.push({expected:"boolean",code:"invalid_type",input,inst});return payload}});$ZodBigInt=$constructor("$ZodBigInt",(inst,def)=>{$ZodType.init(inst,def);inst._zod.pattern=bigint;inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=BigInt(payload.value)}catch(_3){}if(typeof payload.value==="bigint")return payload;payload.issues.push({expected:"bigint",code:"invalid_type",input:payload.value,inst});return payload}});$ZodBigIntFormat=$constructor("$ZodBigIntFormat",(inst,def)=>{$ZodCheckBigIntFormat.init(inst,def);$ZodBigInt.init(inst,def)});$ZodSymbol=$constructor("$ZodSymbol",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,_ctx)=>{const input=payload.value;if(typeof input==="symbol")return payload;payload.issues.push({expected:"symbol",code:"invalid_type",input,inst});return payload}});$ZodUndefined=$constructor("$ZodUndefined",(inst,def)=>{$ZodType.init(inst,def);inst._zod.pattern=_undefined;inst._zod.values=new Set([void 0]);inst._zod.parse=(payload,_ctx)=>{const input=payload.value;if(typeof input==="undefined")return payload;payload.issues.push({expected:"undefined",code:"invalid_type",input,inst});return payload}});$ZodNull=$constructor("$ZodNull",(inst,def)=>{$ZodType.init(inst,def);inst._zod.pattern=_null;inst._zod.values=new Set([null]);inst._zod.parse=(payload,_ctx)=>{const input=payload.value;if(input===null)return payload;payload.issues.push({expected:"null",code:"invalid_type",input,inst});return payload}});$ZodAny=$constructor("$ZodAny",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=payload=>payload});$ZodUnknown=$constructor("$ZodUnknown",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=payload=>payload});$ZodNever=$constructor("$ZodNever",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,_ctx)=>{payload.issues.push({expected:"never",code:"invalid_type",input:payload.value,inst});return payload}});$ZodVoid=$constructor("$ZodVoid",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,_ctx)=>{const input=payload.value;if(typeof input==="undefined")return payload;payload.issues.push({expected:"void",code:"invalid_type",input,inst});return payload}});$ZodDate=$constructor("$ZodDate",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,_ctx)=>{if(def.coerce){try{payload.value=new Date(payload.value)}catch(_err){}}const input=payload.value;const isDate=input instanceof Date;const isValidDate=isDate&&!Number.isNaN(input.getTime());if(isValidDate)return payload;payload.issues.push({expected:"date",code:"invalid_type",input,...isDate?{received:"Invalid Date"}:{},inst});return payload}});$ZodArray=$constructor("$ZodArray",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,ctx)=>{const input=payload.value;if(!Array.isArray(input)){payload.issues.push({expected:"array",code:"invalid_type",input,inst});return payload}payload.value=Array(input.length);const proms=[];for(let i2=0;i2<input.length;i2++){const item=input[i2];const result=def.element._zod.run({value:item,issues:[]},ctx);if(result instanceof Promise){proms.push(result.then(result2=>handleArrayResult(result2,payload,i2)))}else{handleArrayResult(result,payload,i2)}}if(proms.length){return Promise.all(proms).then(()=>payload)}return payload}});$ZodObject=$constructor("$ZodObject",(inst,def)=>{$ZodType.init(inst,def);const desc=Object.getOwnPropertyDescriptor(def,"shape");if(!desc?.get){const sh=def.shape;Object.defineProperty(def,"shape",{get:()=>{const newSh={...sh};Object.defineProperty(def,"shape",{value:newSh});return newSh}})}const _normalized=cached(()=>normalizeDef(def));defineLazy(inst._zod,"propValues",()=>{const shape=def.shape;const propValues={};for(const key in shape){const field=shape[key]._zod;if(field.values){propValues[key]??(propValues[key]=new Set);for(const v3 of field.values)propValues[key].add(v3)}}return propValues});const isObject2=isObject;const catchall=def.catchall;let value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);const input=payload.value;if(!isObject2(input)){payload.issues.push({expected:"object",code:"invalid_type",input,inst});return payload}payload.value={};const proms=[];const shape=value.shape;for(const key of value.keys){const el=shape[key];const isOptionalIn=el._zod.optin==="optional";const isOptionalOut=el._zod.optout==="optional";const r2=el._zod.run({value:input[key],issues:[]},ctx);if(r2 instanceof Promise){proms.push(r2.then(r3=>handlePropertyResult(r3,payload,key,input,isOptionalIn,isOptionalOut)))}else{handlePropertyResult(r2,payload,key,input,isOptionalIn,isOptionalOut)}}if(!catchall){return proms.length?Promise.all(proms).then(()=>payload):payload}return handleCatchall(proms,input,payload,ctx,_normalized.value,inst)}});$ZodObjectJIT=$constructor("$ZodObjectJIT",(inst,def)=>{$ZodObject.init(inst,def);const superParse=inst._zod.parse;const _normalized=cached(()=>normalizeDef(def));const generateFastpass=shape=>{const doc=new Doc(["shape","payload","ctx"]);const normalized=_normalized.value;const parseStr=key=>{const k2=esc(key);return`shape[${k2}]._zod.run({ value: input[${k2}], issues: [] }, ctx)`};doc.write(`const input = payload.value;`);const ids=Object.create(null);let counter=0;for(const key of normalized.keys){ids[key]=`key_${counter++}`}doc.write(`const newResult = {};`);for(const key of normalized.keys){const id2=ids[key];const k2=esc(key);const schema=shape[key];const isOptionalIn=schema?._zod?.optin==="optional";const isOptionalOut=schema?._zod?.optout==="optional";doc.write(`const ${id2} = ${parseStr(key)};`);if(isOptionalIn&&isOptionalOut){doc.write(`
|
|
54
54
|
if (${id2}.issues.length) {
|
|
55
55
|
if (${k2} in input) {
|
|
56
56
|
payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
|
|
@@ -115,7 +115,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
115
115
|
`}}function tryAcquireOnce({path:path4,nonce:nonce4,content}){if(publishAtomic(path4,content)){let released=false;return{kind:"acquired",held:{nonce:nonce4,release(){if(released)return;released=true;const found=readOwner(path4);if(found?.owner?.nonce===nonce4){try{unlinkSync2(path4)}catch{}}}}}}const inspection=inspectLockSnapshot(path4);if(inspection.state==="absent")return{kind:"retry"};if(inspection.state==="stale"){const reclaimer=reclaimStale(path4,inspection.ino);return reclaimer?{kind:"reclaiming",owner:reclaimer}:{kind:"retry"}}return{kind:"held",owner:inspection.owner}}function reclaimPollMs(pollMs){return Math.min(pollMs,50)}function acquireLock(path4,opts={}){const waitMs=opts.waitMs??3e5;const pollMs=opts.pollMs??200;const attempt=newAttempt(path4,opts);const deadline=Date.now()+waitMs;let waiting=false;for(;;){const result=tryAcquireOnce(attempt);if(result.kind==="acquired")return result.held;if(result.kind==="retry")continue;const left=deadline-Date.now();if(left<=0)throw lockTimeoutError(path4,opts,result.owner,waitMs);if(!waiting){waiting=true;opts.onWait?.()}sleepSync(Math.min(result.kind==="reclaiming"?reclaimPollMs(pollMs):pollMs,left))}}function lockTimeoutError(path4,opts,owner2,waitMs){return opts.onTimeout?.(owner2)??new Error(`${opts.label??"a lock"} is held by a live process (pid ${owner2.pid}) and did not release within ${Math.round(waitMs/1e3)}s - retry, or if it is wedged, remove ${path4}`)}import{createHash}from"node:crypto";import{lstatSync as lstatSync2,mkdirSync as mkdirSync3}from"node:fs";import{userInfo}from"node:os";import{join as join2}from"node:path";var LocalConsumerHeldError=class extends Error{};function localConsumerClaimPath(servers,space2,owner2,actor2,lifecycleUid){const user=userInfo();const root=process.platform==="linux"?`/tmp/cotal-consumers-${user.uid}`:join2(user.homedir,".cotal-consumers");mkdirSync3(root,{recursive:true,mode:448});const st2=lstatSync2(root);if(!st2.isDirectory()||st2.isSymbolicLink()||process.platform!=="win32"&&(st2.uid!==user.uid||(st2.mode&63)!==0))throw new Error("local consumer custody directory is not private to this OS user");const targets=[...new Set(servers.split(",").map(s3=>{const u2=new URL(s3.trim().includes("://")?s3.trim():`nats://${s3.trim()}`);u2.username="";u2.password="";if(!u2.port)u2.port=u2.protocol==="nats:"?"4222":u2.protocol==="wss:"?"443":"80";return u2.href}))].sort();const key=createHash("sha256").update(JSON.stringify([targets,space2,owner2,actor2,lifecycleUid])).digest("hex");const path4=join2(root,`${key}.lock`);try{const file2=lstatSync2(path4);if(!file2.isFile()||file2.isSymbolicLink()||process.platform!=="win32"&&(file2.uid!==user.uid||(file2.mode&63)!==0))throw new Error("local consumer custody file is not private to this OS user")}catch(error51){if(error51.code!=="ENOENT")throw error51}return path4}function acquireLocalConsumer(servers,space2,owner2,actor2,lifecycleUid){return acquireLock(localConsumerClaimPath(servers,space2,owner2,actor2,lifecycleUid),{waitMs:0,label:"local inbox consumer",onTimeout:()=>new LocalConsumerHeldError(`local inbox already has a consuming session for ${owner2}.${actor2} in space "${space2}"; preserve that session and choose a distinct actor for a new launch`)})}init_subjects();init_endpoint_subjects();init_canonical();init_endpoint_error();init_endpoint_grants();init_endpoint_subjects();init_issued_authority();init_subjects();init_registry_contract();init_agent_endpoint();init_registry_client();init_endpoint_envelope();init_endpoint_records();init_lifecycle_state();init_environment_manager_grants();init_canonical();init_endpoint_envelope();init_endpoint_subjects();init_identity();init_subjects();init_lifecycle_state();var dec6=new TextDecoder;init_endpoint_envelope();init_endpoint_records();init_subjects();init_lifecycle_state();var enc6=new TextEncoder;init_endpoint_cluster();init_endpoint_journal();init_endpoint_binding();init_endpoint_binding();init_canonical();init_space_resource_definitions();init_space_quiescence_resources();init_space_deletion_targets();init_endpoint_envelope();init_broker_identity();var import_jetstream25=__toESM(require_mod4(),1);var import_transport_node25=__toESM(require_transport_node(),1);init_jetstream_missing();init_space_resource_definitions();var import_kv12=__toESM(require_mod6(),1);init_subjects();init_channels();init_space_resource_definitions();init_canonical();init_channels();init_subjects();init_space_resource_definitions();var DEFAULT_FIELDS={replay:true,replayWindow:true,deliveryClass:true};var CHANNEL_FIELDS={...DEFAULT_FIELDS,description:true,instructions:true};init_space_resource_definitions();init_endpoint_binding();init_issued_authority();init_run_admission();init_streams();init_backup_config();init_canonical();var import_jetstream26=__toESM(require_mod4(),1);init_endpoint_service();init_endpoint_service();init_endpoint_invoke();init_endpoint_call();init_endpoint_envelope();init_kv_scan();init_canonical();init_service_gate();init_endpoint_envelope();init_endpoint_records();init_endpoint_subjects();init_lifecycle_state();var enc7=new TextEncoder;var dec7=new TextDecoder;init_endpoint_envelope();init_endpoint_subjects();init_subjects();init_endpoint_serve();init_endpoint_describe_observation();init_endpoint_verbs();init_endpoint_invoke();var import_jetstream27=__toESM(require_mod4(),1);var import_transport_node26=__toESM(require_transport_node(),1);init_canonical();init_endpoint_envelope();init_deadline();init_endpoint_subjects();init_endpoint_records();init_endpoint_journal();init_endpoint_binding();var import_jetstream28=__toESM(require_mod4(),1);var import_transport_node27=__toESM(require_transport_node(),1);init_endpoint_binding();init_endpoint_records();init_jetstream_missing();init_endpoint_action();init_endpoint_error();var COMMON_FIELDS=["v","executor","attemptId","ts","phase"];var PHASE_FIELDS={claimed:COMMON_FIELDS,launching:[...COMMON_FIELDS,"addr"],launched:[...COMMON_FIELDS,"addr"],settled:[...COMMON_FIELDS,"addr"]};init_endpoint_error();var BASE=["v","ts","state","claimant"];var STATE_FIELDS={claimed:BASE,launching:[...BASE,"lifecycleUid","launchAttemptId","executor"],live:[...BASE,"lifecycleUid","runtimeOwner"],preserved:[...BASE,"lifecycleUid","runtimeOwner"],relaunching:[...BASE,"lifecycleUid","launchAttemptId","executor"],draining:[...BASE,"lifecycleUid","runtimeOwner","enteredAt"],released:BASE};init_endpoint_checkpoint();init_endpoint_contract_store();init_lifecycle_state();init_endpoint_service();init_evict();init_endpoint_guard();init_canonical();init_endpoint_envelope();init_endpoint_subjects();init_endpoint_signing();var HANDLE_MAX_LIVE_TTL_MS=24*60*60*1e3;var HANDLE_MAX_STURDY_TTL_MS=30*24*60*60*1e3;var HANDLE_MAX_BYTES=64*1024;init_endpoint_envelope();init_canonical();init_subjects();init_endpoint_subjects();init_endpoint_signing();init_endpoint_error();init_endpoint_subjects();var SESSION_GRANT_MAX_TTL_MS=24*60*60*1e3;var SESSION_GRANT_MAX_BYTES=16*1024;var SESSION_TERMINAL_STATES=Object.freeze(["closed","expired","superseded","retired"]);var TERMINAL_STATE_SNAP=new Set(SESSION_TERMINAL_STATES);init_endpoint_error();var MAX_B64_CHARS=4*1024*1024;var B64_ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var B64_INV=(()=>{const m2=new Int16Array(128).fill(-1);for(let i2=0;i2<B64_ALPHABET.length;i2++)m2[B64_ALPHABET.charCodeAt(i2)]=i2;return m2})();init_endpoint_envelope();init_endpoint_binding();var import_jetstream29=__toESM(require_mod4(),1);init_endpoint_supervisor();init_endpoint_service();init_endpoint_records();init_endpoint_subjects();init_subjects();init_endpoint_receipt();init_endpoint_signing();var RENEW_AT_FRACTION=1/3;var OVERLAP_MS=10*60*1e3;init_endpoint_traits();init_safe_pattern();init_resolve();function presenceAges(p2,now){return{conditionSince:ageAt(now,p2.condition?.since),statusSince:ageAt(now,p2.statusSince),activitySince:p2.activity?ageAt(now,p2.activitySince):void 0,activeAt:ageAt(now,p2.activeAt)}}function formatAge(ms){const s3=Math.floor(ms/1e3);if(s3<60)return`${s3}s`;if(s3<3600)return`${Math.floor(s3/60)}m`;if(s3<86400)return`${Math.floor(s3/3600)}h`;return`${Math.floor(s3/86400)}d`}function ageAt(now,at2){if(typeof at2!=="number"||!Number.isFinite(at2))return void 0;return Math.max(0,now-at2)}init_process_runtime();function oneLine(text3){return text3.replace(/[\p{Cc}\p{Cf}\p{Default_Ignorable_Code_Point}\p{Zl}\p{Zp}]/gu,c3=>{let escaped="";for(let i2=0;i2<c3.length;i2++)escaped+=`\\u${c3.charCodeAt(i2).toString(16).padStart(4,"0")}`;return escaped})}var PRESENCE_TEXT_MAX=200;function presenceText(text3){const shown=Array.from(text3,oneLine);const width=s3=>[...s3].length;if(shown.reduce((n3,s3)=>n3+width(s3),0)<=PRESENCE_TEXT_MAX)return shown.join("");let kept="";let n2=0;for(const s3 of shown){n2+=width(s3);if(n2>PRESENCE_TEXT_MAX-1)break;kept+=s3}return`${kept}\u2026`}init_connection_cleanup();init_native_connection();init_text_encoding();function parseJoinLink(link){const tls=link.startsWith("cotals://");if(!tls&&!link.startsWith("cotal://"))throw new Error(`not a Cotal link (expected cotal:// or cotals://): ${link}`);const u2=new URL(link.replace(/^cotals?:\/\//,tls?"https://":"http://"));if(!u2.hostname)throw new Error(`Cotal link has no host: ${link}`);const space2=decodeURIComponent(u2.pathname.replace(/^\/+/,"").split("/")[0]??"");if(!space2)throw new Error(`Cotal link has no space (cotal://host/<space>): ${link}`);const chParam=u2.searchParams.get("channels")??u2.searchParams.get("channel");const channels=chParam?chParam.split(",").map(s3=>s3.trim()).filter(Boolean):void 0;const user=u2.username?decodeURIComponent(u2.username):void 0;const pass=u2.password?decodeURIComponent(u2.password):void 0;return{servers:`nats://${u2.hostname}:${u2.port||"4222"}`,space:space2,channels,tls,token:user&&!pass?user:void 0,user:pass?user:void 0,pass:pass||void 0}}function brokerUrlHasUserinfo(servers){return servers.split(",").some(entry=>/^[^:/?#]+:\/\/[^/?#]*@/.test(entry.includes("://")?entry.trim():`nats://${entry.trim()}`))}init_identity();init_secret_store();init_provision();init_jwt();var import_nkeys10=__toESM(require_mod(),1);init_identity();init_nkey_signer();init_jwt();var import_nkeys11=__toESM(require_mod(),1);init_subjects();init_streams();init_anycast_requests();init_transfer();init_backup_config();init_backup();init_channels();init_members();init_acls();init_connection_cleanup();init_native_connection();var import_transport_node28=__toESM(require_transport_node(),1);init_endpoint();var import_kv13=__toESM(require_mod6(),1);init_subjects();init_members();init_kv_scan();init_identity();init_deadline();init_jetstream_missing();init_evict();init_lease();init_liveness();init_agent_file();import{lstatSync as lstatSync4,mkdirSync as mkdirSync5,unlinkSync as unlinkSync3}from"node:fs";import{join as join3}from"node:path";function ensureDirNoSymlink(parent,...segments){let dir=parent;for(const seg of segments){dir=join3(dir,seg);let st2;try{st2=lstatSync4(dir)}catch(e3){if(e3.code==="ENOENT"){mkdirSync5(dir,{mode:448});continue}throw e3}if(st2.isSymbolicLink())throw new Error(`refusing to write under "${dir}": it is a symlink`);if(!st2.isDirectory())throw new Error(`refusing to write under "${dir}": not a directory`)}return dir}init_secret_fs();init_secret_fs();import{mkdtempSync,readFileSync as readFileSync3,realpathSync as realpathSync2,rmSync as rmSync2,rmdirSync,statSync as statSync3}from"node:fs";import{tmpdir}from"node:os";import{basename,dirname as dirname4,join as join4,resolve as resolve2}from"node:path";import{createHmac,randomBytes as randomBytes3,timingSafeEqual}from"node:crypto";import{lstatSync as lstatSync5}from"node:fs";import{dirname as dirname3}from"node:path";var CONTROL_PROTOCOL_VERSION=1;var CONTROL_SERVER_AUTH_DEADLINE_MS=5e3;var MAX_HANDSHAKE_LINE_BYTES=1024;var MAX_CONTROL_REQUEST_BYTES=1<<20;var BASE64URL_43=/^[A-Za-z0-9_-]{43}$/;var MAC_CHARS=43;var MAC_PREFIX_BYTES=MAC_CHARS+1;var NEWLINE=10;var SPACE=32;var utf8=new TextDecoder("utf-8",{fatal:true});function assertControlVersion(version2,where){if(version2===CONTROL_PROTOCOL_VERSION)return;throw new Error(`${where} carries control protocol version ${JSON.stringify(version2)}, and this build speaks only version ${CONTROL_PROTOCOL_VERSION}. A launcher and connector from different releases refuse each other instead of falling back; upgrade both to the same release.`)}function assertControlEndpoint(endpoint){assertControlVersion(endpoint.version,"the control endpoint");if(typeof endpoint.token!=="string"||!endpoint.token)throw new Error("the control endpoint has no key")}function transcriptMac(token2,role,nc,ns,body){const mac3=createHmac("sha256",Buffer.from(token2,"utf8"));mac3.update(`cotal-control/${CONTROL_PROTOCOL_VERSION}\0${role}\0${nc}\0${ns}`,"utf8");if(body!==void 0)mac3.update("\0","utf8").update(body);return mac3.digest("base64url")}function macMatches(presented,expected){if(typeof presented!=="string"||!BASE64URL_43.test(presented))return false;return timingSafeEqual(Buffer.from(presented,"ascii"),Buffer.from(expected,"ascii"))}function openSealed(line,expected){if(line.length<MAC_PREFIX_BYTES||line[MAC_CHARS]!==SPACE)return void 0;const body=line.subarray(MAC_PREFIX_BYTES);if(!macMatches(line.subarray(0,MAC_CHARS).toString("latin1"),expected(body)))return void 0;try{return utf8.decode(body)}catch{return void 0}}function parseHandshake(line){try{const value=JSON.parse(utf8.decode(line));return value&&typeof value==="object"&&!Array.isArray(value)?value:void 0}catch{return void 0}}function lineReader(cap,onLine,oversize){let buf=Buffer.alloc(0);let stopped=false;return chunk=>{if(stopped)return;buf=buf.length?Buffer.concat([buf,chunk]):chunk;for(;;){const limit=cap();const nl=buf.indexOf(NEWLINE);const length=nl<0?buf.length:nl;if(length>limit){stopped=true;return oversize()}if(nl<0)return;const line=buf.subarray(0,nl);buf=buf.subarray(nl+1);if(!onLine(line)){stopped=true;return}}}}var nonce3=()=>randomBytes3(32).toString("base64url");function socketDir(path4){return process.platform==="win32"?void 0:dirname3(path4)}function assertPrivateDir(dir){const st2=lstatSync5(dir);const uid2=process.getuid();const problem=st2.isSymbolicLink()?"is a symbolic link, not a directory":!st2.isDirectory()?"is not a directory":st2.uid!==uid2?`is owned by uid ${st2.uid}, not by this user (uid ${uid2})`:(st2.mode&63)!==0?`has mode ${(st2.mode&4095).toString(8)}, which lets group or others in`:void 0;if(problem)throw new Error(`control socket directory ${dir} ${problem}, so it is not a private directory of this user. Remove it if you did not create it, or point TMPDIR at a directory only you can write, and relaunch.`)}function assertControlSocketDir(path4){if(path4.startsWith("\0"))throw new Error("control socket path is in the Linux abstract namespace, which any local user can bind; use a path in a private directory");const dir=socketDir(path4);if(!dir)return;try{assertPrivateDir(dir)}catch(e3){if(e3.code!=="ENOENT")throw e3;throw new Error(`control socket directory ${dir} does not exist. The launcher makes it when it mints the endpoint; for a hand-driven COTAL_CONTROL_SOCKET, make it yourself with mode 0700.`)}}function serverExchange(sock,endpoint,onRequest,opts={}){assertControlEndpoint(endpoint);let nc;const ns=nonce3();let settled=false;const drop=()=>{if(!settled){settled=true;clearTimeout(deadline);sock.destroy()}return false};const deadline=setTimeout(drop,opts.deadlineMs??CONTROL_SERVER_AUTH_DEADLINE_MS);deadline.unref?.();const onClose=()=>{settled=true;clearTimeout(deadline)};const onLine=line=>{if(settled)return false;if(nc===void 0){const hello=parseHandshake(line);if(!hello||hello.v!==CONTROL_PROTOCOL_VERSION||typeof hello.nonce!=="string"||!BASE64URL_43.test(hello.nonce))return drop();nc=hello.nonce;try{sock.write(JSON.stringify({v:CONTROL_PROTOCOL_VERSION,nonce:ns,mac:transcriptMac(endpoint.token,"server",nc,ns)})+"\n")}catch{return drop()}return true}const proven=nc;const request=openSealed(line,body=>transcriptMac(endpoint.token,"client",proven,ns,body));if(request===void 0)return drop();settled=true;clearTimeout(deadline);sock.off("data",onData);sock.off("close",onClose);onRequest({request,seal:text3=>{const body=Buffer.from(text3,"utf8");const receipt2=transcriptMac(endpoint.token,"receipt",proven,ns,body);return{line:`${transcriptMac(endpoint.token,"reply",proven,ns,body)} ${text3}
|
|
116
116
|
`,receiptMatches:presented=>macMatches(presented,receipt2)}}});return false};const onData=lineReader(()=>nc===void 0?MAX_HANDSHAKE_LINE_BYTES:MAC_PREFIX_BYTES+MAX_CONTROL_REQUEST_BYTES,onLine,()=>void drop());sock.on("data",onData);sock.on("close",onClose)}var DIR_PREFIX="cotal-launch-";var MATERIAL_FILE="material.json";var LAUNCH_MATERIAL_ENV="COTAL_LAUNCH_MATERIAL";function readLaunchMaterial(path4){let raw;try{if(process.platform!=="win32"){const mode=statSync3(path4).mode&511;if(mode&63)throw new Error(`is readable beyond its owner (mode ${mode.toString(8)}) - refusing to read connection material out of a file other local users can open`)}raw=readFileSync3(path4,"utf8")}catch(e3){throw new Error(`launch material: cannot read ${path4} (${e3 instanceof Error?e3.message:String(e3)})`)}let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error(`launch material: ${path4} is not valid JSON`)}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))throw new Error(`launch material: ${path4} must contain a JSON object`);return validate(parsed,path4)}function validate(raw,path4){const material={};const str2=key=>{const v3=raw[key];if(v3===void 0)return;if(typeof v3!=="string"||!v3.trim())throw new Error(`launch material: ${path4} has a ${key} that is not a non-empty string`);if(key==="controlKey"&&v3!==v3.trim())throw new Error(`launch material: ${path4} has a controlKey with whitespace around it`);material[key]=v3};str2("servers");str2("creds");str2("token");str2("controlKey");if(raw.controlToken!==void 0)throw new Error(`launch material: ${path4} carries controlToken, the control key field of a release before the control exchange. This build reads controlKey and refuses the old field; launch with a launcher from the same release.`);if(raw.controlVersion!==void 0){assertControlVersion(raw.controlVersion,`launch material ${path4}`);material.controlVersion=raw.controlVersion}if(material.controlKey===void 0!==(material.controlVersion===void 0))throw new Error(`launch material: ${path4} has ${material.controlKey===void 0?"a controlVersion without a controlKey":"a controlKey without a controlVersion"}. The control key and its protocol version travel together; a launcher and connector from different releases refuse each other.`);if(raw.eventsRequired!==void 0){if(raw.eventsRequired!==true)throw new Error(`launch material: ${path4} has eventsRequired that is not exactly true`);material.eventsRequired=true}if(raw.eventPayloadsWithheld!==void 0){if(raw.eventPayloadsWithheld!==true)throw new Error(`launch material: ${path4} has eventPayloadsWithheld that is not true`);material.eventPayloadsWithheld=true}if(raw.userAuth!==void 0){const u2=raw.userAuth;if(typeof u2!=="object"||u2===null||Array.isArray(u2))throw new Error(`launch material: ${path4} has a userAuth that is not an object`);const{owner:owner2,actor:actor2,sentinelCredsPath,bearerCmd}=u2;const named={owner:owner2,actor:actor2,sentinelCredsPath};for(const[k2,v3]of Object.entries(named))if(typeof v3!=="string"||!v3.trim())throw new Error(`launch material: ${path4} has a userAuth.${k2} that is not a non-empty string`);if(!Array.isArray(bearerCmd)||bearerCmd.length===0||!bearerCmd.every(a3=>typeof a3==="string"&&a3))throw new Error(`launch material: ${path4} has a userAuth.bearerCmd that is not a non-empty array of strings`);material.userAuth={owner:owner2,actor:actor2,sentinelCredsPath,bearerCmd}}if(Object.keys(material).length===0)throw new Error(`launch material: ${path4} carries nothing this reader recognises. A launch that references material and supplies none is a broken launcher, not an open-mode launch, so it is refused rather than defaulted.`);return material}function discardLaunchMaterial(path4){const file2=resolve2(path4);try{rmSync2(file2,{force:true})}catch{}const dir=dirname4(file2);if(basename(file2)!==MATERIAL_FILE||!basename(dir).startsWith(DIR_PREFIX))return;try{if(realpathSync2(dirname4(dir))!==realpathSync2(tmpdir()))return;rmdirSync(dir)}catch{}}init_secret_fs();init_kv_scan();init_jetstream_missing();init_endpoint();var import_transport_node29=__toESM(require_transport_node(),1);var import_jetstream30=__toESM(require_mod4(),1);var import_kv14=__toESM(require_mod6(),1);init_endpoint();init_subjects();init_space_deletion_targets();init_identity();init_provision();import{BlockList,isIPv4,isIPv6}from"node:net";var LOOPBACK=new BlockList;LOOPBACK.addSubnet("127.0.0.0",8,"ipv4");LOOPBACK.addAddress("::1","ipv6");init_subjects();var TARGET_FIELDS=["space","owner","actor","lifecycleUid"];var STRING_FIELDS=[...TARGET_FIELDS,"kind","server","authProvider","exchangeUrl","sentinelCreds","actorToken"];var LIST_FIELDS=["subscribe","allowSubscribe","allowPublish"];var FIELDS=new Set([...STRING_FIELDS,...LIST_FIELDS,"tlsRequired","idp","policy"]);init_subjects();import{AsyncLocalStorage}from"node:async_hooks";function claims(ext){return[ext.name,...ext.aliases??[]].map(word=>`${ext.kind}:${word}`)}var Registry=class{#byKey=new Map;#providers=new Map;#aliases=new Map;#stage=new AsyncLocalStorage;register(...exts){const stage=this.#stage.getStore();const taken=this.#claimed();for(const staged of stage?.values()??[])for(const key of claims(staged))taken.add(key);for(const ext of exts){for(const key of claims(ext)){if(taken.has(key))throw new Error(`extension already registered: ${key}`);taken.add(key)}}if(stage)for(const ext of exts)stage.set(`${ext.kind}:${ext.name}`,ext);else this.#publish(exts)}#claimed(){return new Set([...this.#byKey.keys(),...this.#aliases.keys()])}#publish(exts){for(const ext of exts){const key=`${ext.kind}:${ext.name}`;this.#byKey.set(key,ext);for(const alias of claims(ext).slice(1))this.#aliases.set(alias,key)}}unregister(kind,name2){const key=`${kind}:${name2}`;const ext=this.#byKey.get(key);if(!ext)return false;for(const alias of claims(ext).slice(1))this.#aliases.delete(alias);return this.#byKey.delete(key)}async runStaged(load){const stage=new Map;const value=await this.#stage.run(stage,load);return{value,staged:[...stage.values()]}}commitStaged(staged){const taken=this.#claimed();for(const ext of staged)for(const key of claims(ext))if(taken.has(key))throw new Error(`extension already registered: ${key}`);this.#publish(staged)}has(kind,name2){return this.#byKey.has(this.#canonical(kind,name2))}#canonical(kind,word){const key=`${kind}:${word}`;return this.#aliases.get(key)??key}resolve(kind,name2){const ext=this.#byKey.get(this.#canonical(kind,name2));if(!ext){if(this.#providers.has(`${kind}:${name2}`))throw new Error(`${kind} "${name2}" is declared by a provider this process has not loaded`);throw new Error(`no ${kind} registered for "${name2}"`)}return ext}provide(provider){const keys=provider.provides.map(ref=>`${ref.kind}:${ref.name}`);for(const key of keys)if(this.#providers.has(key))throw new Error(`extension provider already declared: ${key}`);const entry={provider};for(const key of keys)this.#providers.set(key,entry)}provides(kind,name2){return this.#providers.has(`${kind}:${name2}`)}async load(kind,name2){const entry=this.#providers.get(`${kind}:${name2}`);if(entry){entry.loading??=entry.provider.load();await entry.loading;if(!this.#byKey.has(this.#canonical(kind,name2)))throw new Error(`the provider declared for ${kind} "${name2}" loaded without registering it`)}return this.resolve(kind,name2)}all(kind){const values=[...this.#byKey.values()];return kind===void 0?values:values.filter(e3=>e3.kind===kind)}};var registry2=new Registry;import{execFile}from"node:child_process";init_subjects();function bearerCommandFailure(err3,stderr,timeoutMs,stdout=""){const said=stderr.trim();const retryAfter=/^retry-after (\d+)$/.exec(stdout.trim());if(said)return Object.assign(new Error(said),retryAfter?{retryAfterSeconds:Number(retryAfter[1])}:{});if(err3.killed)return new Error(`the bearer command timed out after ${timeoutMs}ms`);if(err3.signal)return new Error(`the bearer command was killed by ${err3.signal}`);if(typeof err3.code==="number")return new Error(`the bearer command exited with code ${err3.code} and printed nothing`);return new Error(err3.message)}function runAgentBearer(argv,opts={}){const timeoutMs=opts.timeoutMs??3e4;return new Promise((resolve6,reject)=>{execFile(argv[0],argv.slice(1),{timeout:timeoutMs,maxBuffer:64*1024,env:opts.env,signal:opts.signal},(err3,stdout,stderr)=>err3?reject(bearerCommandFailure(err3,stderr,timeoutMs,stdout)):resolve6(stdout.trim()))})}init_event_channel();init_subjects();var SELECTION_MAX_ITEMS=32;init_canonical_json();var EMPTY_CONVERSATION_SELECTION=Object.freeze({v:1,channels:Object.freeze([]),role:null,capabilities:Object.freeze([]),endpoints:Object.freeze([])});init_subjects();init_base64url();function managerCallerBinding(bearer,expected){let payload;try{const parts=bearer.split(".");if(parts.length!==3)throw new Error("invalid JWT");payload=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(fromBase64url(parts[1])))}catch{throw new Error("manager control exchange returned an invalid bearer")}const act=payload?.act;if(!act||act.view!=="manager-caller"||payload.sub!==expected.owner||act.owner!==expected.owner||act.actor!==expected.actor||act.lifecycleUid!==expected.lifecycleUid||!(payload.aud===expected.space||Array.isArray(payload.aud)&&payload.aud.length===1&&payload.aud[0]===expected.space))throw new Error("manager control exchange returned different space, principal, lifecycle or view coordinates");if(typeof act.managerInstanceId!=="string")throw new Error("manager control exchange returned no concrete manager instance");const instanceId=assertLifecycleToken(act.managerInstanceId,"managerInstanceId");if(expected.instanceId!==void 0&&instanceId!==expected.instanceId)throw new Error("manager control exchange selected a different manager instance");return{caller:{owner:expected.owner,actor:expected.actor,uid:expected.lifecycleUid},instanceId,...typeof act.credentialId==="string"?{credentialId:act.credentialId}:{}}}init_remote_manager_authority();init_remote_service_authority();init_endpoint_capability_policy();init_canonical();init_endpoint_error();init_identity();init_remote_manager_authority();init_subjects();var DELEGATED_RECOVERY_REASONS=Object.freeze(["provider-unknown","store-unavailable","authority-unavailable","identity-unverified","descriptor-incomplete","retiring","authority-drift","identity-changed","scope-changed"]);init_canonical();init_artifact();function partText(p2){if(p2.kind==="text")return p2.text;if(p2.kind==="artifact")return`[artifact ${p2.name} (${p2.mediaType}, ${p2.size} bytes) ${p2.digest}]`;if(p2.kind==="data"){const encoded=JSON.stringify(p2.data);return encoded===void 0?`[empty data part]`:encoded}if(registry2.has("part-renderer",p2.kind)){const renderer=registry2.resolve("part-renderer",p2.kind);try{return renderer.render(p2)}catch(e3){return`[part renderer for ${JSON.stringify(p2.kind)} failed: ${e3.message}]`}}return`[unrenderable part kind ${JSON.stringify(p2.kind)} \u2014 no renderer for it on this surface]`}function partsToText(parts){return parts.map(partText).join(" ")}var AGUI_FRAME_KIND="ag-ui.frame";var AGUI_EVENT_TYPE=Object.freeze({RUN_STARTED:"RUN_STARTED",RUN_FINISHED:"RUN_FINISHED",RUN_ERROR:"RUN_ERROR",TEXT_MESSAGE_START:"TEXT_MESSAGE_START",TEXT_MESSAGE_CONTENT:"TEXT_MESSAGE_CONTENT",TEXT_MESSAGE_END:"TEXT_MESSAGE_END",TOOL_CALL_START:"TOOL_CALL_START",TOOL_CALL_ARGS:"TOOL_CALL_ARGS",TOOL_CALL_END:"TOOL_CALL_END",TOOL_CALL_RESULT:"TOOL_CALL_RESULT",REASONING_MESSAGE_START:"REASONING_MESSAGE_START",REASONING_MESSAGE_CONTENT:"REASONING_MESSAGE_CONTENT",REASONING_MESSAGE_END:"REASONING_MESSAGE_END",CUSTOM:"CUSTOM"});function isAguiFramePart(part){if(typeof part!=="object"||part===null)return false;try{return part.kind===AGUI_FRAME_KIND}catch{return false}}init_event_channel();init_event_channel();import{createHash as createHash6}from"node:crypto";import{constants as constants3}from"node:fs";import{lstat,open,readdir}from"node:fs/promises";import{dirname as dirname5,join as join5,relative,sep}from"node:path";init_subjects();var EVENT_SUBJECT_RECORD_VERSION=1;var SubjectFrontierCorruptError=class extends Error{path;invariant;constructor(path4,invariant,detail){super(`subject frontier ${path4}: expected ${invariant} \u2014 ${detail}`);this.path=path4;this.invariant=invariant;this.name="SubjectFrontierCorruptError"}};var EventStateConflictError=class extends Error{constructor(message){super(message);this.name="EventStateConflictError"}};function eventPrincipalLocation(opts){const h3=value=>createHash6("sha256").update(value).digest("hex").slice(0,16);const principalDir=join5(opts.workspaceRoot,".cotal","events",h3(opts.space),h3(opts.principal));return{principalDir,lockPath:join5(principalDir,".lock"),subjectPath:join5(principalDir,"subject.json")}}var isSafeNonNegInt=n2=>typeof n2==="number"&&Number.isSafeInteger(n2)&&n2>=0;async function readEventSubjectRecord(path4,opts){let st2;try{st2=await lstat(path4)}catch(e3){if(e3.code==="ENOENT")return void 0;throw e3}if(st2.isSymbolicLink())throw new SubjectFrontierCorruptError(path4,"a real subject record, never a symlink","the writer never wrote a symlink");let bytes;try{const fh=await open(path4,constants3.O_RDONLY|(constants3.O_NOFOLLOW??0));try{bytes=await fh.readFile()}finally{await fh.close()}}catch(e3){const code2=e3.code;if(code2==="ENOENT")return void 0;if(code2==="ELOOP")throw new SubjectFrontierCorruptError(path4,"a real subject record, never a symlink","the record became a symlink between the check and the open");throw e3}let raw;try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new SubjectFrontierCorruptError(path4,"valid UTF-8","invalid UTF-8 bytes; refusing rather than substituting U+FFFD")}if(raw.length===0)throw new SubjectFrontierCorruptError(path4,"a non-empty file","the file is zero bytes \u2014 distinct from missing, and never treated as virgin");let parsed;try{parsed=JSON.parse(raw)}catch(e3){throw new SubjectFrontierCorruptError(path4,"parseable JSON",e3.message)}const d2=parsed;if(d2?.v!==EVENT_SUBJECT_RECORD_VERSION)throw new SubjectFrontierCorruptError(path4,`v === ${EVENT_SUBJECT_RECORD_VERSION}`,String(d2?.v));if(d2.space!==opts.space)throw new SubjectFrontierCorruptError(path4,"space matches",`file=${String(d2.space)} caller=${opts.space}`);if(d2.principal!==opts.principal)throw new SubjectFrontierCorruptError(path4,"principal matches",`file=${String(d2.principal)} caller=${opts.principal}`);if(!isSafeNonNegInt(d2.tip)||d2.tip>=Number.MAX_SAFE_INTEGER)throw new SubjectFrontierCorruptError(path4,"tip is a safe non-negative integer below Number.MAX_SAFE_INTEGER",String(d2.tip));return{v:d2.v,space:d2.space,principal:d2.principal,tip:d2.tip}}async function recoverEventSubjectTip(principalDir,principal){let entries;try{entries=await readdir(principalDir,{withFileTypes:true})}catch(e3){if(e3.code==="ENOENT")return 0;throw e3}let best=0;for(const ent of entries){if(ent.isSymbolicLink())throw new SubjectFrontierCorruptError(join5(principalDir,ent.name),"a real directory beside the record, never a symlink","following it would carry this scan outside the principal directory, and the writer that creates these directories refuses a symlinked component for the same reason");if(!ent.isDirectory())continue;const walPath=join5(principalDir,ent.name,"wal.json");let st2;try{st2=await lstat(walPath)}catch(e3){const code2=e3.code;if(code2==="ENOENT"||code2==="ENOTDIR")continue;throw e3}if(st2.isSymbolicLink())throw new SubjectFrontierCorruptError(walPath,"a real thread log, never a symlink","following it would read a log this principal's writer never wrote");if(st2.nlink>1)throw new SubjectFrontierCorruptError(walPath,"a thread log with exactly one name",`it has ${st2.nlink}, so the same file is reachable from outside this principal's directory and its tip is not this principal's to read`);let raw;try{const fh=await open(walPath,constants3.O_RDONLY|(constants3.O_NOFOLLOW??0));try{raw=await fh.readFile()}finally{await fh.close()}}catch(e3){const code2=e3.code;if(code2==="ENOENT"||code2==="ENOTDIR")continue;if(code2==="ELOOP")throw new SubjectFrontierCorruptError(walPath,"a real thread log, never a symlink","the file became a symlink between the check and the open");throw e3}let doc;try{doc=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(raw))}catch(e3){throw new SubjectFrontierCorruptError(walPath,"a readable thread log while recovering the subject tip",e3.message)}if(doc.principal!==principal)throw new SubjectFrontierCorruptError(walPath,`a thread log for principal ${principal}`,`found ${String(doc.principal)}`);const seq=doc.frontier?.lastSubjectSeq;if(!isSafeNonNegInt(seq))throw new SubjectFrontierCorruptError(walPath,"frontier.lastSubjectSeq is a safe non-negative integer",String(seq));if(seq>best)best=seq;const pending=doc.pending;if(pending&&pending.state==="acked"){const acked=pending.ackSeq;if(!isSafeNonNegInt(acked))throw new SubjectFrontierCorruptError(walPath,"an acked pending carries a safe non-negative ackSeq",String(acked));if(!(acked>seq))throw new SubjectFrontierCorruptError(walPath,"an acked pending is ahead of the frontier it will fold into",`ackSeq=${acked} frontier.lastSubjectSeq=${seq}`);if(acked>best)best=acked}}return best}async function recordedEventTip(path4,opts){const record2=await readEventSubjectRecord(path4,opts);return record2===void 0?recoverEventSubjectTip(dirname5(path4),opts.principal):record2.tip}async function checkEventStartup(opts){const principal=principalKey(opts.principal.owner,opts.principal.actor).key;const loc=eventPrincipalLocation({...opts,principal});ensureDirNoSymlink(opts.workspaceRoot,...relative(opts.workspaceRoot,loc.principalDir).split(sep));if(await recordedEventTip(loc.subjectPath,{space:opts.space,principal})!==0)return;const rows=await opts.retainedMessages();if(rows.some(row=>row.sender===principal&&row.channel===eventChannel(opts.principal)&&row.messages>0)){throw new EventStateConflictError(`Cannot start events for ${principal}: this state root has no acknowledged transcript frontier, but the broker retains events for this principal. Reuse the previous state root or launch with a new principal. Refusing before work; the existing transcript and local logs are unchanged.`)}}init_schema_profile();init_broker_floor();init_endpoint_envelope();init_endpoint_records();init_endpoint_envelope();init_endpoint_subjects();init_endpoint_records();init_canonical();init_kv_scan();init_endpoint_envelope();init_endpoint_subjects();init_endpoint_records();init_canonical();init_kv_scan();init_endpoint_envelope();init_endpoint_subjects();init_endpoint_records();init_canonical();init_kv_scan();init_endpoint_envelope();init_endpoint_records();init_run_driver_grants();init_endpoint_subjects();init_subjects();var TURN_INPUT_SCHEMA=deepFreeze3({type:"object",additionalProperties:false,required:["payload"],oneOf:[{required:["deadlineMs"]},{required:["deadlineAt"]}],properties:{payload:{type:"string",minLength:1,maxLength:65536},deadlineMs:{type:"integer",minimum:1},deadlineAt:{type:"integer",minimum:1},handoffFrom:{type:"string",minLength:1,maxLength:200}}});var TURN_OUTPUT_SCHEMA=deepFreeze3({type:"object",additionalProperties:false,required:["name","owner","actor","uid","goalId","fingerprint","deadlineAt","executor"],properties:{name:{type:"string"},owner:{type:"string"},actor:{type:"string"},uid:{type:"string"},goalId:{type:"string"},fingerprint:{type:"string"},deadlineAt:{type:"integer",minimum:1},executor:{type:"object",additionalProperties:false,required:["lifecycleUid","epoch"],properties:{lifecycleUid:{type:"string"},epoch:{type:"integer",minimum:0}}}}});var TURN_YIELD_OUTPUT_SCHEMA=deepFreeze3({type:"object",additionalProperties:false,required:["goalId","state"],properties:{goalId:{type:"string"},state:{enum:["succeeded","failed","cancelled","expired","uncertain"]}}});var CANCEL_INPUT_SCHEMA=deepFreeze3({type:"object",additionalProperties:false,required:["goalId"],properties:{goalId:{type:"string",minLength:1},mode:{enum:["graceful","terminate"]}}});function deepFreeze3(v3){if(v3!==null&&typeof v3==="object"){for(const child of Object.values(v3))deepFreeze3(child);Object.freeze(v3)}return v3}var TURN_NOTICE_NONCE="turn-pending-notice-v1";function turnNoticeFilter(space2,instanceId,seat){return[spacePrefix(space2),...epPlaneTokens(seat),"reply",endpointToken("manager"),assertLifecycleToken(instanceId,"instanceId"),"*",...callerRailTokens(seat),TURN_NOTICE_NONCE].join(".")}function shownSpawner(name2,fallback){return name2!==void 0&&name2.trim()?name2:fallback}function renderOnceTask(t2){let context=t2.payload;try{const p2=JSON.parse(t2.payload);if(typeof p2.context==="string")context=p2.context}catch{}const from=shownSpawner(t2.spawner,"your spawner");const deadline=t2.deadlineAt!==void 0?`, or at ${new Date(t2.deadlineAt).toISOString()} if you are still working then`:"";return`\u{1F3AF} Cotal \u2014 ${from} started this seat for one task (goal ${t2.goalId}):
|
|
117
117
|
${context}
|
|
118
|
-
(This is the only task this seat takes. Do it with your own tools, and send your result to whoever needs it, for example with cotal_dm to ${from}, before you end your turn: this seat is stopped when your turn ends${deadline}, and a result you have not sent reaches no one. If you cannot finish, call cotal_yield with blocked or handoff and say why.)`}var nonBlank=()=>({type:"string",pattern:"^\\s*\\S"});var AGENT_ROW_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,required:["name","id","agent","space","mode","status","uptimeMs","mesh","lifecycleUid"],properties:{name:{type:"string"},id:{type:"string"},role:{type:"string"},agent:{type:"string"},space:{type:"string"},mode:{type:"string"},status:{type:"string"},uptimeMs:{type:"integer",minimum:0},mesh:{type:"string"},joinHealth:{type:"object",additionalProperties:false,required:["state","reason"],properties:{state:{type:"string",const:"degraded"},reason:{type:"string"}}},condition:{type:"object",additionalProperties:false,required:["code"],properties:{code:{type:"string"},source:{type:"string"},message:{type:"string"},since:{type:"number"}}},startupNotice:{type:"string",minLength:1,maxLength:1024},activeAt:{type:"number"},meshView:{type:"string",enum:["current","stale","unpopulated"]},presenceIdentityVerified:{type:"boolean"},presenceObservedAt:{type:"integer",minimum:0},offlineSince:{type:"integer",minimum:0},lifecycleUid:{type:"string"},authHealth:{type:"string"},authReason:{type:"string"},model:{type:"string"},variant:{type:"string"},provider:{type:"string"},cwd:{type:"string"},pid:{type:"integer",minimum:1},spawner:{type:"string"},instanceId:{type:"string"},host:{type:"string"},resume:{type:"object",additionalProperties:false,required:["source"],properties:{source:{type:"string"},title:{type:"string"},transcriptSha256:{type:"string"},host:{type:"string"},transferredAt:{type:"string"}}}}});var INSPECT_INPUT_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,required:["name"],properties:{name:{type:"string",minLength:1}}});var PERSONA_ENDPOINTS_SCHEMA=deepFreeze4({type:"array",items:{type:"object",additionalProperties:false,required:["endpoint","commands"],properties:{endpoint:{type:"string"},commands:{type:"array",items:{type:"string"}},instanceId:{type:"string"}}}});var SPAWN_INPUT_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,required:["name"],properties:{name:{type:"string",minLength:1},agent:nonBlank(),defaultAgent:nonBlank(),role:nonBlank(),config:nonBlank(),identity:nonBlank(),model:nonBlank(),variant:nonBlank(),launchOptions:{type:"object"},resume:nonBlank(),resumeClaim:nonBlank(),resumeAgent:nonBlank(),events:{type:"boolean"},eventPayloads:{type:"boolean"},cwd:nonBlank(),prompt:nonBlank(),persona:{type:"object",additionalProperties:false,required:["prompt"],properties:{prompt:nonBlank(),role:nonBlank(),model:nonBlank(),variant:nonBlank(),description:nonBlank(),subscribe:{type:"array",items:{type:"string"}},allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}},capabilities:{type:"array",items:{type:"string"}},endpoints:PERSONA_ENDPOINTS_SCHEMA,save:{type:"boolean"}}},runId:nonBlank(),subscribe:{type:"array",items:{type:"string"}},allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}},join:{type:"array",items:{type:"string"}},callerAcl:{type:"object",additionalProperties:false,required:["allowSubscribe","allowPublish"],properties:{allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}}}},shareTools:{type:"array",items:{type:"string"}},runtime:nonBlank(),supervise:{type:"object",additionalProperties:false,required:["restarts","windowMs"],properties:{restarts:{type:"integer",minimum:1},windowMs:{type:"integer",minimum:1}}},once:{type:"object",additionalProperties:false,properties:{deadlineMs:{anyOf:[{const:-1},{type:"integer",minimum:1,maximum:Number.MAX_SAFE_INTEGER}]}}}}});var SPAWN_OUTPUT_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,required:["name","owner","actor","uid","goalId","fingerprint","executor"],properties:{name:{type:"string"},owner:{type:"string"},actor:{type:"string"},uid:{type:"string"},goalId:{type:"string"},fingerprint:{type:"string"},readinessDeadlineMs:{type:"integer",minimum:1},executor:{type:"object",additionalProperties:false,required:["lifecycleUid","epoch"],properties:{lifecycleUid:{type:"string"},epoch:{type:"integer",minimum:0}}}}});var GRACEFUL_INPUT_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,properties:{graceful:{type:"boolean"}}});var STOP_OUTPUT_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,required:["name","stopped","graceful"],properties:{name:{type:"string"},stopped:{type:"boolean"},graceful:{type:"boolean"}}});function deepFreeze4(v3){if(v3!==null&&typeof v3==="object"){for(const child of Object.values(v3))deepFreeze4(child);Object.freeze(v3)}return v3}var import_nkeys12=__toESM(require_mod(),1);init_canonical();init_endpoint_envelope();init_identity();init_schema_profile();init_endpoint_signing();var TOOL_RESULTS_ENDPOINT="tool-results";var TOOL_RESULT_MAX_CONTENT_BYTES=64*1024;var TOOL_RESULT_MAX_RETENTION_MS=60*60*1e3;var TOOL_RESULT_CONSENT_MAX_TTL_MS=24*60*60*1e3;function deepFreeze5(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))deepFreeze5(child);Object.freeze(value)}return value}var text2={type:"string",minLength:1};var id={type:"string",minLength:1,maxLength:200,pattern:"^[A-Za-z0-9_-]+$"};var actor={type:"string",minLength:1,pattern:"^[A-Za-z0-9_]+$"};var owner={type:"string",pattern:"^u_[a-z2-7]{26}$"};var uid={type:"string",pattern:"^[a-z0-9]{26,32}$"};var space={type:"string",minLength:1,pattern:"^[A-Za-z0-9_-]+$"};var uint2={type:"integer",minimum:0,maximum:Number.MAX_SAFE_INTEGER};var bool={type:"boolean"};var closed3=properties=>({type:"object",additionalProperties:false,required:Object.keys(properties),properties});var target=closed3({owner,actor,lifecycleUid:uid});var pair={threadId:text2,toolCallId:text2};var status=(state,fields={})=>closed3({state:{const:state},...fields});var TOOL_RESULT_CONSENT_SCHEMA=deepFreeze5(closed3({v:{const:1},kind:{const:"tool-result-consent"},id,space,target,holder:closed3({owner,actor}),iat:uint2,exp:uint2,issuer:closed3({keyId:id}),sig:{type:"string",pattern:"^[A-Za-z0-9_-]{86}$"}}));var TOOL_RESULT_REVOCATION_SCHEMA=deepFreeze5(closed3({v:{const:1},kind:{const:"tool-result-revocation"},space,consentId:id,target,revokedAt:uint2}));var TOOL_RESULT_SERVING_MATERIAL_SCHEMA=deepFreeze5(closed3({v:{const:1},kind:{const:"tool-result-serving-material"},space,accountPublicKey:{type:"string",pattern:"^A[A-Z2-7]{55}$"},target,grant:closed3({endpoint:{const:TOOL_RESULTS_ENDPOINT},instanceId:uid,epoch:uint2,registrationRevision:{...uint2,minimum:1}}),credential:{type:"string",minLength:1,maxLength:16384},snapshot:closed3({t0:uint2,watermark:uint2,watermarkTakenAt:uint2,revokedConsentIds:{type:"array",uniqueItems:true,items:id}}),expiresAt:uint2}));var TOOL_RESULT_INPUT_SCHEMA=deepFreeze5(closed3(pair));var TOOL_RESULT_ANSWER_SCHEMAS=deepFreeze5({available:status("available",{...pair,content:{type:"string",maxLength:TOOL_RESULT_MAX_CONTENT_BYTES},truncated:bool,byteCount:{...uint2,maximum:TOOL_RESULT_MAX_CONTENT_BYTES},error:bool,capturedAt:uint2}),pending:status("pending",pair),"not-shared":status("not-shared"),missing:status("missing"),expired:status("expired")});var TOOL_RESULT_OUTPUT_SCHEMA=deepFreeze5({oneOf:Object.values(TOOL_RESULT_ANSWER_SCHEMAS)});var TOOL_RESULT_CONSENT_INPUT_SCHEMA=deepFreeze5(closed3({consent:TOOL_RESULT_CONSENT_SCHEMA}));var TOOL_RESULT_CONSENT_OUTPUT_SCHEMA=deepFreeze5(status("active",{consentId:id}));var TOOL_RESULT_REVOKE_INPUT_SCHEMA=deepFreeze5(closed3({consentId:id}));var TOOL_RESULT_REVOKE_ANSWER_SCHEMAS=deepFreeze5({known:status("known",{consentId:id}),refused:status("refused",{consentId:id}),unknown:status("unknown",{consentId:id})});var TOOL_RESULT_REVOKE_OUTPUT_SCHEMA=deepFreeze5({oneOf:Object.values(TOOL_RESULT_REVOKE_ANSWER_SCHEMAS)});var TOOL_RESULTS_COMMANDS=deepFreeze5([{name:"tool-result",capability:"tool-results.read",input:TOOL_RESULT_INPUT_SCHEMA,output:TOOL_RESULT_OUTPUT_SCHEMA},{name:"tool-result-consent",capability:"tool-results.consent",input:TOOL_RESULT_CONSENT_INPUT_SCHEMA,output:TOOL_RESULT_CONSENT_OUTPUT_SCHEMA},{name:"tool-result-revoke",capability:"tool-results.revoke",input:TOOL_RESULT_REVOKE_INPUT_SCHEMA,output:TOOL_RESULT_REVOKE_OUTPUT_SCHEMA}]);var TOOL_RESULTS_CLUSTER=deepFreeze5({urn:"ai.cotal.tool-results",revision:1,attributes:[],events:[],commands:TOOL_RESULTS_COMMANDS.map(row=>({name:row.name,class:"ephemeral",targeted:true,modes:["handle"],capability:row.capability,inputDigest:singleDocumentClosure(row.input).closureDigest,outputDigest:singleDocumentClosure(row.output).closureDigest}))});init_event_payloads();var import_nkeys13=__toESM(require_mod(),1);init_base64url();var LANG_PROBLEM_DETAIL_KIND="ai.cotal.lang.problem";var RUN_ACTIVATION_WAIT_MS=15e3;var RUN_LAUNCH_DEADLINE_MS=RUN_ACTIVATION_WAIT_MS+1e4;init_issued_authority();init_provision();init_issued_authority();init_subjects();init_endpoint_subjects();init_persona_endpoints();var DELEGABLE_CAPABILITIES=Object.freeze(["spawn","run","admin"]);init_persona_endpoints();var import_jetstream31=__toESM(require_mod4(),1);var import_transport_node30=__toESM(require_transport_node(),1);init_backup();init_issued_authority();init_jetstream_missing();init_run_admission();init_endpoint_envelope();init_issued_authority();init_endpoint_subjects();init_endpoint_records();init_run_submission();init_canonical();init_endpoint_journal();init_endpoint_caller();init_endpoint_subjects();init_endpoint_error();init_connection_cleanup();var import_jetstream32=__toESM(require_mod4(),1);var import_kv15=__toESM(require_mod6(),1);init_endpoint();init_endpoint_binding();init_endpoint_envelope();init_lifecycle_state();init_endpoint_records();init_issued_authority();init_identity();init_provision();init_renewal();init_streams();init_service_gate();init_contract_manifest();init_renewal();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_KEY","COTAL_CONTROL_VERSION","COTAL_CONTROL_TOKEN","COTAL_LINK"];function readMaterial(env){const path4=env[LAUNCH_MATERIAL_ENV]?.trim();if(!path4)return void 0;const direct=DIRECT_MATERIAL_VARS.filter(k2=>env[k2]?.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(path4)}function controlFromEnv(env=process.env){if(env.COTAL_CONTROL_TOKEN?.trim())throw new Error("COTAL config: COTAL_CONTROL_TOKEN is the control key variable of a release before the control exchange. Set COTAL_CONTROL_KEY and COTAL_CONTROL_VERSION instead; this build refuses the old name rather than guess which protocol it meant.");const path4=env.COTAL_CONTROL_SOCKET?.trim();const material=readMaterial(env);const token2=material?material.controlKey:directControlKey(env);if(path4&&token2){const direct=env.COTAL_CONTROL_VERSION;const version2=material?material.controlVersion:direct?.trim()?/^(0|[1-9][0-9]*)$/.test(direct)?Number(direct):direct:void 0;assertControlVersion(version2,material?"this launch's material":"COTAL_CONTROL_VERSION");return{path:path4,token:token2,version:version2}}if(!path4&&!token2)return void 0;if(path4)throw new Error("COTAL config: COTAL_CONTROL_SOCKET is set but no control key could be resolved - neither the launch material nor COTAL_CONTROL_KEY 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 key 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 directControlKey(env){const key=env.COTAL_CONTROL_KEY;if(!key?.trim()){if(env.COTAL_CONTROL_VERSION?.trim())throw new Error("COTAL config: COTAL_CONTROL_VERSION is set without COTAL_CONTROL_KEY. The version travels with the key; set both or neither.");return void 0}if(key!==key.trim())throw new Error("COTAL config: COTAL_CONTROL_KEY has whitespace around it. A key is used as given, never trimmed; remove the whitespace.");return key}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(v3){if(!v3)return[];return v3.split(",").map(s3=>s3.trim()).filter(Boolean)}function endpointsEnv(v3){let raw;try{raw=JSON.parse(v3)}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(v3){return v3===void 0?void 0:splitList(v3)}var EnvFlagError=class extends Error{};function envFlag(env,name2){const value=env[name2]?.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: ${name2} must be 1/true/yes/on or 0/false/no/off, got "${env[name2]}"`)}function scrubLaunchMaterial(env=process.env){const path4=env[LAUNCH_MATERIAL_ENV]?.trim();delete env[LAUNCH_MATERIAL_ENV];if(path4)discardLaunchMaterial(path4)}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 name2=env.COTAL_NAME?.trim()||def?.name||(link?userInfo2().username:void 0);if(!name2)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(e3){throw new Error(`COTAL config: ${e3.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(c3=>resolvedMuted.includes(c3));if(bothModes.length)throw new Error(`COTAL config: channel(s) [${bothModes.join(", ")}] are in both quiet and muted`);for(const[field,chans]of[["quiet",resolvedQuiet],["muted",resolvedMuted]])for(const ch of chans){assertValidChannel(ch);if(!isConcreteChannel(ch))throw new Error(`COTAL config: ${field} channel "${ch}" must be concrete (no wildcard)`);if(!channelInAllow(resolvedAllowSub,ch))throw new Error(`COTAL config: ${field} channel "${ch}" is not within allowSubscribe [${resolvedAllowSub.join(", ")}]`)}const material=readMaterial(env);if(env.COTAL_SERVERS?.trim()&&brokerUrlHasUserinfo(env.COTAL_SERVERS))throw new Error("COTAL config: COTAL_SERVERS must not embed credentials; name the broker URL without user:password@, and pass the credential in COTAL_CREDS, COTAL_TOKEN or a COTAL_LINK");const credsPath=material?.creds??env.COTAL_CREDS?.trim();const initialCreds=credsPath?readFileSync4(credsPath,"utf8"):void 0;const credsId=initialCreds?idFromCreds(initialCreds):void 0;const boundedCreds=initialCreds!==void 0&&typeof credsClaims(initialCreds).exp==="number";const declaredId=env.COTAL_ID?.trim()||void 0;if(declaredId&&credsId&&declaredId!==credsId)throw new Error(`COTAL config: COTAL_ID ${declaredId} != creds identity ${credsId} - they must be the same nkey`);const userVars=material?.userAuth?{owner:material.userAuth.owner,actor:material.userAuth.actor,sentinel:material.userAuth.sentinelCredsPath,bearerCmd:JSON.stringify(material.userAuth.bearerCmd)}:{owner:env.COTAL_OWNER?.trim(),actor:env.COTAL_ACTOR?.trim(),sentinel:env.COTAL_SENTINEL_CREDS?.trim(),bearerCmd:env.COTAL_BEARER_CMD?.trim()};const userSet=Object.values(userVars).filter(Boolean).length;if(userSet>0&&userSet<4)throw new Error("COTAL config: user-mode launch needs ALL of COTAL_OWNER, COTAL_ACTOR, COTAL_SENTINEL_CREDS, COTAL_BEARER_CMD \u2014 a partial set is a broken launcher, not a mode");if(userSet&&credsPath)throw new Error("COTAL config: COTAL_CREDS (static auth) and COTAL_OWNER/... (user-mode auth) are mutually exclusive");const lifecycleUid=env.COTAL_LIFECYCLE_UID?.trim()||void 0;const backfillFloorRaw=env.COTAL_BACKFILL_FLOOR?.trim()||void 0;let backfillFloor;if(backfillFloorRaw!==void 0){const n2=Number(backfillFloorRaw);if(!Number.isInteger(n2)||n2<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=n2}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(a3=>typeof a3==="string"))throw new Error("COTAL config: COTAL_BEARER_CMD must be a non-empty JSON array of strings");userAuth={owner:userVars.owner,actor:userVars.actor,sentinelCreds:readFileSync4(userVars.sentinel,"utf8"),bearerCmd}}const eventsRequired=material?.eventsRequired===true||!material&&envFlag(env,"COTAL_EVENTS_REQUIRED")===true;if(eventsRequired&&!userAuth)throw new Error("COTAL config: COTAL_EVENTS_REQUIRED is valid only for a user-mode registration launch");if(eventsRequired){const principal=userSet===4?{owner:userVars.owner,actor:userVars.actor}:{owner:DEV_OWNER,actor:credsId??declaredId??""};if(!principal.actor)throw new Error("COTAL config: this space requires events, but the session has no stable principal to derive its event channel");const channel=eventChannel(principal);if(!channelInAllow(resolvedAllowPub,channel))throw new Error(`COTAL config: space "${env.COTAL_SPACE?.trim()||link?.space||"demo"}" requires events, but this session's grant does not cover its event channel "${channel}". Widen the whole user-auth actor row with \`cotal actor grant ${principal.actor} --owner ${principal.owner} --scope <current-scope> --allow-subscribe <current-read> --allow-publish '<current-post>,${channel}' --role <current-role> --label <current-label>\`; actor grant replaces the whole row, so preserve every current field.`)}return{space:env.COTAL_SPACE?.trim()||link?.space||"demo",id:credsId??declaredId,lifecycleUid,backfillFloor,acceptedToken,managerInstanceId,creds:boundedCreds?async()=>readFileSync4(credsPath,"utf8"):initialCreds,userAuth,name:name2,role:env.COTAL_ROLE||def?.role||void 0,description:def?.description,tags:def?.tags,meta:def?.meta,capabilities:splitList(env.COTAL_CAPABILITIES).length?splitList(env.COTAL_CAPABILITIES):def?.capabilities,endpoints:env.COTAL_ENDPOINTS!==void 0?endpointsEnv(env.COTAL_ENDPOINTS):def?.endpoints,model:env.COTAL_MODEL?.trim()||void 0,variant:env.COTAL_VARIANT?.trim()||void 0,servers:material?.servers||env.COTAL_SERVERS?.trim()||link?.servers||DEFAULT_SERVER,subscribe:resolvedSubscribe,allowSubscribe:resolvedAllowSub,allowPublish:resolvedAllowPub,eventsRequired,eventPayloadsWithheld:material?.eventPayloadsWithheld===true||envFlag(env,"COTAL_EVENT_PAYLOADS")===false,quiet:resolvedQuiet,muted:resolvedMuted,kind:assertValidKind(env.COTAL_KIND?.trim()||def?.kind||"agent"),token:material?.token||env.COTAL_TOKEN?.trim()||link?.token,user:link?.user,pass:link?.pass,tls:envFlag(env,"COTAL_TLS")||link?.tls||false,feedbackKey:env.COTAL_FEEDBACK_KEY?.trim()||void 0,feedbackUrl:env.COTAL_FEEDBACK_URL?.trim()||void 0}}function eventPlaneArmed(config2,env=process.env){return envFlag(env,"COTAL_EVENTS")===true||config2.eventsRequired===true}function feedbackLine(config2){const dest=config2.feedbackKey?"":`Without a feedback key it goes to the public cotal.ai intake and needs a contact email \u2014 the tool will tell you to ask the user for one if it can't find it. `;return`Use cotal_feedback with origin="human" when the user asks you to send feedback or gives you feedback to pass along. If you independently hit a major Cotal issue \u2014 for example repeated Cotal tool failures, inability to connect, lost/incorrect mesh messages, or a workflow-blocking bug \u2014 send cotal_feedback yourself with origin="agent". Do not send minor noise or secrets; include diagnostics only when they help debug the Cotal issue. `+dest}import{AsyncLocalStorage as AsyncLocalStorage2}from"node:async_hooks";import{EventEmitter as EventEmitter2}from"node:events";import{hostname as hostname2}from"node:os";import{createHash as createHash8,randomUUID as randomUUID10}from"node:crypto";import{open as open3,readFile as readFile2,unlink as unlink2}from"node:fs/promises";import{hostname}from"node:os";import{dirname as dirname7,join as join7}from"node:path";import{createHash as createHash7,randomUUID as randomUUID9}from"node:crypto";import{constants as constants4}from"node:fs";import{lstat as lstat2,open as open2,readFile,readdir as readdir2,rename,unlink}from"node:fs/promises";import{dirname as dirname6,join as join6}from"node:path";var EVENT_WAL_VERSION=4;var WalCorruptError=class extends Error{path;invariant;constructor(path4,invariant,detail){super(`event WAL at ${path4} is unusable (${invariant}): ${detail}`);this.path=path4;this.invariant=invariant;this.name="WalCorruptError"}};var WalStaleWriterError=class extends Error{path;expectedGen;foundGen;constructor(path4,expectedGen,foundGen){super(`event WAL at ${path4} 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=path4;this.expectedGen=expectedGen;this.foundGen=foundGen;this.name="WalStaleWriterError"}};var isSafeNonNegInt2=n2=>Number.isSafeInteger(n2)&&n2>=0;function docGeneration(path4,doc){if(typeof doc.v==="number"&&doc.v<3)return 0;if(!isSafeNonNegInt2(doc.gen))throw new WalCorruptError(path4,"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(path4){return open2(path4,constants4.O_WRONLY|constants4.O_CREAT|constants4.O_EXCL|(constants4.O_NOFOLLOW??0),384)}function assertPendingVintage(path4,p2,f2){if(p2.E!==f2.lastSubjectSeq)throw new WalCorruptError(path4,"pending.E === frontier.lastSubjectSeq",`pending.E=${p2.E} frontier.lastSubjectSeq=${f2.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(p2.seq!==f2.seq+1)throw new WalCorruptError(path4,"pending.seq === frontier.seq + 1",`pending.seq=${p2.seq} frontier.seq=${f2.seq} \u2014 a pending frame must be exactly the frontier's successor`);if(p2.state==="sent_unacked"){if(p2.ackSeq!==void 0)throw new WalCorruptError(path4,"sent_unacked has no ackSeq",`state is "sent_unacked" but ackSeq=${String(p2.ackSeq)} \u2014 the document contradicts its own tag`);return}if(!isSafeNonNegInt2(p2.ackSeq))throw new WalCorruptError(path4,"acked.ackSeq present",`state is "acked" but ackSeq is ${String(p2.ackSeq)}`);if(!(p2.ackSeq>f2.lastSubjectSeq))throw new WalCorruptError(path4,"acked.ackSeq > frontier.lastSubjectSeq",`ackSeq=${p2.ackSeq} frontier.lastSubjectSeq=${f2.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(path4,field,v3,nullable2){if(v3===null&&nullable2)return null;if(typeof v3!=="object"||v3===null)throw new WalCorruptError(path4,`${field} is an object${nullable2?" or null":""}`,JSON.stringify(v3));const b3=v3;if(b3.run!==void 0&&typeof b3.run!=="string")throw new WalCorruptError(path4,`${field}.run is a string or absent`,JSON.stringify(b3.run));const lists={text:b3.text,reasoning:b3.reasoning,tools:b3.tools};for(const[k2,list]of Object.entries(lists)){if(!Array.isArray(list)||list.some(x2=>typeof x2!=="string"))throw new WalCorruptError(path4,`${field}.${k2} is an array of strings`,JSON.stringify(list))}if(b3.run===void 0&&b3.text.concat(b3.reasoning,b3.tools).length>0)throw new WalCorruptError(path4,`${field} has no open run while messages or tool calls are open`,JSON.stringify(b3));return{run:b3.run,text:b3.text,reasoning:b3.reasoning,tools:b3.tools}}function parsePayloadCalls(path4,value){if(value===void 0)return void 0;if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).length>4096||Object.entries(value).some(([id2,allowed])=>!id2||typeof allowed!=="boolean"))throw new WalCorruptError(path4,"payloadCalls is a bounded boolean record","invalid call classification");return{...value}}function parseDoc(path4,raw,space2,threadId,principal){let d2;try{d2=JSON.parse(raw)}catch(e3){throw new WalCorruptError(path4,"parseable JSON",e3.message)}if(typeof d2!=="object"||d2===null)throw new WalCorruptError(path4,"document is an object",typeof d2);const doc=d2;if(typeof doc.v!=="number"||!Number.isSafeInteger(doc.v)||doc.v<1)throw new WalCorruptError(path4,"v is a positive integer",`found v=${String(doc.v)}`);if(doc.v>EVENT_WAL_VERSION)throw new WalCorruptError(path4,`v <= ${EVENT_WAL_VERSION}`,`this WAL is v${doc.v} and this build understands v${EVENT_WAL_VERSION} \u2014 THE STATE IS NEWER THAN THE CODE, which is what a code rollback across the v2 migration (persisted bracket state) or the v3 one (the write generation) leaves behind. The migration is forward-only by design: there is no downgrade, because a lossy one would silently discard state this file exists to preserve. Run the newer build, or move this WAL aside and accept that the thread restarts from a new epoch.`);if(doc.space!==space2)throw new WalCorruptError(path4,"space matches",`WAL space=${String(doc.space)} caller=${space2}`);if(doc.threadId!==threadId)throw new WalCorruptError(path4,"threadId matches",`WAL threadId=${String(doc.threadId)} caller=${threadId}`);if(doc.principal!==principal)throw new WalCorruptError(path4,"principal matches",`WAL principal=${String(doc.principal)} caller=${principal}`);if(typeof doc.epoch!=="string"||doc.epoch.length===0)throw new WalCorruptError(path4,"epoch is a non-empty string",String(doc.epoch));const f2=doc.frontier;if(!f2||!isSafeNonNegInt2(f2.seq)||!isSafeNonNegInt2(f2.lastSubjectSeq))throw new WalCorruptError(path4,"frontier is well-formed",JSON.stringify(doc.frontier));if(f2.sourceCursor!==void 0&&typeof f2.sourceCursor!=="string")throw new WalCorruptError(path4,"frontier.sourceCursor is a string or absent",typeof f2.sourceCursor);if(f2.seq===0!==(f2.lastSubjectSeq===0))throw new WalCorruptError(path4,"frontier.seq and lastSubjectSeq are both zero or both nonzero",JSON.stringify(f2));if((f2.seq>0||f2.lastSubjectSeq>0)&&typeof f2.sourceCursor!=="string")throw new WalCorruptError(path4,"a nonzero frontier carries its sourceCursor",JSON.stringify(f2));if(doc.pending!==null&&typeof doc.pending!=="object")throw new WalCorruptError(path4,"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 p2=doc.pending;if(p2.state!=="sent_unacked"&&p2.state!=="acked")throw new WalCorruptError(path4,"pending.state is a known tag",String(p2.state));if(typeof p2.id!=="string"||p2.id.length===0)throw new WalCorruptError(path4,"pending.id is a non-empty string",String(p2.id));try{assertIdToken(p2.id,"event WAL pending.id")}catch(e3){throw new WalCorruptError(path4,"pending.id satisfies the wire id grammar",e3.message)}if(!isSafeNonNegInt2(p2.E)||!isSafeNonNegInt2(p2.seq))throw new WalCorruptError(path4,"pending E/seq are safe non-negative integers",JSON.stringify(p2));if(typeof p2.sourceCursor!=="string")throw new WalCorruptError(path4,"pending.sourceCursor is a string",typeof p2.sourceCursor);if(!Array.isArray(p2.body)||p2.body.length===0)throw new WalCorruptError(path4,"pending.body is a non-empty array of parts",JSON.stringify(p2.body));if(doc.v===1)throw new WalCorruptError(path4,"a v1 WAL has no frame in flight",`this v1 document holds a ${String(p2.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.`);p2.brackets=parseBrackets(path4,"pending.brackets",p2.brackets,false);if(p2.payload!==void 0){const payload=p2.payload;if(doc.v<4||!payload||typeof payload!=="object"||!Array.isArray(payload.body)||payload.body.length===0||!isSafeNonNegInt2(payload.E)||payload.ackSeq!==void 0&&(!isSafeNonNegInt2(payload.ackSeq)||payload.ackSeq<=payload.E))throw new WalCorruptError(path4,"pending payload is a v4 frozen publication",JSON.stringify(payload));assertIdToken(payload.id,"event WAL payload id")}p2.payloadCalls=parsePayloadCalls(path4,p2.payloadCalls);pending=p2;assertPendingVintage(path4,pending,f2)}const brackets=doc.v===1?null:parseBrackets(path4,"brackets",doc.brackets,true);return{v:EVENT_WAL_VERSION,gen:docGeneration(path4,doc),space:space2,epoch:doc.epoch,threadId,principal,frontier:f2,pending,payloadCalls:parsePayloadCalls(path4,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(path4,doc){this.path=path4;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}async pendingSiblings(){const threadDir=createHash7("sha256").update(this.threadId).digest("hex").slice(0,16);if(dirname6(this.path).split(/[\\/]/).pop()!==threadDir)return[];const parent=dirname6(dirname6(this.path));const siblings=[];for(const entry of await readdir2(parent,{withFileTypes:true})){if(!/^[a-f0-9]{16}$/.test(entry.name))continue;const path4=join6(parent,entry.name,"wal.json");if(path4===this.path)continue;if(entry.isSymbolicLink())throw new WalCorruptError(path4,"a real thread directory","found a symlink");if(!entry.isDirectory())continue;let bytes;try{const st2=await lstat2(path4);if(!st2.isFile()||st2.nlink!==1)throw new WalCorruptError(path4,"a real thread log with one name","refusing linked or non-file state");const file2=await open2(path4,constants4.O_RDONLY|(constants4.O_NOFOLLOW??0));try{bytes=await file2.readFile()}finally{await file2.close()}}catch(e3){if(e3.code==="ENOENT")continue;throw e3}const raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes);const doc=JSON.parse(raw);if(doc.pending?.state!=="sent_unacked")continue;const threadId=doc.threadId;if(typeof threadId!=="string"||createHash7("sha256").update(threadId).digest("hex").slice(0,16)!==entry.name)throw new WalCorruptError(path4,"thread id matches its directory","refusing misplaced state");const sibling=new _EventWal(path4,parseDoc(path4,raw,this.space,threadId,this.principal));if(sibling.pending)siblings.push(sibling)}return siblings.sort((a3,b3)=>a3.pending.E-b3.pending.E)}subject;static async open(path4,opts){let raw;let bytes;try{bytes=await readFile(path4)}catch(e3){if(e3.code!=="ENOENT")throw e3}if(bytes!==void 0){try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new WalCorruptError(path4,"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(path4,"WAL exists when the subject may","no WAL file, but this thread may already have published");return new _EventWal(path4,_EventWal.virgin(opts.space,opts.threadId,opts.principal))}if(raw.length===0)throw new WalCorruptError(path4,"WAL is non-empty","the file is zero bytes \u2014 distinct from missing and never treated as a virgin thread");return new _EventWal(path4,parseDoc(path4,raw,opts.space,opts.threadId,opts.principal))}static virgin(space2,threadId,principal){return{v:EVENT_WAL_VERSION,gen:0,space:space2,epoch:randomUUID9(),threadId,principal,frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}}}async bindSubjectFrontier(frontier){if(this.subject===frontier)return;if(this.subject)throw new Error(`event WAL ${this.path}: a DIFFERENT subject frontier is already bound`);this.subject=frontier}get expectedTip(){if(!this.subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so there is no expectation to publish. The subject is shared by every thread of this principal, so this document's own last ack is not it; bind the principal's record with bindSubjectFrontier first.`);return this.subject.tip}async beginSend(frame){return this.serialize(async()=>{if(this.doc.pending)throw new Error(`event WAL ${this.path}: a frame is already pending; one emit unit is one pending frame`);assertIdToken(frame.id,"event WAL pending id");if(frame.E!==this.expectedTip)throw new Error(`event WAL ${this.path}: E=${frame.E} is not the subject's tip ${this.expectedTip}`);if(frame.seq!==this.doc.frontier.seq+1)throw new Error(`event WAL ${this.path}: seq=${frame.seq} is not the frontier's successor ${this.doc.frontier.seq+1}`);if(!Array.isArray(frame.body)||frame.body.length===0)throw new Error(`event WAL ${this.path}: a frame body must be a non-empty array of parts`);parsePayloadCalls(this.path,frame.payloadCalls);if(frame.payload){assertIdToken(frame.payload.id,"event WAL payload id");if(!isSafeNonNegInt2(frame.payload.E)||!Array.isArray(frame.payload.body)||frame.payload.body.length===0||frame.payload.ackSeq!==void 0)throw new Error("event WAL payload must be an unacknowledged frozen publication")}await this.write({...this.doc,pending:{state:"sent_unacked",...frame}})})}async recordPayloadAck(ackSeq){return this.serialize(async()=>{const p2=this.doc.pending;if(!p2?.payload||p2.state!=="sent_unacked"||p2.payload.ackSeq!==void 0)throw new Error("event WAL has no unacknowledged sibling payload");if(!isSafeNonNegInt2(ackSeq)||ackSeq<=p2.payload.E)throw new Error("payload ack must advance its frozen expectation");await this.write({...this.doc,pending:{...p2,payload:{...p2.payload,ackSeq}}})})}async recordAck(ackSeq){return this.serialize(async()=>{const p2=this.doc.pending;if(!p2||p2.state!=="sent_unacked")throw new Error(`event WAL ${this.path}: no sent_unacked frame to ack`);if(p2.payload&&p2.payload.ackSeq===void 0)throw new Error("event WAL cannot acknowledge public frame before sibling payload");if(!isSafeNonNegInt2(ackSeq))throw new Error(`event WAL ${this.path}: ackSeq must be a safe non-negative integer, got ${String(ackSeq)}`);if(ackSeq<=this.expectedTip)throw new Error(`event WAL ${this.path}: ackSeq=${ackSeq} is not ahead of the subject's tip ${this.expectedTip}`);const subject=this.subject;if(!subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so this ack has no shared record to advance`);await this.assertNotClobbering();await subject.advance(ackSeq);await this.write({...this.doc,pending:{...p2,state:"acked",ackSeq}})})}async fold(){return this.serialize(async()=>{const p2=this.doc.pending;if(!p2||p2.state!=="acked"||p2.ackSeq===void 0)throw new Error(`event WAL ${this.path}: no acked frame to fold`);await this.write({...this.doc,frontier:{seq:p2.seq,lastSubjectSeq:p2.ackSeq,sourceCursor:p2.sourceCursor},pending:null,brackets:p2.brackets,payloadCalls:p2.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:randomUUID9(),frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}})})}async write(next){await this.assertNotClobbering();const stamped={...next,gen:this.doc.gen+1};const tmp=join6(dirname6(this.path),`.${createHash7("sha256").update(this.path).digest("hex").slice(0,12)}.${process.pid}.${randomUUID9().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(e3){await unlink(tmp).catch(()=>{});throw e3}this.doc=stamped}async assertNotClobbering(){let bytes;try{bytes=await readFile(this.path)}catch(e3){if(e3.code!=="ENOENT")throw e3}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(e3){throw new WalCorruptError(this.path,"parseable JSON",e3.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 h2(value){return createHash8("sha256").update(value).digest("hex").slice(0,16)}function eventWalLocation(opts){const principal=eventPrincipalLocation(opts);const threadDir=join7(principal.principalDir,h2(opts.threadId));return{...principal,threadDir,walPath:join7(threadDir,"wal.json")}}var PrincipalLockError=class extends Error{path;invariant;constructor(path4,invariant,detail){super(`event WAL principal lock at ${path4} (${invariant}): ${detail}`);this.path=path4;this.invariant=invariant;this.name="PrincipalLockError"}};var held=new Map;function ownerIsAlive(pid){try{process.kill(pid,0);return true}catch(e3){return e3.code!=="ESRCH"}}async function createLockFile(path4){try{return await openExclusiveNoFollow(path4)}catch(e3){if(e3.code==="EEXIST")return void 0;throw e3}}async function reclaimIfOwnerIsGone(path4){let raw;try{raw=await readFile2(path4,"utf8")}catch(e3){if(e3.code==="ENOENT")return;throw e3}let record2;try{record2=JSON.parse(raw)}catch{throw new PrincipalLockError(path4,"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 r2=record2;if(!Number.isSafeInteger(r2.pid)||r2.pid<=0||typeof r2.host!=="string"||r2.host.length===0)throw new PrincipalLockError(path4,"the lock names its owner",`the record carries pid=${String(r2.pid)} host=${String(r2.host)}, which names nobody checkable`);const here=hostname();if(r2.host!==here)throw new PrincipalLockError(path4,"the recorded owner is on THIS host",`held by pid ${r2.pid} on ${r2.host} while this process runs on ${here}; liveness on another machine is not observable from here`);if(ownerIsAlive(r2.pid))throw new PrincipalLockError(path4,"the recorded owner is gone",`pid ${r2.pid} on ${here} is still running and holds this principal's emitter`);await unlink2(path4).catch(e3=>{if(e3.code!=="ENOENT")throw e3})}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:randomUUID10(),acquiredAt:new Date().toISOString()});try{await fh.writeFile(record2,"utf8");await fh.sync()}catch(e3){await fh.close().catch(()=>{});await unlink2(lockPath).catch(()=>{});throw e3}const lock={path:lockPath,async release(){if(held.get(lockPath)!==lock)return;held.delete(lockPath);await fh.close().catch(()=>{});await unlink2(lockPath).catch(e3=>{if(e3.code!=="ENOENT")throw e3})}};held.set(lockPath,lock);return lock}async function fsyncDir(dir){let fh;try{fh=await open3(dir,"r")}catch(e3){const code2=e3.code;if(code2==="EPERM"||code2==="EACCES")return;throw e3}try{await fh.sync()}catch(e3){const code2=e3.code;if(code2!=="EBADF"&&code2!=="EINVAL"&&code2!=="EPERM"&&code2!=="EISDIR")throw e3}finally{await fh.close()}}async function ensureEventWalDir(opts){const loc=eventWalLocation(opts);ensureDirNoSymlink(opts.workspaceRoot,".cotal","events",h2(opts.space),h2(opts.principal),h2(opts.threadId));for(let dir=loc.threadDir;;dir=dirname7(dir)){await fsyncDir(dir);if(dir===opts.workspaceRoot||dirname7(dir)===dir)break}const lock=await acquirePrincipalLock(loc.lockPath);return{...loc,lock}}async function checkEventStartup2(ep,env){const workspaceRoot=resolveEventsStateRoot(env);try{await checkEventStartup({workspaceRoot,space:ep.space,principal:ep.principal,retainedMessages:async()=>(await ep.chatRetention()).senders})}catch(error51){if(!(error51 instanceof EventStateConflictError))throw error51;const principal=principalKey(ep.principal.owner,ep.principal.actor).key;const threadId="startup-pending-inspection";const{walPath}=eventWalLocation({workspaceRoot,space:ep.space,principal,threadId});const inspection=await EventWal.open(walPath,{space:ep.space,principal,threadId,subjectMayExist:false});if((await inspection.pendingSiblings()).length===0)throw error51}}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=(uid2,goalId)=>`${uid2}:${goalId}`;function onceHandoffState(uid2,goalId){return proc().handoffs.get(keyOf(uid2,goalId))?.state??"pending"}function claimOnceHandoff(uid2,goalIds){const p2=proc();if(goalIds.some(id2=>onceHandoffState(uid2,id2)!=="pending"))return false;for(const id2 of goalIds){const timer2=setTimeout(()=>p2.timedOut?.(uid2,id2),ONCE_HANDOFF_MS);timer2.unref?.();p2.handoffs.set(keyOf(uid2,id2),{state:"claimed",timer:timer2})}return true}function confirmOnceHandoff(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state==="sealed")return false;if(h3?.timer!==void 0)clearTimeout(h3.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"confirmed"});return true}function sealOnceHandoff(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state!=="claimed")return false;if(h3.timer!==void 0)clearTimeout(h3.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"sealed"});return true}function endOnceHandoff(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state==="confirmed"||h3?.state==="sealed")return;if(h3?.timer!==void 0)clearTimeout(h3.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"sealed"})}function stopOnceHandoffTimer(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state!=="claimed"||h3.timer===void 0)return;clearTimeout(h3.timer);h3.timer=void 0}function onOnceHandoffTimeout(fn2){proc().timedOut=fn2}function registerOnceExit(fn2){proc().exit=fn2}function exitOnceSeat(){const p2=proc();if(p2.exiting)return p2.exiting;const exiting=askOnceExit(p2.exit).then(ending=>{if(!ending){p2.exiting=void 0;return false}setTimeout(()=>process.exit(1),ONCE_EXIT_GRACE_MS);return true});p2.exiting=exiting;return exiting}async function askOnceExit(exit){let ending;try{ending=exit?.()}catch{return true}if(ending instanceof Promise)ending=await ending.catch(()=>false);return ending!==false}init_peer_label();var LABEL_MAX_CODE_POINTS=40;function capped(s3,max){const points=Array.from(s3);return points.length<=max?s3:`${points.slice(0,max-1).join("")}\u2026`}function attributionSafe(s3){return peerLabel({name:s3})}var FROM_MAX_CODE_POINTS=160;var FROM_MIN_CODE_POINTS=" (unverified name)".length+2;function fmtFrom(i2,maxCodePoints=FROM_MAX_CODE_POINTS){if(!Number.isInteger(maxCodePoints)||maxCodePoints<FROM_MIN_CODE_POINTS)throw new RangeError(`a sender label bound must be a whole number of at least ${FROM_MIN_CODE_POINTS} code points, got ${maxCodePoints}`);const named=i2.fromName.trim()!=="";const label=peerLabel({name:named?i2.fromName:i2.fromId,...i2.fromRole?{role:i2.fromRole}:{}});const marker=named?" (unverified name)":i2.fromRole?" (unverified role)":"";return`${capped(label,maxCodePoints-marker.length)}${marker}`}function fmtBody(text3){return text3.split(LINE_BREAK).join("\n ")}function fmtItem(i2){return formatItem(i2)}function fmtDeliveryItem(i2){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(i2.fromId)}`,...i2.id?[`message_id=${field(i2.id)}`]:[],...i2.contextId?[`context_id=${field(i2.contextId)}`]:[],...i2.replyTo?[`reply_to=${field(i2.replyTo)}`]:[]];return formatItem(i2,`[${metadata2.join(" ")}] `)}function formatItem(i2,metadata2="",attributionMax){const h3=i2.historical?"(history) ":"";const body=`${metadata2}${h3}${redeliveryNote(i2)}${fmtBody(i2.text)}`;if(i2.notice)return`[${i2.notice} notice from the delivery daemon] ${body}`;const label=s3=>attributionMax===void 0?attributionSafe(s3??""):capped(attributionSafe(s3??""),LABEL_MAX_CODE_POINTS);const from=head2=>fmtFrom(i2,attributionMax===void 0?void 0:Math.min(FROM_MAX_CODE_POINTS,attributionMax-Array.from(head2).length-"] ".length));if(i2.kind==="dm")return`[DM from ${from("[DM from ")}] ${body}`;if(i2.kind==="anycast"){const head2=`[@${label(i2.service)} from `;return`${head2}${from(head2)}] ${body}`}const head=`[#${label(i2.channel)}${i2.mentionsMe?" @you":""} `;return`${head}${from(head)}] ${body}`}function redeliveryNote(i2){const n2=i2.deliveryCount;if(n2===void 0||n2<=1)return"";if(i2.firstDeliveryCount===void 0||i2.firstDeliveryCount>1)return`(broker redelivery, delivery ${n2}: prior model handoff unknown) `;if(i2.handedOverAt!==void 0&&i2.handedOverAt<n2)return`(broker redelivery, delivery ${n2}: an earlier handoff in this session was not confirmed) `;return""}function fmtChannel(channel){const safe=attributionSafe(channel??"").trim();return safe.length?safe:"?"}var CONNECTOR_VERSION="0.171.2";var MANAGER_BEARER_MARGIN_MS=12e4;function compareRelease(a3,b3){const[x2,y3]=[a3,b3].map(v3=>v3.split(/[-+]/)[0].split(".").map(Number));for(let i2=0;i2<3;i2++)if(x2[i2]!==y3[i2])return(x2[i2]??0)-(y3[i2]??0);return 0}function bearerExpiryMs2(token2){try{const exp=JSON.parse(Buffer.from(token2.split(".")[1]??"","base64url").toString("utf8")).exp;return typeof exp==="number"&&Number.isFinite(exp)?exp*1e3:void 0}catch{return void 0}}function abortable(p2,signal){if(!signal)return p2;if(signal.aborted)return Promise.reject(signal.reason);return new Promise((resolve6,reject)=>{const onAbort=()=>reject(signal.reason);signal.addEventListener("abort",onAbort,{once:true});p2.then(v3=>{signal.removeEventListener("abort",onAbort);resolve6(v3)},e3=>{signal.removeEventListener("abort",onAbort);reject(e3)})})}var AgentManagerCalls=class{getConfig;getEndpoint;getLaunchEnv;invokeEndpoint;constructor(getConfig,getEndpoint,getLaunchEnv,invokeEndpoint){this.getConfig=getConfig;this.getEndpoint=getEndpoint;this.getLaunchEnv=getLaunchEnv;this.invokeEndpoint=invokeEndpoint}get config(){return this.getConfig()}get ep(){return this.getEndpoint()}get launchEnv(){return this.getLaunchEnv()}clear(){this.managerBearers.clear()}dropBearer(argv){this.managerBearers.delete(JSON.stringify(argv))}async listManagerEndpoints(input,instance){const user=this.config.userAuth;if(!user)return{none:"manager calls ride this session's own credential on this mesh, so the session view covers them"};if(!user.bearerCmd)return{none:"this session's bearer comes from its host, which issues no manager-call bearer, so the manager view has no credential"};const managerInstanceId=instance??this.config.managerInstanceId;const token2=await this.managerCallBearer([...user.bearerCmd,"--manager-call",...managerInstanceId?["--manager-instance",managerInstanceId]:[]]).catch(e3=>{throw e3 instanceof Error?new Error(e3.message.replace("--manager-instance <instanceId>","the instance argument")):e3});const exp=bearerExpiryMs2(token2);return withUserManagerListing({...this.config,managerInstanceId},token2,exp===void 0?void 0:exp/1e3,async(nc,listing)=>listing===void 0?{unbound:true}:this.ep.listEndpointsOver(nc,listing,input))}managerBearers=new Map;managerCallBearer(argv,signal){const key=JSON.stringify(argv);const held2=this.managerBearers.get(key);if(held2&&(held2.refreshAt===void 0||Date.now()<held2.refreshAt))return abortable(held2.flight,signal);const entry={flight:this.execBearerCmd(argv)};this.managerBearers.set(key,entry);entry.flight.then(token2=>{const exp=bearerExpiryMs2(token2);if(exp===void 0||exp-MANAGER_BEARER_MARGIN_MS<=Date.now()){if(this.managerBearers.get(key)===entry)this.managerBearers.delete(key)}else entry.refreshAt=exp-MANAGER_BEARER_MARGIN_MS},()=>{if(this.managerBearers.get(key)===entry)this.managerBearers.delete(key)});return abortable(entry.flight,signal)}async execBearerCmd(argv,signal,timeoutMs){const bearer=await runAgentBearer(argv,{env:this.launchEnv,signal,timeoutMs});if(!bearer)throw new Error(`bearer command printed nothing (${argv[0]})`);return bearer}async managerInvoke(command,args,opts={}){const clean=args===void 0?void 0:Object.fromEntries(Object.entries(args).filter(([,v3])=>v3!==void 0));let r2;let dropBearer;try{const input=clean&&Object.keys(clean).length?clean:void 0;if(this.config.userAuth){const bearerCmd=this.config.userAuth.bearerCmd;if(!bearerCmd)throw new EpEnvelopeError("failed-precondition",`${command}: this agent's bearer comes from its host, which issues no manager-call bearer, so manager operations are unavailable`,void 0,"not-executed");const managerInstanceId=opts.instanceId??this.config.managerInstanceId;const{instanceId:_instanceId,follow,...invokeOpts}=opts;const bearerArgv=[...bearerCmd,"--manager-call",...managerInstanceId?["--manager-instance",managerInstanceId]:[]];const bearer=signal=>this.managerCallBearer(bearerArgv,signal).catch(e3=>{if(signal?.aborted||!(e3 instanceof Error)||e3 instanceof EpEnvelopeError)throw e3;const message=e3.message.replace("--manager-instance <instanceId>","the instance argument");if(typeof e3.retryAfterSeconds==="number")throw new EpEnvelopeError("resource-exhausted",message,void 0,"not-executed");if(e3.message.startsWith("agent-bearer: exchange refused:"))throw new EpEnvelopeError("permission-denied",message,void 0,"not-executed");throw new Error(message)});dropBearer=()=>{this.managerBearers.delete(JSON.stringify(bearerArgv))};r2=await invokeUserManager({...this.config,managerInstanceId},bearer,command,input,{...invokeOpts,follow:follow?(submit,prepare)=>this.ep.followServiceGoal(BASELINE_LIFECYCLE_ENDPOINT,submit,opts.deadlineMs,{prepare,reconcile:async(goalId,attributed,context)=>{const instanceId=attributed.responder?.instanceId;if(!instanceId)throw new Error("accepted goal has no broker-attributed manager instance");const bearer2=signal=>this.execBearerCmd([...bearerCmd,"--manager-call","--manager-instance",instanceId],signal,Math.min(3e4,context.deadlineMs));const config2={...this.config,managerInstanceId:instanceId,lifecycleUid:context.caller.uid,userAuth:{...this.config.userAuth,owner:context.caller.owner,actor:context.caller.actor}};const queryRes=await invokeUserManager(config2,bearer2,"goal-result",{goalId},{signal:context.signal,deadlineMs:Math.min(invokeOpts.deadlineMs??1e4,context.deadlineMs)});if(queryRes.reply.ok!==true)throw new Error(queryRes.reply.error?.message??"goal-result query refused");return queryRes.reply.data}}):void 0})}else{const launchLocal=command==="stop"||command==="spawn"||command==="define-persona";const classInstanceId=this.config.creds&&launchLocal&&opts.instanceId===void 0?this.config.managerInstanceId:void 0;r2=await this.invokeEndpoint(BASELINE_LIFECYCLE_ENDPOINT,command,input,{...opts,...classInstanceId!==void 0?{classInstanceId}:{}})}}catch(e3){dropBearer?.();if(e3 instanceof EpEnvelopeError){const submitted=command==="spawn"&&e3.outcome==="unknown"?e3.details?.find(d2=>d2.kind===EP_UNANSWERED&&d2.endpoint===BASELINE_LIFECYCLE_ENDPOINT&&d2.command===command&&typeof d2.requestId==="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(d2.requestId)):void 0;if(submitted)return{...controlReplyFromThrown(e3,`${e3.code}: ${e3.message}`),outcome:"unknown",data:{goalId:submitted.requestId,submissionUnknown:true}};const undeclared=undeclaredArg(e3);if(undeclared!==void 0&&command!=="status")return{...controlReplyFromThrown(e3,await this.undeclaredArgMessage(command,e3,undeclared)),...e3.outcome?{outcome:e3.outcome}:{}};const unknownDefinition=command==="define-persona"&&e3.outcome!=="not-executed"&&e3.code==="deadline-exceeded"&&e3.details?.some(d2=>d2.kind===EP_UNANSWERED&&d2.command===command);const unknownYield=command==="turn-yield"&&e3.code==="deadline-exceeded"&&e3.outcome==="unknown"&&e3.details?.some(d2=>d2.kind===EP_UNANSWERED&&d2.endpoint===BASELINE_LIFECYCLE_ENDPOINT&&d2.command===command);const message=unknownYield?`${e3.code}: ${e3.message}. The yield may already have been recorded. After reconnecting, retry cotal_yield with the same turn id and intended status. An already-settled reply confirms the turn is terminal, not which attempt settled it. A successful reply records the yield if it is still active. This retry is not a read-only check.`:unknownDefinition?`${e3.code}: ${e3.message}`:unansweredRequest(e3)?`${e3.message} (no responder answered - a manager may be down, or this credential holds no "${command}" capability and the broker denied the request)`:`${e3.code}: ${e3.message}`;return{...controlReplyFromThrown(e3,message),...e3.outcome?{outcome:e3.outcome}:{}}}return{ok:false,error:e3.message}}if(r2.reply.ok!==true)dropBearer?.();return{...controlReplyFrom(r2.reply),instanceId:r2.responder?.instanceId,...r2.reply.error?.outcome?{outcome:r2.reply.error.outcome}:{}}}async undeclaredArgMessage(command,e3,key){const head=`${e3.code}: ${e3.message}. The manager's ${command} does not take "${key}", which this connector at Cotal ${CONNECTOR_VERSION} sends`;const instanceId=undeclaredArgInstance(e3);const answer=instanceId===void 0?void 0:await this.managerInvoke("status",void 0,{instanceId}).catch(()=>void 0);const reported=answer?.ok===true&&answer.instanceId===instanceId?answer.data?.version:void 0;const manager=typeof reported==="string"&&/^\d+\.\d+\.\d+/.test(reported)?reported:void 0;const updateManager=`on the manager's host run \`cotal update --self\`, then \`cotal manager restart\`, or, if you set "${key}", call again without it`;if(manager===void 0)return`${head}, so the manager most likely runs an older Cotal: ${updateManager}`;const order=compareRelease(CONNECTOR_VERSION,manager);if(order>0)return`${head}. The manager runs Cotal ${manager}, the older side: ${updateManager}`;if(order<0)return`${head}. The manager runs Cotal ${manager}, so this connector is the older side: run \`cotal update --self\` here and start a new session`;return`${head}. The manager also reports Cotal ${manager}, so one side is another build of that version: reinstall that side`}};var legacyRail=new Map;var LEGACY_RAIL_RECHECK_MS=60*6e4;var LEGACY_RAIL_MAX=32;function onLegacyRail(key){const until=legacyRail.get(key);if(until===void 0)return false;if(Date.now()<until)return true;legacyRail.delete(key);return false}function rememberLegacyRail(key){legacyRail.set(key,Date.now()+LEGACY_RAIL_RECHECK_MS);if(legacyRail.size>LEGACY_RAIL_MAX)legacyRail.delete(legacyRail.keys().next().value)}async function withUserManagerListing(config2,token2,exp,ask){const user=config2.userAuth;const binding=managerCallerBinding(token2,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId});const railKey=binding.credentialId??token2;const connectOpts=standaloneConnectOpts({bearer:token2,sentinelCreds:user.sentinelCreds,tls:config2.tls});const connId=String(connectOpts.name);const nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:1e4});const issued=async()=>{try{const caller=await issuedUserCaller(nc,config2.space,connId,binding.caller);legacyRail.delete(railKey);return caller}catch(e3){if(!isPermissionDenied(e3))throw e3;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 resolve6=(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 resolve6(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 resolve6(signal,remaining())}};const connect3=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const token2=await bearer(signal);let credentialId;try{({caller,instanceId,credentialId}=managerCallerBinding(token2,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId}))}catch{throw new EpEnvelopeError("failed-precondition","the manager control bearer is not bound to the expected caller and manager instance",void 0,"not-executed")}const connectOpts=standaloneConnectOpts({bearer:token2,sentinelCreds:user.sentinelCreds,tls:config2.tls});signal?.throwIfAborted();const left=deadline-Date.now();if(left<=0)throw new EpEnvelopeError("deadline-exceeded","the deadline passed before the manager was connected; the manager request WAS NOT RUN",void 0,"not-executed");try{nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:left})}catch(error51){signal?.throwIfAborted();if(error51 instanceof EpEnvelopeError)throw error51;throw new EpEnvelopeError(isAuthRejection(error51)?"permission-denied":"unavailable",error51 instanceof Error?error51.message:String(error51),void 0,"not-executed")}if(signal?.aborted)onAbort();signal?.throwIfAborted();const railKey=credentialId??token2;if(onLegacyRail(railKey)){skippedAcceptedRead={key:railKey,connId:String(connectOpts.name)}}else{try{caller=await issuedUserCaller(nc,config2.space,String(connectOpts.name),caller)}catch(e3){if(!isPermissionDenied(e3))throw e3;rememberLegacyRail(railKey)}}};const prepare=async(signal,deadline)=>{await connect3(signal,deadline);service=await resolvePrepared(signal,deadline)};const invoke=async(signal=opts.signal)=>{const unfollowable=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable)return unfollowable;const invokeOpts={target:opts.target,deadlineMs:opts.deadlineMs,signal};const result=await invokeCommand(nc,config2.space,service,command,args,invokeOpts);if(result.reply.ok===false&&replyRefusedBeforeEffect(result.reply.error)){try{service=await resolve6(signal);const unfollowable2=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable2)throw new Error(unfollowable2.reply.error.message)}catch(error51){return{...result,reply:{...result.reply,error:{...result.reply.error,message:`${command} WAS NOT RUN; manager instance ${instanceId} refused before effects, and re-resolution failed: ${error51 instanceof Error?error51.message:String(error51)}`}}}}return invokeCommand(nc,config2.space,service,command,args,invokeOpts)}return result};opts.signal?.addEventListener("abort",onAbort,{once:true});try{if(opts.follow)return await opts.follow(invoke,prepare);await connect3();service=await resolvePrepared();return await invoke()}finally{opts.signal?.removeEventListener("abort",onAbort);const control=nc;if(control)await drainAndClose(control,2e3)}}import{randomBytes as randomBytes4}from"node:crypto";var COMMAND_LIST_MS=1e4;var MAX_QUEUED_COMMANDS=8;var ENDED_COMMANDS_KEPT=32;var CommandRefused=class extends Error{code;constructor(code2,message){super(message);this.code=code2;this.name="CommandRefused"}};var B32="abcdefghijklmnopqrstuvwxyz234567";var refused=(code2,message)=>new EpEnvelopeError(code2,message,void 0,"not-executed");var what=c3=>`the ${c3.target} "${c3.name}"`;function cut(text3,max){const chars=[...text3];return chars.length<=max?text3:`${chars.slice(0,max-1).join("")}\u2026`}function fitText(text3,max){return typeof text3==="string"&&text3!==""?cut(text3,max):void 0}function within(work,ms){let timer2;const late=new Promise((_3,reject)=>{timer2=setTimeout(()=>reject(new Error(`no answer within ${ms/1e3} s`)),ms)});return Promise.race([Promise.resolve().then(work),late]).finally(()=>clearTimeout(timer2))}function createCommandLane(dispatcher,onQueued){const entries=new Map;const ended=[];let closed4=false;const queued=()=>[...entries.values()].filter(e3=>e3.state.kind==="queued");const known=id2=>{const e3=entries.get(id2);if(!e3)throw refused("not-found",`command ${id2} is not known to this agent`);return e3};function end(e3,state){e3.state=state;ended.push(e3.id);while(ended.length>ENDED_COMMANDS_KEPT)entries.delete(ended.shift())}async function list(){if(!dispatcher)return{supported:false};let listed;try{listed=await within(()=>dispatcher.list(),COMMAND_LIST_MS)}catch(e3){throw refused("unavailable",`the harness did not list its commands: ${e3.message}`)}if(!Array.isArray(listed))throw refused("internal","the connector's list is not an array");const commands=[];for(const e3 of listed){if(!isAgentCommandName(e3?.name))continue;if(!dispatcher.targets.has(e3.target))throw refused("internal",`the connector listed the ${String(e3.target)} "${e3.name}" but runs no ${String(e3.target)}s`);const description=fitText(e3.description,AGENT_COMMAND_DESCRIPTION_MAX),inputHint=fitText(e3.inputHint,AGENT_COMMAND_INPUT_HINT_MAX);commands.push({name:e3.name,target:e3.target,...description?{description}:{},...inputHint?{inputHint}:{}})}if(commands.length>AGENT_COMMAND_LIST_MAX)throw refused("resource-exhausted",`the harness lists ${commands.length} commands and skills, over the ${AGENT_COMMAND_LIST_MAX} a reply carries`);return{supported:true,commands}}function run(input){if(!dispatcher)throw refused("unimplemented","this agent's connector runs no commands or skills");if(!dispatcher.targets.has(input.target))throw refused("unimplemented",`this agent's connector runs no ${input.target}s`);if(closed4)throw refused("unavailable","this agent is stopping");if(queued().length>=MAX_QUEUED_COMMANDS)throw refused("resource-exhausted",`${MAX_QUEUED_COMMANDS} commands are already queued`);let id2;do id2=Array.from(randomBytes4(26),b3=>B32[b3&31]).join("");while(entries.has(id2));entries.set(id2,{id:id2,command:{target:input.target,name:input.name,args:input.args??""},state:{kind:"queued"}});onQueued();return{id:id2}}function cancel({id:id2}){const e3=known(id2);if(e3.state.kind==="queued")end(e3,{kind:"cancelled"});else if(e3.state.kind!=="cancelled")throw new EpEnvelopeError("conflict",`command ${id2} is ${e3.state.kind}, so it can no longer be cancelled`,[{kind:AGENT_COMMAND_STATE_DETAIL,state:e3.state}],"not-executed");return{state:e3.state}}return{handlers:[{command:"commands",contract:AGENT_CONTRACTS.commands,handler:()=>list()},{command:"command",contract:AGENT_CONTRACTS.command,handler:ctx=>run(ctx.request.args)},{command:"command-cancel",contract:AGENT_CONTRACTS["command-cancel"],handler:ctx=>cancel(ctx.request.args)},{command:"command-state",contract:AGENT_CONTRACTS["command-state"],handler:ctx=>({state:known(ctx.request.args.id).state})}],get queued(){return queued().length},async dispatchNext(){const e3=queued()[0];if(!e3)return"empty";e3.state={kind:"taken"};try{await dispatcher.dispatch(e3.command);end(e3,{kind:"started"});return"dispatched"}catch(err3){const message=String(err3?.message??err3);end(e3,err3 instanceof CommandRefused?{kind:"refused",code:err3.code,message:cut(message,AGENT_COMMAND_MESSAGE_MAX)}:{kind:"unknown",code:"internal",message:cut(`the harness failed, so ${what(e3.command)} may have started: ${message}`,AGENT_COMMAND_MESSAGE_MAX)});return"failed"}},close(){closed4=true;for(const e3 of queued())end(e3,{kind:"refused",code:"unavailable",message:`the agent stopped before ${what(e3.command)} started`})}}}import{randomBytes as randomBytes5}from"node:crypto";var PROMPT_DESK_MIN_MAX_PAYLOAD=524288;var PROMPT_SUMMARY_MAX_BYTES=4096;var PROMPT_ANSWER_REPLY_MS=1e4;var PROMPT_OPEN_MS=Object.freeze({min:1e3,max:7*24*60*60*1e3});var PROMPT_SETTLE_MS=Object.freeze({min:1e3,max:24*60*60*1e3});var PromptRefused=class extends Error{reason;constructor(reason,message){super(message);this.reason=reason;this.name="PromptRefused"}};var NONE={tie:"none"};function stepPrompt(state,event,at2){const close=(outcome,attempted)=>({kind:"move",next:{kind:"closed",at:at2,outcome},end:{attempted}});if(state.kind==="open"){switch(event.kind){case"accept":return{kind:"move",next:{kind:"sent",answer:event.answer,delivery:"unconfirmed"},deliver:true};case"settle":{const e3=event.evidence;if(e3.kind==="local")return close({kind:"local",seen:e3.seen},false);if(e3.kind==="observed")return close(e3.seen.tie==="prompt"?{kind:"local",seen:e3.seen}:{kind:"withdrawn",seen:e3.seen},false);if(e3.kind==="withdrawn")return close({kind:"withdrawn",seen:NONE},false);return{kind:"stay",warn:"a confirmation came for a prompt with no accepted answer"}}case"expiry":return close({kind:"expired"},false);case"close":return close({kind:"withdrawn",seen:NONE},false);case"delivery":return{kind:"stay",warn:"a delivery result came for a prompt with no deliver call"};case"settle-time":return{kind:"cannot-happen",why:"the settle time starts at the accepted answer"}}}if(state.kind==="sent"){const answer=state.answer;switch(event.kind){case"accept":return{kind:"never-reached",why:"an answer to a sent prompt meets check 3 or 4"};case"delivery":if(state.delivery==="delivered")return{kind:"cannot-happen",why:"deliver has one result"};if(event.result==="delivered")return{kind:"move",next:{kind:"sent",answer,delivery:"delivered"}};if(event.result==="confirmed")return close({kind:"answered",answer},true);if(event.result==="gone")return close({kind:"undelivered",answer},true);return{kind:"stay",warn:"deliver failed, which proves nothing about the hand-over"};case"settle":{const e3=event.evidence;if(e3.kind==="confirmed")return close({kind:"answered",answer},true);if(e3.kind==="local")return close({kind:"local",seen:e3.seen,late:answer},true);if(e3.kind==="observed")return close({kind:"unconfirmed",answer,seen:e3.seen},true);return close({kind:"unconfirmed",answer,seen:NONE},true)}case"expiry":return{kind:"stay"};case"settle-time":case"close":return close({kind:"unconfirmed",answer,seen:NONE},true)}}if(event.kind==="accept")return{kind:"never-reached",why:"an answer to a closed prompt meets check 3 or 4"};if(event.kind==="settle")return{kind:"stay",warn:"a report came for a closed prompt",report:true};return{kind:"stay"}}var iso=ms=>new Date(ms).toISOString();function describe(v3){try{if(v3 instanceof Error)return v3.message;const json2=JSON.stringify(v3);if(json2!==void 0)return json2.length>200?`${json2.slice(0,200)}...`:json2}catch{}try{return typeof v3==="bigint"?`${v3}n`:String(v3)}catch{return`a ${typeof v3} with no text form`}}function ignoreRejection(v3){try{const then=v3?.then;if(typeof then!=="function")return false;then.call(v3,void 0,()=>{})}catch{}return true}function deliveryKind(d2){try{return d2?.kind}catch{return void 0}}var B322="abcdefghijklmnopqrstuvwxyz234567";var EFFECTS=new Set(["proceed","refuse","cancel"]);function deepFreeze6(value){if(value!==null&&typeof value==="object"&&!Object.isFrozen(value)){for(const child of Object.values(value))deepFreeze6(child);Object.freeze(value)}return value}function timer(ms,fn2){const t2=setTimeout(fn2,ms);t2.unref();return t2}function refused2(code2,message,details){return new EpEnvelopeError(code2,message,details,"not-executed")}function parseSeen(s3){const o3=s3;if(o3&&typeof o3==="object"&&!Array.isArray(o3)){const keys=Object.keys(o3).length;if(o3.tie==="none"&&keys===1)return{tie:"none"};if((o3.tie==="prompt"||o3.tie==="subject")&&keys===2&&EFFECTS.has(o3.effect))return{tie:o3.tie,effect:o3.effect}}throw new TypeError(`settle: ${describe(s3)} is not a sighting ({ tie: "prompt" | "subject", effect } or { tie: "none" })`)}function parseEvidence(e3){const o3=e3;if(o3&&typeof o3==="object"&&!Array.isArray(o3)){const keys=Object.keys(o3).length;if((o3.kind==="confirmed"||o3.kind==="withdrawn")&&keys===1)return{kind:o3.kind};if((o3.kind==="local"||o3.kind==="observed")&&keys===2)return{kind:o3.kind,seen:parseSeen(o3.seen)}}throw new TypeError(`settle: ${describe(e3)} is not an Evidence`)}var LONGEST_BY=Object.freeze({id:`${"w".repeat(64)}.${"w".repeat(64)}`,uid:"w".repeat(32),authority:"owner"});var ANY_AT="2000-01-01T00:00:00.000Z";var LONGEST_SEEN=Object.freeze({tie:"subject",effect:"proceed"});function largestSummaryBytes(base,options){let max=0;const measure=state=>{max=Math.max(max,Buffer.byteLength(JSON.stringify({...base,state})))};const closed4=outcome=>({kind:"closed",at:ANY_AT,outcome});measure({kind:"open"});measure(closed4({kind:"expired"}));measure(closed4({kind:"withdrawn",seen:LONGEST_SEEN}));measure(closed4({kind:"local",seen:LONGEST_SEEN}));for(const o3 of options){const answer={by:LONGEST_BY,option:o3.id,effect:o3.effect,at:ANY_AT};measure({kind:"sent",answer,delivery:"unconfirmed"});measure({kind:"sent",answer,delivery:"delivered"});measure(closed4({kind:"answered",answer}));measure(closed4({kind:"unconfirmed",answer,seen:LONGEST_SEEN}));measure(closed4({kind:"undelivered",answer}));measure(closed4({kind:"local",seen:LONGEST_SEEN,late:answer}))}return max}var Desk=class{ep;held=new Map;closedOrder=[];live=0;seq=0;stepping=false;later=[];presenceOwed=false;serving=false;closed=false;warn;constructor(ep,warn){this.ep=ep;this.warn=msg=>{try{warn(msg)}catch{}}}get waiting(){return this.live}handlers(){return[{command:"prompts",contract:AGENT_CONTRACTS.prompts,handler:ctx=>this.list(ctx)},{command:"prompt",contract:AGENT_CONTRACTS.prompt,handler:ctx=>this.read(ctx)},{command:"prompt-answer",contract:AGENT_CONTRACTS["prompt-answer"],handler:ctx=>this.answer(ctx)}]}served(ready){this.seq=this.ep.nextPromptsSeq();this.serving=true;ready.then(()=>{this.presenceOwed=true;this.flushPresence()},()=>{})}close(){if(this.closed)return;this.closed=true;this.defer(()=>{for(const h3 of[...this.held.values()])if(h3.state.kind!=="closed")this.apply(h3,{kind:"close"})})}open(spec,hooks){if(this.closed)throw new PromptRefused("closed","the prompt desk has closed; the harness answers this dialog");const invalid2=why=>new PromptRefused("invalid",why);if(!spec||typeof spec!=="object")throw invalid2("a prompt spec is an object");if(!hooks||typeof hooks.deliver!=="function"||typeof hooks.end!=="function"||hooks.check!==void 0&&typeof hooks.check!=="function")throw invalid2("hooks need deliver and end, and check when given, as functions");for(const[name2,value,range]of[["openMs",spec.openMs,PROMPT_OPEN_MS],["settleMs",spec.settleMs,PROMPT_SETTLE_MS]])if(!Number.isSafeInteger(value)||value<range.min||value>range.max)throw invalid2(`${name2} must be an integer from ${range.min} to ${range.max} ms, not ${String(value)}`);let canonical;try{canonical=canonicalJson(spec.content)}catch(e3){throw invalid2(`the content is not interchangeable JSON: ${describe(e3)}`)}const contentBytes=Buffer.byteLength(canonical);if(contentBytes>AGENT_PROMPT_CONTENT_MAX_BYTES)throw new PromptRefused("too-large",`the canonical content is ${contentBytes} bytes, over ${AGENT_PROMPT_CONTENT_MAX_BYTES}`);const content=deepFreeze6(JSON.parse(canonical));let id2;do id2=Array.from(randomBytes5(26),b3=>B322[b3&31]).join("");while(this.held.has(id2));const digest=agentPromptDigest(content);const now=Date.now();const openedAt=iso(now),expiresAtMs=now+spec.openMs,expiresAt=iso(expiresAtMs);const validate2=AGENT_CONTRACTS.prompt.output.validate;if(!validate2({prompt:{id:id2,digest,openedAt,expiresAt,state:{kind:"open"},content}})){const first=validate2.errors?.[0];throw invalid2(`the content does not match the prompt schema: ${first?`${first.instancePath||"/"} ${first.message}`:"invalid"}`)}const options=new Map;for(const o3 of content.options){if(options.has(o3.id))throw invalid2(`option id "${o3.id}" is used twice`);options.set(o3.id,o3);if(o3.form==="required"&&content.form===void 0)throw invalid2(`option "${o3.id}" submits a form, and the content has none`)}if(content.form!==void 0&&!content.options.some(o3=>o3.form==="required"))throw invalid2("the content has a form, and no option submits it");const input=content.subject?.type==="tool"?content.subject.input:void 0;if(input?.kind==="omitted"&&content.options.some(o3=>o3.effect==="proceed"))throw invalid2("a tool input that is omitted can be refused remotely, never approved: no option may proceed");let form;if(content.form!==void 0){const schema=content.form.schema;for(const name2 of schema.required??[])if(!Object.hasOwn(schema.properties,name2))throw invalid2(`form.schema.required names "${name2}", which is not a property`);try{form=compileContractSchema({root:{...schema,additionalProperties:false}})}catch(e3){throw invalid2(`form.schema does not compile: ${describe(e3)}`)}}const base={id:id2,digest,openedAt,expiresAt,kind:content.kind,title:content.title,contentBytes,...content.source!==void 0?{source:content.source}:{}};const largest=largestSummaryBytes(base,content.options);if(largest>PROMPT_SUMMARY_MAX_BYTES)throw new PromptRefused("too-large",`the summary encodes to ${largest} bytes in its largest state, over ${PROMPT_SUMMARY_MAX_BYTES}`);if(this.live>=AGENT_PROMPT_LIST_MAX)throw new PromptRefused("full",`${AGENT_PROMPT_LIST_MAX} prompts are open or sent`);const h3={id:id2,hooks,settleMs:spec.settleMs,expiresAtMs,base:deepFreeze6(base),live:{content,options,...form?{form}:{}},state:deepFreeze6({kind:"open"}),reports:0,ended:false,waiters:new Set};this.held.set(id2,h3);this.live++;this.bump();h3.expiry=timer(Math.max(0,expiresAtMs-Date.now()),()=>this.expire(h3));if(!this.stepping)this.flushPresence();return Object.freeze({id:id2,settle:evidence=>{const e3=parseEvidence(evidence);this.defer(()=>this.apply(h3,{kind:"settle",evidence:e3}))}})}expire(h3){const left=h3.expiresAtMs-Date.now();if(left>0){h3.expiry=timer(left,()=>this.expire(h3));return}this.defer(()=>this.apply(h3,{kind:"expiry"}))}settleTime(h3){const left=h3.settleAtMs-Date.now();if(left>0){h3.settle=timer(left,()=>this.settleTime(h3));return}this.defer(()=>this.apply(h3,{kind:"settle-time"}))}run(fn2){if(this.stepping)throw new Error("prompt desk: a step started inside another step");this.stepping=true;try{return fn2()}finally{try{for(let next=this.later.shift();next;next=this.later.shift())next()}finally{this.stepping=false;this.flushPresence()}}}defer(fn2){if(this.stepping)this.later.push(fn2);else this.run(fn2)}apply(h3,event,why){const step=stepPrompt(h3.state,event,iso(Date.now()));if(step.kind==="cannot-happen"||step.kind==="never-reached"){this.warn(`prompt desk bug: event ${event.kind} met prompt ${h3.id} in state ${h3.state.kind}, a row that ${step.kind==="cannot-happen"?"cannot happen":"is never reached"}: ${step.why}`);return}if(step.kind==="stay"){if(step.report)this.warn(`prompt ${h3.id} is closed, so a "${event.evidence.kind}" report is ignored (${++h3.reports} so far)`);else if(step.warn)this.warn(`prompt ${h3.id}: ${step.warn}${why?`: ${why}`:""}`);if(event.kind==="delivery"&&event.result==="failed")this.answerWaiters(h3);return}h3.state=deepFreeze6(step.next);this.bump();if(h3.state.kind==="closed")this.retire(h3);if(!(h3.state.kind==="sent"&&h3.state.delivery==="unconfirmed"))this.answerWaiters(h3);if(step.end)this.end(h3,step.end.attempted)}answerWaiters(h3){for(const w2 of h3.waiters){clearTimeout(w2.timer);w2.resolve(h3.state)}h3.waiters.clear()}retire(h3){clearTimeout(h3.expiry);clearTimeout(h3.settle);h3.live=void 0;this.live--;this.closedOrder.push(h3.id);while(this.closedOrder.length>AGENT_PROMPT_LIST_MAX)this.held.delete(this.closedOrder.shift())}end(h3,attempted){if(h3.ended){this.warn(`prompt desk bug: prompt ${h3.id} ended twice`);return}h3.ended=true;const hooks=h3.hooks;h3.hooks=void 0;try{ignoreRejection(hooks.end({attempted}))}catch(e3){this.warn(`prompt ${h3.id}: the adapter's end threw: ${describe(e3)}`)}}bump(){this.seq=this.ep.nextPromptsSeq();this.presenceOwed=true}flushPresence(){if(!this.presenceOwed||this.closed||!this.serving)return;this.presenceOwed=false;this.ep.setPromptsPresence({open:this.live,seq:this.seq}).catch(e3=>{if(!this.closed)this.warn(`the prompts presence field was not written: ${describe(e3)}`)})}fit(ctx,data){if(ctx.replyFits(data,Number.MAX_SAFE_INTEGER))return data;const bytes=Buffer.byteLength(JSON.stringify({v:1,id:ctx.request.id,ok:true,data}));const limit=this.ep.maxPayload;throw refused2("resource-exhausted",`the reply is ${bytes} bytes, over this connection's max_payload of ${limit}`,[{kind:AGENT_PROMPT_SIZE_DETAIL,bytes,limit}])}summary(h3){return{...h3.base,state:h3.state}}list(ctx){const open7=[];for(const h3 of this.held.values())if(h3.state.kind!=="closed")open7.push(this.summary(h3));const closed4=this.closedOrder.map(id2=>this.summary(this.held.get(id2)));const runtime={id:ctx.principal.runtimeId,startedAt:processRuntime(ctx.principal.uid).startedAt};return this.fit(ctx,{runtime,seq:this.seq,open:open7,closed:closed4})}read(ctx){const{id:id2}=ctx.request.args;const h3=this.held.get(id2);if(h3===void 0)throw refused2("not-found",`prompt ${id2} is not known to this runtime`);if(h3.live===void 0)throw refused2("failed-precondition",`prompt ${id2} is closed`,[{kind:AGENT_PROMPT_STATE_DETAIL,state:h3.state}]);const{digest,openedAt,expiresAt}=h3.base;return this.fit(ctx,{prompt:{id:id2,digest,openedAt,expiresAt,state:h3.state,content:h3.live.content}})}answer(ctx){const got=this.run(()=>this.decide(ctx));return got instanceof Promise?got.then(state=>({state})):{state:got}}decide(ctx){const a3=ctx.request.args;try{canonicalJson(a3)}catch(e3){throw refused2("bad-request",`the answer is not interchangeable JSON: ${describe(e3)}`)}if(ctx.caller.owner===ctx.principal.owner&&ctx.caller.actor===ctx.principal.actor)throw refused2("permission-denied","an agent never answers its own prompt");const h3=this.held.get(a3.id);if(h3===void 0)throw refused2("not-found",`prompt ${a3.id} is not known to this runtime`);const fingerprint=answerFingerprint(a3,ctx.caller);if(h3.fingerprint===fingerprint)return h3.state;if(h3.state.kind!=="open"||h3.live===void 0)throw refused2("conflict",`prompt ${a3.id} is not open`,[{kind:AGENT_PROMPT_STATE_DETAIL,state:h3.state}]);if(a3.digest!==h3.base.digest)throw refused2("failed-precondition",`the digest is not prompt ${a3.id}'s`,[{kind:AGENT_PROMPT_DIGEST_DETAIL,digest:h3.base.digest}]);const option=h3.live.options.get(a3.option);if(option===void 0)throw refused2("bad-request",`option "${a3.option}" is not one of the prompt's`);if(option.note==="required"&&(a3.note===void 0||a3.note===""))throw refused2("bad-request",`option "${option.id}" needs a note`);if(option.note===void 0&&a3.note!==void 0)throw refused2("bad-request",`option "${option.id}" takes no note`);if(option.form==="required"&&a3.values===void 0)throw refused2("bad-request",`option "${option.id}" submits the form and needs values`);if(option.form===void 0&&a3.values!==void 0)throw refused2("bad-request",`option "${option.id}" takes no values`);if(a3.values!==void 0&&!h3.live.form(a3.values)){const first=h3.live.form.errors?.[0];throw refused2("bad-request",`the values do not match the form: ${first?`${first.instancePath||"/"} ${first.message}`:"invalid"}`)}const by={id:`${ctx.caller.owner}.${ctx.caller.actor}`,uid:ctx.caller.uid,authority:ctx.authority};const verdict=deepFreeze6({option:option.id,...a3.note!==void 0?{note:a3.note}:{},...a3.values!==void 0?{values:structuredClone(a3.values)}:{},by});let refusal;try{refusal=h3.hooks.check?.(verdict)}catch(e3){this.warn(`prompt ${h3.id}: the adapter's check threw: ${describe(e3)}`);throw refused2("internal",`the agent could not check this answer: ${describe(e3)}`)}if(refusal!==void 0){if(typeof refusal!=="string"){this.warn(`prompt ${h3.id}: the adapter's check returned ${ignoreRejection(refusal)?"a promise, and check is synchronous":`${typeof refusal}, not a message or undefined`}`);throw refused2("internal","the agent could not check this answer")}throw refused2("bad-request",refusal||"the agent refused this answer")}if(Date.now()>=h3.expiresAtMs)throw refused2("expired",`prompt ${h3.id} expired at ${h3.base.expiresAt}`);const acceptedAt=Date.now();const answer={by,option:option.id,effect:option.effect,at:iso(acceptedAt)};const step=stepPrompt(h3.state,{kind:"accept",answer},answer.at);if(step.kind!=="move"||!step.deliver)throw refused2("internal","prompt desk bug: an open prompt did not accept");h3.state=deepFreeze6(step.next);h3.fingerprint=fingerprint;this.bump();h3.settleAtMs=acceptedAt+h3.settleMs;h3.settle=timer(h3.settleMs,()=>this.settleTime(h3));const wait=new Promise(resolve6=>{const w2={resolve:resolve6,timer:timer(PROMPT_ANSWER_REPLY_MS,()=>this.defer(()=>{if(h3.waiters.delete(w2))resolve6(h3.state)}))};h3.waiters.add(w2)});this.deliver(h3,verdict);return wait}deliver(h3,verdict){let result;try{result=Promise.resolve(h3.hooks.deliver(verdict))}catch(e3){result=Promise.reject(e3)}const failed=why=>this.defer(()=>this.apply(h3,{kind:"delivery",result:"failed"},why));result.then(d2=>{const kind=deliveryKind(d2);if(kind==="confirmed"||kind==="delivered"||kind==="gone")this.defer(()=>this.apply(h3,{kind:"delivery",result:kind}));else failed(`deliver resolved with ${describe(d2)}, which is not a Delivery`)},e3=>failed(describe(e3))).catch(e3=>this.warn(`prompt desk bug: applying prompt ${h3.id}'s delivery result threw: ${describe(e3)}`))}};function answerFingerprint(a3,caller){return contractDigest({id:a3.id,digest:a3.digest,option:a3.option,note:a3.note??null,values:a3.values??null,caller:`${caller.owner}.${caller.actor}.${caller.uid}`})}function createPromptDesk(ep,warn){return new Desk(ep,warn)}async function openAgentEndpoint(ep,opts){if(typeof opts?.warn!=="function")throw new TypeError("openAgentEndpoint needs opts.warn");const max=ep.maxPayload;if(max<PROMPT_DESK_MIN_MAX_PAYLOAD)throw new Error(`the agent endpoint needs a connection whose max_payload is at least ${PROMPT_DESK_MIN_MAX_PAYLOAD} bytes, and this one is ${max}`);const warn=msg=>{try{opts.warn(msg)}catch{}};const desk=createPromptDesk(ep,warn);const lane=createCommandLane(opts.dispatcher,opts.onQueued??(()=>{}));const serve=ep.servePrincipal({handlers:[...desk.handlers(),...lane.handlers]});desk.served(serve.ready);let closing;const close=()=>closing??=(()=>{ep.off("transport",onTransport);desk.close();lane.close();return serve.stop()})();const onTransport=t2=>{if(!t2.connected||closing)return;let now;try{now=ep.maxPayload}catch{return}if(now>=PROMPT_DESK_MIN_MAX_PAYLOAD)return;warn(`the agent endpoint closed: the connection's max_payload is ${now} bytes, under the ${PROMPT_DESK_MIN_MAX_PAYLOAD} its largest replies need`);void close()};ep.on("transport",onTransport);void serve.failed.then(err3=>{if(closing)return;warn(`the agent endpoint closed: ${err3.message}`);void close()});try{await serve.ready}catch(e3){void close();throw e3}return{prompts:desk,commands:lane,close}}import{randomUUID as randomUUID11}from"node:crypto";import{createHash as createHash9}from"node:crypto";var CHANNEL_CATCHUP_AGE_MS=5*6e4;function afterRecallMark(a3,b3){return a3.ts!==b3.ts?a3.ts>b3.ts:a3.id>b3.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;function deliveryNoticeOf(m2){for(const p2 of m2.parts){if(p2.kind!=="data"||typeof p2.data!=="object"||p2.data===null||Array.isArray(p2.data))continue;if(ANYCAST_NOTICE_KEY in p2.data)return"anycast";if(MENTION_NOTICE_KEY in p2.data)return"mention"}return void 0}function idlessDigest(m2){return createHash9("sha256").update(JSON.stringify(m2)).digest("base64url")}function handOver(item){item.handedOverAt??=item.deliveryCount??0}function ingestDedupKey(id2){return id2===""?void 0:id2}var AgentInbox=class{deps;constructor(deps){this.deps=deps}get ep(){return this.deps.endpoint()}get config(){return this.deps.config()}get _transportConnected(){return this.deps.transportConnected()}emit(event,item){this.deps.emit(event,item)}handleEndpointWarning(error51){this.deps.warning(error51)}noteDirected(item){this.deps.noteDirected(item)}inOrder(write){return this.deps.inOrder(write)}requireConnected(){return this.deps.requireConnected()}seedChannelModes(config2){for(const c3 of config2.quiet??[])this.channelModes.set(c3,"quiet");for(const c3 of config2.muted??[])this.channelModes.set(c3,"muted")}onTransport(connected){if(!connected){this.transportDrops++;for(const p2 of this.inbox.filter(x2=>x2.take&&!this.inFlightIds.has(x2.item.recvKey)))this.regate(p2)}if(connected&&this.mayAskTakes()){this.dropLapsedTakes();for(const p2 of this.gated)if(p2.taking===void 0)this.emit("incoming",p2.item)}}stop(){for(const key of[...this.renewals.keys()])this.stopRenewal(key);clearTimeout(this.takeRetry);this.takeRetry=void 0}inbox=[];gated=[];arrivals=0;heldTake;takeRetry;handledIds=new Set;handledIdsPrev=new Set;evictedClassifications=new Map;inFlightIds=new Map;lowerOnRelease=new Set;renewals=new Map;classificationUnsafe=false;protectedPullOnlyIds=new Set;protectedDropIds=new Set;dropUnsafe=false;_lastInboxDrainedAt;_lastAutomaticDrainedAt;_lastAutomaticHeadDrainedAt;_attention="open";_recallCursor={ts:0,id:""};aheadDelivered=new Set;channelModes=new Map;focusSince;enteringFocus=false;recvKeySecret=randomUUID11().replace(/-/g,"");recvKeySeq=0;focusExcludedIds=new Map;focusIdless=new Map;focusIdlessEntries=0;idlessEpoch=0;recallLock=Promise.resolve();transportDrops=0;focusRecallUnsafeChannels=new Set;get lastInboxDrainedAt(){return this._lastInboxDrainedAt}get lastAutomaticDrainedAt(){return this._lastAutomaticDrainedAt}get lastAutomaticHeadDrainedAt(){return this._lastAutomaticHeadDrainedAt}oldestAutomaticKey(){let head;for(const pending of this.inbox){if(pending.pullOnly)continue;if(head===void 0||pending.receivedAt<head.receivedAt)head=pending}return head?.item.recvKey}noteAutomaticHeadProgress(selected){const head=this.oldestAutomaticKey();if(head===void 0)return;if(selected.some(p2=>!p2.pullOnly&&p2.item.recvKey===head))this._lastAutomaticHeadDrainedAt=Date.now()}automaticQueueStalledForMs(now=Date.now()){const oldest=this.oldestAutomaticReceivedAt();if(oldest===void 0)return void 0;const since=Math.max(oldest,this._lastAutomaticHeadDrainedAt??0);const held2=now-since;return held2>0?held2:0}get channelDeliveryIssue(){return this.dropUnsafe?"Channel drop tracking exhausted. Ambient channel traffic is suppressed until restart; non-historical mentions on unmuted channels wake to pull their buffered body. Focus recall may be incomplete.":void 0}async ingestNotice(m2,delivery,meta3,notice){const holder=await this.ep.deliveryLeaseHolder(0);this.ingest(m2,delivery,meta3,holder!==void 0&&holder===m2.from.id?notice:void 0)}ingest(m2,delivery,meta3,notice){const key=ingestDedupKey(m2.id);if(key!==void 0&&(this.handledIds.has(key)||this.handledIdsPrev.has(key))){if(delivery.durable)delivery.ack();return}if(key!==void 0&&(this.protectedPullOnlyIds.has(key)||this.protectedDropIds.has(key))){if(delivery.durable)delivery.ack();return}const existing=key===void 0?void 0:this.inbox.find(p2=>p2.item.id===key)??this.gated.find(p2=>p2.item.id===key);if(existing){if(delivery.durable){existing.ack=delivery.ack;this.own(existing,delivery.redelivery);if(delivery.take)existing.take=delivery.take;if(this.inFlightIds.has(existing.item.recvKey))this.keepOwned(existing.item.recvKey);else if(existing.take&&existing.takenCount!==existing.item.deliveryCount)this.regate(existing);this.emit("incoming",existing.item)}return}if(!meta3)throw new Error(`message ${m2.id} delivered without MessageMeta \u2014 its class is unauthenticated`);const historical=meta3.historical||meta3.kind==="channel"&&delivery.durable&&Date.now()-m2.ts>CHANNEL_CATCHUP_AGE_MS;const item=this.toInboxItem(m2,meta3.kind,historical);if(notice)item.notice=notice;else if(!delivery.take)this.noteDirected(item);if(item.kind==="channel"){const cm=this.channelModes.get(item.channel??"");const digest=item.id===""&&(this.enteringFocus||this._attention==="focus")?idlessDigest(m2):void 0;const tally=digest===void 0?void 0:this.reserveIdless(digest,item.channel??"");const copy2=tally?this.settleIdless(tally):void 0;const idless=copy2&&{digest,copy:copy2};if(this.enteringFocus)this.excludeFromFocus(item);if(this.dropUnsafe){this.excludeFromFocus(item);if(cm!=="muted"&&item.mentionsMe&&!item.historical){this.buffer(item,delivery,true,idless);this.emit("mention-wake",item)}else delivery.ack();return}if(cm==="muted"){this.evictedClassifications.delete(item.id);this.excludeFromFocus(item);this.protectDisposition(item.id,"drop");delivery.ack();return}const remembered=item.id===""?void 0:this.evictedClassifications.get(item.id);if(remembered)this.evictedClassifications.delete(item.id);const snapshottedPullOnly=item.historical||!item.mentionsMe&&(remembered?.pullOnly??cm==="quiet");if(cm==="quiet"||snapshottedPullOnly)this.excludeFromFocus(item);if(this._attention==="focus"&&item.mentionsMe&&!item.historical&&this.focusRecallUnsafeChannels.has(item.channel??"")){this.excludeFromFocus(item);this.buffer(item,delivery,true,idless);this.emit("mention-wake",item);return}if(cm!=="quiet"&&!snapshottedPullOnly&&this._attention==="focus"){this.protectDisposition(item.id,"drop");delivery.ack();if(item.id==="")this.buffer(item,{ack:()=>{}},true,idless);if(item.mentionsMe)this.emit("mention-wake",item);return}const automaticReply=this.config.channelRepliesPullOnly===true&&!!item.replyTo;const pullOnly=snapshottedPullOnly||!item.mentionsMe&&(automaticReply||this.classificationUnsafe);if(pullOnly)this.excludeFromFocus(item);this.buffer(item,delivery,pullOnly,idless);return}this.buffer(item,delivery,false)}buffer(item,delivery,pullOnly,idless){const pending={item,ack:delivery.ack,pullOnly,receivedAt:Date.now(),arrival:this.arrivals++};this.own(pending,delivery.redelivery);if(idless)pending.idless={tally:this.focusIdless,...idless};if(delivery.take){pending.take=delivery.take;this.gated.push(pending);if(this.gated.length>MAX_INBOX)this.gated.shift();this.emit("incoming",item);return}this.admit(pending);this.emit("incoming",item)}admit(pending){let at2=this.inbox.length;while(at2>0&&this.inbox[at2-1].arrival>pending.arrival)at2--;this.inbox.splice(at2,0,pending);if(this.inbox.length>MAX_INBOX){let excess=this.inbox.length-MAX_INBOX;while(excess-- >0){const evictable=p2=>!this.inFlightIds.has(p2.item.recvKey);let index2=this.inbox.findIndex(p2=>p2.pullOnly&&evictable(p2));if(index2<0)index2=this.inbox.findIndex(p2=>p2.item.kind==="channel"&&evictable(p2));if(index2<0)index2=this.inbox.findIndex(evictable);if(index2<0)break;const[evicted]=this.inbox.splice(index2,1);const sacrificingDirected=evicted.item.kind!=="channel";this.rememberEvicted(evicted);if(evicted.idless?.tally===this.focusIdless)this.unsettleIdless(evicted.idless.digest,evicted.idless.copy);if(!sacrificingDirected)evicted.ack()}}}rememberEvicted(p2){if(p2.item.kind!=="channel"||p2.item.mentionsMe||!p2.item.channel)return;if(p2.item.id==="")return;if(this.classificationUnsafe)return;if(!this.evictedClassifications.has(p2.item.id)&&this.evictedClassifications.size>=CLASSIFICATION_CAP){this.classificationUnsafe=true;this.evictedClassifications.clear();return}this.evictedClassifications.set(p2.item.id,{pullOnly:p2.pullOnly,channel:p2.item.channel})}excludeFromFocus(item){if(!this.enteringFocus&&this._attention!=="focus"||item.kind!=="channel"||!item.channel)return;if(item.id==="")return;if(!this.focusExcludedIds.has(item.id)&&this.focusExcludedIds.size>=FOCUS_EXCLUSION_CAP){const oldest=this.focusExcludedIds.entries().next().value;if(oldest){this.focusExcludedIds.delete(oldest[0]);this.focusRecallUnsafeChannels.add(oldest[1])}}this.focusExcludedIds.set(item.id,item.channel)}reserveIdless(digest,channel){if(this.focusIdlessEntries>=FOCUS_EXCLUSION_CAP){this.focusRecallUnsafeChannels.add(channel);return void 0}let tally=this.focusIdless.get(digest);if(!tally)this.focusIdless.set(digest,tally={channel,unbound:[],bound:new Set});this.focusIdlessEntries++;return tally}settleIdless(tally){const episode=this.focusIdless;const drops=this.transportDrops;const unbounded=()=>{if(episode===this.focusIdless)this.focusRecallUnsafeChannels.add(tally.channel)};const copy2={epoch:this.idlessEpoch,ready:Promise.resolve()};copy2.ready=this.ep.chatFrontier().then(frontier=>{if(drops===this.transportDrops)copy2.frontier=frontier;else unbounded()},unbounded);tally.unbound.push(copy2);return copy2}dropEmptyIdless(digest,tally){if(!tally.unbound.length&&!tally.bound.size)this.focusIdless.delete(digest)}unsettleIdless(digest,copy2){const tally=this.focusIdless.get(digest);if(!tally)return;if(tally.unbound.includes(copy2)){copy2.evicted=true;return}if(copy2.seq===void 0||!tally.bound.delete(copy2.seq))return;this.focusIdlessEntries--;this.dropEmptyIdless(digest,tally)}settleIdlessRead(channel,epoch,retained){for(const[digest,tally]of this.focusIdless){if(tally.channel!==channel)continue;const before=tally.unbound.length+tally.bound.size;tally.unbound=tally.unbound.filter(c3=>c3.epoch>=epoch);for(const seq of tally.bound)if(!retained.has(seq))tally.bound.delete(seq);this.focusIdlessEntries-=before-tally.unbound.length-tally.bound.size;this.dropEmptyIdless(digest,tally)}}async idlessReady(tallies,channel){const reads=[];for(const tally of tallies.values())if(tally.channel===channel)for(const c3 of tally.unbound)reads.push(c3.ready);await Promise.all(reads)}bindIdless(tally,epoch,free){let bound=Infinity;for(let i2=tally.unbound.length-1;i2>=0;i2--){const copy2=tally.unbound[i2];if(copy2.frontier===void 0)continue;bound=Math.min(bound,copy2.frontier);if(copy2.epoch>=epoch)continue;let at2=free.length-1;while(at2>=0&&free[at2]>bound)at2--;if(at2<0)continue;const[seq]=free.splice(at2,1);tally.unbound.splice(i2,1);if(copy2.evicted){this.focusIdlessEntries--;continue}copy2.seq=seq;tally.bound.add(seq)}}idlessUnsure(tally,epoch,seq){if(!tally||tally.bound.has(seq))return false;return tally.unbound.some(c3=>c3.epoch>=epoch&&c3.frontier!==void 0&&c3.frontier>=seq)}protectDisposition(id2,disposition){if(id2==="")return;const ids=disposition==="drop"?this.protectedDropIds:this.protectedPullOnlyIds;if((disposition==="drop"?this.dropUnsafe:this.classificationUnsafe)||ids.has(id2))return;if(ids.size>=PROTECTED_DISPOSITION_CAP){if(disposition==="drop")this.dropUnsafe=true;else this.classificationUnsafe=true;if(disposition!=="drop")ids.clear();return}ids.add(id2)}toInboxItem(m2,kind,historical){const text3=partsToText(m2.parts);return{id:m2.id,recvKey:m2.id!==""?m2.id:`${this.recvKeySecret}.${++this.recvKeySeq}`,ts:m2.ts,fromId:m2.from.id,fromName:m2.from.name,fromRole:m2.from.role,kind,channel:m2.channel,service:m2.toService,mentions:m2.mentions,mentionsMe:m2.mentions?.includes(this.config.name.toLowerCase())??false,historical,text:text3,replyTo:m2.replyTo,contextId:m2.contextId}}peekInbox(scope="all"){this.dropLapsedTakes();return this.inbox.filter(p2=>this.inScope(p2,scope)).map(p2=>p2.item)}inboxPreview(scope="all"){this.dropLapsedTakes();const askable=scope==="pull-only"?[]:this.gated.filter(p2=>this.mayOffer(p2));return[...this.inbox.filter(p2=>this.inScope(p2,scope)),...askable].sort((a3,b3)=>a3.arrival-b3.arrival).map(p2=>p2.item)}async takeChosen(scope,choose,waitMs=TAKE_WAIT_MS){const chosen=choose(this.inboxPreview(scope));const keys=new Set(chosen.map(i2=>i2.recvKey));const asked=scope==="pull-only"?[]:this.gated.filter(p2=>keys.has(p2.item.recvKey)&&this.mayOffer(p2));for(const p2 of asked)p2.awaited=(p2.awaited??0)+1;const runs=asked.map(p2=>p2.taking!==void 0&&p2.takingDrops===this.transportDrops?p2.taking:this.startTake(p2));if(runs.length){let timer2;const waited=new Promise(resolve6=>{timer2=setTimeout(resolve6,waitMs);timer2.unref?.()});await Promise.race([Promise.allSettled(runs),waited]);clearTimeout(timer2)}for(const p2 of asked)p2.awaited=(p2.awaited??1)-1;const showable=new Map(this.peekInbox(scope).map(i2=>[i2.recvKey,i2]));const shown=chosen.flatMap(i2=>showable.get(i2.recvKey)??[]);for(const i2 of shown)handOver(i2);return shown}heldTakes(){const count=this.gated.filter(p2=>p2.taking===void 0).length;const waiting=this.gated.filter(p2=>p2.taking!==void 0&&p2.takingDrops===this.transportDrops).length;if(waiting)return{count:waiting+(this.heldTake?count:0),detail:"the delivery daemon has not answered the take yet"};return count&&this.heldTake?{count,detail:this.heldTake.detail}:{count}}mayAskTakes(){return this._transportConnected&&(!this.heldTake||Date.now()>=this.heldTake.retryAt)}mayOffer(p2){return p2.taking!==void 0&&this._transportConnected||this.mayAskTakes()}startTake(p2){const run=this.runTake(p2).catch(e3=>this.handleEndpointWarning(e3)).finally(()=>{if(p2.taking===run)p2.taking=void 0});p2.taking=run;p2.takingDrops=this.transportDrops;return run}async runTake(p2){const take=p2.take;if(!take)return;if(!this._transportConnected)return;if(!this.renewOwned(p2)){this.dropGated(p2);return}const count=p2.item.deliveryCount;const drops=this.transportDrops;const outcome=await take();if(!this.gated.includes(p2)||p2.take!==take)return;if(this.transportDrops!==drops){if(p2.takingDrops!==drops)return;if(this._transportConnected)this.emit("incoming",p2.item);return}if(outcome.taken){this.heldTake=void 0;const current=p2.item.deliveryCount===count&&p2.ownedUntil!==void 0&&Date.now()<p2.ownedUntil;if(!current)return;p2.takenCount=count;p2.takenOnce=true;this.gated.splice(this.gated.indexOf(p2),1);this.noteDirected(p2.item);this.admit(p2);if(!p2.awaited)this.emit("incoming",p2.item);return}if(outcome.drop){this.dropGated(p2);return}const first=this.heldTake?.reason!==outcome.reason;this.heldTake={reason:outcome.reason,detail:outcome.detail,retryAt:Date.now()+TAKE_RETRY_MS};this.takeRetry??=setTimeout(()=>{this.takeRetry=void 0;for(const held2 of this.gated)this.emit("incoming",held2.item)},TAKE_RETRY_MS);this.takeRetry.unref?.();if(first&&outcome.reason!=="daemon-busy")this.handleEndpointWarning(new Error(outcome.detail))}dropGated(p2){const i2=this.gated.indexOf(p2);if(i2>=0)this.gated.splice(i2,1)}regate(p2){const i2=this.inbox.indexOf(p2);if(i2<0)return;this.inbox.splice(i2,1);p2.takenCount=void 0;this.gated.push(p2)}dropLapsedTakes(){const now=Date.now();this.inbox=this.inbox.filter(p2=>!p2.take||this.inFlightIds.has(p2.item.recvKey)||p2.ownedUntil!==void 0&&now<p2.ownedUntil);this.gated=this.gated.filter(p2=>p2.taking!==void 0||p2.ownedUntil===void 0||now<p2.ownedUntil)}holdInFlight(ids){let fresh=0;for(const id2 of ids)if(!this.inFlightIds.has(id2))fresh++;if(this.inFlightIds.size+fresh>MAX_IN_FLIGHT)return false;for(const id2 of ids){this.inFlightIds.set(id2,(this.inFlightIds.get(id2)??0)+1);this.keepOwned(id2)}const held2=new Set(ids);for(const p2 of this.inbox)if(held2.has(p2.item.recvKey))handOver(p2.item);return true}isInFlight(id2){return this.inFlightIds.has(id2)}releaseInFlight(ids){for(const id2 of ids){const held2=this.inFlightIds.get(id2);if(held2===void 0)continue;if(held2<=1){this.inFlightIds.delete(id2);this.stopRenewal(id2);if(!this.lowerOnRelease.delete(id2))continue;const p2=this.inbox.find(pending=>pending.item.recvKey===id2);if(p2&&!p2.pullOnly){p2.pullOnly=true;this.excludeFromFocus(p2.item)}}else this.inFlightIds.set(id2,held2-1)}}own(p2,redelivery){p2.redelivery=redelivery;p2.ownedUntil=redelivery&&Date.now()+redelivery.ackWaitMs;p2.item.deliveryCount=redelivery?.deliveryCount;p2.item.firstDeliveryCount??=redelivery?.deliveryCount??1}keepOwned(key){if(this.renewals.has(key))return;const p2=this.inbox.find(x2=>x2.item.recvKey===key);if(!p2?.redelivery||!this.renewOwned(p2))return;const timer2=setInterval(()=>{const held2=this.inbox.find(x2=>x2.item.recvKey===key);if(!held2||!this.renewOwned(held2))this.stopRenewal(key)},p2.redelivery.ackWaitMs/2);timer2.unref?.();this.renewals.set(key,timer2)}stopRenewal(key){clearInterval(this.renewals.get(key));this.renewals.delete(key)}renewOwned(p2){if(!p2.redelivery||p2.ownedUntil===void 0||Date.now()>=p2.ownedUntil)return false;if(!this._transportConnected)return true;try{p2.redelivery.working()}catch{return false}p2.ownedUntil=Date.now()+p2.redelivery.ackWaitMs;return true}drainInbox(limit,scope="all"){this.dropLapsedTakes();const eligible=this.inbox.filter(p2=>this.inScope(p2,scope));const n2=limit&&limit>0?Math.min(limit,eligible.length):eligible.length;const selected=eligible.slice(0,n2);this.noteAutomaticHeadProgress(selected);const taken=new Set(selected);this.inbox=this.inbox.filter(p2=>!taken.has(p2));const automatic=selected.some(p2=>!p2.pullOnly);const items=this.commitPending(selected);if(items.length)this._lastInboxDrainedAt=Date.now();if(items.length&&automatic)this._lastAutomaticDrainedAt=Date.now();return items}drainInboxDeliveries(keys){const requested=[...new Set(keys)];const wanted=new Set(requested);const regated=this.gated.filter(p2=>wanted.has(p2.item.recvKey)&&p2.takenOnce);const unshown=new Set(this.gated.filter(p2=>wanted.has(p2.item.recvKey)&&!p2.takenOnce).map(p2=>p2.item.recvKey));if(regated.length)this.gated=this.gated.filter(p2=>!regated.includes(p2));const selected=[...this.inbox.filter(p2=>wanted.has(p2.item.recvKey)),...regated];this.noteAutomaticHeadProgress(selected);const present=new Set(selected.map(p2=>p2.item.recvKey));const pullOnly=new Map(selected.map(p2=>[p2.item.recvKey,p2.pullOnly]));for(const id2 of requested){const remembered=id2!==""?this.evictedClassifications.get(id2):void 0;if(!pullOnly.has(id2)&&remembered)pullOnly.set(id2,remembered.pullOnly)}this.inbox=this.inbox.filter(p2=>!present.has(p2.item.recvKey));const automatic=selected.some(p2=>!p2.pullOnly);const items=this.commitPending(selected);if(items.length)this._lastInboxDrainedAt=Date.now();if(items.length&&automatic)this._lastAutomaticDrainedAt=Date.now();for(const id2 of requested){if(!present.has(id2)&&!unshown.has(id2)&&!id2.startsWith(`${this.recvKeySecret}.`)){this.markHandled(id2,pullOnly.get(id2)??false);this.evictedClassifications.delete(id2)}}return{items,missingKeys:requested.filter(key=>!present.has(key)&&!unshown.has(key))}}commitPending(taken){for(const p2 of taken){p2.ack();this.markHandled(p2.item.id,p2.pullOnly);this.evictedClassifications.delete(p2.item.id)}return taken.map(p2=>p2.item)}inScope(p2,scope){return scope==="all"||(scope==="pull-only"?p2.pullOnly:!p2.pullOnly)}markHandled(id2,pullOnly=false){if(id2==="")return;if(pullOnly)this.protectDisposition(id2,"pull-only");this.handledIds.add(id2);if(this.handledIds.size>=4096){this.handledIdsPrev=this.handledIds;this.handledIds=new Set}}inboxKeys(scope="all"){const held2=scope==="pull-only"?[]:this.gated;return[...this.inbox.filter(p2=>this.inScope(p2,scope)),...held2].map(p2=>p2.item.recvKey)}inboxPending(scope="all"){const held2=scope==="pull-only"?[]:this.gated;return[...this.inbox.filter(p2=>this.inScope(p2,scope)),...held2].map(p2=>p2.item)}inboxCount(scope="all"){const held2=scope==="pull-only"?0:this.gated.length;return held2+(scope==="all"?this.inbox.length:this.inbox.filter(p2=>this.inScope(p2,scope)).length)}inboxSnapshot(limit=3){if(!Number.isInteger(limit)||limit<0||limit>8)throw new Error(`inbox preview limit must be a whole number from 0 to 8, got ${limit}`);this.dropLapsedTakes();return{unread:this.inbox.length+this.gated.length,items:this.inbox.slice(0,limit).map(p2=>({...p2.item}))}}oldestAutomaticReceivedAt(){let oldest;for(const pending of[...this.inbox,...this.gated]){if(pending.pullOnly)continue;if(oldest===void 0||pending.receivedAt<oldest)oldest=pending.receivedAt}return oldest}get recallCursor(){return this._recallCursor}noteRecalled(mark){if(afterRecallMark(mark,this._recallCursor))this._recallCursor=mark}recallAhead(item){return item.ts>Date.now()}recallAheadSeen(id2){return this.aheadDelivered.has(id2)}recallAheadRoom(){return MAX_AHEAD-this.aheadDelivered.size}noteRecalledAhead(id2){if(this.aheadDelivered.size<MAX_AHEAD)this.aheadDelivered.add(id2)}resetRecallWalk(){this._recallCursor={ts:0,id:""};this.aheadDelivered.clear()}inboxScope(key){const pending=this.inbox.find(p2=>p2.item.recvKey===key)??this.gated.find(p2=>p2.item.recvKey===key);return pending?pending.pullOnly?"pull-only":"automatic":void 0}directedPendingCount(){return this.gated.length+this.inbox.filter(p2=>!p2.pullOnly&&(p2.item.kind!=="channel"||!p2.item.historical&&p2.item.mentionsMe)).length}inboxWake(skip){this.dropLapsedTakes();const held2=this.mayAskTakes()?this.gated.filter(p2=>(p2.taking===void 0||p2.takingDrops!==this.transportDrops)&&!skip?.(p2.item)).length:0;return held2+this.inbox.filter(p2=>{const it2=p2.item;if(p2.pullOnly||it2.kind==="channel"&&it2.historical||skip?.(it2))return false;if(it2.kind!=="channel"||it2.mentionsMe)return true;return this._attention==="open"}).length}get attention(){return this._attention}channelMode(channel){return channel?this.channelModes.get(channel):void 0}channelModeEntries(){return Object.fromEntries(this.channelModes)}async setChannelMode(channel,mode){if(!isConcreteChannel(channel))throw new Error(`"${channel}" must be a concrete channel (no wildcard) to set its attention`);if(!channelInAllow(this.config.allowSubscribe,channel))throw new Error(`"${channel}" is not within your read ACL (allowSubscribe) [${this.config.allowSubscribe.join(", ")}]`);await this.inOrder(()=>{if(mode==="normal")this.channelModes.delete(channel);else{this.channelModes.set(channel,mode);this.lowerBuffered(channel,mode==="muted")}return this.ep.setChannelModes(this.channelModeEntries())})}lowerBuffered(channel,mentions,keep=[]){for(const p2 of this.inbox){if(p2.pullOnly||p2.item.kind!=="channel"||!p2.item.channel||!channelInAllow([channel],p2.item.channel))continue;if(channelInAllow(keep,p2.item.channel))continue;if(p2.item.mentionsMe&&!mentions)continue;if(this.inFlightIds.has(p2.item.recvKey)){this.lowerOnRelease.add(p2.item.recvKey);continue}p2.pullOnly=true;this.excludeFromFocus(p2.item)}}async setAttention(mode){await this.inOrder(async()=>{if(mode==="focus"){await this.requireConnected();this.focusExcludedIds.clear();this.focusIdless=new Map;this.focusIdlessEntries=0;this.focusRecallUnsafeChannels.clear();this.enteringFocus=this._attention!=="focus";try{this.focusSince=await this.ep.chatFrontier()}catch(error51){this.enteringFocus=false;this.focusExcludedIds.clear();this.focusIdless=new Map;this.focusIdlessEntries=0;this.focusRecallUnsafeChannels.clear();throw error51}this.enteringFocus=false;this.resetRecallWalk()}else{this.enteringFocus=false;this.focusSince=void 0;this.focusExcludedIds.clear();this.focusIdless=new Map;this.focusIdlessEntries=0;this.focusRecallUnsafeChannels.clear();this.resetRecallWalk()}this._attention=mode;await this.ep.setAttention(mode)})}async recallAmbient(underway=new Set){const run=this.recallLock.then(()=>this.recallAmbientOnce(underway));this.recallLock=run.catch(()=>{});return run}async recallAmbientOnce(underway){if(this._attention!=="focus"||this.focusSince===void 0)return{items:[],droppedChannels:[]};const items=[];const droppedChannels=[];for(const channel of this.ep.joinedChannels()){if(!isConcreteChannel(channel)){droppedChannels.push(channel);continue}if(this.focusRecallUnsafeChannels.has(channel)){droppedChannels.push(channel);continue}const tallies=this.focusIdless;let epoch=0;let read;for(let attempt=1;attempt<=IDLESS_READS;attempt++){epoch=++this.idlessEpoch;await this.idlessReady(tallies,channel);read=await this.ep.recallChannel(channel,this.focusSince);if(read.unanswered)break;await this.idlessReady(tallies,channel);const unsure=read.messages.some((m2,i2)=>m2.id===""&&this.idlessUnsure(tallies.get(idlessDigest(m2)),epoch,read.seqs[i2]));if(!unsure)break}const{messages,seqs,dropped,unanswered}=read;if(unanswered){droppedChannels.push(channel);continue}if(this.focusRecallUnsafeChannels.has(channel)){droppedChannels.push(channel);continue}const retained=new Set;const digests=[];const free=new Map;for(const[i2,m2]of messages.entries()){if(m2.id!==""||tallies!==this.focusIdless)continue;retained.add(seqs[i2]);const digest=digests[i2]=idlessDigest(m2);if(tallies.get(digest)?.bound.has(seqs[i2]))continue;const list=free.get(digest);if(list)list.push(seqs[i2]);else free.set(digest,[seqs[i2]])}for(const[digest,list]of free){const tally=tallies.get(digest);if(tally)this.bindIdless(tally,epoch,list)}let incomplete=dropped;for(const[i2,m2]of messages.entries()){if(m2.id!==""){if(underway.has(m2.id)||!this.focusExcludedIds.has(m2.id))items.push(this.toInboxItem(m2,"channel",true));continue}if(tallies!==this.focusIdless)continue;const seq=seqs[i2];const digest=digests[i2];const tally=tallies.get(digest);if(tally?.bound.has(seq))continue;if(this.idlessUnsure(tally,epoch,seq)){incomplete=true;continue}const fresh=this.inbox.length<MAX_INBOX?this.reserveIdless(digest,channel):void 0;if(!fresh){incomplete=true;continue}const copy2={epoch,frontier:seq,ready:Promise.resolve(),seq};fresh.bound.add(seq);this.buffer(this.toInboxItem(m2,"channel",true),{ack:()=>{}},true,{digest,copy:copy2})}if(tallies===this.focusIdless)this.settleIdlessRead(channel,epoch,retained);if(incomplete)droppedChannels.push(channel)}items.sort((a3,b3)=>a3.ts-b3.ts);return{items,droppedChannels}}};var SPAWN_TIMEOUT_MS=4e4;var CONNECT_GRACE_MS=1e4;function isLocalServer(servers){return servers.split(",").every(s3=>/^(?:[a-z]+:\/\/)?(?:[^@/]*@)?(?:localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(?::\d+)?(?:\/|$)/i.test(s3.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}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,t2){if(t2.yielded!==void 0)return`turn "${goalId}" was already yielded ${t2.yielded} by this seat${t2.yielded==="done"?" (ending a session turn yields done)":""}, so this yield was not recorded`;const deadline=t2.deadlineAt!==void 0?` (deadline ${new Date(t2.deadlineAt).toISOString()})`:"";return`turn "${goalId}" was already settled ${t2.once!==void 0?"by its manager":"by the run"}${deadline}, so this yield was not recorded`}var MAX_DATE_MS=864e13;function isPendingTurn(t2){const r2=t2;if(typeof r2!=="object"||r2===null||typeof r2.goalId!=="string"||typeof r2.payload!=="string")return false;if(!Number.isSafeInteger(r2.acceptedAt)||r2.acceptedAt<0)return false;if(r2.once!==void 0&&r2.once!==true)return false;if(r2.deadlineAt===void 0)return r2.once===true;return Number.isSafeInteger(r2.deadlineAt)&&r2.deadlineAt>=1&&r2.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 sleep(ms){return new Promise(r2=>setTimeout(r2,ms))}var AUTOMATIC_QUEUE_STALL_MS=6e5;function renderAskRequest(p2){const escalation=renderEscalation(p2);if(escalation!=="")return escalation;const ask=p2.ask;if(ask===null||typeof ask!=="object")return"";const a3=ask;const entries=a3.schema!==null&&typeof a3.schema==="object"?Object.entries(a3.schema):[];const fields=entries.length===0?"any record":entries.map(([k2,v3])=>`${k2}: ${String(v3)}`).join(", ");const by=typeof a3.deadlineAt==="number"?`, by ${new Date(a3.deadlineAt).toISOString()}`:"";const refused3=typeof a3.refused==="string"?`
|
|
118
|
+
(This is the only task this seat takes. Do it with your own tools, and send your result to whoever needs it, for example with cotal_dm to ${from}, before you end your turn: this seat is stopped when your turn ends${deadline}, and a result you have not sent reaches no one. If you cannot finish, call cotal_yield with blocked or handoff and say why.)`}var nonBlank=()=>({type:"string",pattern:"^\\s*\\S"});var AGENT_ROW_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,required:["name","id","agent","space","mode","status","uptimeMs","mesh","lifecycleUid"],properties:{name:{type:"string"},id:{type:"string"},role:{type:"string"},agent:{type:"string"},space:{type:"string"},mode:{type:"string"},status:{type:"string"},uptimeMs:{type:"integer",minimum:0},mesh:{type:"string"},joinHealth:{type:"object",additionalProperties:false,required:["state","reason"],properties:{state:{type:"string",const:"degraded"},reason:{type:"string"}}},condition:{type:"object",additionalProperties:false,required:["code"],properties:{code:{type:"string"},source:{type:"string"},message:{type:"string"},since:{type:"number"}}},startupNotice:{type:"string",minLength:1,maxLength:1024},activeAt:{type:"number"},meshView:{type:"string",enum:["current","stale","unpopulated"]},presenceIdentityVerified:{type:"boolean"},presenceObservedAt:{type:"integer",minimum:0},offlineSince:{type:"integer",minimum:0},lifecycleUid:{type:"string"},authHealth:{type:"string"},authReason:{type:"string"},model:{type:"string"},variant:{type:"string"},provider:{type:"string"},cwd:{type:"string"},pid:{type:"integer",minimum:1},spawner:{type:"string"},instanceId:{type:"string"},host:{type:"string"},resume:{type:"object",additionalProperties:false,required:["source"],properties:{source:{type:"string"},title:{type:"string"},transcriptSha256:{type:"string"},host:{type:"string"},transferredAt:{type:"string"}}}}});var INSPECT_INPUT_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,required:["name"],properties:{name:{type:"string",minLength:1}}});var PERSONA_ENDPOINTS_SCHEMA=deepFreeze4({type:"array",items:{type:"object",additionalProperties:false,required:["endpoint","commands"],properties:{endpoint:{type:"string"},commands:{type:"array",items:{type:"string"}},instanceId:{type:"string"}}}});var SPAWN_INPUT_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,required:["name"],properties:{name:{type:"string",minLength:1},agent:nonBlank(),defaultAgent:nonBlank(),role:nonBlank(),config:nonBlank(),identity:nonBlank(),model:nonBlank(),variant:nonBlank(),launchOptions:{type:"object"},resume:nonBlank(),resumeClaim:nonBlank(),resumeAgent:nonBlank(),events:{type:"boolean"},eventPayloads:{type:"boolean"},cwd:nonBlank(),prompt:nonBlank(),persona:{type:"object",additionalProperties:false,required:["prompt"],properties:{prompt:nonBlank(),role:nonBlank(),model:nonBlank(),variant:nonBlank(),description:nonBlank(),subscribe:{type:"array",items:{type:"string"}},allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}},capabilities:{type:"array",items:{type:"string"}},endpoints:PERSONA_ENDPOINTS_SCHEMA,save:{type:"boolean"}}},runId:nonBlank(),subscribe:{type:"array",items:{type:"string"}},allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}},join:{type:"array",items:{type:"string"}},callerAcl:{type:"object",additionalProperties:false,required:["allowSubscribe","allowPublish"],properties:{allowSubscribe:{type:"array",items:{type:"string"}},allowPublish:{type:"array",items:{type:"string"}}}},shareTools:{type:"array",items:{type:"string"}},runtime:nonBlank(),supervise:{type:"object",additionalProperties:false,required:["restarts","windowMs"],properties:{restarts:{type:"integer",minimum:1},windowMs:{type:"integer",minimum:1}}},once:{type:"object",additionalProperties:false,properties:{deadlineMs:{anyOf:[{const:-1},{type:"integer",minimum:1,maximum:Number.MAX_SAFE_INTEGER}]}}}}});var SPAWN_OUTPUT_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,required:["name","owner","actor","uid","goalId","fingerprint","executor"],properties:{name:{type:"string"},owner:{type:"string"},actor:{type:"string"},uid:{type:"string"},goalId:{type:"string"},fingerprint:{type:"string"},readinessDeadlineMs:{type:"integer",minimum:1},executor:{type:"object",additionalProperties:false,required:["lifecycleUid","epoch"],properties:{lifecycleUid:{type:"string"},epoch:{type:"integer",minimum:0}}}}});var GRACEFUL_INPUT_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,properties:{graceful:{type:"boolean"}}});var STOP_OUTPUT_SCHEMA=deepFreeze4({type:"object",additionalProperties:false,required:["name","stopped","graceful"],properties:{name:{type:"string"},stopped:{type:"boolean"},graceful:{type:"boolean"}}});function deepFreeze4(v3){if(v3!==null&&typeof v3==="object"){for(const child of Object.values(v3))deepFreeze4(child);Object.freeze(v3)}return v3}var import_nkeys12=__toESM(require_mod(),1);init_canonical();init_endpoint_envelope();init_identity();init_schema_profile();init_endpoint_signing();var TOOL_RESULTS_ENDPOINT="tool-results";var TOOL_RESULT_MAX_CONTENT_BYTES=64*1024;var TOOL_RESULT_MAX_RETENTION_MS=60*60*1e3;var TOOL_RESULT_CONSENT_MAX_TTL_MS=24*60*60*1e3;function deepFreeze5(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))deepFreeze5(child);Object.freeze(value)}return value}var text2={type:"string",minLength:1};var id={type:"string",minLength:1,maxLength:200,pattern:"^[A-Za-z0-9_-]+$"};var actor={type:"string",minLength:1,pattern:"^[A-Za-z0-9_]+$"};var owner={type:"string",pattern:"^u_[a-z2-7]{26}$"};var uid={type:"string",pattern:"^[a-z0-9]{26,32}$"};var space={type:"string",minLength:1,pattern:"^[A-Za-z0-9_-]+$"};var uint2={type:"integer",minimum:0,maximum:Number.MAX_SAFE_INTEGER};var bool={type:"boolean"};var closed3=properties=>({type:"object",additionalProperties:false,required:Object.keys(properties),properties});var target=closed3({owner,actor,lifecycleUid:uid});var pair={threadId:text2,toolCallId:text2};var status=(state,fields={})=>closed3({state:{const:state},...fields});var TOOL_RESULT_CONSENT_SCHEMA=deepFreeze5(closed3({v:{const:1},kind:{const:"tool-result-consent"},id,space,target,holder:closed3({owner,actor}),iat:uint2,exp:uint2,issuer:closed3({keyId:id}),sig:{type:"string",pattern:"^[A-Za-z0-9_-]{86}$"}}));var TOOL_RESULT_REVOCATION_SCHEMA=deepFreeze5(closed3({v:{const:1},kind:{const:"tool-result-revocation"},space,consentId:id,target,revokedAt:uint2}));var TOOL_RESULT_SERVING_MATERIAL_SCHEMA=deepFreeze5(closed3({v:{const:1},kind:{const:"tool-result-serving-material"},space,accountPublicKey:{type:"string",pattern:"^A[A-Z2-7]{55}$"},target,grant:closed3({endpoint:{const:TOOL_RESULTS_ENDPOINT},instanceId:uid,epoch:uint2,registrationRevision:{...uint2,minimum:1}}),credential:{type:"string",minLength:1,maxLength:16384},snapshot:closed3({t0:uint2,watermark:uint2,watermarkTakenAt:uint2,revokedConsentIds:{type:"array",uniqueItems:true,items:id}}),expiresAt:uint2}));var TOOL_RESULT_INPUT_SCHEMA=deepFreeze5(closed3(pair));var TOOL_RESULT_ANSWER_SCHEMAS=deepFreeze5({available:status("available",{...pair,content:{type:"string",maxLength:TOOL_RESULT_MAX_CONTENT_BYTES},truncated:bool,byteCount:{...uint2,maximum:TOOL_RESULT_MAX_CONTENT_BYTES},error:bool,capturedAt:uint2}),pending:status("pending",pair),"not-shared":status("not-shared"),missing:status("missing"),expired:status("expired")});var TOOL_RESULT_OUTPUT_SCHEMA=deepFreeze5({oneOf:Object.values(TOOL_RESULT_ANSWER_SCHEMAS)});var TOOL_RESULT_CONSENT_INPUT_SCHEMA=deepFreeze5(closed3({consent:TOOL_RESULT_CONSENT_SCHEMA}));var TOOL_RESULT_CONSENT_OUTPUT_SCHEMA=deepFreeze5(status("active",{consentId:id}));var TOOL_RESULT_REVOKE_INPUT_SCHEMA=deepFreeze5(closed3({consentId:id}));var TOOL_RESULT_REVOKE_ANSWER_SCHEMAS=deepFreeze5({known:status("known",{consentId:id}),refused:status("refused",{consentId:id}),unknown:status("unknown",{consentId:id})});var TOOL_RESULT_REVOKE_OUTPUT_SCHEMA=deepFreeze5({oneOf:Object.values(TOOL_RESULT_REVOKE_ANSWER_SCHEMAS)});var TOOL_RESULTS_COMMANDS=deepFreeze5([{name:"tool-result",capability:"tool-results.read",input:TOOL_RESULT_INPUT_SCHEMA,output:TOOL_RESULT_OUTPUT_SCHEMA},{name:"tool-result-consent",capability:"tool-results.consent",input:TOOL_RESULT_CONSENT_INPUT_SCHEMA,output:TOOL_RESULT_CONSENT_OUTPUT_SCHEMA},{name:"tool-result-revoke",capability:"tool-results.revoke",input:TOOL_RESULT_REVOKE_INPUT_SCHEMA,output:TOOL_RESULT_REVOKE_OUTPUT_SCHEMA}]);var TOOL_RESULTS_CLUSTER=deepFreeze5({urn:"ai.cotal.tool-results",revision:1,attributes:[],events:[],commands:TOOL_RESULTS_COMMANDS.map(row=>({name:row.name,class:"ephemeral",targeted:true,modes:["handle"],capability:row.capability,inputDigest:singleDocumentClosure(row.input).closureDigest,outputDigest:singleDocumentClosure(row.output).closureDigest}))});init_event_payloads();var import_nkeys13=__toESM(require_mod(),1);init_base64url();var LANG_PROBLEM_DETAIL_KIND="ai.cotal.lang.problem";var RUN_ACTIVATION_WAIT_MS=15e3;var RUN_LAUNCH_DEADLINE_MS=RUN_ACTIVATION_WAIT_MS+1e4;init_issued_authority();init_provision();init_issued_authority();init_subjects();init_endpoint_subjects();init_persona_endpoints();var DELEGABLE_CAPABILITIES=Object.freeze(["spawn","run","admin"]);init_persona_endpoints();var import_jetstream31=__toESM(require_mod4(),1);var import_transport_node30=__toESM(require_transport_node(),1);init_backup();init_issued_authority();init_jetstream_missing();init_run_admission();init_endpoint_envelope();init_issued_authority();init_endpoint_subjects();init_endpoint_records();init_run_submission();init_canonical();init_endpoint_journal();init_endpoint_caller();init_endpoint_subjects();init_endpoint_error();init_connection_cleanup();var import_jetstream32=__toESM(require_mod4(),1);var import_kv15=__toESM(require_mod6(),1);init_endpoint();init_endpoint_binding();init_endpoint_envelope();init_lifecycle_state();init_endpoint_records();init_issued_authority();init_identity();init_provision();init_renewal();init_streams();init_service_gate();init_contract_manifest();init_renewal();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_KEY","COTAL_CONTROL_VERSION","COTAL_CONTROL_TOKEN","COTAL_LINK"];function readMaterial(env){const path4=env[LAUNCH_MATERIAL_ENV]?.trim();if(!path4)return void 0;const direct=DIRECT_MATERIAL_VARS.filter(k2=>env[k2]?.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(path4)}function controlFromEnv(env=process.env){if(env.COTAL_CONTROL_TOKEN?.trim())throw new Error("COTAL config: COTAL_CONTROL_TOKEN is the control key variable of a release before the control exchange. Set COTAL_CONTROL_KEY and COTAL_CONTROL_VERSION instead; this build refuses the old name rather than guess which protocol it meant.");const path4=env.COTAL_CONTROL_SOCKET?.trim();const material=readMaterial(env);const token2=material?material.controlKey:directControlKey(env);if(path4&&token2){const direct=env.COTAL_CONTROL_VERSION;const version2=material?material.controlVersion:direct?.trim()?/^(0|[1-9][0-9]*)$/.test(direct)?Number(direct):direct:void 0;assertControlVersion(version2,material?"this launch's material":"COTAL_CONTROL_VERSION");return{path:path4,token:token2,version:version2}}if(!path4&&!token2)return void 0;if(path4)throw new Error("COTAL config: COTAL_CONTROL_SOCKET is set but no control key could be resolved - neither the launch material nor COTAL_CONTROL_KEY 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 key 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 directControlKey(env){const key=env.COTAL_CONTROL_KEY;if(!key?.trim()){if(env.COTAL_CONTROL_VERSION?.trim())throw new Error("COTAL config: COTAL_CONTROL_VERSION is set without COTAL_CONTROL_KEY. The version travels with the key; set both or neither.");return void 0}if(key!==key.trim())throw new Error("COTAL config: COTAL_CONTROL_KEY has whitespace around it. A key is used as given, never trimmed; remove the whitespace.");return key}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(v3){if(!v3)return[];return v3.split(",").map(s3=>s3.trim()).filter(Boolean)}function endpointsEnv(v3){let raw;try{raw=JSON.parse(v3)}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(v3){return v3===void 0?void 0:splitList(v3)}var EnvFlagError=class extends Error{};function envFlag(env,name2){const value=env[name2]?.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: ${name2} must be 1/true/yes/on or 0/false/no/off, got "${env[name2]}"`)}function scrubLaunchMaterial(env=process.env){const path4=env[LAUNCH_MATERIAL_ENV]?.trim();delete env[LAUNCH_MATERIAL_ENV];if(path4)discardLaunchMaterial(path4)}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 name2=env.COTAL_NAME?.trim()||def?.name||(link?userInfo2().username:void 0);if(!name2)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(e3){throw new Error(`COTAL config: ${e3.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(c3=>resolvedMuted.includes(c3));if(bothModes.length)throw new Error(`COTAL config: channel(s) [${bothModes.join(", ")}] are in both quiet and muted`);for(const[field,chans]of[["quiet",resolvedQuiet],["muted",resolvedMuted]])for(const ch of chans){assertValidChannel(ch);if(!isConcreteChannel(ch))throw new Error(`COTAL config: ${field} channel "${ch}" must be concrete (no wildcard)`);if(!channelInAllow(resolvedAllowSub,ch))throw new Error(`COTAL config: ${field} channel "${ch}" is not within allowSubscribe [${resolvedAllowSub.join(", ")}]`)}const material=readMaterial(env);if(env.COTAL_SERVERS?.trim()&&brokerUrlHasUserinfo(env.COTAL_SERVERS))throw new Error("COTAL config: COTAL_SERVERS must not embed credentials; name the broker URL without user:password@, and pass the credential in COTAL_CREDS, COTAL_TOKEN or a COTAL_LINK");const credsPath=material?.creds??env.COTAL_CREDS?.trim();const initialCreds=credsPath?readFileSync4(credsPath,"utf8"):void 0;const credsId=initialCreds?idFromCreds(initialCreds):void 0;const boundedCreds=initialCreds!==void 0&&typeof credsClaims(initialCreds).exp==="number";const declaredId=env.COTAL_ID?.trim()||void 0;if(declaredId&&credsId&&declaredId!==credsId)throw new Error(`COTAL config: COTAL_ID ${declaredId} != creds identity ${credsId} - they must be the same nkey`);const userVars=material?.userAuth?{owner:material.userAuth.owner,actor:material.userAuth.actor,sentinel:material.userAuth.sentinelCredsPath,bearerCmd:JSON.stringify(material.userAuth.bearerCmd)}:{owner:env.COTAL_OWNER?.trim(),actor:env.COTAL_ACTOR?.trim(),sentinel:env.COTAL_SENTINEL_CREDS?.trim(),bearerCmd:env.COTAL_BEARER_CMD?.trim()};const userSet=Object.values(userVars).filter(Boolean).length;if(userSet>0&&userSet<4)throw new Error("COTAL config: user-mode launch needs ALL of COTAL_OWNER, COTAL_ACTOR, COTAL_SENTINEL_CREDS, COTAL_BEARER_CMD \u2014 a partial set is a broken launcher, not a mode");if(userSet&&credsPath)throw new Error("COTAL config: COTAL_CREDS (static auth) and COTAL_OWNER/... (user-mode auth) are mutually exclusive");const lifecycleUid=env.COTAL_LIFECYCLE_UID?.trim()||void 0;const backfillFloorRaw=env.COTAL_BACKFILL_FLOOR?.trim()||void 0;let backfillFloor;if(backfillFloorRaw!==void 0){const n2=Number(backfillFloorRaw);if(!Number.isInteger(n2)||n2<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=n2}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(a3=>typeof a3==="string"))throw new Error("COTAL config: COTAL_BEARER_CMD must be a non-empty JSON array of strings");userAuth={owner:userVars.owner,actor:userVars.actor,sentinelCreds:readFileSync4(userVars.sentinel,"utf8"),bearerCmd}}const eventsRequired=material?.eventsRequired===true||!material&&envFlag(env,"COTAL_EVENTS_REQUIRED")===true;if(eventsRequired&&!userAuth)throw new Error("COTAL config: COTAL_EVENTS_REQUIRED is valid only for a user-mode registration launch");if(eventsRequired){const principal=userSet===4?{owner:userVars.owner,actor:userVars.actor}:{owner:DEV_OWNER,actor:credsId??declaredId??""};if(!principal.actor)throw new Error("COTAL config: this space requires events, but the session has no stable principal to derive its event channel");const channel=eventChannel(principal);if(!channelInAllow(resolvedAllowPub,channel))throw new Error(`COTAL config: space "${env.COTAL_SPACE?.trim()||link?.space||"demo"}" requires events, but this session's grant does not cover its event channel "${channel}". Widen the whole user-auth actor row with \`cotal actor grant ${principal.actor} --owner ${principal.owner} --scope <current-scope> --allow-subscribe <current-read> --allow-publish '<current-post>,${channel}' --role <current-role> --label <current-label>\`; actor grant replaces the whole row, so preserve every current field.`)}return{space:env.COTAL_SPACE?.trim()||link?.space||"demo",id:credsId??declaredId,lifecycleUid,backfillFloor,acceptedToken,managerInstanceId,creds:boundedCreds?async()=>readFileSync4(credsPath,"utf8"):initialCreds,userAuth,name:name2,role:env.COTAL_ROLE||def?.role||void 0,description:def?.description,tags:def?.tags,meta:def?.meta,capabilities:splitList(env.COTAL_CAPABILITIES).length?splitList(env.COTAL_CAPABILITIES):def?.capabilities,endpoints:env.COTAL_ENDPOINTS!==void 0?endpointsEnv(env.COTAL_ENDPOINTS):def?.endpoints,model:env.COTAL_MODEL?.trim()||void 0,variant:env.COTAL_VARIANT?.trim()||void 0,servers:material?.servers||env.COTAL_SERVERS?.trim()||link?.servers||DEFAULT_SERVER,subscribe:resolvedSubscribe,allowSubscribe:resolvedAllowSub,allowPublish:resolvedAllowPub,eventsRequired,eventPayloadsWithheld:material?.eventPayloadsWithheld===true||envFlag(env,"COTAL_EVENT_PAYLOADS")===false,quiet:resolvedQuiet,muted:resolvedMuted,kind:assertValidKind(env.COTAL_KIND?.trim()||def?.kind||"agent"),token:material?.token||env.COTAL_TOKEN?.trim()||link?.token,user:link?.user,pass:link?.pass,tls:envFlag(env,"COTAL_TLS")||link?.tls||false,feedbackKey:env.COTAL_FEEDBACK_KEY?.trim()||void 0,feedbackUrl:env.COTAL_FEEDBACK_URL?.trim()||void 0}}function eventPlaneArmed(config2,env=process.env){return envFlag(env,"COTAL_EVENTS")===true||config2.eventsRequired===true}function feedbackLine(config2){const dest=config2.feedbackKey?"":`Without a feedback key it goes to the public cotal.ai intake and needs a contact email \u2014 the tool will tell you to ask the user for one if it can't find it. `;return`Use cotal_feedback with origin="human" when the user asks you to send feedback or gives you feedback to pass along. If you independently hit a major Cotal issue \u2014 for example repeated Cotal tool failures, inability to connect, lost/incorrect mesh messages, or a workflow-blocking bug \u2014 send cotal_feedback yourself with origin="agent". Do not send minor noise or secrets; include diagnostics only when they help debug the Cotal issue. `+dest}import{AsyncLocalStorage as AsyncLocalStorage2}from"node:async_hooks";import{EventEmitter as EventEmitter2}from"node:events";import{hostname as hostname2}from"node:os";import{createHash as createHash8,randomUUID as randomUUID11}from"node:crypto";import{open as open3,readFile as readFile2,unlink as unlink2}from"node:fs/promises";import{hostname}from"node:os";import{dirname as dirname7,join as join7}from"node:path";import{createHash as createHash7,randomUUID as randomUUID10}from"node:crypto";import{constants as constants4}from"node:fs";import{lstat as lstat2,open as open2,readFile,readdir as readdir2,rename,unlink}from"node:fs/promises";import{dirname as dirname6,join as join6}from"node:path";var EVENT_WAL_VERSION=4;var WalCorruptError=class extends Error{path;invariant;constructor(path4,invariant,detail){super(`event WAL at ${path4} is unusable (${invariant}): ${detail}`);this.path=path4;this.invariant=invariant;this.name="WalCorruptError"}};var WalStaleWriterError=class extends Error{path;expectedGen;foundGen;constructor(path4,expectedGen,foundGen){super(`event WAL at ${path4} 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=path4;this.expectedGen=expectedGen;this.foundGen=foundGen;this.name="WalStaleWriterError"}};var isSafeNonNegInt2=n2=>Number.isSafeInteger(n2)&&n2>=0;function docGeneration(path4,doc){if(typeof doc.v==="number"&&doc.v<3)return 0;if(!isSafeNonNegInt2(doc.gen))throw new WalCorruptError(path4,"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(path4){return open2(path4,constants4.O_WRONLY|constants4.O_CREAT|constants4.O_EXCL|(constants4.O_NOFOLLOW??0),384)}function assertPendingVintage(path4,p2,f2){if(p2.E!==f2.lastSubjectSeq)throw new WalCorruptError(path4,"pending.E === frontier.lastSubjectSeq",`pending.E=${p2.E} frontier.lastSubjectSeq=${f2.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(p2.seq!==f2.seq+1)throw new WalCorruptError(path4,"pending.seq === frontier.seq + 1",`pending.seq=${p2.seq} frontier.seq=${f2.seq} \u2014 a pending frame must be exactly the frontier's successor`);if(p2.state==="sent_unacked"){if(p2.ackSeq!==void 0)throw new WalCorruptError(path4,"sent_unacked has no ackSeq",`state is "sent_unacked" but ackSeq=${String(p2.ackSeq)} \u2014 the document contradicts its own tag`);return}if(!isSafeNonNegInt2(p2.ackSeq))throw new WalCorruptError(path4,"acked.ackSeq present",`state is "acked" but ackSeq is ${String(p2.ackSeq)}`);if(!(p2.ackSeq>f2.lastSubjectSeq))throw new WalCorruptError(path4,"acked.ackSeq > frontier.lastSubjectSeq",`ackSeq=${p2.ackSeq} frontier.lastSubjectSeq=${f2.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(path4,field,v3,nullable2){if(v3===null&&nullable2)return null;if(typeof v3!=="object"||v3===null)throw new WalCorruptError(path4,`${field} is an object${nullable2?" or null":""}`,JSON.stringify(v3));const b3=v3;if(b3.run!==void 0&&typeof b3.run!=="string")throw new WalCorruptError(path4,`${field}.run is a string or absent`,JSON.stringify(b3.run));const lists={text:b3.text,reasoning:b3.reasoning,tools:b3.tools};for(const[k2,list]of Object.entries(lists)){if(!Array.isArray(list)||list.some(x2=>typeof x2!=="string"))throw new WalCorruptError(path4,`${field}.${k2} is an array of strings`,JSON.stringify(list))}if(b3.run===void 0&&b3.text.concat(b3.reasoning,b3.tools).length>0)throw new WalCorruptError(path4,`${field} has no open run while messages or tool calls are open`,JSON.stringify(b3));return{run:b3.run,text:b3.text,reasoning:b3.reasoning,tools:b3.tools}}function parsePayloadCalls(path4,value){if(value===void 0)return void 0;if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).length>4096||Object.entries(value).some(([id2,allowed])=>!id2||typeof allowed!=="boolean"))throw new WalCorruptError(path4,"payloadCalls is a bounded boolean record","invalid call classification");return{...value}}function parseDoc(path4,raw,space2,threadId,principal){let d2;try{d2=JSON.parse(raw)}catch(e3){throw new WalCorruptError(path4,"parseable JSON",e3.message)}if(typeof d2!=="object"||d2===null)throw new WalCorruptError(path4,"document is an object",typeof d2);const doc=d2;if(typeof doc.v!=="number"||!Number.isSafeInteger(doc.v)||doc.v<1)throw new WalCorruptError(path4,"v is a positive integer",`found v=${String(doc.v)}`);if(doc.v>EVENT_WAL_VERSION)throw new WalCorruptError(path4,`v <= ${EVENT_WAL_VERSION}`,`this WAL is v${doc.v} and this build understands v${EVENT_WAL_VERSION} \u2014 THE STATE IS NEWER THAN THE CODE, which is what a code rollback across the v2 migration (persisted bracket state) or the v3 one (the write generation) leaves behind. The migration is forward-only by design: there is no downgrade, because a lossy one would silently discard state this file exists to preserve. Run the newer build, or move this WAL aside and accept that the thread restarts from a new epoch.`);if(doc.space!==space2)throw new WalCorruptError(path4,"space matches",`WAL space=${String(doc.space)} caller=${space2}`);if(doc.threadId!==threadId)throw new WalCorruptError(path4,"threadId matches",`WAL threadId=${String(doc.threadId)} caller=${threadId}`);if(doc.principal!==principal)throw new WalCorruptError(path4,"principal matches",`WAL principal=${String(doc.principal)} caller=${principal}`);if(typeof doc.epoch!=="string"||doc.epoch.length===0)throw new WalCorruptError(path4,"epoch is a non-empty string",String(doc.epoch));const f2=doc.frontier;if(!f2||!isSafeNonNegInt2(f2.seq)||!isSafeNonNegInt2(f2.lastSubjectSeq))throw new WalCorruptError(path4,"frontier is well-formed",JSON.stringify(doc.frontier));if(f2.sourceCursor!==void 0&&typeof f2.sourceCursor!=="string")throw new WalCorruptError(path4,"frontier.sourceCursor is a string or absent",typeof f2.sourceCursor);if(f2.seq===0!==(f2.lastSubjectSeq===0))throw new WalCorruptError(path4,"frontier.seq and lastSubjectSeq are both zero or both nonzero",JSON.stringify(f2));if((f2.seq>0||f2.lastSubjectSeq>0)&&typeof f2.sourceCursor!=="string")throw new WalCorruptError(path4,"a nonzero frontier carries its sourceCursor",JSON.stringify(f2));if(doc.pending!==null&&typeof doc.pending!=="object")throw new WalCorruptError(path4,"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 p2=doc.pending;if(p2.state!=="sent_unacked"&&p2.state!=="acked")throw new WalCorruptError(path4,"pending.state is a known tag",String(p2.state));if(typeof p2.id!=="string"||p2.id.length===0)throw new WalCorruptError(path4,"pending.id is a non-empty string",String(p2.id));try{assertIdToken(p2.id,"event WAL pending.id")}catch(e3){throw new WalCorruptError(path4,"pending.id satisfies the wire id grammar",e3.message)}if(!isSafeNonNegInt2(p2.E)||!isSafeNonNegInt2(p2.seq))throw new WalCorruptError(path4,"pending E/seq are safe non-negative integers",JSON.stringify(p2));if(typeof p2.sourceCursor!=="string")throw new WalCorruptError(path4,"pending.sourceCursor is a string",typeof p2.sourceCursor);if(!Array.isArray(p2.body)||p2.body.length===0)throw new WalCorruptError(path4,"pending.body is a non-empty array of parts",JSON.stringify(p2.body));if(doc.v===1)throw new WalCorruptError(path4,"a v1 WAL has no frame in flight",`this v1 document holds a ${String(p2.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.`);p2.brackets=parseBrackets(path4,"pending.brackets",p2.brackets,false);if(p2.payload!==void 0){const payload=p2.payload;if(doc.v<4||!payload||typeof payload!=="object"||!Array.isArray(payload.body)||payload.body.length===0||!isSafeNonNegInt2(payload.E)||payload.ackSeq!==void 0&&(!isSafeNonNegInt2(payload.ackSeq)||payload.ackSeq<=payload.E))throw new WalCorruptError(path4,"pending payload is a v4 frozen publication",JSON.stringify(payload));assertIdToken(payload.id,"event WAL payload id")}p2.payloadCalls=parsePayloadCalls(path4,p2.payloadCalls);pending=p2;assertPendingVintage(path4,pending,f2)}const brackets=doc.v===1?null:parseBrackets(path4,"brackets",doc.brackets,true);return{v:EVENT_WAL_VERSION,gen:docGeneration(path4,doc),space:space2,epoch:doc.epoch,threadId,principal,frontier:f2,pending,payloadCalls:parsePayloadCalls(path4,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(path4,doc){this.path=path4;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}async pendingSiblings(){const threadDir=createHash7("sha256").update(this.threadId).digest("hex").slice(0,16);if(dirname6(this.path).split(/[\\/]/).pop()!==threadDir)return[];const parent=dirname6(dirname6(this.path));const siblings=[];for(const entry of await readdir2(parent,{withFileTypes:true})){if(!/^[a-f0-9]{16}$/.test(entry.name))continue;const path4=join6(parent,entry.name,"wal.json");if(path4===this.path)continue;if(entry.isSymbolicLink())throw new WalCorruptError(path4,"a real thread directory","found a symlink");if(!entry.isDirectory())continue;let bytes;try{const st2=await lstat2(path4);if(!st2.isFile()||st2.nlink!==1)throw new WalCorruptError(path4,"a real thread log with one name","refusing linked or non-file state");const file2=await open2(path4,constants4.O_RDONLY|(constants4.O_NOFOLLOW??0));try{bytes=await file2.readFile()}finally{await file2.close()}}catch(e3){if(e3.code==="ENOENT")continue;throw e3}const raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes);const doc=JSON.parse(raw);if(doc.pending?.state!=="sent_unacked")continue;const threadId=doc.threadId;if(typeof threadId!=="string"||createHash7("sha256").update(threadId).digest("hex").slice(0,16)!==entry.name)throw new WalCorruptError(path4,"thread id matches its directory","refusing misplaced state");const sibling=new _EventWal(path4,parseDoc(path4,raw,this.space,threadId,this.principal));if(sibling.pending)siblings.push(sibling)}return siblings.sort((a3,b3)=>a3.pending.E-b3.pending.E)}subject;static async open(path4,opts){let raw;let bytes;try{bytes=await readFile(path4)}catch(e3){if(e3.code!=="ENOENT")throw e3}if(bytes!==void 0){try{raw=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new WalCorruptError(path4,"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(path4,"WAL exists when the subject may","no WAL file, but this thread may already have published");return new _EventWal(path4,_EventWal.virgin(opts.space,opts.threadId,opts.principal))}if(raw.length===0)throw new WalCorruptError(path4,"WAL is non-empty","the file is zero bytes \u2014 distinct from missing and never treated as a virgin thread");return new _EventWal(path4,parseDoc(path4,raw,opts.space,opts.threadId,opts.principal))}static virgin(space2,threadId,principal){return{v:EVENT_WAL_VERSION,gen:0,space:space2,epoch:randomUUID10(),threadId,principal,frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}}}async bindSubjectFrontier(frontier){if(this.subject===frontier)return;if(this.subject)throw new Error(`event WAL ${this.path}: a DIFFERENT subject frontier is already bound`);this.subject=frontier}get expectedTip(){if(!this.subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so there is no expectation to publish. The subject is shared by every thread of this principal, so this document's own last ack is not it; bind the principal's record with bindSubjectFrontier first.`);return this.subject.tip}async beginSend(frame){return this.serialize(async()=>{if(this.doc.pending)throw new Error(`event WAL ${this.path}: a frame is already pending; one emit unit is one pending frame`);assertIdToken(frame.id,"event WAL pending id");if(frame.E!==this.expectedTip)throw new Error(`event WAL ${this.path}: E=${frame.E} is not the subject's tip ${this.expectedTip}`);if(frame.seq!==this.doc.frontier.seq+1)throw new Error(`event WAL ${this.path}: seq=${frame.seq} is not the frontier's successor ${this.doc.frontier.seq+1}`);if(!Array.isArray(frame.body)||frame.body.length===0)throw new Error(`event WAL ${this.path}: a frame body must be a non-empty array of parts`);parsePayloadCalls(this.path,frame.payloadCalls);if(frame.payload){assertIdToken(frame.payload.id,"event WAL payload id");if(!isSafeNonNegInt2(frame.payload.E)||!Array.isArray(frame.payload.body)||frame.payload.body.length===0||frame.payload.ackSeq!==void 0)throw new Error("event WAL payload must be an unacknowledged frozen publication")}await this.write({...this.doc,pending:{state:"sent_unacked",...frame}})})}async recordPayloadAck(ackSeq){return this.serialize(async()=>{const p2=this.doc.pending;if(!p2?.payload||p2.state!=="sent_unacked"||p2.payload.ackSeq!==void 0)throw new Error("event WAL has no unacknowledged sibling payload");if(!isSafeNonNegInt2(ackSeq)||ackSeq<=p2.payload.E)throw new Error("payload ack must advance its frozen expectation");await this.write({...this.doc,pending:{...p2,payload:{...p2.payload,ackSeq}}})})}async recordAck(ackSeq){return this.serialize(async()=>{const p2=this.doc.pending;if(!p2||p2.state!=="sent_unacked")throw new Error(`event WAL ${this.path}: no sent_unacked frame to ack`);if(p2.payload&&p2.payload.ackSeq===void 0)throw new Error("event WAL cannot acknowledge public frame before sibling payload");if(!isSafeNonNegInt2(ackSeq))throw new Error(`event WAL ${this.path}: ackSeq must be a safe non-negative integer, got ${String(ackSeq)}`);if(ackSeq<=this.expectedTip)throw new Error(`event WAL ${this.path}: ackSeq=${ackSeq} is not ahead of the subject's tip ${this.expectedTip}`);const subject=this.subject;if(!subject)throw new Error(`event WAL ${this.path}: no subject frontier is bound, so this ack has no shared record to advance`);await this.assertNotClobbering();await subject.advance(ackSeq);await this.write({...this.doc,pending:{...p2,state:"acked",ackSeq}})})}async fold(){return this.serialize(async()=>{const p2=this.doc.pending;if(!p2||p2.state!=="acked"||p2.ackSeq===void 0)throw new Error(`event WAL ${this.path}: no acked frame to fold`);await this.write({...this.doc,frontier:{seq:p2.seq,lastSubjectSeq:p2.ackSeq,sourceCursor:p2.sourceCursor},pending:null,brackets:p2.brackets,payloadCalls:p2.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:randomUUID10(),frontier:{seq:0,lastSubjectSeq:0,sourceCursor:void 0},pending:null,brackets:{run:void 0,text:[],reasoning:[],tools:[]}})})}async write(next){await this.assertNotClobbering();const stamped={...next,gen:this.doc.gen+1};const tmp=join6(dirname6(this.path),`.${createHash7("sha256").update(this.path).digest("hex").slice(0,12)}.${process.pid}.${randomUUID10().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(e3){await unlink(tmp).catch(()=>{});throw e3}this.doc=stamped}async assertNotClobbering(){let bytes;try{bytes=await readFile(this.path)}catch(e3){if(e3.code!=="ENOENT")throw e3}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(e3){throw new WalCorruptError(this.path,"parseable JSON",e3.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 h2(value){return createHash8("sha256").update(value).digest("hex").slice(0,16)}function eventWalLocation(opts){const principal=eventPrincipalLocation(opts);const threadDir=join7(principal.principalDir,h2(opts.threadId));return{...principal,threadDir,walPath:join7(threadDir,"wal.json")}}var PrincipalLockError=class extends Error{path;invariant;constructor(path4,invariant,detail){super(`event WAL principal lock at ${path4} (${invariant}): ${detail}`);this.path=path4;this.invariant=invariant;this.name="PrincipalLockError"}};var held=new Map;function ownerIsAlive(pid){try{process.kill(pid,0);return true}catch(e3){return e3.code!=="ESRCH"}}async function createLockFile(path4){try{return await openExclusiveNoFollow(path4)}catch(e3){if(e3.code==="EEXIST")return void 0;throw e3}}async function reclaimIfOwnerIsGone(path4){let raw;try{raw=await readFile2(path4,"utf8")}catch(e3){if(e3.code==="ENOENT")return;throw e3}let record2;try{record2=JSON.parse(raw)}catch{throw new PrincipalLockError(path4,"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 r2=record2;if(!Number.isSafeInteger(r2.pid)||r2.pid<=0||typeof r2.host!=="string"||r2.host.length===0)throw new PrincipalLockError(path4,"the lock names its owner",`the record carries pid=${String(r2.pid)} host=${String(r2.host)}, which names nobody checkable`);const here=hostname();if(r2.host!==here)throw new PrincipalLockError(path4,"the recorded owner is on THIS host",`held by pid ${r2.pid} on ${r2.host} while this process runs on ${here}; liveness on another machine is not observable from here`);if(ownerIsAlive(r2.pid))throw new PrincipalLockError(path4,"the recorded owner is gone",`pid ${r2.pid} on ${here} is still running and holds this principal's emitter`);await unlink2(path4).catch(e3=>{if(e3.code!=="ENOENT")throw e3})}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:randomUUID11(),acquiredAt:new Date().toISOString()});try{await fh.writeFile(record2,"utf8");await fh.sync()}catch(e3){await fh.close().catch(()=>{});await unlink2(lockPath).catch(()=>{});throw e3}const lock={path:lockPath,async release(){if(held.get(lockPath)!==lock)return;held.delete(lockPath);await fh.close().catch(()=>{});await unlink2(lockPath).catch(e3=>{if(e3.code!=="ENOENT")throw e3})}};held.set(lockPath,lock);return lock}async function fsyncDir(dir){let fh;try{fh=await open3(dir,"r")}catch(e3){const code2=e3.code;if(code2==="EPERM"||code2==="EACCES")return;throw e3}try{await fh.sync()}catch(e3){const code2=e3.code;if(code2!=="EBADF"&&code2!=="EINVAL"&&code2!=="EPERM"&&code2!=="EISDIR")throw e3}finally{await fh.close()}}async function ensureEventWalDir(opts){const loc=eventWalLocation(opts);ensureDirNoSymlink(opts.workspaceRoot,".cotal","events",h2(opts.space),h2(opts.principal),h2(opts.threadId));for(let dir=loc.threadDir;;dir=dirname7(dir)){await fsyncDir(dir);if(dir===opts.workspaceRoot||dirname7(dir)===dir)break}const lock=await acquirePrincipalLock(loc.lockPath);return{...loc,lock}}async function checkEventStartup2(ep,env){const workspaceRoot=resolveEventsStateRoot(env);try{await checkEventStartup({workspaceRoot,space:ep.space,principal:ep.principal,retainedMessages:async()=>(await ep.chatRetention()).senders})}catch(error51){if(!(error51 instanceof EventStateConflictError))throw error51;const principal=principalKey(ep.principal.owner,ep.principal.actor).key;const threadId="startup-pending-inspection";const{walPath}=eventWalLocation({workspaceRoot,space:ep.space,principal,threadId});const inspection=await EventWal.open(walPath,{space:ep.space,principal,threadId,subjectMayExist:false});if((await inspection.pendingSiblings()).length===0)throw error51}}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=(uid2,goalId)=>`${uid2}:${goalId}`;function onceHandoffState(uid2,goalId){return proc().handoffs.get(keyOf(uid2,goalId))?.state??"pending"}function claimOnceHandoff(uid2,goalIds){const p2=proc();if(goalIds.some(id2=>onceHandoffState(uid2,id2)!=="pending"))return false;for(const id2 of goalIds){const timer2=setTimeout(()=>p2.timedOut?.(uid2,id2),ONCE_HANDOFF_MS);timer2.unref?.();p2.handoffs.set(keyOf(uid2,id2),{state:"claimed",timer:timer2})}return true}function confirmOnceHandoff(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state==="sealed")return false;if(h3?.timer!==void 0)clearTimeout(h3.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"confirmed"});return true}function sealOnceHandoff(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state!=="claimed")return false;if(h3.timer!==void 0)clearTimeout(h3.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"sealed"});return true}function endOnceHandoff(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state==="confirmed"||h3?.state==="sealed")return;if(h3?.timer!==void 0)clearTimeout(h3.timer);proc().handoffs.set(keyOf(uid2,goalId),{state:"sealed"})}function stopOnceHandoffTimer(uid2,goalId){const h3=proc().handoffs.get(keyOf(uid2,goalId));if(h3?.state!=="claimed"||h3.timer===void 0)return;clearTimeout(h3.timer);h3.timer=void 0}function onOnceHandoffTimeout(fn2){proc().timedOut=fn2}function registerOnceExit(fn2){proc().exit=fn2}function exitOnceSeat(){const p2=proc();if(p2.exiting)return p2.exiting;const exiting=askOnceExit(p2.exit).then(ending=>{if(!ending){p2.exiting=void 0;return false}setTimeout(()=>process.exit(1),ONCE_EXIT_GRACE_MS);return true});p2.exiting=exiting;return exiting}async function askOnceExit(exit){let ending;try{ending=exit?.()}catch{return true}if(ending instanceof Promise)ending=await ending.catch(()=>false);return ending!==false}init_peer_label();var LABEL_MAX_CODE_POINTS=40;function capped(s3,max){const points=Array.from(s3);return points.length<=max?s3:`${points.slice(0,max-1).join("")}\u2026`}function attributionSafe(s3){return peerLabel({name:s3})}var FROM_MAX_CODE_POINTS=160;var FROM_MIN_CODE_POINTS=" (unverified name)".length+2;function fmtFrom(i2,maxCodePoints=FROM_MAX_CODE_POINTS){if(!Number.isInteger(maxCodePoints)||maxCodePoints<FROM_MIN_CODE_POINTS)throw new RangeError(`a sender label bound must be a whole number of at least ${FROM_MIN_CODE_POINTS} code points, got ${maxCodePoints}`);const named=i2.fromName.trim()!=="";const label=peerLabel({name:named?i2.fromName:i2.fromId,...i2.fromRole?{role:i2.fromRole}:{}});const marker=named?" (unverified name)":i2.fromRole?" (unverified role)":"";return`${capped(label,maxCodePoints-marker.length)}${marker}`}function fmtBody(text3){return text3.split(LINE_BREAK).join("\n ")}function fmtItem(i2){return formatItem(i2)}function fmtDeliveryItem(i2){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(i2.fromId)}`,...i2.id?[`message_id=${field(i2.id)}`]:[],...i2.contextId?[`context_id=${field(i2.contextId)}`]:[],...i2.replyTo?[`reply_to=${field(i2.replyTo)}`]:[]];return formatItem(i2,`[${metadata2.join(" ")}] `)}function formatItem(i2,metadata2="",attributionMax){const h3=i2.historical?"(history) ":"";const body=`${metadata2}${h3}${redeliveryNote(i2)}${fmtBody(i2.text)}`;if(i2.notice)return`[${i2.notice} notice from the delivery daemon] ${body}`;const label=s3=>attributionMax===void 0?attributionSafe(s3??""):capped(attributionSafe(s3??""),LABEL_MAX_CODE_POINTS);const from=head2=>fmtFrom(i2,attributionMax===void 0?void 0:Math.min(FROM_MAX_CODE_POINTS,attributionMax-Array.from(head2).length-"] ".length));if(i2.kind==="dm")return`[DM from ${from("[DM from ")}] ${body}`;if(i2.kind==="anycast"){const head2=`[@${label(i2.service)} from `;return`${head2}${from(head2)}] ${body}`}const head=`[#${label(i2.channel)}${i2.mentionsMe?" @you":""} `;return`${head}${from(head)}] ${body}`}function redeliveryNote(i2){const n2=i2.deliveryCount;if(n2===void 0||n2<=1)return"";if(i2.firstDeliveryCount===void 0||i2.firstDeliveryCount>1)return`(broker redelivery, delivery ${n2}: prior model handoff unknown) `;if(i2.handedOverAt!==void 0&&i2.handedOverAt<n2)return`(broker redelivery, delivery ${n2}: an earlier handoff in this session was not confirmed) `;return""}function fmtChannel(channel){const safe=attributionSafe(channel??"").trim();return safe.length?safe:"?"}var CONNECTOR_VERSION="0.171.3";var MANAGER_BEARER_MARGIN_MS=12e4;function compareRelease(a3,b3){const[x2,y3]=[a3,b3].map(v3=>v3.split(/[-+]/)[0].split(".").map(Number));for(let i2=0;i2<3;i2++)if(x2[i2]!==y3[i2])return(x2[i2]??0)-(y3[i2]??0);return 0}function bearerExpiryMs2(token2){try{const exp=JSON.parse(Buffer.from(token2.split(".")[1]??"","base64url").toString("utf8")).exp;return typeof exp==="number"&&Number.isFinite(exp)?exp*1e3:void 0}catch{return void 0}}function abortable(p2,signal){if(!signal)return p2;if(signal.aborted)return Promise.reject(signal.reason);return new Promise((resolve6,reject)=>{const onAbort=()=>reject(signal.reason);signal.addEventListener("abort",onAbort,{once:true});p2.then(v3=>{signal.removeEventListener("abort",onAbort);resolve6(v3)},e3=>{signal.removeEventListener("abort",onAbort);reject(e3)})})}var AgentManagerCalls=class{getConfig;getEndpoint;getLaunchEnv;invokeEndpoint;constructor(getConfig,getEndpoint,getLaunchEnv,invokeEndpoint){this.getConfig=getConfig;this.getEndpoint=getEndpoint;this.getLaunchEnv=getLaunchEnv;this.invokeEndpoint=invokeEndpoint}get config(){return this.getConfig()}get ep(){return this.getEndpoint()}get launchEnv(){return this.getLaunchEnv()}clear(){this.managerBearers.clear()}dropBearer(argv){this.managerBearers.delete(JSON.stringify(argv))}async listManagerEndpoints(input,instance){const user=this.config.userAuth;if(!user)return{none:"manager calls ride this session's own credential on this mesh, so the session view covers them"};if(!user.bearerCmd)return{none:"this session's bearer comes from its host, which issues no manager-call bearer, so the manager view has no credential"};const managerInstanceId=instance??this.config.managerInstanceId;const token2=await this.managerCallBearer([...user.bearerCmd,"--manager-call",...managerInstanceId?["--manager-instance",managerInstanceId]:[]]).catch(e3=>{throw e3 instanceof Error?new Error(e3.message.replace("--manager-instance <instanceId>","the instance argument")):e3});const exp=bearerExpiryMs2(token2);return withUserManagerListing({...this.config,managerInstanceId},token2,exp===void 0?void 0:exp/1e3,async(nc,listing)=>listing===void 0?{unbound:true}:this.ep.listEndpointsOver(nc,listing,input))}managerBearers=new Map;managerCallBearer(argv,signal){const key=JSON.stringify(argv);const held2=this.managerBearers.get(key);if(held2&&(held2.refreshAt===void 0||Date.now()<held2.refreshAt))return abortable(held2.flight,signal);const entry={flight:this.execBearerCmd(argv)};this.managerBearers.set(key,entry);entry.flight.then(token2=>{const exp=bearerExpiryMs2(token2);if(exp===void 0||exp-MANAGER_BEARER_MARGIN_MS<=Date.now()){if(this.managerBearers.get(key)===entry)this.managerBearers.delete(key)}else entry.refreshAt=exp-MANAGER_BEARER_MARGIN_MS},()=>{if(this.managerBearers.get(key)===entry)this.managerBearers.delete(key)});return abortable(entry.flight,signal)}async execBearerCmd(argv,signal,timeoutMs){const bearer=await runAgentBearer(argv,{env:this.launchEnv,signal,timeoutMs});if(!bearer)throw new Error(`bearer command printed nothing (${argv[0]})`);return bearer}async managerInvoke(command,args,opts={}){const clean=args===void 0?void 0:Object.fromEntries(Object.entries(args).filter(([,v3])=>v3!==void 0));let r2;let dropBearer;try{const input=clean&&Object.keys(clean).length?clean:void 0;if(this.config.userAuth){const bearerCmd=this.config.userAuth.bearerCmd;if(!bearerCmd)throw new EpEnvelopeError("failed-precondition",`${command}: this agent's bearer comes from its host, which issues no manager-call bearer, so manager operations are unavailable`,void 0,"not-executed");const managerInstanceId=opts.instanceId??this.config.managerInstanceId;const{instanceId:_instanceId,follow,...invokeOpts}=opts;const bearerArgv=[...bearerCmd,"--manager-call",...managerInstanceId?["--manager-instance",managerInstanceId]:[]];const bearer=signal=>this.managerCallBearer(bearerArgv,signal).catch(e3=>{if(signal?.aborted||!(e3 instanceof Error)||e3 instanceof EpEnvelopeError)throw e3;const message=e3.message.replace("--manager-instance <instanceId>","the instance argument");if(typeof e3.retryAfterSeconds==="number")throw new EpEnvelopeError("resource-exhausted",message,void 0,"not-executed");if(e3.message.startsWith("agent-bearer: exchange refused:"))throw new EpEnvelopeError("permission-denied",message,void 0,"not-executed");throw new Error(message)});dropBearer=()=>{this.managerBearers.delete(JSON.stringify(bearerArgv))};r2=await invokeUserManager({...this.config,managerInstanceId},bearer,command,input,{...invokeOpts,follow:follow?(submit,prepare)=>this.ep.followServiceGoal(BASELINE_LIFECYCLE_ENDPOINT,submit,opts.deadlineMs,{prepare,reconcile:async(goalId,attributed,context)=>{const instanceId=attributed.responder?.instanceId;if(!instanceId)throw new Error("accepted goal has no broker-attributed manager instance");const bearer2=signal=>this.execBearerCmd([...bearerCmd,"--manager-call","--manager-instance",instanceId],signal,Math.min(3e4,context.deadlineMs));const config2={...this.config,managerInstanceId:instanceId,lifecycleUid:context.caller.uid,userAuth:{...this.config.userAuth,owner:context.caller.owner,actor:context.caller.actor}};const queryRes=await invokeUserManager(config2,bearer2,"goal-result",{goalId},{signal:context.signal,deadlineMs:Math.min(invokeOpts.deadlineMs??1e4,context.deadlineMs)});if(queryRes.reply.ok!==true)throw new Error(queryRes.reply.error?.message??"goal-result query refused");return queryRes.reply.data}}):void 0})}else{const launchLocal=command==="stop"||command==="spawn"||command==="define-persona";const classInstanceId=this.config.creds&&launchLocal&&opts.instanceId===void 0?this.config.managerInstanceId:void 0;r2=await this.invokeEndpoint(BASELINE_LIFECYCLE_ENDPOINT,command,input,{...opts,...classInstanceId!==void 0?{classInstanceId}:{}})}}catch(e3){dropBearer?.();if(e3 instanceof EpEnvelopeError){const submitted=command==="spawn"&&e3.outcome==="unknown"?e3.details?.find(d2=>d2.kind===EP_UNANSWERED&&d2.endpoint===BASELINE_LIFECYCLE_ENDPOINT&&d2.command===command&&typeof d2.requestId==="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(d2.requestId)):void 0;if(submitted)return{...controlReplyFromThrown(e3,`${e3.code}: ${e3.message}`),outcome:"unknown",data:{goalId:submitted.requestId,submissionUnknown:true}};const undeclared=undeclaredArg(e3);if(undeclared!==void 0&&command!=="status")return{...controlReplyFromThrown(e3,await this.undeclaredArgMessage(command,e3,undeclared)),...e3.outcome?{outcome:e3.outcome}:{}};const unknownDefinition=command==="define-persona"&&e3.outcome!=="not-executed"&&e3.code==="deadline-exceeded"&&e3.details?.some(d2=>d2.kind===EP_UNANSWERED&&d2.command===command);const unknownYield=command==="turn-yield"&&e3.code==="deadline-exceeded"&&e3.outcome==="unknown"&&e3.details?.some(d2=>d2.kind===EP_UNANSWERED&&d2.endpoint===BASELINE_LIFECYCLE_ENDPOINT&&d2.command===command);const message=unknownYield?`${e3.code}: ${e3.message}. The yield may already have been recorded. After reconnecting, retry cotal_yield with the same turn id and intended status. An already-settled reply confirms the turn is terminal, not which attempt settled it. A successful reply records the yield if it is still active. This retry is not a read-only check.`:unknownDefinition?`${e3.code}: ${e3.message}`:unansweredRequest(e3)?`${e3.message} (no responder answered - a manager may be down, or this credential holds no "${command}" capability and the broker denied the request)`:`${e3.code}: ${e3.message}`;return{...controlReplyFromThrown(e3,message),...e3.outcome?{outcome:e3.outcome}:{}}}return{ok:false,error:e3.message}}if(r2.reply.ok!==true)dropBearer?.();return{...controlReplyFrom(r2.reply),instanceId:r2.responder?.instanceId,...r2.reply.error?.outcome?{outcome:r2.reply.error.outcome}:{}}}async undeclaredArgMessage(command,e3,key){const head=`${e3.code}: ${e3.message}. The manager's ${command} does not take "${key}", which this connector at Cotal ${CONNECTOR_VERSION} sends`;const instanceId=undeclaredArgInstance(e3);const answer=instanceId===void 0?void 0:await this.managerInvoke("status",void 0,{instanceId}).catch(()=>void 0);const reported=answer?.ok===true&&answer.instanceId===instanceId?answer.data?.version:void 0;const manager=typeof reported==="string"&&/^\d+\.\d+\.\d+/.test(reported)?reported:void 0;const updateManager=`on the manager's host run \`cotal update --self\`, then \`cotal manager restart\`, or, if you set "${key}", call again without it`;if(manager===void 0)return`${head}, so the manager most likely runs an older Cotal: ${updateManager}`;const order=compareRelease(CONNECTOR_VERSION,manager);if(order>0)return`${head}. The manager runs Cotal ${manager}, the older side: ${updateManager}`;if(order<0)return`${head}. The manager runs Cotal ${manager}, so this connector is the older side: run \`cotal update --self\` here and start a new session`;return`${head}. The manager also reports Cotal ${manager}, so one side is another build of that version: reinstall that side`}};var legacyRail=new Map;var LEGACY_RAIL_RECHECK_MS=60*6e4;var LEGACY_RAIL_MAX=32;function onLegacyRail(key){const until=legacyRail.get(key);if(until===void 0)return false;if(Date.now()<until)return true;legacyRail.delete(key);return false}function rememberLegacyRail(key){legacyRail.set(key,Date.now()+LEGACY_RAIL_RECHECK_MS);if(legacyRail.size>LEGACY_RAIL_MAX)legacyRail.delete(legacyRail.keys().next().value)}async function withUserManagerListing(config2,token2,exp,ask){const user=config2.userAuth;const binding=managerCallerBinding(token2,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId});const railKey=binding.credentialId??token2;const connectOpts=standaloneConnectOpts({bearer:token2,sentinelCreds:user.sentinelCreds,tls:config2.tls});const connId=String(connectOpts.name);const nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:1e4});const issued=async()=>{try{const caller=await issuedUserCaller(nc,config2.space,connId,binding.caller);legacyRail.delete(railKey);return caller}catch(e3){if(!isPermissionDenied(e3))throw e3;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 resolve6=(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 resolve6(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 resolve6(signal,remaining())}};const connect3=async(signal=opts.signal,deadline=Date.now()+(opts.deadlineMs??1e4))=>{const token2=await bearer(signal);let credentialId;try{({caller,instanceId,credentialId}=managerCallerBinding(token2,{space:config2.space,owner:user.owner,actor:user.actor,lifecycleUid:config2.lifecycleUid,instanceId:config2.managerInstanceId}))}catch{throw new EpEnvelopeError("failed-precondition","the manager control bearer is not bound to the expected caller and manager instance",void 0,"not-executed")}const connectOpts=standaloneConnectOpts({bearer:token2,sentinelCreds:user.sentinelCreds,tls:config2.tls});signal?.throwIfAborted();const left=deadline-Date.now();if(left<=0)throw new EpEnvelopeError("deadline-exceeded","the deadline passed before the manager was connected; the manager request WAS NOT RUN",void 0,"not-executed");try{nc=await dialerFor(config2.servers)({servers:config2.servers,...connectOpts,maxReconnectAttempts:0,timeout:left})}catch(error51){signal?.throwIfAborted();if(error51 instanceof EpEnvelopeError)throw error51;throw new EpEnvelopeError(isAuthRejection(error51)?"permission-denied":"unavailable",error51 instanceof Error?error51.message:String(error51),void 0,"not-executed")}if(signal?.aborted)onAbort();signal?.throwIfAborted();const railKey=credentialId??token2;if(onLegacyRail(railKey)){skippedAcceptedRead={key:railKey,connId:String(connectOpts.name)}}else{try{caller=await issuedUserCaller(nc,config2.space,String(connectOpts.name),caller)}catch(e3){if(!isPermissionDenied(e3))throw e3;rememberLegacyRail(railKey)}}};const prepare=async(signal,deadline)=>{await connect3(signal,deadline);service=await resolvePrepared(signal,deadline)};const invoke=async(signal=opts.signal)=>{const unfollowable=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable)return unfollowable;const invokeOpts={target:opts.target,deadlineMs:opts.deadlineMs,signal};const result=await invokeCommand(nc,config2.space,service,command,args,invokeOpts);if(result.reply.ok===false&&replyRefusedBeforeEffect(result.reply.error)){try{service=await resolve6(signal);const unfollowable2=opts.follow?goalFollowRefusal(service):void 0;if(unfollowable2)throw new Error(unfollowable2.reply.error.message)}catch(error51){return{...result,reply:{...result.reply,error:{...result.reply.error,message:`${command} WAS NOT RUN; manager instance ${instanceId} refused before effects, and re-resolution failed: ${error51 instanceof Error?error51.message:String(error51)}`}}}}return invokeCommand(nc,config2.space,service,command,args,invokeOpts)}return result};opts.signal?.addEventListener("abort",onAbort,{once:true});try{if(opts.follow)return await opts.follow(invoke,prepare);await connect3();service=await resolvePrepared();return await invoke()}finally{opts.signal?.removeEventListener("abort",onAbort);const control=nc;if(control)await drainAndClose(control,2e3)}}import{randomBytes as randomBytes4}from"node:crypto";var COMMAND_LIST_MS=1e4;var MAX_QUEUED_COMMANDS=8;var ENDED_COMMANDS_KEPT=32;var CommandRefused=class extends Error{code;constructor(code2,message){super(message);this.code=code2;this.name="CommandRefused"}};var B32="abcdefghijklmnopqrstuvwxyz234567";var refused=(code2,message)=>new EpEnvelopeError(code2,message,void 0,"not-executed");var what=c3=>`the ${c3.target} "${c3.name}"`;function cut(text3,max){const chars=[...text3];return chars.length<=max?text3:`${chars.slice(0,max-1).join("")}\u2026`}function fitText(text3,max){return typeof text3==="string"&&text3!==""?cut(text3,max):void 0}function within(work,ms){let timer2;const late=new Promise((_3,reject)=>{timer2=setTimeout(()=>reject(new Error(`no answer within ${ms/1e3} s`)),ms)});return Promise.race([Promise.resolve().then(work),late]).finally(()=>clearTimeout(timer2))}function createCommandLane(dispatcher,onQueued){const entries=new Map;const ended=[];let closed4=false;const queued=()=>[...entries.values()].filter(e3=>e3.state.kind==="queued");const known=id2=>{const e3=entries.get(id2);if(!e3)throw refused("not-found",`command ${id2} is not known to this agent`);return e3};function end(e3,state){e3.state=state;ended.push(e3.id);while(ended.length>ENDED_COMMANDS_KEPT)entries.delete(ended.shift())}async function list(){if(!dispatcher)return{supported:false};let listed;try{listed=await within(()=>dispatcher.list(),COMMAND_LIST_MS)}catch(e3){throw refused("unavailable",`the harness did not list its commands: ${e3.message}`)}if(!Array.isArray(listed))throw refused("internal","the connector's list is not an array");const commands=[];for(const e3 of listed){if(!isAgentCommandName(e3?.name))continue;if(!dispatcher.targets.has(e3.target))throw refused("internal",`the connector listed the ${String(e3.target)} "${e3.name}" but runs no ${String(e3.target)}s`);const description=fitText(e3.description,AGENT_COMMAND_DESCRIPTION_MAX),inputHint=fitText(e3.inputHint,AGENT_COMMAND_INPUT_HINT_MAX);commands.push({name:e3.name,target:e3.target,...description?{description}:{},...inputHint?{inputHint}:{}})}if(commands.length>AGENT_COMMAND_LIST_MAX)throw refused("resource-exhausted",`the harness lists ${commands.length} commands and skills, over the ${AGENT_COMMAND_LIST_MAX} a reply carries`);return{supported:true,commands}}function run(input){if(!dispatcher)throw refused("unimplemented","this agent's connector runs no commands or skills");if(!dispatcher.targets.has(input.target))throw refused("unimplemented",`this agent's connector runs no ${input.target}s`);if(closed4)throw refused("unavailable","this agent is stopping");if(queued().length>=MAX_QUEUED_COMMANDS)throw refused("resource-exhausted",`${MAX_QUEUED_COMMANDS} commands are already queued`);let id2;do id2=Array.from(randomBytes4(26),b3=>B32[b3&31]).join("");while(entries.has(id2));entries.set(id2,{id:id2,command:{target:input.target,name:input.name,args:input.args??""},state:{kind:"queued"}});onQueued();return{id:id2}}function cancel({id:id2}){const e3=known(id2);if(e3.state.kind==="queued")end(e3,{kind:"cancelled"});else if(e3.state.kind!=="cancelled")throw new EpEnvelopeError("conflict",`command ${id2} is ${e3.state.kind}, so it can no longer be cancelled`,[{kind:AGENT_COMMAND_STATE_DETAIL,state:e3.state}],"not-executed");return{state:e3.state}}return{handlers:[{command:"commands",contract:AGENT_CONTRACTS.commands,handler:()=>list()},{command:"command",contract:AGENT_CONTRACTS.command,handler:ctx=>run(ctx.request.args)},{command:"command-cancel",contract:AGENT_CONTRACTS["command-cancel"],handler:ctx=>cancel(ctx.request.args)},{command:"command-state",contract:AGENT_CONTRACTS["command-state"],handler:ctx=>({state:known(ctx.request.args.id).state})}],get queued(){return queued().length},async dispatchNext(){const e3=queued()[0];if(!e3)return"empty";e3.state={kind:"taken"};try{await dispatcher.dispatch(e3.command);end(e3,{kind:"started"});return"dispatched"}catch(err3){const message=String(err3?.message??err3);end(e3,err3 instanceof CommandRefused?{kind:"refused",code:err3.code,message:cut(message,AGENT_COMMAND_MESSAGE_MAX)}:{kind:"unknown",code:"internal",message:cut(`the harness failed, so ${what(e3.command)} may have started: ${message}`,AGENT_COMMAND_MESSAGE_MAX)});return"failed"}},close(){closed4=true;for(const e3 of queued())end(e3,{kind:"refused",code:"unavailable",message:`the agent stopped before ${what(e3.command)} started`})}}}import{randomBytes as randomBytes5}from"node:crypto";var PROMPT_DESK_MIN_MAX_PAYLOAD=524288;var PROMPT_SUMMARY_MAX_BYTES=4096;var PROMPT_ANSWER_REPLY_MS=1e4;var PROMPT_OPEN_MS=Object.freeze({min:1e3,max:7*24*60*60*1e3});var PROMPT_SETTLE_MS=Object.freeze({min:1e3,max:24*60*60*1e3});var PromptRefused=class extends Error{reason;constructor(reason,message){super(message);this.reason=reason;this.name="PromptRefused"}};var NONE={tie:"none"};function stepPrompt(state,event,at2){const close=(outcome,attempted)=>({kind:"move",next:{kind:"closed",at:at2,outcome},end:{attempted}});if(state.kind==="open"){switch(event.kind){case"accept":return{kind:"move",next:{kind:"sent",answer:event.answer,delivery:"unconfirmed"},deliver:true};case"settle":{const e3=event.evidence;if(e3.kind==="local")return close({kind:"local",seen:e3.seen},false);if(e3.kind==="observed")return close(e3.seen.tie==="prompt"?{kind:"local",seen:e3.seen}:{kind:"withdrawn",seen:e3.seen},false);if(e3.kind==="withdrawn")return close({kind:"withdrawn",seen:NONE},false);return{kind:"stay",warn:"a confirmation came for a prompt with no accepted answer"}}case"expiry":return close({kind:"expired"},false);case"close":return close({kind:"withdrawn",seen:NONE},false);case"delivery":return{kind:"stay",warn:"a delivery result came for a prompt with no deliver call"};case"settle-time":return{kind:"cannot-happen",why:"the settle time starts at the accepted answer"}}}if(state.kind==="sent"){const answer=state.answer;switch(event.kind){case"accept":return{kind:"never-reached",why:"an answer to a sent prompt meets check 3 or 4"};case"delivery":if(state.delivery==="delivered")return{kind:"cannot-happen",why:"deliver has one result"};if(event.result==="delivered")return{kind:"move",next:{kind:"sent",answer,delivery:"delivered"}};if(event.result==="confirmed")return close({kind:"answered",answer},true);if(event.result==="gone")return close({kind:"undelivered",answer},true);return{kind:"stay",warn:"deliver failed, which proves nothing about the hand-over"};case"settle":{const e3=event.evidence;if(e3.kind==="confirmed")return close({kind:"answered",answer},true);if(e3.kind==="local")return close({kind:"local",seen:e3.seen,late:answer},true);if(e3.kind==="observed")return close({kind:"unconfirmed",answer,seen:e3.seen},true);return close({kind:"unconfirmed",answer,seen:NONE},true)}case"expiry":return{kind:"stay"};case"settle-time":case"close":return close({kind:"unconfirmed",answer,seen:NONE},true)}}if(event.kind==="accept")return{kind:"never-reached",why:"an answer to a closed prompt meets check 3 or 4"};if(event.kind==="settle")return{kind:"stay",warn:"a report came for a closed prompt",report:true};return{kind:"stay"}}var iso=ms=>new Date(ms).toISOString();function describe(v3){try{if(v3 instanceof Error)return v3.message;const json2=JSON.stringify(v3);if(json2!==void 0)return json2.length>200?`${json2.slice(0,200)}...`:json2}catch{}try{return typeof v3==="bigint"?`${v3}n`:String(v3)}catch{return`a ${typeof v3} with no text form`}}function ignoreRejection(v3){try{const then=v3?.then;if(typeof then!=="function")return false;then.call(v3,void 0,()=>{})}catch{}return true}function deliveryKind(d2){try{return d2?.kind}catch{return void 0}}var B322="abcdefghijklmnopqrstuvwxyz234567";var EFFECTS=new Set(["proceed","refuse","cancel"]);function deepFreeze6(value){if(value!==null&&typeof value==="object"&&!Object.isFrozen(value)){for(const child of Object.values(value))deepFreeze6(child);Object.freeze(value)}return value}function timer(ms,fn2){const t2=setTimeout(fn2,ms);t2.unref();return t2}function refused2(code2,message,details){return new EpEnvelopeError(code2,message,details,"not-executed")}function parseSeen(s3){const o3=s3;if(o3&&typeof o3==="object"&&!Array.isArray(o3)){const keys=Object.keys(o3).length;if(o3.tie==="none"&&keys===1)return{tie:"none"};if((o3.tie==="prompt"||o3.tie==="subject")&&keys===2&&EFFECTS.has(o3.effect))return{tie:o3.tie,effect:o3.effect}}throw new TypeError(`settle: ${describe(s3)} is not a sighting ({ tie: "prompt" | "subject", effect } or { tie: "none" })`)}function parseEvidence(e3){const o3=e3;if(o3&&typeof o3==="object"&&!Array.isArray(o3)){const keys=Object.keys(o3).length;if((o3.kind==="confirmed"||o3.kind==="withdrawn")&&keys===1)return{kind:o3.kind};if((o3.kind==="local"||o3.kind==="observed")&&keys===2)return{kind:o3.kind,seen:parseSeen(o3.seen)}}throw new TypeError(`settle: ${describe(e3)} is not an Evidence`)}var LONGEST_BY=Object.freeze({id:`${"w".repeat(64)}.${"w".repeat(64)}`,uid:"w".repeat(32),authority:"owner"});var ANY_AT="2000-01-01T00:00:00.000Z";var LONGEST_SEEN=Object.freeze({tie:"subject",effect:"proceed"});function largestSummaryBytes(base,options){let max=0;const measure=state=>{max=Math.max(max,Buffer.byteLength(JSON.stringify({...base,state})))};const closed4=outcome=>({kind:"closed",at:ANY_AT,outcome});measure({kind:"open"});measure(closed4({kind:"expired"}));measure(closed4({kind:"withdrawn",seen:LONGEST_SEEN}));measure(closed4({kind:"local",seen:LONGEST_SEEN}));for(const o3 of options){const answer={by:LONGEST_BY,option:o3.id,effect:o3.effect,at:ANY_AT};measure({kind:"sent",answer,delivery:"unconfirmed"});measure({kind:"sent",answer,delivery:"delivered"});measure(closed4({kind:"answered",answer}));measure(closed4({kind:"unconfirmed",answer,seen:LONGEST_SEEN}));measure(closed4({kind:"undelivered",answer}));measure(closed4({kind:"local",seen:LONGEST_SEEN,late:answer}))}return max}var Desk=class{ep;held=new Map;closedOrder=[];live=0;seq=0;stepping=false;later=[];presenceOwed=false;serving=false;closed=false;warn;constructor(ep,warn){this.ep=ep;this.warn=msg=>{try{warn(msg)}catch{}}}get waiting(){return this.live}handlers(){return[{command:"prompts",contract:AGENT_CONTRACTS.prompts,handler:ctx=>this.list(ctx)},{command:"prompt",contract:AGENT_CONTRACTS.prompt,handler:ctx=>this.read(ctx)},{command:"prompt-answer",contract:AGENT_CONTRACTS["prompt-answer"],handler:ctx=>this.answer(ctx)}]}served(ready){this.seq=this.ep.nextPromptsSeq();this.serving=true;ready.then(()=>{this.presenceOwed=true;this.flushPresence()},()=>{})}close(){if(this.closed)return;this.closed=true;this.defer(()=>{for(const h3 of[...this.held.values()])if(h3.state.kind!=="closed")this.apply(h3,{kind:"close"})})}open(spec,hooks){if(this.closed)throw new PromptRefused("closed","the prompt desk has closed; the harness answers this dialog");const invalid2=why=>new PromptRefused("invalid",why);if(!spec||typeof spec!=="object")throw invalid2("a prompt spec is an object");if(!hooks||typeof hooks.deliver!=="function"||typeof hooks.end!=="function"||hooks.check!==void 0&&typeof hooks.check!=="function")throw invalid2("hooks need deliver and end, and check when given, as functions");for(const[name2,value,range]of[["openMs",spec.openMs,PROMPT_OPEN_MS],["settleMs",spec.settleMs,PROMPT_SETTLE_MS]])if(!Number.isSafeInteger(value)||value<range.min||value>range.max)throw invalid2(`${name2} must be an integer from ${range.min} to ${range.max} ms, not ${String(value)}`);let canonical;try{canonical=canonicalJson(spec.content)}catch(e3){throw invalid2(`the content is not interchangeable JSON: ${describe(e3)}`)}const contentBytes=Buffer.byteLength(canonical);if(contentBytes>AGENT_PROMPT_CONTENT_MAX_BYTES)throw new PromptRefused("too-large",`the canonical content is ${contentBytes} bytes, over ${AGENT_PROMPT_CONTENT_MAX_BYTES}`);const content=deepFreeze6(JSON.parse(canonical));let id2;do id2=Array.from(randomBytes5(26),b3=>B322[b3&31]).join("");while(this.held.has(id2));const digest=agentPromptDigest(content);const now=Date.now();const openedAt=iso(now),expiresAtMs=now+spec.openMs,expiresAt=iso(expiresAtMs);const validate2=AGENT_CONTRACTS.prompt.output.validate;if(!validate2({prompt:{id:id2,digest,openedAt,expiresAt,state:{kind:"open"},content}})){const first=validate2.errors?.[0];throw invalid2(`the content does not match the prompt schema: ${first?`${first.instancePath||"/"} ${first.message}`:"invalid"}`)}const options=new Map;for(const o3 of content.options){if(options.has(o3.id))throw invalid2(`option id "${o3.id}" is used twice`);options.set(o3.id,o3);if(o3.form==="required"&&content.form===void 0)throw invalid2(`option "${o3.id}" submits a form, and the content has none`)}if(content.form!==void 0&&!content.options.some(o3=>o3.form==="required"))throw invalid2("the content has a form, and no option submits it");const input=content.subject?.type==="tool"?content.subject.input:void 0;if(input?.kind==="omitted"&&content.options.some(o3=>o3.effect==="proceed"))throw invalid2("a tool input that is omitted can be refused remotely, never approved: no option may proceed");let form;if(content.form!==void 0){const schema=content.form.schema;for(const name2 of schema.required??[])if(!Object.hasOwn(schema.properties,name2))throw invalid2(`form.schema.required names "${name2}", which is not a property`);try{form=compileContractSchema({root:{...schema,additionalProperties:false}})}catch(e3){throw invalid2(`form.schema does not compile: ${describe(e3)}`)}}const base={id:id2,digest,openedAt,expiresAt,kind:content.kind,title:content.title,contentBytes,...content.source!==void 0?{source:content.source}:{}};const largest=largestSummaryBytes(base,content.options);if(largest>PROMPT_SUMMARY_MAX_BYTES)throw new PromptRefused("too-large",`the summary encodes to ${largest} bytes in its largest state, over ${PROMPT_SUMMARY_MAX_BYTES}`);if(this.live>=AGENT_PROMPT_LIST_MAX)throw new PromptRefused("full",`${AGENT_PROMPT_LIST_MAX} prompts are open or sent`);const h3={id:id2,hooks,settleMs:spec.settleMs,expiresAtMs,base:deepFreeze6(base),live:{content,options,...form?{form}:{}},state:deepFreeze6({kind:"open"}),reports:0,ended:false,waiters:new Set};this.held.set(id2,h3);this.live++;this.bump();h3.expiry=timer(Math.max(0,expiresAtMs-Date.now()),()=>this.expire(h3));if(!this.stepping)this.flushPresence();return Object.freeze({id:id2,settle:evidence=>{const e3=parseEvidence(evidence);this.defer(()=>this.apply(h3,{kind:"settle",evidence:e3}))}})}expire(h3){const left=h3.expiresAtMs-Date.now();if(left>0){h3.expiry=timer(left,()=>this.expire(h3));return}this.defer(()=>this.apply(h3,{kind:"expiry"}))}settleTime(h3){const left=h3.settleAtMs-Date.now();if(left>0){h3.settle=timer(left,()=>this.settleTime(h3));return}this.defer(()=>this.apply(h3,{kind:"settle-time"}))}run(fn2){if(this.stepping)throw new Error("prompt desk: a step started inside another step");this.stepping=true;try{return fn2()}finally{try{for(let next=this.later.shift();next;next=this.later.shift())next()}finally{this.stepping=false;this.flushPresence()}}}defer(fn2){if(this.stepping)this.later.push(fn2);else this.run(fn2)}apply(h3,event,why){const step=stepPrompt(h3.state,event,iso(Date.now()));if(step.kind==="cannot-happen"||step.kind==="never-reached"){this.warn(`prompt desk bug: event ${event.kind} met prompt ${h3.id} in state ${h3.state.kind}, a row that ${step.kind==="cannot-happen"?"cannot happen":"is never reached"}: ${step.why}`);return}if(step.kind==="stay"){if(step.report)this.warn(`prompt ${h3.id} is closed, so a "${event.evidence.kind}" report is ignored (${++h3.reports} so far)`);else if(step.warn)this.warn(`prompt ${h3.id}: ${step.warn}${why?`: ${why}`:""}`);if(event.kind==="delivery"&&event.result==="failed")this.answerWaiters(h3);return}h3.state=deepFreeze6(step.next);this.bump();if(h3.state.kind==="closed")this.retire(h3);if(!(h3.state.kind==="sent"&&h3.state.delivery==="unconfirmed"))this.answerWaiters(h3);if(step.end)this.end(h3,step.end.attempted)}answerWaiters(h3){for(const w2 of h3.waiters){clearTimeout(w2.timer);w2.resolve(h3.state)}h3.waiters.clear()}retire(h3){clearTimeout(h3.expiry);clearTimeout(h3.settle);h3.live=void 0;this.live--;this.closedOrder.push(h3.id);while(this.closedOrder.length>AGENT_PROMPT_LIST_MAX)this.held.delete(this.closedOrder.shift())}end(h3,attempted){if(h3.ended){this.warn(`prompt desk bug: prompt ${h3.id} ended twice`);return}h3.ended=true;const hooks=h3.hooks;h3.hooks=void 0;try{ignoreRejection(hooks.end({attempted}))}catch(e3){this.warn(`prompt ${h3.id}: the adapter's end threw: ${describe(e3)}`)}}bump(){this.seq=this.ep.nextPromptsSeq();this.presenceOwed=true}flushPresence(){if(!this.presenceOwed||this.closed||!this.serving)return;this.presenceOwed=false;this.ep.setPromptsPresence({open:this.live,seq:this.seq}).catch(e3=>{if(!this.closed)this.warn(`the prompts presence field was not written: ${describe(e3)}`)})}fit(ctx,data){if(ctx.replyFits(data,Number.MAX_SAFE_INTEGER))return data;const bytes=Buffer.byteLength(JSON.stringify({v:1,id:ctx.request.id,ok:true,data}));const limit=this.ep.maxPayload;throw refused2("resource-exhausted",`the reply is ${bytes} bytes, over this connection's max_payload of ${limit}`,[{kind:AGENT_PROMPT_SIZE_DETAIL,bytes,limit}])}summary(h3){return{...h3.base,state:h3.state}}list(ctx){const open7=[];for(const h3 of this.held.values())if(h3.state.kind!=="closed")open7.push(this.summary(h3));const closed4=this.closedOrder.map(id2=>this.summary(this.held.get(id2)));const runtime={id:ctx.principal.runtimeId,startedAt:processRuntime(ctx.principal.uid).startedAt};return this.fit(ctx,{runtime,seq:this.seq,open:open7,closed:closed4})}read(ctx){const{id:id2}=ctx.request.args;const h3=this.held.get(id2);if(h3===void 0)throw refused2("not-found",`prompt ${id2} is not known to this runtime`);if(h3.live===void 0)throw refused2("failed-precondition",`prompt ${id2} is closed`,[{kind:AGENT_PROMPT_STATE_DETAIL,state:h3.state}]);const{digest,openedAt,expiresAt}=h3.base;return this.fit(ctx,{prompt:{id:id2,digest,openedAt,expiresAt,state:h3.state,content:h3.live.content}})}answer(ctx){const got=this.run(()=>this.decide(ctx));return got instanceof Promise?got.then(state=>({state})):{state:got}}decide(ctx){const a3=ctx.request.args;try{canonicalJson(a3)}catch(e3){throw refused2("bad-request",`the answer is not interchangeable JSON: ${describe(e3)}`)}if(ctx.caller.owner===ctx.principal.owner&&ctx.caller.actor===ctx.principal.actor)throw refused2("permission-denied","an agent never answers its own prompt");const h3=this.held.get(a3.id);if(h3===void 0)throw refused2("not-found",`prompt ${a3.id} is not known to this runtime`);const fingerprint=answerFingerprint(a3,ctx.caller);if(h3.fingerprint===fingerprint)return h3.state;if(h3.state.kind!=="open"||h3.live===void 0)throw refused2("conflict",`prompt ${a3.id} is not open`,[{kind:AGENT_PROMPT_STATE_DETAIL,state:h3.state}]);if(a3.digest!==h3.base.digest)throw refused2("failed-precondition",`the digest is not prompt ${a3.id}'s`,[{kind:AGENT_PROMPT_DIGEST_DETAIL,digest:h3.base.digest}]);const option=h3.live.options.get(a3.option);if(option===void 0)throw refused2("bad-request",`option "${a3.option}" is not one of the prompt's`);if(option.note==="required"&&(a3.note===void 0||a3.note===""))throw refused2("bad-request",`option "${option.id}" needs a note`);if(option.note===void 0&&a3.note!==void 0)throw refused2("bad-request",`option "${option.id}" takes no note`);if(option.form==="required"&&a3.values===void 0)throw refused2("bad-request",`option "${option.id}" submits the form and needs values`);if(option.form===void 0&&a3.values!==void 0)throw refused2("bad-request",`option "${option.id}" takes no values`);if(a3.values!==void 0&&!h3.live.form(a3.values)){const first=h3.live.form.errors?.[0];throw refused2("bad-request",`the values do not match the form: ${first?`${first.instancePath||"/"} ${first.message}`:"invalid"}`)}const by={id:`${ctx.caller.owner}.${ctx.caller.actor}`,uid:ctx.caller.uid,authority:ctx.authority};const verdict=deepFreeze6({option:option.id,...a3.note!==void 0?{note:a3.note}:{},...a3.values!==void 0?{values:structuredClone(a3.values)}:{},by});let refusal;try{refusal=h3.hooks.check?.(verdict)}catch(e3){this.warn(`prompt ${h3.id}: the adapter's check threw: ${describe(e3)}`);throw refused2("internal",`the agent could not check this answer: ${describe(e3)}`)}if(refusal!==void 0){if(typeof refusal!=="string"){this.warn(`prompt ${h3.id}: the adapter's check returned ${ignoreRejection(refusal)?"a promise, and check is synchronous":`${typeof refusal}, not a message or undefined`}`);throw refused2("internal","the agent could not check this answer")}throw refused2("bad-request",refusal||"the agent refused this answer")}if(Date.now()>=h3.expiresAtMs)throw refused2("expired",`prompt ${h3.id} expired at ${h3.base.expiresAt}`);const acceptedAt=Date.now();const answer={by,option:option.id,effect:option.effect,at:iso(acceptedAt)};const step=stepPrompt(h3.state,{kind:"accept",answer},answer.at);if(step.kind!=="move"||!step.deliver)throw refused2("internal","prompt desk bug: an open prompt did not accept");h3.state=deepFreeze6(step.next);h3.fingerprint=fingerprint;this.bump();h3.settleAtMs=acceptedAt+h3.settleMs;h3.settle=timer(h3.settleMs,()=>this.settleTime(h3));const wait=new Promise(resolve6=>{const w2={resolve:resolve6,timer:timer(PROMPT_ANSWER_REPLY_MS,()=>this.defer(()=>{if(h3.waiters.delete(w2))resolve6(h3.state)}))};h3.waiters.add(w2)});this.deliver(h3,verdict);return wait}deliver(h3,verdict){let result;try{result=Promise.resolve(h3.hooks.deliver(verdict))}catch(e3){result=Promise.reject(e3)}const failed=why=>this.defer(()=>this.apply(h3,{kind:"delivery",result:"failed"},why));result.then(d2=>{const kind=deliveryKind(d2);if(kind==="confirmed"||kind==="delivered"||kind==="gone")this.defer(()=>this.apply(h3,{kind:"delivery",result:kind}));else failed(`deliver resolved with ${describe(d2)}, which is not a Delivery`)},e3=>failed(describe(e3))).catch(e3=>this.warn(`prompt desk bug: applying prompt ${h3.id}'s delivery result threw: ${describe(e3)}`))}};function answerFingerprint(a3,caller){return contractDigest({id:a3.id,digest:a3.digest,option:a3.option,note:a3.note??null,values:a3.values??null,caller:`${caller.owner}.${caller.actor}.${caller.uid}`})}function createPromptDesk(ep,warn){return new Desk(ep,warn)}async function openAgentEndpoint(ep,opts){if(typeof opts?.warn!=="function")throw new TypeError("openAgentEndpoint needs opts.warn");const max=ep.maxPayload;if(max<PROMPT_DESK_MIN_MAX_PAYLOAD)throw new Error(`the agent endpoint needs a connection whose max_payload is at least ${PROMPT_DESK_MIN_MAX_PAYLOAD} bytes, and this one is ${max}`);const warn=msg=>{try{opts.warn(msg)}catch{}};const desk=createPromptDesk(ep,warn);const lane=createCommandLane(opts.dispatcher,opts.onQueued??(()=>{}));const serve=ep.servePrincipal({handlers:[...desk.handlers(),...lane.handlers]});desk.served(serve.ready);let closing;const close=()=>closing??=(()=>{ep.off("transport",onTransport);desk.close();lane.close();return serve.stop()})();const onTransport=t2=>{if(!t2.connected||closing)return;let now;try{now=ep.maxPayload}catch{return}if(now>=PROMPT_DESK_MIN_MAX_PAYLOAD)return;warn(`the agent endpoint closed: the connection's max_payload is ${now} bytes, under the ${PROMPT_DESK_MIN_MAX_PAYLOAD} its largest replies need`);void close()};ep.on("transport",onTransport);void serve.failed.then(err3=>{if(closing)return;warn(`the agent endpoint closed: ${err3.message}`);void close()});try{await serve.ready}catch(e3){void close();throw e3}return{prompts:desk,commands:lane,close}}import{randomUUID as randomUUID12}from"node:crypto";import{createHash as createHash9}from"node:crypto";var CHANNEL_CATCHUP_AGE_MS=5*6e4;function afterRecallMark(a3,b3){return a3.ts!==b3.ts?a3.ts>b3.ts:a3.id>b3.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;function deliveryNoticeOf(m2){for(const p2 of m2.parts){if(p2.kind!=="data"||typeof p2.data!=="object"||p2.data===null||Array.isArray(p2.data))continue;if(ANYCAST_NOTICE_KEY in p2.data)return"anycast";if(MENTION_NOTICE_KEY in p2.data)return"mention"}return void 0}function idlessDigest(m2){return createHash9("sha256").update(JSON.stringify(m2)).digest("base64url")}function handOver(item){item.handedOverAt??=item.deliveryCount??0}function ingestDedupKey(id2){return id2===""?void 0:id2}var AgentInbox=class{deps;constructor(deps){this.deps=deps}get ep(){return this.deps.endpoint()}get config(){return this.deps.config()}get _transportConnected(){return this.deps.transportConnected()}emit(event,item){this.deps.emit(event,item)}handleEndpointWarning(error51){this.deps.warning(error51)}noteDirected(item){this.deps.noteDirected(item)}inOrder(write){return this.deps.inOrder(write)}requireConnected(){return this.deps.requireConnected()}seedChannelModes(config2){for(const c3 of config2.quiet??[])this.channelModes.set(c3,"quiet");for(const c3 of config2.muted??[])this.channelModes.set(c3,"muted")}onTransport(connected){if(!connected){this.transportDrops++;for(const p2 of this.inbox.filter(x2=>x2.take&&!this.inFlightIds.has(x2.item.recvKey)))this.regate(p2)}if(connected&&this.mayAskTakes()){this.dropLapsedTakes();for(const p2 of this.gated)if(p2.taking===void 0)this.emit("incoming",p2.item)}}stop(){for(const key of[...this.renewals.keys()])this.stopRenewal(key);clearTimeout(this.takeRetry);this.takeRetry=void 0}inbox=[];gated=[];arrivals=0;heldTake;takeRetry;handledIds=new Set;handledIdsPrev=new Set;evictedClassifications=new Map;inFlightIds=new Map;lowerOnRelease=new Set;renewals=new Map;classificationUnsafe=false;protectedPullOnlyIds=new Set;protectedDropIds=new Set;dropUnsafe=false;_lastInboxDrainedAt;_lastAutomaticDrainedAt;_lastAutomaticHeadDrainedAt;_attention="open";_recallCursor={ts:0,id:""};aheadDelivered=new Set;channelModes=new Map;focusSince;enteringFocus=false;recvKeySecret=randomUUID12().replace(/-/g,"");recvKeySeq=0;focusExcludedIds=new Map;focusIdless=new Map;focusIdlessEntries=0;idlessEpoch=0;recallLock=Promise.resolve();transportDrops=0;focusRecallUnsafeChannels=new Set;get lastInboxDrainedAt(){return this._lastInboxDrainedAt}get lastAutomaticDrainedAt(){return this._lastAutomaticDrainedAt}get lastAutomaticHeadDrainedAt(){return this._lastAutomaticHeadDrainedAt}oldestAutomaticKey(){let head;for(const pending of this.inbox){if(pending.pullOnly)continue;if(head===void 0||pending.receivedAt<head.receivedAt)head=pending}return head?.item.recvKey}noteAutomaticHeadProgress(selected){const head=this.oldestAutomaticKey();if(head===void 0)return;if(selected.some(p2=>!p2.pullOnly&&p2.item.recvKey===head))this._lastAutomaticHeadDrainedAt=Date.now()}automaticQueueStalledForMs(now=Date.now()){const oldest=this.oldestAutomaticReceivedAt();if(oldest===void 0)return void 0;const since=Math.max(oldest,this._lastAutomaticHeadDrainedAt??0);const held2=now-since;return held2>0?held2:0}get channelDeliveryIssue(){return this.dropUnsafe?"Channel drop tracking exhausted. Ambient channel traffic is suppressed until restart; non-historical mentions on unmuted channels wake to pull their buffered body. Focus recall may be incomplete.":void 0}async ingestNotice(m2,delivery,meta3,notice){const holder=await this.ep.deliveryLeaseHolder(0);this.ingest(m2,delivery,meta3,holder!==void 0&&holder===m2.from.id?notice:void 0)}ingest(m2,delivery,meta3,notice){const key=ingestDedupKey(m2.id);if(key!==void 0&&(this.handledIds.has(key)||this.handledIdsPrev.has(key))){if(delivery.durable)delivery.ack();return}if(key!==void 0&&(this.protectedPullOnlyIds.has(key)||this.protectedDropIds.has(key))){if(delivery.durable)delivery.ack();return}const existing=key===void 0?void 0:this.inbox.find(p2=>p2.item.id===key)??this.gated.find(p2=>p2.item.id===key);if(existing){if(delivery.durable){existing.ack=delivery.ack;this.own(existing,delivery.redelivery);if(delivery.take)existing.take=delivery.take;if(this.inFlightIds.has(existing.item.recvKey))this.keepOwned(existing.item.recvKey);else if(existing.take&&existing.takenCount!==existing.item.deliveryCount)this.regate(existing);this.emit("incoming",existing.item)}return}if(!meta3)throw new Error(`message ${m2.id} delivered without MessageMeta \u2014 its class is unauthenticated`);const historical=meta3.historical||meta3.kind==="channel"&&delivery.durable&&Date.now()-m2.ts>CHANNEL_CATCHUP_AGE_MS;const item=this.toInboxItem(m2,meta3.kind,historical);if(notice)item.notice=notice;else if(!delivery.take)this.noteDirected(item);if(item.kind==="channel"){const cm=this.channelModes.get(item.channel??"");const digest=item.id===""&&(this.enteringFocus||this._attention==="focus")?idlessDigest(m2):void 0;const tally=digest===void 0?void 0:this.reserveIdless(digest,item.channel??"");const copy2=tally?this.settleIdless(tally):void 0;const idless=copy2&&{digest,copy:copy2};if(this.enteringFocus)this.excludeFromFocus(item);if(this.dropUnsafe){this.excludeFromFocus(item);if(cm!=="muted"&&item.mentionsMe&&!item.historical){this.buffer(item,delivery,true,idless);this.emit("mention-wake",item)}else delivery.ack();return}if(cm==="muted"){this.evictedClassifications.delete(item.id);this.excludeFromFocus(item);this.protectDisposition(item.id,"drop");delivery.ack();return}const remembered=item.id===""?void 0:this.evictedClassifications.get(item.id);if(remembered)this.evictedClassifications.delete(item.id);const snapshottedPullOnly=item.historical||!item.mentionsMe&&(remembered?.pullOnly??cm==="quiet");if(cm==="quiet"||snapshottedPullOnly)this.excludeFromFocus(item);if(this._attention==="focus"&&item.mentionsMe&&!item.historical&&this.focusRecallUnsafeChannels.has(item.channel??"")){this.excludeFromFocus(item);this.buffer(item,delivery,true,idless);this.emit("mention-wake",item);return}if(cm!=="quiet"&&!snapshottedPullOnly&&this._attention==="focus"){this.protectDisposition(item.id,"drop");delivery.ack();if(item.id==="")this.buffer(item,{ack:()=>{}},true,idless);if(item.mentionsMe)this.emit("mention-wake",item);return}const automaticReply=this.config.channelRepliesPullOnly===true&&!!item.replyTo;const pullOnly=snapshottedPullOnly||!item.mentionsMe&&(automaticReply||this.classificationUnsafe);if(pullOnly)this.excludeFromFocus(item);this.buffer(item,delivery,pullOnly,idless);return}this.buffer(item,delivery,false)}buffer(item,delivery,pullOnly,idless){const pending={item,ack:delivery.ack,pullOnly,receivedAt:Date.now(),arrival:this.arrivals++};this.own(pending,delivery.redelivery);if(idless)pending.idless={tally:this.focusIdless,...idless};if(delivery.take){pending.take=delivery.take;this.gated.push(pending);if(this.gated.length>MAX_INBOX)this.gated.shift();this.emit("incoming",item);return}this.admit(pending);this.emit("incoming",item)}admit(pending){let at2=this.inbox.length;while(at2>0&&this.inbox[at2-1].arrival>pending.arrival)at2--;this.inbox.splice(at2,0,pending);if(this.inbox.length>MAX_INBOX){let excess=this.inbox.length-MAX_INBOX;while(excess-- >0){const evictable=p2=>!this.inFlightIds.has(p2.item.recvKey);let index2=this.inbox.findIndex(p2=>p2.pullOnly&&evictable(p2));if(index2<0)index2=this.inbox.findIndex(p2=>p2.item.kind==="channel"&&evictable(p2));if(index2<0)index2=this.inbox.findIndex(evictable);if(index2<0)break;const[evicted]=this.inbox.splice(index2,1);const sacrificingDirected=evicted.item.kind!=="channel";this.rememberEvicted(evicted);if(evicted.idless?.tally===this.focusIdless)this.unsettleIdless(evicted.idless.digest,evicted.idless.copy);if(!sacrificingDirected)evicted.ack()}}}rememberEvicted(p2){if(p2.item.kind!=="channel"||p2.item.mentionsMe||!p2.item.channel)return;if(p2.item.id==="")return;if(this.classificationUnsafe)return;if(!this.evictedClassifications.has(p2.item.id)&&this.evictedClassifications.size>=CLASSIFICATION_CAP){this.classificationUnsafe=true;this.evictedClassifications.clear();return}this.evictedClassifications.set(p2.item.id,{pullOnly:p2.pullOnly,channel:p2.item.channel})}excludeFromFocus(item){if(!this.enteringFocus&&this._attention!=="focus"||item.kind!=="channel"||!item.channel)return;if(item.id==="")return;if(!this.focusExcludedIds.has(item.id)&&this.focusExcludedIds.size>=FOCUS_EXCLUSION_CAP){const oldest=this.focusExcludedIds.entries().next().value;if(oldest){this.focusExcludedIds.delete(oldest[0]);this.focusRecallUnsafeChannels.add(oldest[1])}}this.focusExcludedIds.set(item.id,item.channel)}reserveIdless(digest,channel){if(this.focusIdlessEntries>=FOCUS_EXCLUSION_CAP){this.focusRecallUnsafeChannels.add(channel);return void 0}let tally=this.focusIdless.get(digest);if(!tally)this.focusIdless.set(digest,tally={channel,unbound:[],bound:new Set});this.focusIdlessEntries++;return tally}settleIdless(tally){const episode=this.focusIdless;const drops=this.transportDrops;const unbounded=()=>{if(episode===this.focusIdless)this.focusRecallUnsafeChannels.add(tally.channel)};const copy2={epoch:this.idlessEpoch,ready:Promise.resolve()};copy2.ready=this.ep.chatFrontier().then(frontier=>{if(drops===this.transportDrops)copy2.frontier=frontier;else unbounded()},unbounded);tally.unbound.push(copy2);return copy2}dropEmptyIdless(digest,tally){if(!tally.unbound.length&&!tally.bound.size)this.focusIdless.delete(digest)}unsettleIdless(digest,copy2){const tally=this.focusIdless.get(digest);if(!tally)return;if(tally.unbound.includes(copy2)){copy2.evicted=true;return}if(copy2.seq===void 0||!tally.bound.delete(copy2.seq))return;this.focusIdlessEntries--;this.dropEmptyIdless(digest,tally)}settleIdlessRead(channel,epoch,retained){for(const[digest,tally]of this.focusIdless){if(tally.channel!==channel)continue;const before=tally.unbound.length+tally.bound.size;tally.unbound=tally.unbound.filter(c3=>c3.epoch>=epoch);for(const seq of tally.bound)if(!retained.has(seq))tally.bound.delete(seq);this.focusIdlessEntries-=before-tally.unbound.length-tally.bound.size;this.dropEmptyIdless(digest,tally)}}async idlessReady(tallies,channel){const reads=[];for(const tally of tallies.values())if(tally.channel===channel)for(const c3 of tally.unbound)reads.push(c3.ready);await Promise.all(reads)}bindIdless(tally,epoch,free){let bound=Infinity;for(let i2=tally.unbound.length-1;i2>=0;i2--){const copy2=tally.unbound[i2];if(copy2.frontier===void 0)continue;bound=Math.min(bound,copy2.frontier);if(copy2.epoch>=epoch)continue;let at2=free.length-1;while(at2>=0&&free[at2]>bound)at2--;if(at2<0)continue;const[seq]=free.splice(at2,1);tally.unbound.splice(i2,1);if(copy2.evicted){this.focusIdlessEntries--;continue}copy2.seq=seq;tally.bound.add(seq)}}idlessUnsure(tally,epoch,seq){if(!tally||tally.bound.has(seq))return false;return tally.unbound.some(c3=>c3.epoch>=epoch&&c3.frontier!==void 0&&c3.frontier>=seq)}protectDisposition(id2,disposition){if(id2==="")return;const ids=disposition==="drop"?this.protectedDropIds:this.protectedPullOnlyIds;if((disposition==="drop"?this.dropUnsafe:this.classificationUnsafe)||ids.has(id2))return;if(ids.size>=PROTECTED_DISPOSITION_CAP){if(disposition==="drop")this.dropUnsafe=true;else this.classificationUnsafe=true;if(disposition!=="drop")ids.clear();return}ids.add(id2)}toInboxItem(m2,kind,historical){const text3=partsToText(m2.parts);return{id:m2.id,recvKey:m2.id!==""?m2.id:`${this.recvKeySecret}.${++this.recvKeySeq}`,ts:m2.ts,fromId:m2.from.id,fromName:m2.from.name,fromRole:m2.from.role,kind,channel:m2.channel,service:m2.toService,mentions:m2.mentions,mentionsMe:m2.mentions?.includes(this.config.name.toLowerCase())??false,historical,text:text3,replyTo:m2.replyTo,contextId:m2.contextId}}peekInbox(scope="all"){this.dropLapsedTakes();return this.inbox.filter(p2=>this.inScope(p2,scope)).map(p2=>p2.item)}inboxPreview(scope="all"){this.dropLapsedTakes();const askable=scope==="pull-only"?[]:this.gated.filter(p2=>this.mayOffer(p2));return[...this.inbox.filter(p2=>this.inScope(p2,scope)),...askable].sort((a3,b3)=>a3.arrival-b3.arrival).map(p2=>p2.item)}async takeChosen(scope,choose,waitMs=TAKE_WAIT_MS){const chosen=choose(this.inboxPreview(scope));const keys=new Set(chosen.map(i2=>i2.recvKey));const asked=scope==="pull-only"?[]:this.gated.filter(p2=>keys.has(p2.item.recvKey)&&this.mayOffer(p2));for(const p2 of asked)p2.awaited=(p2.awaited??0)+1;const runs=asked.map(p2=>p2.taking!==void 0&&p2.takingDrops===this.transportDrops?p2.taking:this.startTake(p2));if(runs.length){let timer2;const waited=new Promise(resolve6=>{timer2=setTimeout(resolve6,waitMs);timer2.unref?.()});await Promise.race([Promise.allSettled(runs),waited]);clearTimeout(timer2)}for(const p2 of asked)p2.awaited=(p2.awaited??1)-1;const showable=new Map(this.peekInbox(scope).map(i2=>[i2.recvKey,i2]));const shown=chosen.flatMap(i2=>showable.get(i2.recvKey)??[]);for(const i2 of shown)handOver(i2);return shown}heldTakes(){const count=this.gated.filter(p2=>p2.taking===void 0).length;const waiting=this.gated.filter(p2=>p2.taking!==void 0&&p2.takingDrops===this.transportDrops).length;if(waiting)return{count:waiting+(this.heldTake?count:0),detail:"the delivery daemon has not answered the take yet"};return count&&this.heldTake?{count,detail:this.heldTake.detail}:{count}}mayAskTakes(){return this._transportConnected&&(!this.heldTake||Date.now()>=this.heldTake.retryAt)}mayOffer(p2){return p2.taking!==void 0&&this._transportConnected||this.mayAskTakes()}startTake(p2){const run=this.runTake(p2).catch(e3=>this.handleEndpointWarning(e3)).finally(()=>{if(p2.taking===run)p2.taking=void 0});p2.taking=run;p2.takingDrops=this.transportDrops;return run}async runTake(p2){const take=p2.take;if(!take)return;if(!this._transportConnected)return;if(!this.renewOwned(p2)){this.dropGated(p2);return}const count=p2.item.deliveryCount;const drops=this.transportDrops;const outcome=await take();if(!this.gated.includes(p2)||p2.take!==take)return;if(this.transportDrops!==drops){if(p2.takingDrops!==drops)return;if(this._transportConnected)this.emit("incoming",p2.item);return}if(outcome.taken){this.heldTake=void 0;const current=p2.item.deliveryCount===count&&p2.ownedUntil!==void 0&&Date.now()<p2.ownedUntil;if(!current)return;p2.takenCount=count;p2.takenOnce=true;this.gated.splice(this.gated.indexOf(p2),1);this.noteDirected(p2.item);this.admit(p2);if(!p2.awaited)this.emit("incoming",p2.item);return}if(outcome.drop){this.dropGated(p2);return}const first=this.heldTake?.reason!==outcome.reason;this.heldTake={reason:outcome.reason,detail:outcome.detail,retryAt:Date.now()+TAKE_RETRY_MS};this.takeRetry??=setTimeout(()=>{this.takeRetry=void 0;for(const held2 of this.gated)this.emit("incoming",held2.item)},TAKE_RETRY_MS);this.takeRetry.unref?.();if(first&&outcome.reason!=="daemon-busy")this.handleEndpointWarning(new Error(outcome.detail))}dropGated(p2){const i2=this.gated.indexOf(p2);if(i2>=0)this.gated.splice(i2,1)}regate(p2){const i2=this.inbox.indexOf(p2);if(i2<0)return;this.inbox.splice(i2,1);p2.takenCount=void 0;this.gated.push(p2)}dropLapsedTakes(){const now=Date.now();this.inbox=this.inbox.filter(p2=>!p2.take||this.inFlightIds.has(p2.item.recvKey)||p2.ownedUntil!==void 0&&now<p2.ownedUntil);this.gated=this.gated.filter(p2=>p2.taking!==void 0||p2.ownedUntil===void 0||now<p2.ownedUntil)}holdInFlight(ids){let fresh=0;for(const id2 of ids)if(!this.inFlightIds.has(id2))fresh++;if(this.inFlightIds.size+fresh>MAX_IN_FLIGHT)return false;for(const id2 of ids){this.inFlightIds.set(id2,(this.inFlightIds.get(id2)??0)+1);this.keepOwned(id2)}const held2=new Set(ids);for(const p2 of this.inbox)if(held2.has(p2.item.recvKey))handOver(p2.item);return true}isInFlight(id2){return this.inFlightIds.has(id2)}releaseInFlight(ids){for(const id2 of ids){const held2=this.inFlightIds.get(id2);if(held2===void 0)continue;if(held2<=1){this.inFlightIds.delete(id2);this.stopRenewal(id2);if(!this.lowerOnRelease.delete(id2))continue;const p2=this.inbox.find(pending=>pending.item.recvKey===id2);if(p2&&!p2.pullOnly){p2.pullOnly=true;this.excludeFromFocus(p2.item)}}else this.inFlightIds.set(id2,held2-1)}}own(p2,redelivery){p2.redelivery=redelivery;p2.ownedUntil=redelivery&&Date.now()+redelivery.ackWaitMs;p2.item.deliveryCount=redelivery?.deliveryCount;p2.item.firstDeliveryCount??=redelivery?.deliveryCount??1}keepOwned(key){if(this.renewals.has(key))return;const p2=this.inbox.find(x2=>x2.item.recvKey===key);if(!p2?.redelivery||!this.renewOwned(p2))return;const timer2=setInterval(()=>{const held2=this.inbox.find(x2=>x2.item.recvKey===key);if(!held2||!this.renewOwned(held2))this.stopRenewal(key)},p2.redelivery.ackWaitMs/2);timer2.unref?.();this.renewals.set(key,timer2)}stopRenewal(key){clearInterval(this.renewals.get(key));this.renewals.delete(key)}renewOwned(p2){if(!p2.redelivery||p2.ownedUntil===void 0||Date.now()>=p2.ownedUntil)return false;if(!this._transportConnected)return true;try{p2.redelivery.working()}catch{return false}p2.ownedUntil=Date.now()+p2.redelivery.ackWaitMs;return true}drainInbox(limit,scope="all"){this.dropLapsedTakes();const eligible=this.inbox.filter(p2=>this.inScope(p2,scope));const n2=limit&&limit>0?Math.min(limit,eligible.length):eligible.length;const selected=eligible.slice(0,n2);this.noteAutomaticHeadProgress(selected);const taken=new Set(selected);this.inbox=this.inbox.filter(p2=>!taken.has(p2));const automatic=selected.some(p2=>!p2.pullOnly);const items=this.commitPending(selected);if(items.length)this._lastInboxDrainedAt=Date.now();if(items.length&&automatic)this._lastAutomaticDrainedAt=Date.now();return items}drainInboxDeliveries(keys){const requested=[...new Set(keys)];const wanted=new Set(requested);const regated=this.gated.filter(p2=>wanted.has(p2.item.recvKey)&&p2.takenOnce);const unshown=new Set(this.gated.filter(p2=>wanted.has(p2.item.recvKey)&&!p2.takenOnce).map(p2=>p2.item.recvKey));if(regated.length)this.gated=this.gated.filter(p2=>!regated.includes(p2));const selected=[...this.inbox.filter(p2=>wanted.has(p2.item.recvKey)),...regated];this.noteAutomaticHeadProgress(selected);const present=new Set(selected.map(p2=>p2.item.recvKey));const pullOnly=new Map(selected.map(p2=>[p2.item.recvKey,p2.pullOnly]));for(const id2 of requested){const remembered=id2!==""?this.evictedClassifications.get(id2):void 0;if(!pullOnly.has(id2)&&remembered)pullOnly.set(id2,remembered.pullOnly)}this.inbox=this.inbox.filter(p2=>!present.has(p2.item.recvKey));const automatic=selected.some(p2=>!p2.pullOnly);const items=this.commitPending(selected);if(items.length)this._lastInboxDrainedAt=Date.now();if(items.length&&automatic)this._lastAutomaticDrainedAt=Date.now();for(const id2 of requested){if(!present.has(id2)&&!unshown.has(id2)&&!id2.startsWith(`${this.recvKeySecret}.`)){this.markHandled(id2,pullOnly.get(id2)??false);this.evictedClassifications.delete(id2)}}return{items,missingKeys:requested.filter(key=>!present.has(key)&&!unshown.has(key))}}commitPending(taken){for(const p2 of taken){p2.ack();this.markHandled(p2.item.id,p2.pullOnly);this.evictedClassifications.delete(p2.item.id)}return taken.map(p2=>p2.item)}inScope(p2,scope){return scope==="all"||(scope==="pull-only"?p2.pullOnly:!p2.pullOnly)}markHandled(id2,pullOnly=false){if(id2==="")return;if(pullOnly)this.protectDisposition(id2,"pull-only");this.handledIds.add(id2);if(this.handledIds.size>=4096){this.handledIdsPrev=this.handledIds;this.handledIds=new Set}}inboxKeys(scope="all"){const held2=scope==="pull-only"?[]:this.gated;return[...this.inbox.filter(p2=>this.inScope(p2,scope)),...held2].map(p2=>p2.item.recvKey)}inboxPending(scope="all"){const held2=scope==="pull-only"?[]:this.gated;return[...this.inbox.filter(p2=>this.inScope(p2,scope)),...held2].map(p2=>p2.item)}inboxCount(scope="all"){const held2=scope==="pull-only"?0:this.gated.length;return held2+(scope==="all"?this.inbox.length:this.inbox.filter(p2=>this.inScope(p2,scope)).length)}inboxSnapshot(limit=3){if(!Number.isInteger(limit)||limit<0||limit>8)throw new Error(`inbox preview limit must be a whole number from 0 to 8, got ${limit}`);this.dropLapsedTakes();return{unread:this.inbox.length+this.gated.length,items:this.inbox.slice(0,limit).map(p2=>({...p2.item}))}}oldestAutomaticReceivedAt(){let oldest;for(const pending of[...this.inbox,...this.gated]){if(pending.pullOnly)continue;if(oldest===void 0||pending.receivedAt<oldest)oldest=pending.receivedAt}return oldest}get recallCursor(){return this._recallCursor}noteRecalled(mark){if(afterRecallMark(mark,this._recallCursor))this._recallCursor=mark}recallAhead(item){return item.ts>Date.now()}recallAheadSeen(id2){return this.aheadDelivered.has(id2)}recallAheadRoom(){return MAX_AHEAD-this.aheadDelivered.size}noteRecalledAhead(id2){if(this.aheadDelivered.size<MAX_AHEAD)this.aheadDelivered.add(id2)}resetRecallWalk(){this._recallCursor={ts:0,id:""};this.aheadDelivered.clear()}inboxScope(key){const pending=this.inbox.find(p2=>p2.item.recvKey===key)??this.gated.find(p2=>p2.item.recvKey===key);return pending?pending.pullOnly?"pull-only":"automatic":void 0}directedPendingCount(){return this.gated.length+this.inbox.filter(p2=>!p2.pullOnly&&(p2.item.kind!=="channel"||!p2.item.historical&&p2.item.mentionsMe)).length}inboxWake(skip){this.dropLapsedTakes();const held2=this.mayAskTakes()?this.gated.filter(p2=>(p2.taking===void 0||p2.takingDrops!==this.transportDrops)&&!skip?.(p2.item)).length:0;return held2+this.inbox.filter(p2=>{const it2=p2.item;if(p2.pullOnly||it2.kind==="channel"&&it2.historical||skip?.(it2))return false;if(it2.kind!=="channel"||it2.mentionsMe)return true;return this._attention==="open"}).length}get attention(){return this._attention}channelMode(channel){return channel?this.channelModes.get(channel):void 0}channelModeEntries(){return Object.fromEntries(this.channelModes)}async setChannelMode(channel,mode){if(!isConcreteChannel(channel))throw new Error(`"${channel}" must be a concrete channel (no wildcard) to set its attention`);if(!channelInAllow(this.config.allowSubscribe,channel))throw new Error(`"${channel}" is not within your read ACL (allowSubscribe) [${this.config.allowSubscribe.join(", ")}]`);await this.inOrder(()=>{if(mode==="normal")this.channelModes.delete(channel);else{this.channelModes.set(channel,mode);this.lowerBuffered(channel,mode==="muted")}return this.ep.setChannelModes(this.channelModeEntries())})}lowerBuffered(channel,mentions,keep=[]){for(const p2 of this.inbox){if(p2.pullOnly||p2.item.kind!=="channel"||!p2.item.channel||!channelInAllow([channel],p2.item.channel))continue;if(channelInAllow(keep,p2.item.channel))continue;if(p2.item.mentionsMe&&!mentions)continue;if(this.inFlightIds.has(p2.item.recvKey)){this.lowerOnRelease.add(p2.item.recvKey);continue}p2.pullOnly=true;this.excludeFromFocus(p2.item)}}async setAttention(mode){await this.inOrder(async()=>{if(mode==="focus"){await this.requireConnected();this.focusExcludedIds.clear();this.focusIdless=new Map;this.focusIdlessEntries=0;this.focusRecallUnsafeChannels.clear();this.enteringFocus=this._attention!=="focus";try{this.focusSince=await this.ep.chatFrontier()}catch(error51){this.enteringFocus=false;this.focusExcludedIds.clear();this.focusIdless=new Map;this.focusIdlessEntries=0;this.focusRecallUnsafeChannels.clear();throw error51}this.enteringFocus=false;this.resetRecallWalk()}else{this.enteringFocus=false;this.focusSince=void 0;this.focusExcludedIds.clear();this.focusIdless=new Map;this.focusIdlessEntries=0;this.focusRecallUnsafeChannels.clear();this.resetRecallWalk()}this._attention=mode;await this.ep.setAttention(mode)})}async recallAmbient(underway=new Set){const run=this.recallLock.then(()=>this.recallAmbientOnce(underway));this.recallLock=run.catch(()=>{});return run}async recallAmbientOnce(underway){if(this._attention!=="focus"||this.focusSince===void 0)return{items:[],droppedChannels:[]};const items=[];const droppedChannels=[];for(const channel of this.ep.joinedChannels()){if(!isConcreteChannel(channel)){droppedChannels.push(channel);continue}if(this.focusRecallUnsafeChannels.has(channel)){droppedChannels.push(channel);continue}const tallies=this.focusIdless;let epoch=0;let read;for(let attempt=1;attempt<=IDLESS_READS;attempt++){epoch=++this.idlessEpoch;await this.idlessReady(tallies,channel);read=await this.ep.recallChannel(channel,this.focusSince);if(read.unanswered)break;await this.idlessReady(tallies,channel);const unsure=read.messages.some((m2,i2)=>m2.id===""&&this.idlessUnsure(tallies.get(idlessDigest(m2)),epoch,read.seqs[i2]));if(!unsure)break}const{messages,seqs,dropped,unanswered}=read;if(unanswered){droppedChannels.push(channel);continue}if(this.focusRecallUnsafeChannels.has(channel)){droppedChannels.push(channel);continue}const retained=new Set;const digests=[];const free=new Map;for(const[i2,m2]of messages.entries()){if(m2.id!==""||tallies!==this.focusIdless)continue;retained.add(seqs[i2]);const digest=digests[i2]=idlessDigest(m2);if(tallies.get(digest)?.bound.has(seqs[i2]))continue;const list=free.get(digest);if(list)list.push(seqs[i2]);else free.set(digest,[seqs[i2]])}for(const[digest,list]of free){const tally=tallies.get(digest);if(tally)this.bindIdless(tally,epoch,list)}let incomplete=dropped;for(const[i2,m2]of messages.entries()){if(m2.id!==""){if(underway.has(m2.id)||!this.focusExcludedIds.has(m2.id))items.push(this.toInboxItem(m2,"channel",true));continue}if(tallies!==this.focusIdless)continue;const seq=seqs[i2];const digest=digests[i2];const tally=tallies.get(digest);if(tally?.bound.has(seq))continue;if(this.idlessUnsure(tally,epoch,seq)){incomplete=true;continue}const fresh=this.inbox.length<MAX_INBOX?this.reserveIdless(digest,channel):void 0;if(!fresh){incomplete=true;continue}const copy2={epoch,frontier:seq,ready:Promise.resolve(),seq};fresh.bound.add(seq);this.buffer(this.toInboxItem(m2,"channel",true),{ack:()=>{}},true,{digest,copy:copy2})}if(tallies===this.focusIdless)this.settleIdlessRead(channel,epoch,retained);if(incomplete)droppedChannels.push(channel)}items.sort((a3,b3)=>a3.ts-b3.ts);return{items,droppedChannels}}};var SPAWN_TIMEOUT_MS=4e4;var CONNECT_GRACE_MS=1e4;function isLocalServer(servers){return servers.split(",").every(s3=>/^(?:[a-z]+:\/\/)?(?:[^@/]*@)?(?:localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(?::\d+)?(?:\/|$)/i.test(s3.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}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,t2){if(t2.yielded!==void 0)return`turn "${goalId}" was already yielded ${t2.yielded} by this seat${t2.yielded==="done"?" (ending a session turn yields done)":""}, so this yield was not recorded`;const deadline=t2.deadlineAt!==void 0?` (deadline ${new Date(t2.deadlineAt).toISOString()})`:"";return`turn "${goalId}" was already settled ${t2.once!==void 0?"by its manager":"by the run"}${deadline}, so this yield was not recorded`}var MAX_DATE_MS=864e13;function isPendingTurn(t2){const r2=t2;if(typeof r2!=="object"||r2===null||typeof r2.goalId!=="string"||typeof r2.payload!=="string")return false;if(!Number.isSafeInteger(r2.acceptedAt)||r2.acceptedAt<0)return false;if(r2.once!==void 0&&r2.once!==true)return false;if(r2.deadlineAt===void 0)return r2.once===true;return Number.isSafeInteger(r2.deadlineAt)&&r2.deadlineAt>=1&&r2.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 sleep(ms){return new Promise(r2=>setTimeout(r2,ms))}async function waitForStop(work){let timer2;try{await Promise.race([work,new Promise(resolve6=>{timer2=setTimeout(resolve6,3e3)})])}finally{clearTimeout(timer2)}}var AUTOMATIC_QUEUE_STALL_MS=6e5;function renderAskRequest(p2){const escalation=renderEscalation(p2);if(escalation!=="")return escalation;const ask=p2.ask;if(ask===null||typeof ask!=="object")return"";const a3=ask;const entries=a3.schema!==null&&typeof a3.schema==="object"?Object.entries(a3.schema):[];const fields=entries.length===0?"any record":entries.map(([k2,v3])=>`${k2}: ${String(v3)}`).join(", ");const by=typeof a3.deadlineAt==="number"?`, by ${new Date(a3.deadlineAt).toISOString()}`:"";const refused3=typeof a3.refused==="string"?`
|
|
119
119
|
Your last answer was refused: ${a3.refused}`:"";return`
|
|
120
120
|
This turn is an ask: the run needs a record from you at step ${String(p2.step)} with fields ${fields} (attempt ${String(a3.attempt)} of ${String(a3.attempts)}${by}).${refused3}`+renderPauseAnswer(p2,"<json record>")}function renderPauseAnswer(p2,value){return`
|
|
121
121
|
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(p2.run)},"stepKey":${JSON.stringify(p2.step)},"value":${value}}.
|
|
@@ -123,12 +123,12 @@ Replace ${value} with your answer. This route uses your own seat identity and ne
|
|
|
123
123
|
Answer with a record with fields ${entries.map(([k2,v3])=>`${k2}: ${String(v3)}`).join(", ")}.`;const by=typeof c3.deadlineAt==="number"?` It expires at ${new Date(c3.deadlineAt).toISOString()}.`:"";return`
|
|
124
124
|
This turn is a checkpoint escalated to you at step ${String(p2.step)}: ${String(c3.prompt)}${by}${wanted}
|
|
125
125
|
Answer with: \`cotal run answer ${String(p2.run)} ${String(p2.step)} --value '<json>'\``}var MeshAgent=class extends EventEmitter2{ep;config;launchEnv;managerCalls;options;inboxState=new AgentInbox({endpoint:()=>this.ep,config:()=>this.config,transportConnected:()=>this._transportConnected,emit:(event,item)=>this.emit(event,item),warning:error51=>this.handleEndpointWarning(error51),noteDirected:item=>this.noteDirected(item),inOrder:write=>this.inOrder(write),requireConnected:()=>this.requireConnected()});_storedCopiesFull=0;_storedCopiesLimit=0;_connected=false;_transportConnected=false;lastConnectionError;endpointNoticeLog=new Map;_status="idle";activeTurns=new Map;settledTurns=new Map;yieldedSincePull=new Set;turnNoticeArmed=false;turnRetryTimer;legacyTurnPoll;pullTrouble;turnPollBusy=false;turnPullAgain=false;_contextId;correlation=new AsyncLocalStorage2;unanswered=new Map;senders=new Map;asked=new Map;_stopping=false;presenceChain=Promise.resolve();turnStatus;constructor(config2,env,options={}){super();this.config=config2;this.options=options;this.launchEnv=env===void 0?void 0:{...env};this.managerCalls=new AgentManagerCalls(()=>this.config,()=>this.ep,()=>this.launchEnv,(...args)=>this.invokeEndpoint(...args));this.inboxState.seedChannelModes(config2);const userAuth=config2.userAuth;this.ep=new CotalEndpoint({space:config2.space,environment:this.launchEnv===void 0?void 0:this.launchEnv.COTAL_ENVIRONMENT??null,servers:config2.servers,token:config2.token,user:config2.user,pass:config2.pass,creds:config2.creds,lifecycleUid:config2.lifecycleUid,backfillFloor:config2.backfillFloor,acceptedToken:config2.acceptedToken,bearer:userAuth?userAuth.bearer??(()=>this.execBearerCmd(userAuth.bearerCmd)):void 0,sentinelCreds:config2.userAuth?.sentinelCreds,tls:config2.tls,ackWaitMs:config2.ackWaitMs,channels:config2.subscribe,allowSubscribe:config2.allowSubscribe,channelModes:this.channelModeEntries(),watchPresence:false,beforeBind:async()=>{const env2=this.launchEnv??process.env;if(this.eventStartupChecked||!(options.eventsArmed??eventPlaneArmed(config2,env2)))return;try{await checkEventStartup2(this.ep,{...env2,COTAL_WORKSPACE_ROOT:options.eventsWorkspaceRoot??env2.COTAL_WORKSPACE_ROOT});this.eventStartupChecked=true}catch(error51){if(config2.eventsRequired===true)throw error51;this.eventStartupChecked=true;this.eventPlaneBlocked=error51 instanceof Error?error51.message:String(error51);this.lastConnectionError=this.eventPlaneBlocked}},card:{id:config2.id,name:config2.name,role:config2.role,kind:config2.kind,description:config2.description,tags:config2.tags,owner:config2.userAuth?.owner,actor:config2.userAuth?.actor,meta:buildMeta(config2,!options.withholdProcessCwd,options.eventsArmed)}});this.ep.on("message",(m2,d2,meta3)=>{const notice=meta3?.kind==="dm"?deliveryNoticeOf(m2):void 0;if(notice!==void 0)void this.inboxState.ingestNotice(m2,d2,meta3,notice);else this.inboxState.ingest(m2,d2,meta3)});this.ep.on("error",e3=>this.handleEndpointError(e3));this.ep.on("warning",e3=>this.handleEndpointWarning(e3));this.ep.on("stored-copies-full",full=>{this._storedCopiesFull++;this._storedCopiesLimit=full.limit});this.ep.on("transport",e3=>{if(this._stopping)return;if(this._transportConnected===e3.connected)return;this._transportConnected=e3.connected;this.inboxState.onTransport(e3.connected);this.emit("transport",e3);if(e3.connected&&this.turnNoticeArmed&&this.activeTurns.size>0)this.requestTurnPull()});this.ep.on("connection",e3=>{if(this._stopping)return;this._connected=e3.connected;if(e3.connected){this.lastConnectionError=this.eventPlaneBlocked;this.endpointNoticeLog.clear()}this.emit("connection",e3);if(e3.connected&&this.turnNoticeArmed&&this.activeTurns.size>0)this.requestTurnPull()})}get id(){return this.ep.card.id}get connected(){return this._connected}get transportConnected(){return this._transportConnected}get connectionIssue(){const presence=this._connected&&this._transportConnected&&!this._stopping?this.presenceWriteFailure:void 0;if(presence!==void 0&&presence.consecutiveFailures>=2){return`presence writes to bucket ${JSON.stringify(presence.bucket)} have failed ${presence.consecutiveFailures} consecutive times: ${presence.error??"write failed"}`}return this.lastConnectionError}get presenceWriteFailure(){return this.ep.presenceWriteFailure()}get lastInboxDrainedAt(){return this.inboxState.lastInboxDrainedAt}get lastAutomaticDrainedAt(){return this.inboxState.lastAutomaticDrainedAt}get lastAutomaticHeadDrainedAt(){return this.inboxState.lastAutomaticHeadDrainedAt}automaticQueueStalledForMs(now=Date.now()){return this.inboxState.automaticQueueStalledForMs(now)}get stopping(){return this._stopping}get storedCopiesFull(){return this._storedCopiesFull}get storedCopiesLimit(){return this._storedCopiesLimit}clearStoredCopiesFull(seen){this._storedCopiesFull=Math.max(0,this._storedCopiesFull-seen)}get channelDeliveryIssue(){return this.inboxState.channelDeliveryIssue}get connectionState(){if(this._stopping)return"stopped";if(this._connected){if(this.channelDeliveryIssue)return"degraded";if((this.presenceWriteFailure?.consecutiveFailures??0)>=2)return"degraded";if(!this._transportConnected)return"degraded";const held2=this.automaticQueueStalledForMs();return held2!==void 0&&held2>=AUTOMATIC_QUEUE_STALL_MS?"stalled":"ready"}return this._transportConnected?"connecting":"disconnected"}async waitUntilConnected(timeoutMs=15e3){if(this._connected)return;await new Promise((resolve6,reject)=>{let timer2;let settled=false;const finish=error51=>{if(settled)return;settled=true;if(timer2)clearTimeout(timer2);this.off("connection",onConnection);if(error51)reject(error51);else resolve6()};const onConnection=event=>{if(event.connected)finish()};this.on("connection",onConnection);timer2=setTimeout(()=>{const detail=this.connectionIssue?` Last error: ${this.connectionIssue}`:"";finish(new Error(`mesh did not become ready at ${this.config.servers} within ${timeoutMs}ms.${detail}`))},Math.max(1,timeoutMs));if(this._connected)finish()})}setContextId(contextId){const clean=contextId?.trim();this._contextId=clean?clean:void 0}withCorrelation(correlation,fn2){const contextId=correlation.contextId?.trim()||void 0;const replyTo=correlation.replyTo?.trim()||void 0;const peerId=correlation.peerId?.trim()||void 0;return this.correlation.run({contextId,replyTo,peerId},fn2)}answersQuestion(item){if(item.kind!=="dm"||item.historical||!item.contextId)return false;const q2=this.asked.get(item.contextId);return!!q2&&(q2.peerId===item.fromId||!!q2.role&&q2.role===item.fromRole)}stamp(answered){const c3=this.correlation.getStore();if(c3?.replyTo&&(!answered||answered.id===c3.replyTo))return{stamp:{replyTo:c3.replyTo,contextId:c3.contextId??answered?.contextId??this._contextId}};if(answered?.contextId)return{stamp:{replyTo:answered.id,contextId:answered.contextId}};const own=c3?.replyTo?void 0:c3?.contextId;return{stamp:{replyTo:answered?.id,contextId:own??this._contextId},own}}recordQuestion(contextId,to){if(!contextId)return;this.asked.delete(contextId);this.asked.set(contextId,to);if(this.asked.size>MAX_CORRELATIONS)this.asked.delete(this.asked.keys().next().value)}answering(peerId,replyTo){if(replyTo){const e3=this.unanswered.get(replyTo);if(!e3||e3.fromId!==peerId)throw new Error(`replyTo "${attributionSafe(replyTo)}" is not a message from this peer that is waiting for an answer`);return{id:replyTo,contextId:e3.contextId}}const c3=this.correlation.getStore();if(c3?.replyTo){const e3=this.unanswered.get(c3.replyTo);return e3&&e3.fromId===peerId?{id:c3.replyTo,contextId:e3.contextId}:void 0}if(c3?.contextId&&c3.peerId!==peerId)return void 0;const waiting=[...this.unanswered].filter(([,e3])=>e3.fromId===peerId);if(new Set(waiting.map(([,e3])=>e3.contextId)).size>1){const list=waiting.map(([id2,e3])=>` \u2022 replyTo: ${attributionSafe(id2)} \u2014 "${attributionSafe(e3.text??"")}"`);throw new Error(`this peer has messages from more than one conversation waiting for an answer. Re-send with "replyTo" set to the id of the one this answers:
|
|
126
|
-
${list.join("\n")}`)}const first=waiting.find(([,e3])=>!e3.pending);return first&&{id:first[0],contextId:first[1].contextId}}start(retryMs=3e3){if(this._stopping)throw new Error("cannot start a stopped mesh session");if(!this.consumerClaim&&this.config.lifecycleUid){const{owner:owner2,actor:actor2}=this.ep.principal;this.consumerClaim=acquireLocalConsumer(this.config.servers,this.config.space,owner2,actor2,this.config.lifecycleUid)}return this.connectFlight??=this.connectLoop(retryMs)}consumerClaim;connectFlight;agentEndpoint;agentEndpointOpened=false;eventStartupChecked=false;eventPlaneBlocked;async connectLoop(retryMs){while(!this._stopping&&!this._connected){try{await this.ep.start();if(this._stopping)return;this.log(`connected to ${this.config.servers} as ${peerLabel(this.config)} in space "${this.config.space}" on #${this.config.subscribe.join(", #")}`);const historicalBuffered=this.peekInbox("pull-only").filter(i2=>i2.historical).length;this.log(`joined ${this.config.subscribe.length} boot channel(s): ${historicalBuffered} historical message(s) buffered pull-only`+(this.config.backfillFloor!==void 0?` (backfill floor ${this.config.backfillFloor})`:""));this.armTurnRelay();void this.serveAgentEndpoint()}catch(e3){const error51=e3 instanceof Error?e3:new Error(String(e3));if(this._stopping)return;this.lastConnectionError=error51.message;if(error51 instanceof EventStateConflictError){await this.ep.stop();this.consumerClaim?.release();this.consumerClaim=void 0;throw error51}const presence=this._transportConnected?this.ep.presenceWriteFailure():void 0;const forS=presence===void 0?"":presence.forMs<1e3?"<1":String(Math.round(presence.forMs/1e3));const diagnosis=presence?`connected, but this space's presence bucket "${presence.bucket}" has refused every write for ${forS}s (${presence.error??error51.message}) - the transport is fine and the fault is not the network`:this._transportConnected?`transport is connected but the mesh bind did not complete (${error51.message})`:`mesh unreachable (${error51.message})`;this.log(`${diagnosis}; retrying in ${retryMs}ms`);await sleep(retryMs)}}}async serveAgentEndpoint(){if(this.agentEndpointOpened||!this.config.userAuth)return;this.agentEndpointOpened=true;try{const served=await openAgentEndpoint(this.ep,{warn:msg=>this.log(msg),dispatcher:this.options.commands,onQueued:()=>this.emit("command")});if(this._stopping)return void served.close();this.agentEndpoint=served;if(served.commands.queued>0)this.emit("command")}catch(e3){this.log(`the agent endpoint is not served: ${e3.message}`)}}get queuedCommands(){return this.agentEndpoint?.commands.queued??0}dispatchNextCommand(){return this.agentEndpoint?.commands.dispatchNext()??Promise.resolve("empty")}stopFlight;stop(){return this.stopFlight??=this.stopOnce()}async stopOnce(){this._stopping=true;this.emit("stopping");this.inboxState.stop();this.managerCalls.clear();if(this.turnRetryTimer!==void 0){clearTimeout(this.turnRetryTimer);this.turnRetryTimer=void 0}if(this.legacyTurnPoll!==void 0){clearInterval(this.legacyTurnPoll);this.legacyTurnPoll=void 0}const agentEndpointClosed=this.agentEndpoint?.close();this._connected=false;if(this._transportConnected){this._transportConnected=false;this.emit("transport",{connected:false})}await Promise.race([agentEndpointClosed,sleep(3e3)]);const departure=this.inOrder(()=>this.ep.stop(),true);await Promise.race([departure,sleep(3e3)]);await this.ep.stop();await departure;await this.connectFlight?.catch(()=>{});this.consumerClaim?.release();this.consumerClaim=void 0}async reconnect(){if(this._stopping){return{ok:false,message:"This session is shutting down, so its Cotal mesh connection cannot be reconnected. Start a new session instead."}}try{await this.ep.reconnect();const held2=this.automaticQueueStalledForMs();const queued=this.inboxCount("automatic");const stalled=held2!==void 0&&held2>=AUTOMATIC_QUEUE_STALL_MS&&queued>0?` Note: this session's ${queued} queued automatic ${queued===1?"delivery has":"deliveries have"} made no progress for ${Math.round(held2/6e4)} minutes. Reconnecting did not deliver ${queued===1?"it":"them"}: the connection was not what was holding ${queued===1?"it":"them"} up.`:"";const channelIssue=this.channelDeliveryIssue;const message=channelIssue?`Transport reconnected (${this.config.name}@${this.config.space}), but this session remains degraded. ${channelIssue} Direct messages and anycast remain available. Restart this session to restore ambient channel delivery.`:`Reconnected \u2713 (${this.config.name}@${this.config.space})`;return{ok:true,message:`${message}${stalled}`}}catch(e3){if(e3 instanceof DmDurableMissingError){this.handleEndpointWarning(e3);return{ok:false,message:`Reconnect failed: ${missingInboxIssue(e3)}`}}return{ok:false,message:`Reconnect failed: ${e3.message||e3.name}. Still retrying automatically \u2014 or run /reconnect to retry now.`}}}noteDirected(item){if(item.kind!=="dm"&&item.kind!=="anycast")return;this.senders.delete(item.fromId);this.senders.set(item.fromId,item.fromName);if(this.senders.size>MAX_CORRELATIONS)this.senders.delete(this.senders.keys().next().value);if(!item.historical&&item.id!==""&&!this.answersQuestion(item)){this.unanswered.set(item.id,{fromId:item.fromId,contextId:item.contextId,text:item.text.slice(0,80)});if(this.unanswered.size>MAX_CORRELATIONS)this.unanswered.delete(this.unanswered.keys().next().value)}}peekInbox(scope="all"){return this.inboxState.peekInbox(scope)}inboxPreview(scope="all"){return this.inboxState.inboxPreview(scope)}async takeChosen(scope,choose,waitMs){return this.inboxState.takeChosen(scope,choose,waitMs)}heldTakes(){return this.inboxState.heldTakes()}holdInFlight(ids){return this.inboxState.holdInFlight(ids)}isInFlight(id2){return this.inboxState.isInFlight(id2)}releaseInFlight(ids){return this.inboxState.releaseInFlight(ids)}drainInbox(limit,scope="all"){return this.inboxState.drainInbox(limit,scope)}drainInboxDeliveries(keys){return this.inboxState.drainInboxDeliveries(keys)}inboxKeys(scope="all"){return this.inboxState.inboxKeys(scope)}inboxPending(scope="all"){return this.inboxState.inboxPending(scope)}inboxCount(scope="all"){return this.inboxState.inboxCount(scope)}inboxSnapshot(limit=3){return this.inboxState.inboxSnapshot(limit)}oldestAutomaticReceivedAt(){return this.inboxState.oldestAutomaticReceivedAt()}get recallCursor(){return this.inboxState.recallCursor}noteRecalled(mark){return this.inboxState.noteRecalled(mark)}recallAhead(item){return this.inboxState.recallAhead(item)}recallAheadSeen(id2){return this.inboxState.recallAheadSeen(id2)}recallAheadRoom(){return this.inboxState.recallAheadRoom()}noteRecalledAhead(id2){return this.inboxState.noteRecalledAhead(id2)}inboxScope(key){return this.inboxState.inboxScope(key)}directedPendingCount(){return this.inboxState.directedPendingCount()}pendingWake(skip){const turns=[...this.activeTurns.values()].filter(t2=>!t2.surfaced&&this.offerable(t2)).length;return turns+this.inboxWake(skip)}inboxWake(skip){return this.inboxState.inboxWake(skip)}requestWake(){this.emit("wake")}get attention(){return this.inboxState.attention}channelMode(channel){return this.inboxState.channelMode(channel)}channelModeEntries(){return this.inboxState.channelModeEntries()}async setChannelMode(channel,mode){return this.inboxState.setChannelMode(channel,mode)}async setAttention(mode){return this.inboxState.setAttention(mode)}async recallAmbient(underway=new Set){return this.inboxState.recallAmbient(underway)}async send(text3,channel,mentions){try{await this.requireConnected()}catch(error51){throw new Error(`${error51.message}. The message was not sent.`,{cause:error51})}const clean=normalizeMentions(mentions);if(clean)await this.assertKnownMentions(clean);return this.ep.multicast(text3,{channel,mentions:clean,...this.stamp().stamp})}async describeSendChannel(channel){if(this.ep.getChannelConfig(channel))return{known:true,hints:[]};const known=new Set(this.ep.joinedChannels().filter(isConcreteChannel));let unchecked;try{for(const row of await this.ep.listChannels())known.add(row.channel)}catch(e3){unchecked=e3.message}if(known.has(channel))return{known:true,hints:[]};const hints=closeChannelNames(channel,[...known]);return unchecked===void 0?{known:false,hints}:{known:false,hints,unchecked}}async assertKnownMentions(mentions){const{roster,failure}=await this.readRoster();const names=new Set(roster.map(p2=>p2.card.name.toLowerCase()));const unknown2=mentions.filter(m2=>!names.has(m2));if(!unknown2.length)return;if(!failure)throw new Error(`unknown mention${unknown2.length>1?"s":""}: ${unknown2.map(u2=>`@${u2}`).join(", ")} \u2014 no such peer observed in space "${this.config.space}"`);throw this.cannotVerify(`mention${unknown2.length>1?"s":""} ${unknown2.map(u2=>`@${u2}`).join(", ")}`,failure,"The send was not published.")}cannotVerify(subject,failure,outcome){return new Error(`cannot verify ${subject} in space "${this.config.space}": ${presenceReadCondition(failure)}, so absence is not a verdict \u2014 the peer may be present but unread. ${outcome}`,{cause:failure})}async anycast(role,text3){assertValidRole(role);await this.requireConnected();const holdersAtSend=await this.roleHolders(role);const{stamp:stamp2,own}=this.stamp();this.recordQuestion(own,{role});const{msg,ack}=await this.ep.anycastAttributed(role,text3,stamp2);this.rememberSent(ack.seq,msg.id);return{msg,ack,holdersAtSend}}async roleHolders(role){const{roster,failure}=await this.readRoster();if(failure)return void 0;return roster.filter(p2=>p2.card.role===role&&p2.status!=="offline").map(p2=>({id:p2.card.id,name:p2.card.name}))}sentRequests=new Map;rememberSent(seq,id2){const ids=this.sentRequests.get(seq)??[];if(!ids.includes(id2))ids.push(id2);this.sentRequests.delete(seq);this.sentRequests.set(seq,ids);if(this.sentRequests.size>MAX_CORRELATIONS)this.sentRequests.delete(this.sentRequests.keys().next().value)}sentRequestId(seq){const ids=this.sentRequests.get(seq);if(ids&&ids.length>1)throw new Error(`seq ${seq} names ${ids.length} requests this session sent (the role queue was recreated between them), so it is ambiguous; nothing was asked or cancelled`);return ids?.[0]}async anycastStatus(seq){await this.requireConnected();return this.ep.anycastStatus(seq,this.sentRequestId(seq))}async cancelAnycast(seq){await this.requireConnected();return this.ep.cancelAnycast(seq,this.sentRequestId(seq))}resolvePeer(target2){return resolvePeer(this.ep.getRoster(),target2,{selfId:this.id})}heldSender(target2,byName,peer){const name2=this.senders.get(target2);if(name2!==void 0)return{id:target2,name:name2};if(!byName)return void 0;const want=target2.trim().toLowerCase();const rostered=new Set(this.ep.getRoster().map(p2=>p2.card.id));const matches=[...this.senders].filter(([id2,n2])=>!rostered.has(id2)&&n2.toLowerCase()===want);if(peer)matches.unshift([peer.card.id,peer.card.name]);if(matches.length>1)throw new Error(`"${target2}" is ambiguous - ${matches.length} known peers share that name; DM by instance id instead: ${matches.map(([id2,n2])=>`${shownPeerName(n2,id2)} (${id2})`).join("; ")}`);const match=matches[0];return match&&match[0]!==peer?.card.id?{id:match[0],name:match[1]}:void 0}noPeer(target2){const want=target2.trim().toLowerCase();if(target2===this.id||want===this.config.name.toLowerCase())return`"${target2}" is this session: a DM goes to another peer, so nothing was sent. cotal_roster lists who is present.`;const missing=`no peer "${target2}" in space "${this.config.space}"`;if(!want)return missing;const names=[...new Set(this.ep.getRoster().filter(p2=>p2.card.id!==this.id&&p2.card.name.toLowerCase().startsWith(want)).map(p2=>p2.card.name))];if(!names.length)return missing;const shown=names.slice(0,NAMED_SIMILAR).map(n2=>JSON.stringify(n2)).join(", ");const more=names.length>NAMED_SIMILAR?` and ${names.length-NAMED_SIMILAR} more`:"";return`${missing}. A name must match in full, so nothing was sent. Present names that start with it: ${shown}${more}. DM one by its full name or instance id.`}async dm(target2,text3,opts={}){await this.requireConnected();const{roster,failure}=await this.readRoster();const peer=this.senders.has(target2)?roster.find(p2=>p2.card.id===target2):this.resolvePeer(target2);const held2=peer?.card.id===target2?void 0:this.heldSender(target2,!failure,peer);if(!peer&&!held2){if(!failure)throw new Error(this.noPeer(target2));throw this.cannotVerify(`peer "${target2}"`,failure,"The DM was not sent.")}const recipientStatusAtSend=peer?peer.status:"unrostered";const recipient=peer?{id:peer.card.id,name:peer.card.name}:held2;const answered=this.answering(recipient.id,opts.replyTo?.trim()||void 0);const entry=answered&&this.unanswered.get(answered.id);const{stamp:stamp2,own}=this.stamp(answered);this.recordQuestion(own,{peerId:recipient.id});if(entry)entry.pending=true;try{const{msg,ack}=await this.ep.unicastAttributed(recipient.id,text3,stamp2);if(answered)this.unanswered.delete(answered.id);return{msg,peer,recipient,ack,recipientStatusAtSend}}finally{if(entry)entry.pending=false}}pendingSpawns=new Map;async spawn(name2,role,opts){await this.requireConnected();const raw=opts?.model;if(raw!==void 0&&!raw.trim())return{ok:false,error:"model: must not be empty"};const requested=raw?.trim();for(const ch of opts?.join??[]){try{assertValidChannel(ch)}catch(e3){return{ok:false,error:`join: ${e3.message}`}}if(!isConcreteChannel(ch))return{ok:false,error:`join: "${ch}" must be a concrete channel (no wildcard)`};if(!channelInAllow(this.config.allowSubscribe,ch))return{ok:false,error:`join: "${ch}" is not within your read ACL (allowSubscribe) [${this.config.allowSubscribe.join(", ")}]; a spawn can only hand on channels you may read yourself`}}let instance;try{const selected=opts?.instance??this.openManagerInstance();instance=selected===void 0?void 0:assertLifecycleToken(selected,"instance")}catch(e3){return{ok:false,error:e3.message}}if(this.config.userAuth&&instance!==void 0&&this.config.managerInstanceId!==void 0&&instance!==this.config.managerInstanceId)return{ok:false,error:"the requested manager instance differs from this credential's instance authority"};const args={name:name2,role,agent:opts?.agent,model:requested||void 0,variant:opts?.variant,launchOptions:opts?.launchOptions,cwd:opts?.cwd,prompt:opts?.prompt,events:opts?.events,runtime:opts?.runtime,join:opts?.join,persona:opts?.persona,callerAcl:{allowSubscribe:this.config.allowSubscribe,allowPublish:this.config.allowPublish},once:opts?.once};const key=canonicalJson(JSON.parse(JSON.stringify({...args,instance,caller:this.ep.principal,lifecycleUid:this.config.lifecycleUid})));const previous=this.pendingSpawns.get(key);if(previous){const pending=await previous;const allocation=pending.data;if(allocation?.name&&allocation.uid){const inspected=await this.managerInvoke("ps",void 0,pending.instanceId?{instanceId:pending.instanceId}:{});const rows=Array.isArray(inspected.data)?inspected.data:void 0;const row=rows?.find(r2=>r2.name===allocation.name);if(inspected.ok&&rows&&(!row||typeof row.lifecycleUid==="string"&&row.lifecycleUid!==allocation.uid||row.lifecycleUid===allocation.uid&&(row.presenceIdentityVerified===true||row.status==="exited"))){if(this.pendingSpawns.get(key)===previous)this.pendingSpawns.delete(key)}else return pending}else return pending}const invoking=this.managerInvoke("spawn",args,{deadlineMs:SPAWN_TIMEOUT_MS,follow:true,...instance!==void 0?{instanceId:instance}:{}});this.pendingSpawns.set(key,invoking);const reply=await invoking;if(reply.ok||reply.code!=="uncertain"&&reply.outcome!=="unknown"){if(this.pendingSpawns.get(key)===invoking)this.pendingSpawns.delete(key)}if(reply.data?.submissionUnknown||!reply.ok&&reply.outcome==="unknown")return reply;const pinned=requested||opts?.persona?.model;if(!pinned)return reply;const actual=reply.data;const seat=actual?.name??name2;const recorded=await this.inspectModel(seat,instance);const recordedLabel=!recorded.ok?`could not inspect the recorded pin: ${recorded.error}`:recorded.model===void 0?"the manager recorded no model pin":`the manager recorded ${JSON.stringify(recorded.model)}`;if(recorded.ok&&recorded.model!==pinned){return{ok:false,error:`requested model ${JSON.stringify(pinned)} but ${recordedLabel} for "${seat}" \u2014 refusing a spawn whose pin did not land. The seat may already be live; inspect it before retrying, because a retry duplicates the spawn`}}if(!reply.ok&&reply.code!=="uncertain"){return{ok:false,error:`${reply.error??"manager refused"} (requested model ${JSON.stringify(pinned)}; ${recordedLabel} for "${seat}")`}}if(!recorded.ok){return{...reply,data:{...reply.data,pinAudit:{requested:pinned,error:recorded.error,...recorded.unreported?{unreported:true}:{}}}}}return{...reply,data:{...reply.data,model:recorded.model}}}async inspectModel(name2,instance){const info=await this.managerInvoke("inspect",{name:name2},instance===void 0?void 0:{instanceId:instance});if(!info.ok){const unreported=info.code==="not-found"||info.code==="unavailable"&&info.details?.some(d2=>d2.kind===EP_UNANSWERED)===true;return{ok:false,error:info.error??"inspect refused",...unreported?{unreported:true}:{}}}const model=info.data?.model;if(model===void 0)return{ok:true};if(typeof model!=="string")return{ok:false,error:`inspect returned a non-string model for "${name2}"`};return{ok:true,model}}async listManagerEndpoints(input,instance){return this.managerCalls.listManagerEndpoints(input,instance)}managerCallBearer(argv,signal){return this.managerCalls.managerCallBearer(argv,signal)}async execBearerCmd(argv,signal,timeoutMs){return this.managerCalls.execBearerCmd(argv,signal,timeoutMs)}async invokeEndpoint(endpoint,command,args,opts={}){let ownerInstance=opts.instanceId;const seatRead=endpoint===BASELINE_LIFECYCLE_ENDPOINT&&command==="inspect"&&typeof args?.name==="string";let selected;let dropBearer;if(seatRead){const roster=await this.ep.readPresence();const live=roster.filter(p2=>p2.status!=="offline"&&(!this.config.userAuth||p2.card.id.startsWith(`${this.config.userAuth.owner}.`)));const peer=resolvePeer(live,args.name);if(!peer)throw new EpEnvelopeError("not-found",`no agent ${JSON.stringify(args.name)} is held in live presence`,void 0,"not-executed");const instance=peer.card.meta?.["ai.cotal.manager.instance"];if(typeof instance!=="string")throw new EpEnvelopeError("failed-precondition",`agent ${JSON.stringify(peer.card.name)} reports no holding manager instance`,void 0,"not-executed");try{const holdingInstance=assertLifecycleToken(instance,"holding manager instance");ownerInstance??=holdingInstance}catch{throw new EpEnvelopeError("failed-precondition",`agent ${JSON.stringify(peer.card.name)} reports an invalid holding manager instance`,void 0,"not-executed")}selected=peer;opts={...opts,instanceId:ownerInstance};args={...args,name:peer.card.name}}try{let reply;if(seatRead&&this.config.userAuth){const bearerCmd=this.config.userAuth.bearerCmd;if(!bearerCmd)throw new EpEnvelopeError("failed-precondition",`${command}: this agent's bearer comes from its host, which issues no manager-call bearer, so manager operations are unavailable`,void 0,"not-executed");const bearerArgv=[...bearerCmd,"--manager-call","--manager-instance",ownerInstance];const bearer=signal=>this.managerCallBearer(bearerArgv,signal).catch(e3=>{if(e3 instanceof Error&&e3.message.startsWith("agent-bearer: exchange refused:"))throw new EpEnvelopeError("permission-denied",e3.message,void 0,"not-executed");throw e3});dropBearer=()=>{this.managerCalls.dropBearer(bearerArgv)};const{instanceId:_instanceId,classInstanceId:_classInstanceId,follow:_follow,...invokeOpts}=opts;reply=await invokeUserManager({...this.config,managerInstanceId:ownerInstance},bearer,command,args,invokeOpts)}else{reply=await this.ep.invokeService(endpoint,command,args,opts)}if(selected&&reply.reply.ok){const row=reply.reply.data;if(row.id!==selected.card.id&&`${this.ep.principal.owner}.${row.id}`!==selected.card.id||row.lifecycleUid!==selected.lifecycleUid)throw new EpEnvelopeError("expired",`agent ${JSON.stringify(selected.card.name)} changed lifecycle after owner resolution; no current row was accepted`,void 0,"not-executed")}return reply}catch(error51){dropBearer?.();if(seatRead&&ownerInstance!==void 0&&unansweredRequest(error51))throw new EpEnvelopeError("unavailable",`TARGET_UNAVAILABLE: manager instance ${ownerInstance} did not answer ${endpoint}.${command}`,error51.details,error51.outcome);throw error51}}async managerInvoke(command,args,opts={}){return this.managerCalls.managerInvoke(command,args,opts)}async managerTargetFor(name2,instanceId){const info=await this.managerInvoke("inspect",{name:name2},instanceId===void 0?{}:{instanceId});if(!info.ok)return{error:info};const row=info.data;const dot=row.id.indexOf(".");const[owner2,actor2]=dot>0?[row.id.slice(0,dot),row.id.slice(dot+1)]:[this.ep.principal.owner,row.id];return{target:{mode:"owner",owner:owner2,actor:actor2,lifecycleUid:row.lifecycleUid}}}async despawn(name2,opts){await this.requireConnected();const graceful=opts?.graceful??true;if(!name2){if(opts?.instance!==void 0)return{ok:false,error:"instance selects the manager of a named peer; omit it to stop yourself"};if(this.config.turnRelay===false)return{ok:false,error:"this connection belongs to a conversation, not a managed seat, so it has no self to stop; disconnecting retires only this connection"};const instanceId=!this.config.creds?this.config.managerInstanceId:void 0;return this.managerInvoke("stop",{graceful},{target:{mode:"self"},...instanceId!==void 0?{instanceId}:{}})}const pin=this.managerPin(opts?.instance);if("error"in pin)return pin.error;const resolved=await this.managerTargetFor(name2,pin.instanceId);if("error"in resolved)return resolved.error;return this.managerInvoke("despawn",{graceful},{target:resolved.target,...pin})}async run(verb,args,instance){await this.requireConnected();const pin=this.managerPin(instance);if("error"in pin)return pin.error;return this.managerInvoke(`run-${verb}`,args,{deadlineMs:RUN_LAUNCH_DEADLINE_MS,...verb==="answer"?{target:{mode:"self"}}:{},...pin})}openManagerInstance(){return!this.config.creds&&!this.config.userAuth?this.config.managerInstanceId:void 0}managerPin(instance){if(instance===void 0)return{};let instanceId;try{instanceId=assertLifecycleToken(instance,"instance")}catch(e3){return{error:{ok:false,error:e3.message}}}if(this.config.userAuth&&this.config.managerInstanceId!==void 0&&instanceId!==this.config.managerInstanceId)return{error:{ok:false,error:"the requested manager instance differs from this credential's instance authority"}};return{instanceId}}hasTurnRelay(){return this.config.managerInstanceId!==void 0&&(this.config.turnRelay!==false||this.nativeTurnLeaseValid())}turnRelayAuthorized(){return this.config.turnRelay!==false||this.nativeTurnLeaseValid()}nativeTurnLease;authorizeNativeTurnParticipation(lease){const principal=this.ep.principal;const lifecycleUid=this.config.lifecycleUid;if(lease.owner!==principal.owner||lease.actor!==principal.actor||lease.lifecycleUid!==lifecycleUid||lease.name!==this.config.name)throw new Error("the participation lease does not bind this connection's exact owner, actor, lifecycle and name");const managerInstanceId=assertLifecycleToken(lease.managerInstanceId,"participation manager instance");if(!Number.isFinite(lease.expiresAt)||lease.expiresAt<=Date.now())throw new Error("the participation lease is expired");if(this.nativeTurnLease&&this.nativeTurnLease.managerInstanceId!==managerInstanceId)throw new Error("a participation renewal cannot change the launching manager instance");this.nativeTurnLease={...lease,managerInstanceId};this.config.managerInstanceId=managerInstanceId;if(this._connected)this.armTurnRelay()}async participateInTurns(){await this.requireConnected();if(this.config.turnRelay!==false)throw new Error("turn participation is already managed by this seat's launcher");const reply=await this.managerInvoke("turn-participate",void 0,{target:{mode:"self"}});if(!reply.ok)throw new Error(reply.error??"the manager refused workflow turn participation");const data=reply.data;if(!data||typeof data.owner!=="string"||typeof data.actor!=="string"||typeof data.lifecycleUid!=="string"||typeof data.name!=="string"||typeof data.managerInstanceId!=="string"||typeof data.expiresAt!=="number")throw new Error("turn-participate returned an invalid participation lease");const lease=data;if(!reply.instanceId||lease.managerInstanceId!==reply.instanceId)throw new Error("turn-participate lease does not bind the manager instance that answered");this.authorizeNativeTurnParticipation(lease);this.requestTurnPull();return lease}nativeTurnParticipationExpiresAt(){return this.nativeTurnLeaseValid()?this.nativeTurnLease.expiresAt:void 0}activeTurnCount(){return this.activeTurns.size}nativeTurnLeaseValid(){return this.nativeTurnLease!==void 0&&this.nativeTurnLease.expiresAt>Date.now()}armTurnRelay(){if(!this.hasTurnRelay())return;onOnceHandoffTimeout((uid2,goalId)=>{if(uid2===this.onceUid()&&sealOnceHandoff(uid2,goalId))void this.reportUnconfirmed(goalId)});if(!this.turnNoticeArmed){let caller;try{caller=this.ep.serviceRailCaller()}catch(e3){this.log(`the run-turn relay cannot name this seat's reply rail (${e3.message}); no turn will reach this seat`);return}this.ep.tap(()=>this.requestTurnPull(),{subject:turnNoticeFilter(this.config.space,this.config.managerInstanceId,caller)});this.turnNoticeArmed=true}this.requestTurnPull()}requestTurnPull(){if(!this.turnRelayAuthorized()||this._stopping)return;if(this.turnPollBusy){this.turnPullAgain=true;return}void this.pollTurns().catch(e3=>this.turnPullFailed(e3.message,void 0))}async pollTurns(){if(!this.turnRelayAuthorized()||!this._connected||this._stopping||this.turnPollBusy)return;this.turnPollBusy=true;this.turnPullAgain=false;this.yieldedSincePull.clear();try{const r2=await this.managerInvoke("turn-pending",void 0,{target:{mode:"self"}});if(!r2.ok){this.turnPullFailed(r2.error??"refused with no message",r2.code);return}const rows=r2.data?.turns;if(!Array.isArray(rows)){this.turnPullFailed("turn-pending returned no turns array","bad-reply");return}if(this.turnRetryTimer!==void 0){clearTimeout(this.turnRetryTimer);this.turnRetryTimer=void 0}this.noteTurnNotices(r2.data.notices===true);const turns=rows.filter(isPendingTurn);if(turns.length<rows.length)this.notePullTrouble(`turn-pending returned ${rows.length-turns.length} malformed turn(s), dropped`);else this.pullTrouble=void 0;const live=new Set(turns.map(t2=>t2.goalId));for(const t2 of[...this.activeTurns.values()])if(!live.has(t2.goalId))this.settleTurn(t2);let fresh=0;for(const t2 of turns){if(this.activeTurns.has(t2.goalId)||this.yieldedSincePull.has(t2.goalId))continue;const once=t2.once?{spawner:onceSpawner(t2.payload)}:void 0;const surfaced=once!==void 0&&onceHandoffState(this.onceUid(),t2.goalId)==="confirmed";this.activeTurns.set(t2.goalId,{goalId:t2.goalId,payload:t2.payload,acceptedAt:t2.acceptedAt,...t2.deadlineAt!==void 0?{deadlineAt:t2.deadlineAt}:{},...once?{once}:{},surfaced});if(!surfaced)fresh+=1;if(once!==void 0&&!surfaced&&this.options.onceClaimBound)this.boundOnceClaim(t2.goalId)}if(fresh>0)this.requestWake();if(r2.data.stop===true){this.log("the manager does not hold this once seat and its task has ended; ending this seat");void exitOnceSeat()}}finally{this.turnPollBusy=false;if(this.turnPullAgain)this.requestTurnPull()}}noteTurnNotices(sent){if(sent){if(this.legacyTurnPoll!==void 0){clearInterval(this.legacyTurnPoll);this.legacyTurnPoll=void 0}return}if(this.legacyTurnPoll!==void 0||this._stopping)return;this.log(`manager ${this.config.managerInstanceId} sends no turn notices (it predates them), so this seat pulls its turns every ${TURN_PULL_RETRY_MS}ms`);const t2=setInterval(()=>this.requestTurnPull(),TURN_PULL_RETRY_MS);t2.unref?.();this.legacyTurnPoll=t2}turnPullFailed(reason,code2){this.notePullTrouble(reason);const transient=code2===void 0||code2==="unavailable"||code2==="deadline-exceeded";if(!transient||this._stopping||this.turnRetryTimer!==void 0)return;const t2=setTimeout(()=>{this.turnRetryTimer=void 0;this.requestTurnPull()},TURN_PULL_RETRY_MS);t2.unref?.();this.turnRetryTimer=t2}notePullTrouble(reason){if(/still reconciling/i.test(reason))return;if(this.pullTrouble===reason)return;this.pullTrouble=reason;this.log(`the run-turn pull is not answering (${reason}); the seat pulls again on its next turn notice or reconnect`)}peekPendingTurns(){if(this.config.turnRelay===false&&!this.nativeTurnLeaseValid())return void 0;const now=Date.now();const waiting=[...this.activeTurns.values()].filter(t2=>!t2.surfaced&&(t2.deadlineAt===void 0||t2.deadlineAt>now)&&this.offerable(t2)).sort((a3,b3)=>a3.acceptedAt-b3.acceptedAt);if(!waiting.length)return void 0;const once=waiting.find(t2=>t2.once!==void 0);if(once!==void 0)return{text:renderOnceTask({goalId:once.goalId,payload:once.payload,spawner:once.once?.spawner,deadlineAt:once.deadlineAt}),goalIds:[once.goalId],once:true};let asked=false;const blocks=waiting.map(t2=>{let context=t2.payload;let ask="";try{const p2=JSON.parse(t2.payload);if(typeof p2.context==="string"&&p2.context.length>0)context=p2.context;ask=renderAskRequest(p2)}catch{}if(ask!=="")asked=true;return`\u2014 turn ${t2.goalId}${t2.deadlineAt!==void 0?` (deadline ${new Date(t2.deadlineAt).toISOString()})`:""}:
|
|
126
|
+
${list.join("\n")}`)}const first=waiting.find(([,e3])=>!e3.pending);return first&&{id:first[0],contextId:first[1].contextId}}start(retryMs=3e3){if(this._stopping)throw new Error("cannot start a stopped mesh session");if(!this.consumerClaim&&this.config.lifecycleUid){const{owner:owner2,actor:actor2}=this.ep.principal;this.consumerClaim=acquireLocalConsumer(this.config.servers,this.config.space,owner2,actor2,this.config.lifecycleUid)}return this.connectFlight??=this.connectLoop(retryMs)}consumerClaim;connectFlight;agentEndpoint;agentEndpointOpened=false;eventStartupChecked=false;eventPlaneBlocked;async connectLoop(retryMs){while(!this._stopping&&!this._connected){try{await this.ep.start();if(this._stopping)return;this.log(`connected to ${this.config.servers} as ${peerLabel(this.config)} in space "${this.config.space}" on #${this.config.subscribe.join(", #")}`);const historicalBuffered=this.peekInbox("pull-only").filter(i2=>i2.historical).length;this.log(`joined ${this.config.subscribe.length} boot channel(s): ${historicalBuffered} historical message(s) buffered pull-only`+(this.config.backfillFloor!==void 0?` (backfill floor ${this.config.backfillFloor})`:""));this.armTurnRelay();void this.serveAgentEndpoint()}catch(e3){const error51=e3 instanceof Error?e3:new Error(String(e3));if(this._stopping)return;this.lastConnectionError=error51.message;if(error51 instanceof EventStateConflictError){await this.ep.stop();this.consumerClaim?.release();this.consumerClaim=void 0;throw error51}const presence=this._transportConnected?this.ep.presenceWriteFailure():void 0;const forS=presence===void 0?"":presence.forMs<1e3?"<1":String(Math.round(presence.forMs/1e3));const diagnosis=presence?`connected, but this space's presence bucket "${presence.bucket}" has refused every write for ${forS}s (${presence.error??error51.message}) - the transport is fine and the fault is not the network`:this._transportConnected?`transport is connected but the mesh bind did not complete (${error51.message})`:`mesh unreachable (${error51.message})`;this.log(`${diagnosis}; retrying in ${retryMs}ms`);await sleep(retryMs)}}}async serveAgentEndpoint(){if(this.agentEndpointOpened||!this.config.userAuth)return;this.agentEndpointOpened=true;try{const served=await openAgentEndpoint(this.ep,{warn:msg=>this.log(msg),dispatcher:this.options.commands,onQueued:()=>this.emit("command")});if(this._stopping)return void served.close();this.agentEndpoint=served;if(served.commands.queued>0)this.emit("command")}catch(e3){this.log(`the agent endpoint is not served: ${e3.message}`)}}get queuedCommands(){return this.agentEndpoint?.commands.queued??0}dispatchNextCommand(){return this.agentEndpoint?.commands.dispatchNext()??Promise.resolve("empty")}stopFlight;stop(){return this.stopFlight??=this.stopOnce()}async stopOnce(){this._stopping=true;this.emit("stopping");this.inboxState.stop();this.managerCalls.clear();if(this.turnRetryTimer!==void 0){clearTimeout(this.turnRetryTimer);this.turnRetryTimer=void 0}if(this.legacyTurnPoll!==void 0){clearInterval(this.legacyTurnPoll);this.legacyTurnPoll=void 0}const agentEndpointClosed=this.agentEndpoint?.close();this._connected=false;if(this._transportConnected){this._transportConnected=false;this.emit("transport",{connected:false})}if(agentEndpointClosed)await waitForStop(agentEndpointClosed);const departure=this.inOrder(()=>this.ep.stop(),true);await waitForStop(departure);await this.ep.stop();await departure;await this.connectFlight?.catch(()=>{});this.consumerClaim?.release();this.consumerClaim=void 0}async reconnect(){if(this._stopping){return{ok:false,message:"This session is shutting down, so its Cotal mesh connection cannot be reconnected. Start a new session instead."}}try{await this.ep.reconnect();const held2=this.automaticQueueStalledForMs();const queued=this.inboxCount("automatic");const stalled=held2!==void 0&&held2>=AUTOMATIC_QUEUE_STALL_MS&&queued>0?` Note: this session's ${queued} queued automatic ${queued===1?"delivery has":"deliveries have"} made no progress for ${Math.round(held2/6e4)} minutes. Reconnecting did not deliver ${queued===1?"it":"them"}: the connection was not what was holding ${queued===1?"it":"them"} up.`:"";const channelIssue=this.channelDeliveryIssue;const message=channelIssue?`Transport reconnected (${this.config.name}@${this.config.space}), but this session remains degraded. ${channelIssue} Direct messages and anycast remain available. Restart this session to restore ambient channel delivery.`:`Reconnected \u2713 (${this.config.name}@${this.config.space})`;return{ok:true,message:`${message}${stalled}`}}catch(e3){if(e3 instanceof DmDurableMissingError){this.handleEndpointWarning(e3);return{ok:false,message:`Reconnect failed: ${missingInboxIssue(e3)}`}}return{ok:false,message:`Reconnect failed: ${e3.message||e3.name}. Still retrying automatically \u2014 or run /reconnect to retry now.`}}}noteDirected(item){if(item.kind!=="dm"&&item.kind!=="anycast")return;this.senders.delete(item.fromId);this.senders.set(item.fromId,item.fromName);if(this.senders.size>MAX_CORRELATIONS)this.senders.delete(this.senders.keys().next().value);if(!item.historical&&item.id!==""&&!this.answersQuestion(item)){this.unanswered.set(item.id,{fromId:item.fromId,contextId:item.contextId,text:item.text.slice(0,80)});if(this.unanswered.size>MAX_CORRELATIONS)this.unanswered.delete(this.unanswered.keys().next().value)}}peekInbox(scope="all"){return this.inboxState.peekInbox(scope)}inboxPreview(scope="all"){return this.inboxState.inboxPreview(scope)}async takeChosen(scope,choose,waitMs){return this.inboxState.takeChosen(scope,choose,waitMs)}heldTakes(){return this.inboxState.heldTakes()}holdInFlight(ids){return this.inboxState.holdInFlight(ids)}isInFlight(id2){return this.inboxState.isInFlight(id2)}releaseInFlight(ids){return this.inboxState.releaseInFlight(ids)}drainInbox(limit,scope="all"){return this.inboxState.drainInbox(limit,scope)}drainInboxDeliveries(keys){return this.inboxState.drainInboxDeliveries(keys)}inboxKeys(scope="all"){return this.inboxState.inboxKeys(scope)}inboxPending(scope="all"){return this.inboxState.inboxPending(scope)}inboxCount(scope="all"){return this.inboxState.inboxCount(scope)}inboxSnapshot(limit=3){return this.inboxState.inboxSnapshot(limit)}oldestAutomaticReceivedAt(){return this.inboxState.oldestAutomaticReceivedAt()}get recallCursor(){return this.inboxState.recallCursor}noteRecalled(mark){return this.inboxState.noteRecalled(mark)}recallAhead(item){return this.inboxState.recallAhead(item)}recallAheadSeen(id2){return this.inboxState.recallAheadSeen(id2)}recallAheadRoom(){return this.inboxState.recallAheadRoom()}noteRecalledAhead(id2){return this.inboxState.noteRecalledAhead(id2)}inboxScope(key){return this.inboxState.inboxScope(key)}directedPendingCount(){return this.inboxState.directedPendingCount()}pendingWake(skip){const turns=[...this.activeTurns.values()].filter(t2=>!t2.surfaced&&this.offerable(t2)).length;return turns+this.inboxWake(skip)}inboxWake(skip){return this.inboxState.inboxWake(skip)}requestWake(){this.emit("wake")}get attention(){return this.inboxState.attention}channelMode(channel){return this.inboxState.channelMode(channel)}channelModeEntries(){return this.inboxState.channelModeEntries()}async setChannelMode(channel,mode){return this.inboxState.setChannelMode(channel,mode)}async setAttention(mode){return this.inboxState.setAttention(mode)}async recallAmbient(underway=new Set){return this.inboxState.recallAmbient(underway)}async send(text3,channel,mentions){try{await this.requireConnected()}catch(error51){throw new Error(`${error51.message}. The message was not sent.`,{cause:error51})}const clean=normalizeMentions(mentions);if(clean)await this.assertKnownMentions(clean);return this.ep.multicast(text3,{channel,mentions:clean,...this.stamp().stamp})}async describeSendChannel(channel){if(this.ep.getChannelConfig(channel))return{known:true,hints:[]};const known=new Set(this.ep.joinedChannels().filter(isConcreteChannel));let unchecked;try{for(const row of await this.ep.listChannels())known.add(row.channel)}catch(e3){unchecked=e3.message}if(known.has(channel))return{known:true,hints:[]};const hints=closeChannelNames(channel,[...known]);return unchecked===void 0?{known:false,hints}:{known:false,hints,unchecked}}async assertKnownMentions(mentions){const{roster,failure}=await this.readRoster();const names=new Set(roster.map(p2=>p2.card.name.toLowerCase()));const unknown2=mentions.filter(m2=>!names.has(m2));if(!unknown2.length)return;if(!failure)throw new Error(`unknown mention${unknown2.length>1?"s":""}: ${unknown2.map(u2=>`@${u2}`).join(", ")} \u2014 no such peer observed in space "${this.config.space}"`);throw this.cannotVerify(`mention${unknown2.length>1?"s":""} ${unknown2.map(u2=>`@${u2}`).join(", ")}`,failure,"The send was not published.")}cannotVerify(subject,failure,outcome){return new Error(`cannot verify ${subject} in space "${this.config.space}": ${presenceReadCondition(failure)}, so absence is not a verdict \u2014 the peer may be present but unread. ${outcome}`,{cause:failure})}async anycast(role,text3){assertValidRole(role);await this.requireConnected();const holdersAtSend=await this.roleHolders(role);const{stamp:stamp2,own}=this.stamp();this.recordQuestion(own,{role});const{msg,ack}=await this.ep.anycastAttributed(role,text3,stamp2);this.rememberSent(ack.seq,msg.id);return{msg,ack,holdersAtSend}}async roleHolders(role){const{roster,failure}=await this.readRoster();if(failure)return void 0;return roster.filter(p2=>p2.card.role===role&&p2.status!=="offline").map(p2=>({id:p2.card.id,name:p2.card.name}))}sentRequests=new Map;rememberSent(seq,id2){const ids=this.sentRequests.get(seq)??[];if(!ids.includes(id2))ids.push(id2);this.sentRequests.delete(seq);this.sentRequests.set(seq,ids);if(this.sentRequests.size>MAX_CORRELATIONS)this.sentRequests.delete(this.sentRequests.keys().next().value)}sentRequestId(seq){const ids=this.sentRequests.get(seq);if(ids&&ids.length>1)throw new Error(`seq ${seq} names ${ids.length} requests this session sent (the role queue was recreated between them), so it is ambiguous; nothing was asked or cancelled`);return ids?.[0]}async anycastStatus(seq){await this.requireConnected();return this.ep.anycastStatus(seq,this.sentRequestId(seq))}async cancelAnycast(seq){await this.requireConnected();return this.ep.cancelAnycast(seq,this.sentRequestId(seq))}resolvePeer(target2){return resolvePeer(this.ep.getRoster(),target2,{selfId:this.id})}heldSender(target2,byName,peer){const name2=this.senders.get(target2);if(name2!==void 0)return{id:target2,name:name2};if(!byName)return void 0;const want=target2.trim().toLowerCase();const rostered=new Set(this.ep.getRoster().map(p2=>p2.card.id));const matches=[...this.senders].filter(([id2,n2])=>!rostered.has(id2)&&n2.toLowerCase()===want);if(peer)matches.unshift([peer.card.id,peer.card.name]);if(matches.length>1)throw new Error(`"${target2}" is ambiguous - ${matches.length} known peers share that name; DM by instance id instead: ${matches.map(([id2,n2])=>`${shownPeerName(n2,id2)} (${id2})`).join("; ")}`);const match=matches[0];return match&&match[0]!==peer?.card.id?{id:match[0],name:match[1]}:void 0}noPeer(target2){const want=target2.trim().toLowerCase();if(target2===this.id||want===this.config.name.toLowerCase())return`"${target2}" is this session: a DM goes to another peer, so nothing was sent. cotal_roster lists who is present.`;const missing=`no peer "${target2}" in space "${this.config.space}"`;if(!want)return missing;const names=[...new Set(this.ep.getRoster().filter(p2=>p2.card.id!==this.id&&p2.card.name.toLowerCase().startsWith(want)).map(p2=>p2.card.name))];if(!names.length)return missing;const shown=names.slice(0,NAMED_SIMILAR).map(n2=>JSON.stringify(n2)).join(", ");const more=names.length>NAMED_SIMILAR?` and ${names.length-NAMED_SIMILAR} more`:"";return`${missing}. A name must match in full, so nothing was sent. Present names that start with it: ${shown}${more}. DM one by its full name or instance id.`}async dm(target2,text3,opts={}){await this.requireConnected();const{roster,failure}=await this.readRoster();const peer=this.senders.has(target2)?roster.find(p2=>p2.card.id===target2):this.resolvePeer(target2);const held2=peer?.card.id===target2?void 0:this.heldSender(target2,!failure,peer);if(!peer&&!held2){if(!failure)throw new Error(this.noPeer(target2));throw this.cannotVerify(`peer "${target2}"`,failure,"The DM was not sent.")}const recipientStatusAtSend=peer?peer.status:"unrostered";const recipient=peer?{id:peer.card.id,name:peer.card.name}:held2;const answered=this.answering(recipient.id,opts.replyTo?.trim()||void 0);const entry=answered&&this.unanswered.get(answered.id);const{stamp:stamp2,own}=this.stamp(answered);this.recordQuestion(own,{peerId:recipient.id});if(entry)entry.pending=true;try{const{msg,ack}=await this.ep.unicastAttributed(recipient.id,text3,stamp2);if(answered)this.unanswered.delete(answered.id);return{msg,peer,recipient,ack,recipientStatusAtSend}}finally{if(entry)entry.pending=false}}pendingSpawns=new Map;async spawn(name2,role,opts){await this.requireConnected();const raw=opts?.model;if(raw!==void 0&&!raw.trim())return{ok:false,error:"model: must not be empty"};const requested=raw?.trim();for(const ch of opts?.join??[]){try{assertValidChannel(ch)}catch(e3){return{ok:false,error:`join: ${e3.message}`}}if(!isConcreteChannel(ch))return{ok:false,error:`join: "${ch}" must be a concrete channel (no wildcard)`};if(!channelInAllow(this.config.allowSubscribe,ch))return{ok:false,error:`join: "${ch}" is not within your read ACL (allowSubscribe) [${this.config.allowSubscribe.join(", ")}]; a spawn can only hand on channels you may read yourself`}}let instance;try{const selected=opts?.instance??this.openManagerInstance();instance=selected===void 0?void 0:assertLifecycleToken(selected,"instance")}catch(e3){return{ok:false,error:e3.message}}if(this.config.userAuth&&instance!==void 0&&this.config.managerInstanceId!==void 0&&instance!==this.config.managerInstanceId)return{ok:false,error:"the requested manager instance differs from this credential's instance authority"};const args={name:name2,role,agent:opts?.agent,model:requested||void 0,variant:opts?.variant,launchOptions:opts?.launchOptions,cwd:opts?.cwd,prompt:opts?.prompt,events:opts?.events,runtime:opts?.runtime,join:opts?.join,persona:opts?.persona,callerAcl:{allowSubscribe:this.config.allowSubscribe,allowPublish:this.config.allowPublish},once:opts?.once};const key=canonicalJson(JSON.parse(JSON.stringify({...args,instance,caller:this.ep.principal,lifecycleUid:this.config.lifecycleUid})));const previous=this.pendingSpawns.get(key);if(previous){const pending=await previous;const allocation=pending.data;if(allocation?.name&&allocation.uid){const inspected=await this.managerInvoke("ps",void 0,pending.instanceId?{instanceId:pending.instanceId}:{});const rows=Array.isArray(inspected.data)?inspected.data:void 0;const row=rows?.find(r2=>r2.name===allocation.name);if(inspected.ok&&rows&&(!row||typeof row.lifecycleUid==="string"&&row.lifecycleUid!==allocation.uid||row.lifecycleUid===allocation.uid&&(row.presenceIdentityVerified===true||row.status==="exited"))){if(this.pendingSpawns.get(key)===previous)this.pendingSpawns.delete(key)}else return pending}else return pending}const invoking=this.managerInvoke("spawn",args,{deadlineMs:SPAWN_TIMEOUT_MS,follow:true,...instance!==void 0?{instanceId:instance}:{}});this.pendingSpawns.set(key,invoking);const reply=await invoking;if(reply.ok||reply.code!=="uncertain"&&reply.outcome!=="unknown"){if(this.pendingSpawns.get(key)===invoking)this.pendingSpawns.delete(key)}if(reply.data?.submissionUnknown||!reply.ok&&reply.outcome==="unknown")return reply;const pinned=requested||opts?.persona?.model;if(!pinned)return reply;const actual=reply.data;const seat=actual?.name??name2;const recorded=await this.inspectModel(seat,instance);const recordedLabel=!recorded.ok?`could not inspect the recorded pin: ${recorded.error}`:recorded.model===void 0?"the manager recorded no model pin":`the manager recorded ${JSON.stringify(recorded.model)}`;if(recorded.ok&&recorded.model!==pinned){return{ok:false,error:`requested model ${JSON.stringify(pinned)} but ${recordedLabel} for "${seat}" \u2014 refusing a spawn whose pin did not land. The seat may already be live; inspect it before retrying, because a retry duplicates the spawn`}}if(!reply.ok&&reply.code!=="uncertain"){return{ok:false,error:`${reply.error??"manager refused"} (requested model ${JSON.stringify(pinned)}; ${recordedLabel} for "${seat}")`}}if(!recorded.ok){return{...reply,data:{...reply.data,pinAudit:{requested:pinned,error:recorded.error,...recorded.unreported?{unreported:true}:{}}}}}return{...reply,data:{...reply.data,model:recorded.model}}}async inspectModel(name2,instance){const info=await this.managerInvoke("inspect",{name:name2},instance===void 0?void 0:{instanceId:instance});if(!info.ok){const unreported=info.code==="not-found"||info.code==="unavailable"&&info.details?.some(d2=>d2.kind===EP_UNANSWERED)===true;return{ok:false,error:info.error??"inspect refused",...unreported?{unreported:true}:{}}}const model=info.data?.model;if(model===void 0)return{ok:true};if(typeof model!=="string")return{ok:false,error:`inspect returned a non-string model for "${name2}"`};return{ok:true,model}}async listManagerEndpoints(input,instance){return this.managerCalls.listManagerEndpoints(input,instance)}managerCallBearer(argv,signal){return this.managerCalls.managerCallBearer(argv,signal)}async execBearerCmd(argv,signal,timeoutMs){return this.managerCalls.execBearerCmd(argv,signal,timeoutMs)}async invokeEndpoint(endpoint,command,args,opts={}){let ownerInstance=opts.instanceId;const seatRead=endpoint===BASELINE_LIFECYCLE_ENDPOINT&&command==="inspect"&&typeof args?.name==="string";let selected;let dropBearer;if(seatRead){const roster=await this.ep.readPresence();const live=roster.filter(p2=>p2.status!=="offline"&&(!this.config.userAuth||p2.card.id.startsWith(`${this.config.userAuth.owner}.`)));const peer=resolvePeer(live,args.name);if(!peer)throw new EpEnvelopeError("not-found",`no agent ${JSON.stringify(args.name)} is held in live presence`,void 0,"not-executed");const instance=peer.card.meta?.["ai.cotal.manager.instance"];if(typeof instance!=="string")throw new EpEnvelopeError("failed-precondition",`agent ${JSON.stringify(peer.card.name)} reports no holding manager instance`,void 0,"not-executed");try{const holdingInstance=assertLifecycleToken(instance,"holding manager instance");ownerInstance??=holdingInstance}catch{throw new EpEnvelopeError("failed-precondition",`agent ${JSON.stringify(peer.card.name)} reports an invalid holding manager instance`,void 0,"not-executed")}selected=peer;opts={...opts,instanceId:ownerInstance};args={...args,name:peer.card.name}}try{let reply;if(seatRead&&this.config.userAuth){const bearerCmd=this.config.userAuth.bearerCmd;if(!bearerCmd)throw new EpEnvelopeError("failed-precondition",`${command}: this agent's bearer comes from its host, which issues no manager-call bearer, so manager operations are unavailable`,void 0,"not-executed");const bearerArgv=[...bearerCmd,"--manager-call","--manager-instance",ownerInstance];const bearer=signal=>this.managerCallBearer(bearerArgv,signal).catch(e3=>{if(e3 instanceof Error&&e3.message.startsWith("agent-bearer: exchange refused:"))throw new EpEnvelopeError("permission-denied",e3.message,void 0,"not-executed");throw e3});dropBearer=()=>{this.managerCalls.dropBearer(bearerArgv)};const{instanceId:_instanceId,classInstanceId:_classInstanceId,follow:_follow,...invokeOpts}=opts;reply=await invokeUserManager({...this.config,managerInstanceId:ownerInstance},bearer,command,args,invokeOpts)}else{reply=await this.ep.invokeService(endpoint,command,args,opts)}if(selected&&reply.reply.ok){const row=reply.reply.data;if(row.id!==selected.card.id&&`${this.ep.principal.owner}.${row.id}`!==selected.card.id||row.lifecycleUid!==selected.lifecycleUid)throw new EpEnvelopeError("expired",`agent ${JSON.stringify(selected.card.name)} changed lifecycle after owner resolution; no current row was accepted`,void 0,"not-executed")}return reply}catch(error51){dropBearer?.();if(seatRead&&ownerInstance!==void 0&&unansweredRequest(error51))throw new EpEnvelopeError("unavailable",`TARGET_UNAVAILABLE: manager instance ${ownerInstance} did not answer ${endpoint}.${command}`,error51.details,error51.outcome);throw error51}}async managerInvoke(command,args,opts={}){return this.managerCalls.managerInvoke(command,args,opts)}async managerTargetFor(name2,instanceId){const info=await this.managerInvoke("inspect",{name:name2},instanceId===void 0?{}:{instanceId});if(!info.ok)return{error:info};const row=info.data;const dot=row.id.indexOf(".");const[owner2,actor2]=dot>0?[row.id.slice(0,dot),row.id.slice(dot+1)]:[this.ep.principal.owner,row.id];return{target:{mode:"owner",owner:owner2,actor:actor2,lifecycleUid:row.lifecycleUid}}}async despawn(name2,opts){await this.requireConnected();const graceful=opts?.graceful??true;if(!name2){if(opts?.instance!==void 0)return{ok:false,error:"instance selects the manager of a named peer; omit it to stop yourself"};if(this.config.turnRelay===false)return{ok:false,error:"this connection belongs to a conversation, not a managed seat, so it has no self to stop; disconnecting retires only this connection"};const instanceId=!this.config.creds?this.config.managerInstanceId:void 0;return this.managerInvoke("stop",{graceful},{target:{mode:"self"},...instanceId!==void 0?{instanceId}:{}})}const pin=this.managerPin(opts?.instance);if("error"in pin)return pin.error;const resolved=await this.managerTargetFor(name2,pin.instanceId);if("error"in resolved)return resolved.error;return this.managerInvoke("despawn",{graceful},{target:resolved.target,...pin})}async run(verb,args,instance){await this.requireConnected();const pin=this.managerPin(instance);if("error"in pin)return pin.error;return this.managerInvoke(`run-${verb}`,args,{deadlineMs:RUN_LAUNCH_DEADLINE_MS,...verb==="answer"?{target:{mode:"self"}}:{},...pin})}openManagerInstance(){return!this.config.creds&&!this.config.userAuth?this.config.managerInstanceId:void 0}managerPin(instance){if(instance===void 0)return{};let instanceId;try{instanceId=assertLifecycleToken(instance,"instance")}catch(e3){return{error:{ok:false,error:e3.message}}}if(this.config.userAuth&&this.config.managerInstanceId!==void 0&&instanceId!==this.config.managerInstanceId)return{error:{ok:false,error:"the requested manager instance differs from this credential's instance authority"}};return{instanceId}}hasTurnRelay(){return this.config.managerInstanceId!==void 0&&(this.config.turnRelay!==false||this.nativeTurnLeaseValid())}turnRelayAuthorized(){return this.config.turnRelay!==false||this.nativeTurnLeaseValid()}nativeTurnLease;authorizeNativeTurnParticipation(lease){const principal=this.ep.principal;const lifecycleUid=this.config.lifecycleUid;if(lease.owner!==principal.owner||lease.actor!==principal.actor||lease.lifecycleUid!==lifecycleUid||lease.name!==this.config.name)throw new Error("the participation lease does not bind this connection's exact owner, actor, lifecycle and name");const managerInstanceId=assertLifecycleToken(lease.managerInstanceId,"participation manager instance");if(!Number.isFinite(lease.expiresAt)||lease.expiresAt<=Date.now())throw new Error("the participation lease is expired");if(this.nativeTurnLease&&this.nativeTurnLease.managerInstanceId!==managerInstanceId)throw new Error("a participation renewal cannot change the launching manager instance");this.nativeTurnLease={...lease,managerInstanceId};this.config.managerInstanceId=managerInstanceId;if(this._connected)this.armTurnRelay()}async participateInTurns(){await this.requireConnected();if(this.config.turnRelay!==false)throw new Error("turn participation is already managed by this seat's launcher");const reply=await this.managerInvoke("turn-participate",void 0,{target:{mode:"self"}});if(!reply.ok)throw new Error(reply.error??"the manager refused workflow turn participation");const data=reply.data;if(!data||typeof data.owner!=="string"||typeof data.actor!=="string"||typeof data.lifecycleUid!=="string"||typeof data.name!=="string"||typeof data.managerInstanceId!=="string"||typeof data.expiresAt!=="number")throw new Error("turn-participate returned an invalid participation lease");const lease=data;if(!reply.instanceId||lease.managerInstanceId!==reply.instanceId)throw new Error("turn-participate lease does not bind the manager instance that answered");this.authorizeNativeTurnParticipation(lease);this.requestTurnPull();return lease}nativeTurnParticipationExpiresAt(){return this.nativeTurnLeaseValid()?this.nativeTurnLease.expiresAt:void 0}activeTurnCount(){return this.activeTurns.size}nativeTurnLeaseValid(){return this.nativeTurnLease!==void 0&&this.nativeTurnLease.expiresAt>Date.now()}armTurnRelay(){if(!this.hasTurnRelay())return;onOnceHandoffTimeout((uid2,goalId)=>{if(uid2===this.onceUid()&&sealOnceHandoff(uid2,goalId))void this.reportUnconfirmed(goalId)});if(!this.turnNoticeArmed){let caller;try{caller=this.ep.serviceRailCaller()}catch(e3){this.log(`the run-turn relay cannot name this seat's reply rail (${e3.message}); no turn will reach this seat`);return}this.ep.tap(()=>this.requestTurnPull(),{subject:turnNoticeFilter(this.config.space,this.config.managerInstanceId,caller)});this.turnNoticeArmed=true}this.requestTurnPull()}requestTurnPull(){if(!this.turnRelayAuthorized()||this._stopping)return;if(this.turnPollBusy){this.turnPullAgain=true;return}void this.pollTurns().catch(e3=>this.turnPullFailed(e3.message,void 0))}async pollTurns(){if(!this.turnRelayAuthorized()||!this._connected||this._stopping||this.turnPollBusy)return;this.turnPollBusy=true;this.turnPullAgain=false;this.yieldedSincePull.clear();try{const r2=await this.managerInvoke("turn-pending",void 0,{target:{mode:"self"}});if(!r2.ok){this.turnPullFailed(r2.error??"refused with no message",r2.code);return}const rows=r2.data?.turns;if(!Array.isArray(rows)){this.turnPullFailed("turn-pending returned no turns array","bad-reply");return}if(this.turnRetryTimer!==void 0){clearTimeout(this.turnRetryTimer);this.turnRetryTimer=void 0}this.noteTurnNotices(r2.data.notices===true);const turns=rows.filter(isPendingTurn);if(turns.length<rows.length)this.notePullTrouble(`turn-pending returned ${rows.length-turns.length} malformed turn(s), dropped`);else this.pullTrouble=void 0;const live=new Set(turns.map(t2=>t2.goalId));for(const t2 of[...this.activeTurns.values()])if(!live.has(t2.goalId))this.settleTurn(t2);let fresh=0;for(const t2 of turns){if(this.activeTurns.has(t2.goalId)||this.yieldedSincePull.has(t2.goalId))continue;const once=t2.once?{spawner:onceSpawner(t2.payload)}:void 0;const surfaced=once!==void 0&&onceHandoffState(this.onceUid(),t2.goalId)==="confirmed";this.activeTurns.set(t2.goalId,{goalId:t2.goalId,payload:t2.payload,acceptedAt:t2.acceptedAt,...t2.deadlineAt!==void 0?{deadlineAt:t2.deadlineAt}:{},...once?{once}:{},surfaced});if(!surfaced)fresh+=1;if(once!==void 0&&!surfaced&&this.options.onceClaimBound)this.boundOnceClaim(t2.goalId)}if(fresh>0)this.requestWake();if(r2.data.stop===true){this.log("the manager does not hold this once seat and its task has ended; ending this seat");void exitOnceSeat()}}finally{this.turnPollBusy=false;if(this.turnPullAgain)this.requestTurnPull()}}noteTurnNotices(sent){if(sent){if(this.legacyTurnPoll!==void 0){clearInterval(this.legacyTurnPoll);this.legacyTurnPoll=void 0}return}if(this.legacyTurnPoll!==void 0||this._stopping)return;this.log(`manager ${this.config.managerInstanceId} sends no turn notices (it predates them), so this seat pulls its turns every ${TURN_PULL_RETRY_MS}ms`);const t2=setInterval(()=>this.requestTurnPull(),TURN_PULL_RETRY_MS);t2.unref?.();this.legacyTurnPoll=t2}turnPullFailed(reason,code2){this.notePullTrouble(reason);const transient=code2===void 0||code2==="unavailable"||code2==="deadline-exceeded";if(!transient||this._stopping||this.turnRetryTimer!==void 0)return;const t2=setTimeout(()=>{this.turnRetryTimer=void 0;this.requestTurnPull()},TURN_PULL_RETRY_MS);t2.unref?.();this.turnRetryTimer=t2}notePullTrouble(reason){if(/still reconciling/i.test(reason))return;if(this.pullTrouble===reason)return;this.pullTrouble=reason;this.log(`the run-turn pull is not answering (${reason}); the seat pulls again on its next turn notice or reconnect`)}peekPendingTurns(){if(this.config.turnRelay===false&&!this.nativeTurnLeaseValid())return void 0;const now=Date.now();const waiting=[...this.activeTurns.values()].filter(t2=>!t2.surfaced&&(t2.deadlineAt===void 0||t2.deadlineAt>now)&&this.offerable(t2)).sort((a3,b3)=>a3.acceptedAt-b3.acceptedAt);if(!waiting.length)return void 0;const once=waiting.find(t2=>t2.once!==void 0);if(once!==void 0)return{text:renderOnceTask({goalId:once.goalId,payload:once.payload,spawner:once.once?.spawner,deadlineAt:once.deadlineAt}),goalIds:[once.goalId],once:true};let asked=false;const blocks=waiting.map(t2=>{let context=t2.payload;let ask="";try{const p2=JSON.parse(t2.payload);if(typeof p2.context==="string"&&p2.context.length>0)context=p2.context;ask=renderAskRequest(p2)}catch{}if(ask!=="")asked=true;return`\u2014 turn ${t2.goalId}${t2.deadlineAt!==void 0?` (deadline ${new Date(t2.deadlineAt).toISOString()})`:""}:
|
|
127
127
|
${context}${ask}`});const text3=`\u{1F3AF} Cotal \u2014 a run handed you ${waiting.length===1?"its turn":`${waiting.length} turns`}:
|
|
128
128
|
${blocks.join("\n")}
|
|
129
129
|
(Do the work now with your own tools. ${asked?"An ask must be answered through its native route above before ending your host turn. ":""}For ordinary turns, ending your turn yields "done" automatically; call cotal_yield when blocked or handing off an ordinary turn.)`;return{text:text3,goalIds:waiting.map(t2=>t2.goalId)}}commitSurfacedTurns(goalIds){if(this.config.turnRelay===false&&!this.nativeTurnLeaseValid())return;for(const id2 of goalIds){const t2=this.activeTurns.get(id2);if(t2?.once!==void 0&&!confirmOnceHandoff(this.onceUid(),id2))continue;if(t2)t2.surfaced=true}}unsurfaceTurns(goalIds){for(const id2 of goalIds){const t2=this.activeTurns.get(id2);if(t2&&t2.once===void 0)t2.surfaced=false}}claimTurns(goalIds){return claimOnceHandoff(this.onceUid(),goalIds.filter(id2=>(this.activeTurns.get(id2)??this.settledTurns.get(id2))?.once!==void 0))}releaseTurns(goalIds){for(const id2 of goalIds){if(this.activeTurns.get(id2)?.once===void 0)continue;if(sealOnceHandoff(this.onceUid(),id2))void this.reportUnconfirmed(id2)}}noteTurnsDispatched(goalIds){for(const id2 of goalIds)if(this.activeTurns.get(id2)?.once!==void 0)stopOnceHandoffTimer(this.onceUid(),id2)}boundOnceClaim(goalId){const timer2=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);timer2.unref?.()}offerable(t2){return t2.once===void 0||onceHandoffState(this.onceUid(),t2.goalId)==="pending"}onceUid(){return this.config.lifecycleUid??this.config.name}async reportUnconfirmed(goalId){const until=Date.now()+ONCE_HANDOFF_MS;let delay3=1e3;let exitTried=false;for(;;){const r2=await this.managerInvoke("turn-unconfirmed",{goalId},{target:{mode:"self"}}).catch(e3=>({ok:false,error:e3.message,code:void 0}));const transient=!r2.ok&&(r2.code===void 0||r2.code==="unavailable"||r2.code==="deadline-exceeded");if(!transient){this.log(`once task ${goalId}: its handoff was not confirmed; reported to the manager (${r2.ok?"the task failed":r2.error??"refused"})`);return}if(!exitTried&&Date.now()+delay3>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(resolve6=>setTimeout(resolve6,delay3));delay3=Math.min(delay3*2,exitTried?6e4:1e4)}}async yieldTurn(status2,opts={}){if(this.config.turnRelay===false&&!this.nativeTurnLeaseValid())return{ok:false,error:"this personal connection has no valid workflow turn participation lease; opt in or renew it first"};try{await this.requireConnected()}catch(error51){throw new Error(`${error51.message}. The yield was not sent.`,{cause:error51})}const t2=opts.turn!==void 0?this.activeTurns.get(opts.turn):[...this.activeTurns.values()].filter(x2=>x2.surfaced).sort((a3,b3)=>a3.acceptedAt-b3.acceptedAt)[0];if(!t2){const id2=opts.turn??[...this.settledTurns.keys()].at(-1);const settled=id2===void 0?void 0:this.settledTurns.get(id2);if(id2!==void 0&&settled!==void 0)return{ok:false,error:settledTurnError(id2,settled)};return{ok:false,error:opts.turn!==void 0?`no active turn "${opts.turn}" on this seat`:"no turn is active \u2014 nothing to yield"}}if(!t2.surfaced)return{ok:false,error:`turn "${t2.goalId}" has not been surfaced into this session yet; nothing was seen, so nothing can be yielded for it`};if(status2==="handoff"&&(opts.to===void 0||opts.to.length===0))return{ok:false,error:"a handoff yield names its addressee (to)"};const r2=await this.managerInvoke("turn-yield",{goalId:t2.goalId,status:status2,to:opts.to,note:opts.note},{target:{mode:"self"}});if(!r2.ok)return r2;this.yieldedSincePull.add(t2.goalId);if(r2.data?.state!=="succeeded"){this.settleTurn(t2);return{ok:false,error:settledTurnError(t2.goalId,t2)}}this.activeTurns.delete(t2.goalId);this.rememberSettled(t2.goalId,{yielded:status2});return r2}settleTurn(t2){if(t2.once!==void 0)endOnceHandoff(this.onceUid(),t2.goalId);this.activeTurns.delete(t2.goalId);this.rememberSettled(t2.goalId,{...t2.deadlineAt!==void 0?{deadlineAt:t2.deadlineAt}:{},...t2.once!==void 0?{once:true}:{}})}rememberSettled(goalId,settled){this.settledTurns.delete(goalId);this.settledTurns.set(goalId,settled);if(this.settledTurns.size>MAX_SETTLED_TURNS)this.settledTurns.delete(this.settledTurns.keys().next().value)}async purgeHistory(opts){await this.requireConnected();const args={includeDms:opts?.includeDms??false};return this.managerInvoke("purge",args)}async definePersona(def){await this.requireConnected();const pin=this.managerPin(def.instance??this.openManagerInstance());if("error"in pin)return pin.error;if(def.announce!==void 0){if(def.announce.trim()==="")throw new Error("announce: empty channel \u2014 omit it to define silently, or name a concrete channel");try{assertValidChannel(def.announce)}catch(e3){throw new Error(`announce: ${e3?.message??String(e3)}`)}if(!isConcreteChannel(def.announce))throw new Error(`announce: "${def.announce}" is a wildcard \u2014 announce to one concrete channel`)}const args={name:def.name,model:def.model,persona:def.prompt,role:def.role,agent:def.agent,subscribe:def.subscribe,allowSubscribe:def.allowSubscribe,allowPublish:def.allowPublish,capabilities:def.capabilities,endpoints:def.endpoints};const reply=await this.managerInvoke("define-persona",args,pin);if(!reply.ok&&reply.outcome!=="not-executed"&&(reply.outcome==="unknown"||reply.code==="deadline-exceeded"&&reply.details?.some(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(e3){return{...reply,announceError:e3?.message??String(e3),announceOutcome:isPublishPermissionDenied(e3)?"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(name2,instance){await this.requireConnected();const pin=this.managerPin(instance??this.openManagerInstance());if("error"in pin)return pin.error;return this.managerInvoke("show-persona",{name:name2},pin)}async readRoster(){try{return{roster:await this.ep.readPresence()}}catch(e3){return{roster:this.ep.getRoster(),failure:e3}}}get status(){return this._status}inOrder(write,forDeparture=false){if(this._stopping&&!forDeparture)return Promise.reject(new Error("agent is stopping; presence writes are refused"));const next=this.presenceChain.then(write,write);this.presenceChain=next.catch(()=>{});return next}abandonPresenceWrites(){this.presenceChain=Promise.resolve()}async setStatus(status2,activity){await this.inOrder(async()=>{await this.requireConnected();const prev=this.turnStatus;try{if(prev!=="working"&&status2==="working")await this.ep.setCondition(null);await this.publishStatus(status2,activity)}finally{this._status=status2;this.turnStatus=status2;if(prev==="working"&&status2==="idle")this.onTurnBoundary()}})}async resetStatus(status2,activity){await this.inOrder(async()=>{await this.requireConnected();try{await this.publishStatus(status2,activity)}finally{this._status=status2}})}async publishStatus(status2,activity){await this.ep.setStatus(status2,activity)}async setActivity(activity){await this.inOrder(async()=>{await this.requireConnected();await this.ep.setActivity(activity)})}async setCondition(condition){await this.inOrder(()=>this.ep.setCondition(condition))}noteActivity(at2){this.ep.noteActivity(at2)}onTurnBoundary(){for(const t2 of[...this.activeTurns.values()]){if(!t2.surfaced)continue;void this.yieldTurn("done",{turn:t2.goalId}).then(r2=>{if(!r2.ok)this.log(`turn ${t2.goalId} auto-yield: ${r2.error??"refused"}`)}).catch(e3=>this.log(`turn ${t2.goalId} auto-yield: ${e3.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(c3=>({c:c3,d:this.ep.getChannelConfig(c3)?.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):
|
|
130
130
|
${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(c3=>{const joined=mine.some(p2=>subjectMatches(p2,c3.channel));const stored=mine.some(p2=>p2===c3.channel||isChannelFamily(p2)&&subjectMatches(p2,c3.channel));return{channel:c3.channel,description:c3.config?.description,replay:this.ep.channelReplay(c3.channel),joined,durableUnclosed:unclosed.has(c3.channel),deliveryHealth:health(c3.channel,stored),messages:c3.messages,mode:this.channelMode(c3.channel)??"normal",event:this.eventChannelOf(c3.channel)}});for(const pattern of mine){if(isConcreteChannel(pattern))continue;const family=isChannelFamily(pattern);rows.push({channel:pattern,replay:this.ep.channelReplay(pattern),joined:true,durableUnclosed:unclosed.has(pattern),deliveryHealth:family?held2(pattern):void 0,messages:0,mode:"normal",follow:family?"family":"live"})}const present=new Set(rows.map(r2=>r2.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();const legacyDiscoveryMessage=isLocalServer(this.config.servers)?void 0:"this space's host runs an older delivery service, so this durable leave was not applied and the channel stays joined; the host must update the delivery service";const result=await this.ep.leaveChannel(channel,legacyDiscoveryMessage);if(result.left)this.inboxState.lowerBuffered(channel,false,this.joinedChannels());return result}async requireConnected(){return this.whenConnected(CONNECT_GRACE_MS)}async whenConnected(timeoutMs=CONNECT_GRACE_MS){if(this._connected)return;this.ep.retryNow();if(!await this.awaitConnection(timeoutMs))throw new Error(this.notConnectedMessage())}awaitConnection(timeoutMs){return new Promise(resolve6=>{let settled=false;const finish=ok3=>{if(settled)return;settled=true;clearTimeout(timer2);this.ep.off("connection",onConnection);resolve6(ok3)};const onConnection=e3=>{if(e3.connected)finish(true)};const timer2=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){if(error51 instanceof DmDurableMissingError&&!this._connected&&!this._stopping)this.lastConnectionError=missingInboxIssue(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}
|
|
131
|
-
`)}};function presenceReadCondition(failure){return`the presence read failed (${failure.message})`}function missingInboxIssue(e3){return`this session's direct-message inbox is missing on the broker, and on an authenticated mesh only a new launch creates one, so reconnecting cannot restore it. Restart this session, or respawn it if a manager launched it. Missing durable "${e3.durable}" on stream "${e3.stream}". Retries continue in case a broker restore brings it back.`}function closeChannelNames(channel,known){const out=[];for(const name2 of known){if(name2!==channel&&editDistanceAtMostOne(channel,name2))out.push(name2)}out.sort((a3,b3)=>a3.localeCompare(b3));return out.slice(0,3)}function editDistanceAtMostOne(a3,b3){if(a3===b3)return true;const da=a3.length-b3.length;if(da>1||da<-1)return false;let i2=0;let j2=0;let skipped=false;while(i2<a3.length&&j2<b3.length){if(a3[i2]===b3[j2]){i2++;j2++;continue}if(skipped)return false;skipped=true;if(a3.length>b3.length)i2++;else if(b3.length>a3.length)j2++;else{i2++;j2++}}return true}var SUN_PATH_MAX_BYTES=process.platform==="darwin"?104:108;function eventChannelForSession(ep){if(ep.actorIsEphemeral)throw new Error("events are not available for a session with a self-minted identity: this endpoint has no declared id and no credentials, so its actor is a fresh random token per process and its event channel could never match a grant. Launch it with an identity (an authed mesh, or an explicit id) to publish events.");return eventChannel(ep.principal)}var TOOL_RESULT_EVENT="cotal.toolResult";var COTAL_CUSTOM_EVENTS=[TOOL_RESULT_EVENT];var AGUI_PROTOCOL="ag-ui/0.0.57";var AguiVocabularyError=class extends Error{constructor(message){super(message);this.name="AguiVocabularyError"}};var AguiBrackets=class _AguiBrackets{run;text=new Set;reasoning=new Set;tools=new Set;snapshot(){return{run:this.run,text:[...this.text].sort(),reasoning:[...this.reasoning].sort(),tools:[...this.tools].sort()}}static restore(s3){const b3=new _AguiBrackets;b3.run=s3.run;for(const id2 of s3.text)b3.text.add(id2);for(const id2 of s3.reasoning)b3.reasoning.add(id2);for(const id2 of s3.tools)b3.tools.add(id2);return b3}clone(){return _AguiBrackets.restore(this.snapshot())}get open(){return this.run!==void 0}get runId(){return this.run}accept(event){const e3=event;const t2=e3.type;if(t2===AGUI_EVENT_TYPE.RUN_STARTED){if(this.run!==void 0)throw new AguiVocabularyError(`RUN_STARTED for "${String(e3.runId)}" while run "${this.run}" is still open`);this.run=String(e3.runId);return}if(this.run===void 0)throw new AguiVocabularyError(`${t2} emitted outside an open run`);if(t2===AGUI_EVENT_TYPE.RUN_FINISHED||t2===AGUI_EVENT_TYPE.RUN_ERROR){if(t2===AGUI_EVENT_TYPE.RUN_FINISHED&&String(e3.runId)!==this.run)throw new AguiVocabularyError(`RUN_FINISHED for "${String(e3.runId)}" but the open run is "${this.run}"`);const dangling=[...this.text,...this.reasoning,...this.tools];if(dangling.length>0)throw new AguiVocabularyError(`${t2} while still open: ${dangling.join(", ")}`);this.run=void 0;return}switch(t2){case AGUI_EVENT_TYPE.TEXT_MESSAGE_START:return this.openId(this.text,String(e3.messageId),t2);case AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT:return this.requireOpen(this.text,String(e3.messageId),t2);case AGUI_EVENT_TYPE.TEXT_MESSAGE_END:return this.closeId(this.text,String(e3.messageId),t2);case AGUI_EVENT_TYPE.REASONING_MESSAGE_START:return this.openId(this.reasoning,String(e3.messageId),t2);case AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT:return this.requireOpen(this.reasoning,String(e3.messageId),t2);case AGUI_EVENT_TYPE.REASONING_MESSAGE_END:return this.closeId(this.reasoning,String(e3.messageId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_START:return this.openId(this.tools,String(e3.toolCallId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_ARGS:return this.requireOpen(this.tools,String(e3.toolCallId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_END:return this.closeId(this.tools,String(e3.toolCallId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_RESULT:if(this.tools.has(String(e3.toolCallId)))throw new AguiVocabularyError(`TOOL_CALL_RESULT for "${String(e3.toolCallId)}" while its call is still open`);return;case AGUI_EVENT_TYPE.CUSTOM:if(!COTAL_CUSTOM_EVENTS.includes(String(e3.name)))throw new AguiVocabularyError(`CUSTOM "${String(e3.name)}" is not declared in COTAL_CUSTOM_EVENTS, the reviewed table of cotal.* names`);if(e3.name===TOOL_RESULT_EVENT){const defect=toolResultMarkerDefect(e3);if(defect!==void 0)throw new AguiVocabularyError(`${TOOL_RESULT_EVENT} ${defect}`);const id2=e3.value.toolCallId;if(this.tools.has(id2))throw new AguiVocabularyError(`${TOOL_RESULT_EVENT} for "${id2}" while its call is still open`)}return;default:throw new AguiVocabularyError(`${t2} is not in the mapped subset this plane emits`)}}assertClosed(){if(this.run!==void 0)throw new AguiVocabularyError(`run "${this.run}" was never closed`)}openId(set3,id2,t2){if(set3.has(id2))throw new AguiVocabularyError(`${t2} re-opened "${id2}" while already open`);set3.add(id2)}requireOpen(set3,id2,t2){if(!set3.has(id2))throw new AguiVocabularyError(`${t2} for "${id2}" which is not open`)}closeId(set3,id2,t2){if(!set3.delete(id2))throw new AguiVocabularyError(`${t2} for "${id2}" which is not open`)}};function aguiFrame(opts){for(const[field,value]of[["threadId",opts.threadId],["runId",opts.runId],["epoch",opts.epoch]])if(typeof value!=="string"||value.length===0)throw new AguiVocabularyError(`frame ${field} must be a non-empty string`);if(!Number.isSafeInteger(opts.seq)||opts.seq<0)throw new AguiVocabularyError(`frame seq must be a non-negative safe integer, got ${JSON.stringify(opts.seq)}`);if(!Array.isArray(opts.events)||opts.events.length===0)throw new AguiVocabularyError("a frame must carry at least one event");return{kind:AGUI_FRAME_KIND,protocol:AGUI_PROTOCOL,threadId:opts.threadId,runId:opts.runId,epoch:opts.epoch,seq:opts.seq,events:opts.events}}function parseAguiFrame(part){if(!isAguiFramePart(part))throw new AguiVocabularyError(`not an AG-UI frame: expected kind ${JSON.stringify(AGUI_FRAME_KIND)}, got ${JSON.stringify(part?.kind??null)}. Route with isAguiFramePart before calling this.`);const f2=part;if(f2.protocol!==AGUI_PROTOCOL)throw new AguiVocabularyError(`AG-UI protocol mismatch: this consumer understands ${JSON.stringify(AGUI_PROTOCOL)}, the frame declares ${JSON.stringify(f2.protocol??null)}. Refusing rather than rendering the fields that happen to still parse.`);for(const field of["threadId","runId","epoch"])if(typeof f2[field]!=="string"||f2[field].length===0)throw new AguiVocabularyError(`frame ${field} must be a non-empty string`);if(!Number.isSafeInteger(f2.seq)||f2.seq<0)throw new AguiVocabularyError(`frame seq must be a non-negative safe integer, got ${JSON.stringify(f2.seq??null)}`);if(!Array.isArray(f2.events)||f2.events.length===0)throw new AguiVocabularyError("a frame must carry at least one event");const known=new Set(Object.values(AGUI_EVENT_TYPE));f2.events.forEach((e3,i2)=>{if(typeof e3!=="object"||e3===null)throw new AguiVocabularyError(`frame events[${i2}] is not an object`);const t2=e3.type;if(typeof t2!=="string"||!known.has(t2))throw new AguiVocabularyError(`frame events[${i2}] carries an unrecognised type ${JSON.stringify(t2??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(o3){return{type:AGUI_EVENT_TYPE.RUN_STARTED,threadId:o3.threadId,runId:o3.runId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.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[i2,entry]of list.entries()){const e3=entry;if(typeof e3!=="object"||e3===null)throw new AguiVocabularyError(`outcome.interrupts[${i2}] is not an object`);if(typeof e3.id!=="string")throw new AguiVocabularyError(`outcome.interrupts[${i2}].id must be a string`);if(typeof e3.reason!=="string")throw new AguiVocabularyError(`outcome.interrupts[${i2}].reason must be a string`)}}function runFinished(o3){if(o3.outcome?.type==="interrupt")assertInterrupts(o3.outcome.interrupts);return{type:AGUI_EVENT_TYPE.RUN_FINISHED,threadId:o3.threadId,runId:o3.runId,timestamp:o3.timestamp,...o3.outcome?{outcome:o3.outcome}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function runError(o3){return{type:AGUI_EVENT_TYPE.RUN_ERROR,message:o3.message,timestamp:o3.timestamp,...o3.code?{code:o3.code}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function textMessageStart(o3){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_START,messageId:o3.messageId,timestamp:o3.timestamp,...o3.role?{role:o3.role}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function textMessageContent(o3){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,messageId:o3.messageId,delta:o3.delta,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function textMessageEnd(o3){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_END,messageId:o3.messageId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallStart(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_START,toolCallId:o3.toolCallId,toolCallName:o3.toolCallName,timestamp:o3.timestamp,...o3.parentMessageId?{parentMessageId:o3.parentMessageId}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallArgs(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_ARGS,toolCallId:o3.toolCallId,delta:o3.delta,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallEnd(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_END,toolCallId:o3.toolCallId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallResult(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_RESULT,messageId:o3.messageId,toolCallId:o3.toolCallId,content:o3.content,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function toolResultMarker(o3){return{type:AGUI_EVENT_TYPE.CUSTOM,name:TOOL_RESULT_EVENT,value:{toolCallId:o3.toolCallId,isError:o3.isError},...o3.timestamp!==void 0?{timestamp:o3.timestamp}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function reasoningMessageStart(o3){return{type:AGUI_EVENT_TYPE.REASONING_MESSAGE_START,messageId:o3.messageId,role:"reasoning",timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function reasoningMessageContent(o3){return{type:AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT,messageId:o3.messageId,delta:o3.delta,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function reasoningMessageEnd(o3){return{type:AGUI_EVENT_TYPE.REASONING_MESSAGE_END,messageId:o3.messageId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}var TRUNCATABLE_FIELDS=[{type:AGUI_EVENT_TYPE.TOOL_CALL_ARGS,field:"delta"},{type:AGUI_EVENT_TYPE.TOOL_CALL_RESULT,field:"content"},{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,field:"delta"}];var EGRESS_FORBIDDEN_TYPES=new Set([AGUI_EVENT_TYPE.TOOL_CALL_ARGS,AGUI_EVENT_TYPE.TOOL_CALL_RESULT]);var KNOWN_FRAME_KEYS=new Set(["kind","protocol","threadId","runId","epoch","seq","events"]);var KNOWN_EVENT_KEYS_BY_TYPE=new Map([[AGUI_EVENT_TYPE.RUN_STARTED,new Set(["type","timestamp","rawEvent","threadId","runId","parentRunId","input","cotal"])],[AGUI_EVENT_TYPE.RUN_FINISHED,new Set(["type","timestamp","rawEvent","threadId","runId","result","outcome","cotal"])],[AGUI_EVENT_TYPE.RUN_ERROR,new Set(["type","timestamp","rawEvent","message","code","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","name","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_START,new Set(["type","timestamp","rawEvent","toolCallId","toolCallName","parentMessageId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_ARGS,new Set(["type","timestamp","rawEvent","toolCallId","delta","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_END,new Set(["type","timestamp","rawEvent","toolCallId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_RESULT,new Set(["type","timestamp","rawEvent","messageId","toolCallId","content","role","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE.CUSTOM,new Set(["type","timestamp","rawEvent","name","value","cotal"])]]);var TOOL_RESULT_VALUE_KEYS=new Set(["toolCallId","isError"]);function toolResultValueDefect(value){if(typeof value!=="object"||value===null||Array.isArray(value))return"value";const keys=Object.keys(value);for(const key of keys){if(!TOOL_RESULT_VALUE_KEYS.has(key))return`value.${key}`}if(keys.length!==TOOL_RESULT_VALUE_KEYS.size)return"value";const v3=value;if(typeof v3.toolCallId!=="string")return"value";if(typeof v3.isError!=="boolean")return"value";return void 0}function toolResultMarkerDefect(e3){if("rawEvent"in e3)return"carries rawEvent, which the content-free marker never does";const defect=toolResultValueDefect(e3.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 v3=value;return{toolCallId:v3.toolCallId,isError:v3.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 i2=0;i2<events.length;i2++){const e3=events[i2];if(typeof e3!=="object"||e3===null)continue;const t2=e3.type;const allowed=KNOWN_EVENT_KEYS_BY_TYPE.get(t2);if(!allowed)return`events[${i2}]`;for(const key of Object.keys(e3)){if(!allowed.has(key))return`events[${i2}].${key}`}if(t2===AGUI_EVENT_TYPE.CUSTOM&&e3.name===TOOL_RESULT_EVENT){if("rawEvent"in e3)return`events[${i2}].rawEvent`;const defect=toolResultValueDefect(e3.value);if(defect!==void 0)return`events[${i2}].${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(o3){return{type:AGUI_EVENT_TYPE.RUN_ERROR,message:RUN_ERROR_EGRESS_MESSAGE,...o3.timestamp!==void 0?{timestamp:o3.timestamp}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function isEgressRunError(e3){return e3.message===RUN_ERROR_EGRESS_MESSAGE&&!("code"in e3)&&!("rawEvent"in e3)}function isToolResultMarker(e3){return e3.type===AGUI_EVENT_TYPE.CUSTOM&&e3.name===TOOL_RESULT_EVENT}function egressToolResultMarker(e3){if(!("rawEvent"in e3))return e3;const{rawEvent:_dropped,...rest}=e3;return rest}function applyAguiEgressPolicy(events){return events.filter(e3=>!isForbiddenEgressEventType(e3.type)).map(e3=>e3.type===AGUI_EVENT_TYPE.RUN_ERROR?egressRunError(e3):isToolResultMarker(e3)?egressToolResultMarker(e3):e3)}function frozenBodyEgressVerdict(body){let unreadable=false;try{for(const part of body){try{if(!isAguiFramePart(part))continue;const frame=parseAguiFrame(part);for(const e3 of frame.events){if(isForbiddenEgressEventType(e3.type))return"forbidden-kind"}for(const e3 of frame.events){if(e3.type===AGUI_EVENT_TYPE.RUN_ERROR&&!isEgressRunError(e3))return"run-error-content"}const extra=extraPropertyPath(part);if(extra!==void 0)return"extra-property"}catch{unreadable=true}}}catch{unreadable=true}return unreadable?"unreadable":"clean"}import{createHash as createHash11,randomUUID as randomUUID13}from"node:crypto";import{dirname as dirname9,join as join9}from"node:path";import{execFileSync as execFileSync3}from"node:child_process";init_external();init_external();var ok=text3=>({text:text3});var err=text3=>({text:text3,isError:true});function receipt(status2,value){if(status2!==202||typeof value!=="object"||value===null||Array.isArray(value))return void 0;const body=value;if(body.ok!==true||typeof body.id!=="string"||body.id.length===0||body.id.length>200)return void 0;if(/[\u0000-\u001f\u007f]/.test(body.id)||body.id.trim()!==body.id)return void 0;if(typeof body.published!=="boolean")return void 0;return{id:body.id,published:body.published}}async function submitFeedback(input,options={}){const url2=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const headers4={"content-type":"application/json"};const body={...input};if(options.key){headers4.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:headers4,body:JSON.stringify(body),redirect:"error"});raw=await res.text()}catch(e3){return err(`Couldn't reach the feedback intake at ${url2}: ${e3.message} The submission was not retried.`)}let reply=void 0;if(raw)try{reply=JSON.parse(raw)}catch{reply=void 0}const stored=receipt(res.status,reply);if(stored){const note=stored.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent (id ${stored.id})${note}. Thanks!`)}const errorText=typeof reply==="object"&&reply!==null&&typeof reply.error==="string"?reply.error:void 0;if(!res.ok)return err(`Feedback rejected (${res.status}${errorText?`: ${errorText}`:""}).`);return err(`Feedback acceptance is unconfirmed (${res.status}). The request may have reached the intake and was not retried.`)}import{createHash as createHash10}from"node:crypto";import{readFileSync as readFileSync5}from"node:fs";import{join as join8}from"node:path";import{gunzipSync}from"node:zlib";var DOCS_VERSION="0.171.2";function loadDocsMetadata(){return{"version":"0.171.2","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here (informative)","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here (informative)","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept (informative)","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference: the `cotal_*` tool surface every connected agent gets.","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference (informative task card)","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept (informative)","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference (the persisted form of an agent's identity + persona, read by every launcher)","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference (informative)","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide: describes the TypeScript reference implementation, not the wire contract.","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide (informative)","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI), not the wire contract.","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI and connectors), not the wire contract.","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide (informative)","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide (informative)","category":"Guide","summary":"Launch Codex on a Cotal mesh, connect your own Codex conversations, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide (informative)","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-mcp","title":"MCP-only hosts","kind":"Guide","category":"Guide","summary":"Connect an application that supports stdio MCP but has no native Cotal connector."},{"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, resume records, the agent endpoint, agent commands, and the prompt desk."},{"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":"Participant connections can read retained tool payloads for their own owner and for foreign event channels granted by full name."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Start here (informative)","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide (informative)","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept (informative)","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=readFileSync5(join8(import.meta.dirname,"docs-bundle.bin"));if(packed.length!==1338507||createHash10("sha256").update(packed).digest("hex")!=="8b31508a1ab9c88cb75d116b79ac79f925aa4bfedceb6c1e99c2f40ba4d773c7")throw new Error("docs data file docs-bundle.bin beside this module is not the one built with it for Cotal 0.171.2: it changed after this process loaded, usually because Cotal was updated under a running session. Restart the session to read the docs of the installed version");return corpusPacked=packed}var sourceBounds=[[0,2205],[2205,4e3],[4e3,9543],[9543,32236],[32236,36793],[36793,41174],[41174,44902],[44902,52031],[52031,56135],[56135,65932],[65932,70084],[70084,77020],[77020,79338],[79338,83349],[83349,118310],[118310,135221],[135221,151457],[151457,170479],[170479,189102],[189102,204649],[204649,220765],[220765,249952],[249952,255682],[255682,266968],[266968,288575],[288575,293477],[293477,335256],[335256,345893],[345893,380181],[380181,398242],[398242,424385],[424385,456613],[456613,471565],[471565,473519],[473519,482876],[482876,500737],[500737,509147],[509147,513451],[513451,516974],[516974,520417],[520417,522122],[522122,524466],[524466,527314],[527314,535748],[535748,537722],[537722,541460],[541460,554222],[554222,563578],[563578,567328],[567328,574831],[574831,579963],[579963,582967],[582967,593674],[593674,596651],[596651,605371],[605371,608361],[608361,615519],[615519,630228],[630228,643311],[643311,650961],[650961,658818],[658818,662167],[662167,665116],[665116,672673],[672673,676389],[676389,678599],[678599,682061],[682061,685478],[685478,686592],[686592,688341],[688341,692004],[692004,697153],[697153,703838],[703838,714348],[714348,727664],[727664,731263],[731263,745102],[745102,750489],[750489,754960],[754960,757477],[757477,762519],[762519,776765],[776765,783627],[783627,791596],[791596,792413],[792413,797424],[797424,803652],[803652,807334],[807334,811575],[811575,816746],[816746,822327],[822327,825749],[825749,829502],[829502,834667],[834667,838310],[838310,852605],[852605,855496],[855496,858179],[858179,860846],[860846,863516],[863516,867536],[867536,872600],[872600,886556],[886556,895415],[895415,968331],[968331,971622],[971622,972970],[972970,980713],[980713,989811],[989811,1000968],[1000968,1009779],[1009779,1014962],[1014962,1293568],[1293568,1333071],[1333071,1338507]];var sourceLengths=[4844,4048,13962,90847,12661,10741,38583,18738,9941,85121,37758,17584,5187,9872,95812,45725,45759,54323,51871,45083,44139,84086,14399,30234,62436,11149,124617,29580,104168,51325,78815,99650,41285,8265,23413,48356,22989,10590,8346,8195,3587,5381,6543,22188,4726,8905,34074,23523,9352,48175,12971,7373,28193,7140,22854,6860,18419,39073,34913,19825,19375,8355,7031,19589,8312,5100,8160,9930,2248,5412,9845,12608,16240,26828,34218,9208,37640,12378,11095,8235,13306,98213,17095,19868,1638,11606,16289,8719,10286,12927,14071,7511,9451,12695,8527,38435,6724,6405,6095,6534,9711,12679,40667,23081,214696,7461,2878,19155,23391,29007,21160,12616,811071,111760,22568];var decodedBodies=[];function loadDocsSourceLengths(){corpusData();return sourceLengths.slice()}function decodeDocsSource(source){const bounds=sourceBounds[source];if(!Number.isInteger(source)||!bounds)throw new Error("docs source index is out of bounds");const body=JSON.parse(gunzipSync(corpusData().subarray(bounds[0],bounds[1])).toString("utf8"));if(typeof body!=="string"||body.length!==sourceLengths[source])throw new Error("docs source body does not match its generated bounds");return body}function loadDocsSource(source){return decodedBodies[source]??=decodeDocsSource(source)}function loadDocsIndex(){const packed=readFileSync5(join8(import.meta.dirname,"docs-index.bin"));if(packed.length!==673120||createHash10("sha256").update(packed).digest("hex")!=="976f0244a5463566d7f255ca14fb57bd8bebb9f1f4ba0ba1d7555c7efd91cdd6")throw new Error("docs data file docs-index.bin beside this module is not the one built with it for Cotal 0.171.2: it changed after this process loaded, usually because Cotal was updated under a running session. Restart the session to read the docs of the installed version");return gunzipSync(packed)}var TOKEN2=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s3){const raw=s3.toLowerCase().match(TOKEN2);if(!raw)return[];const out=[];for(const r2 of raw){if(r2.length>=2)out.push(r2);const t2=r2.replace(EDGE,"");if(t2.length>=2&&t2!==r2)out.push(t2);if(t2.includes(".")){for(const seg of t2.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,i2)=>length2!==bodyLengths[i2]))throw new Error("docs index does not match the docs bundle it is searching");const n2=header.sections;const length=4*n2+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 i2=0;i2<length;i2++)columns[i2]=bytes.readUInt32LE(4+headerLength+4*i2);const offsets=4*n2;const sectionColumn=offsets+header.terms.length+1;let total=0;for(let i2=0;i2<n2;i2++)total+=columns[3*n2+i2];return{sections:n2,terms:header.terms,headings:header.headings,source:columns.subarray(0,n2),start:columns.subarray(n2,2*n2),end:columns.subarray(2*n2,3*n2),length:columns.subarray(3*n2,4*n2),offsets:columns.subarray(offsets,sectionColumn),postSection:columns.subarray(sectionColumn,sectionColumn+header.postings),postWeight:columns.subarray(sectionColumn+header.postings),avgdl:total/Math.max(1,n2)}}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((p2,source2)=>(pages.get(source2)??p2).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 b3=metadata();const rows=b3.pages.map(p2=>{const kind=p2.kind?`: ${p2.kind}`:"";return`- \`${p2.slug}\`${kind}
|
|
131
|
+
`)}};function presenceReadCondition(failure){return`the presence read failed (${failure.message})`}function missingInboxIssue(e3){return`this session's direct-message inbox is missing on the broker, and on an authenticated mesh only a new launch creates one, so reconnecting cannot restore it. Restart this session, or respawn it if a manager launched it. Missing durable "${e3.durable}" on stream "${e3.stream}". Retries continue in case a broker restore brings it back.`}function closeChannelNames(channel,known){const out=[];for(const name2 of known){if(name2!==channel&&editDistanceAtMostOne(channel,name2))out.push(name2)}out.sort((a3,b3)=>a3.localeCompare(b3));return out.slice(0,3)}function editDistanceAtMostOne(a3,b3){if(a3===b3)return true;const da=a3.length-b3.length;if(da>1||da<-1)return false;let i2=0;let j2=0;let skipped=false;while(i2<a3.length&&j2<b3.length){if(a3[i2]===b3[j2]){i2++;j2++;continue}if(skipped)return false;skipped=true;if(a3.length>b3.length)i2++;else if(b3.length>a3.length)j2++;else{i2++;j2++}}return true}var SUN_PATH_MAX_BYTES=process.platform==="darwin"?104:108;function eventChannelForSession(ep){if(ep.actorIsEphemeral)throw new Error("events are not available for a session with a self-minted identity: this endpoint has no declared id and no credentials, so its actor is a fresh random token per process and its event channel could never match a grant. Launch it with an identity (an authed mesh, or an explicit id) to publish events.");return eventChannel(ep.principal)}var TOOL_RESULT_EVENT="cotal.toolResult";var COTAL_CUSTOM_EVENTS=[TOOL_RESULT_EVENT];var AGUI_PROTOCOL="ag-ui/0.0.57";var AguiVocabularyError=class extends Error{constructor(message){super(message);this.name="AguiVocabularyError"}};var AguiBrackets=class _AguiBrackets{run;text=new Set;reasoning=new Set;tools=new Set;snapshot(){return{run:this.run,text:[...this.text].sort(),reasoning:[...this.reasoning].sort(),tools:[...this.tools].sort()}}static restore(s3){const b3=new _AguiBrackets;b3.run=s3.run;for(const id2 of s3.text)b3.text.add(id2);for(const id2 of s3.reasoning)b3.reasoning.add(id2);for(const id2 of s3.tools)b3.tools.add(id2);return b3}clone(){return _AguiBrackets.restore(this.snapshot())}get open(){return this.run!==void 0}get runId(){return this.run}accept(event){const e3=event;const t2=e3.type;if(t2===AGUI_EVENT_TYPE.RUN_STARTED){if(this.run!==void 0)throw new AguiVocabularyError(`RUN_STARTED for "${String(e3.runId)}" while run "${this.run}" is still open`);this.run=String(e3.runId);return}if(this.run===void 0)throw new AguiVocabularyError(`${t2} emitted outside an open run`);if(t2===AGUI_EVENT_TYPE.RUN_FINISHED||t2===AGUI_EVENT_TYPE.RUN_ERROR){if(t2===AGUI_EVENT_TYPE.RUN_FINISHED&&String(e3.runId)!==this.run)throw new AguiVocabularyError(`RUN_FINISHED for "${String(e3.runId)}" but the open run is "${this.run}"`);const dangling=[...this.text,...this.reasoning,...this.tools];if(dangling.length>0)throw new AguiVocabularyError(`${t2} while still open: ${dangling.join(", ")}`);this.run=void 0;return}switch(t2){case AGUI_EVENT_TYPE.TEXT_MESSAGE_START:return this.openId(this.text,String(e3.messageId),t2);case AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT:return this.requireOpen(this.text,String(e3.messageId),t2);case AGUI_EVENT_TYPE.TEXT_MESSAGE_END:return this.closeId(this.text,String(e3.messageId),t2);case AGUI_EVENT_TYPE.REASONING_MESSAGE_START:return this.openId(this.reasoning,String(e3.messageId),t2);case AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT:return this.requireOpen(this.reasoning,String(e3.messageId),t2);case AGUI_EVENT_TYPE.REASONING_MESSAGE_END:return this.closeId(this.reasoning,String(e3.messageId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_START:return this.openId(this.tools,String(e3.toolCallId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_ARGS:return this.requireOpen(this.tools,String(e3.toolCallId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_END:return this.closeId(this.tools,String(e3.toolCallId),t2);case AGUI_EVENT_TYPE.TOOL_CALL_RESULT:if(this.tools.has(String(e3.toolCallId)))throw new AguiVocabularyError(`TOOL_CALL_RESULT for "${String(e3.toolCallId)}" while its call is still open`);return;case AGUI_EVENT_TYPE.CUSTOM:if(!COTAL_CUSTOM_EVENTS.includes(String(e3.name)))throw new AguiVocabularyError(`CUSTOM "${String(e3.name)}" is not declared in COTAL_CUSTOM_EVENTS, the reviewed table of cotal.* names`);if(e3.name===TOOL_RESULT_EVENT){const defect=toolResultMarkerDefect(e3);if(defect!==void 0)throw new AguiVocabularyError(`${TOOL_RESULT_EVENT} ${defect}`);const id2=e3.value.toolCallId;if(this.tools.has(id2))throw new AguiVocabularyError(`${TOOL_RESULT_EVENT} for "${id2}" while its call is still open`)}return;default:throw new AguiVocabularyError(`${t2} is not in the mapped subset this plane emits`)}}assertClosed(){if(this.run!==void 0)throw new AguiVocabularyError(`run "${this.run}" was never closed`)}openId(set3,id2,t2){if(set3.has(id2))throw new AguiVocabularyError(`${t2} re-opened "${id2}" while already open`);set3.add(id2)}requireOpen(set3,id2,t2){if(!set3.has(id2))throw new AguiVocabularyError(`${t2} for "${id2}" which is not open`)}closeId(set3,id2,t2){if(!set3.delete(id2))throw new AguiVocabularyError(`${t2} for "${id2}" which is not open`)}};function aguiFrame(opts){for(const[field,value]of[["threadId",opts.threadId],["runId",opts.runId],["epoch",opts.epoch]])if(typeof value!=="string"||value.length===0)throw new AguiVocabularyError(`frame ${field} must be a non-empty string`);if(!Number.isSafeInteger(opts.seq)||opts.seq<0)throw new AguiVocabularyError(`frame seq must be a non-negative safe integer, got ${JSON.stringify(opts.seq)}`);if(!Array.isArray(opts.events)||opts.events.length===0)throw new AguiVocabularyError("a frame must carry at least one event");return{kind:AGUI_FRAME_KIND,protocol:AGUI_PROTOCOL,threadId:opts.threadId,runId:opts.runId,epoch:opts.epoch,seq:opts.seq,events:opts.events}}function parseAguiFrame(part){if(!isAguiFramePart(part))throw new AguiVocabularyError(`not an AG-UI frame: expected kind ${JSON.stringify(AGUI_FRAME_KIND)}, got ${JSON.stringify(part?.kind??null)}. Route with isAguiFramePart before calling this.`);const f2=part;if(f2.protocol!==AGUI_PROTOCOL)throw new AguiVocabularyError(`AG-UI protocol mismatch: this consumer understands ${JSON.stringify(AGUI_PROTOCOL)}, the frame declares ${JSON.stringify(f2.protocol??null)}. Refusing rather than rendering the fields that happen to still parse.`);for(const field of["threadId","runId","epoch"])if(typeof f2[field]!=="string"||f2[field].length===0)throw new AguiVocabularyError(`frame ${field} must be a non-empty string`);if(!Number.isSafeInteger(f2.seq)||f2.seq<0)throw new AguiVocabularyError(`frame seq must be a non-negative safe integer, got ${JSON.stringify(f2.seq??null)}`);if(!Array.isArray(f2.events)||f2.events.length===0)throw new AguiVocabularyError("a frame must carry at least one event");const known=new Set(Object.values(AGUI_EVENT_TYPE));f2.events.forEach((e3,i2)=>{if(typeof e3!=="object"||e3===null)throw new AguiVocabularyError(`frame events[${i2}] is not an object`);const t2=e3.type;if(typeof t2!=="string"||!known.has(t2))throw new AguiVocabularyError(`frame events[${i2}] carries an unrecognised type ${JSON.stringify(t2??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(o3){return{type:AGUI_EVENT_TYPE.RUN_STARTED,threadId:o3.threadId,runId:o3.runId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.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[i2,entry]of list.entries()){const e3=entry;if(typeof e3!=="object"||e3===null)throw new AguiVocabularyError(`outcome.interrupts[${i2}] is not an object`);if(typeof e3.id!=="string")throw new AguiVocabularyError(`outcome.interrupts[${i2}].id must be a string`);if(typeof e3.reason!=="string")throw new AguiVocabularyError(`outcome.interrupts[${i2}].reason must be a string`)}}function runFinished(o3){if(o3.outcome?.type==="interrupt")assertInterrupts(o3.outcome.interrupts);return{type:AGUI_EVENT_TYPE.RUN_FINISHED,threadId:o3.threadId,runId:o3.runId,timestamp:o3.timestamp,...o3.outcome?{outcome:o3.outcome}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function runError(o3){return{type:AGUI_EVENT_TYPE.RUN_ERROR,message:o3.message,timestamp:o3.timestamp,...o3.code?{code:o3.code}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function textMessageStart(o3){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_START,messageId:o3.messageId,timestamp:o3.timestamp,...o3.role?{role:o3.role}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function textMessageContent(o3){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,messageId:o3.messageId,delta:o3.delta,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function textMessageEnd(o3){return{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_END,messageId:o3.messageId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallStart(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_START,toolCallId:o3.toolCallId,toolCallName:o3.toolCallName,timestamp:o3.timestamp,...o3.parentMessageId?{parentMessageId:o3.parentMessageId}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallArgs(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_ARGS,toolCallId:o3.toolCallId,delta:o3.delta,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallEnd(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_END,toolCallId:o3.toolCallId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function toolCallResult(o3){return{type:AGUI_EVENT_TYPE.TOOL_CALL_RESULT,messageId:o3.messageId,toolCallId:o3.toolCallId,content:o3.content,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function toolResultMarker(o3){return{type:AGUI_EVENT_TYPE.CUSTOM,name:TOOL_RESULT_EVENT,value:{toolCallId:o3.toolCallId,isError:o3.isError},...o3.timestamp!==void 0?{timestamp:o3.timestamp}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function reasoningMessageStart(o3){return{type:AGUI_EVENT_TYPE.REASONING_MESSAGE_START,messageId:o3.messageId,role:"reasoning",timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function reasoningMessageContent(o3){return{type:AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT,messageId:o3.messageId,delta:o3.delta,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}function reasoningMessageEnd(o3){return{type:AGUI_EVENT_TYPE.REASONING_MESSAGE_END,messageId:o3.messageId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}}var TRUNCATABLE_FIELDS=[{type:AGUI_EVENT_TYPE.TOOL_CALL_ARGS,field:"delta"},{type:AGUI_EVENT_TYPE.TOOL_CALL_RESULT,field:"content"},{type:AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,field:"delta"}];var EGRESS_FORBIDDEN_TYPES=new Set([AGUI_EVENT_TYPE.TOOL_CALL_ARGS,AGUI_EVENT_TYPE.TOOL_CALL_RESULT]);var KNOWN_FRAME_KEYS=new Set(["kind","protocol","threadId","runId","epoch","seq","events"]);var KNOWN_EVENT_KEYS_BY_TYPE=new Map([[AGUI_EVENT_TYPE.RUN_STARTED,new Set(["type","timestamp","rawEvent","threadId","runId","parentRunId","input","cotal"])],[AGUI_EVENT_TYPE.RUN_FINISHED,new Set(["type","timestamp","rawEvent","threadId","runId","result","outcome","cotal"])],[AGUI_EVENT_TYPE.RUN_ERROR,new Set(["type","timestamp","rawEvent","message","code","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","name","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE.TEXT_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_START,new Set(["type","timestamp","rawEvent","toolCallId","toolCallName","parentMessageId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_ARGS,new Set(["type","timestamp","rawEvent","toolCallId","delta","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_END,new Set(["type","timestamp","rawEvent","toolCallId","cotal"])],[AGUI_EVENT_TYPE.TOOL_CALL_RESULT,new Set(["type","timestamp","rawEvent","messageId","toolCallId","content","role","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE.REASONING_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE.CUSTOM,new Set(["type","timestamp","rawEvent","name","value","cotal"])]]);var TOOL_RESULT_VALUE_KEYS=new Set(["toolCallId","isError"]);function toolResultValueDefect(value){if(typeof value!=="object"||value===null||Array.isArray(value))return"value";const keys=Object.keys(value);for(const key of keys){if(!TOOL_RESULT_VALUE_KEYS.has(key))return`value.${key}`}if(keys.length!==TOOL_RESULT_VALUE_KEYS.size)return"value";const v3=value;if(typeof v3.toolCallId!=="string")return"value";if(typeof v3.isError!=="boolean")return"value";return void 0}function toolResultMarkerDefect(e3){if("rawEvent"in e3)return"carries rawEvent, which the content-free marker never does";const defect=toolResultValueDefect(e3.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 v3=value;return{toolCallId:v3.toolCallId,isError:v3.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 i2=0;i2<events.length;i2++){const e3=events[i2];if(typeof e3!=="object"||e3===null)continue;const t2=e3.type;const allowed=KNOWN_EVENT_KEYS_BY_TYPE.get(t2);if(!allowed)return`events[${i2}]`;for(const key of Object.keys(e3)){if(!allowed.has(key))return`events[${i2}].${key}`}if(t2===AGUI_EVENT_TYPE.CUSTOM&&e3.name===TOOL_RESULT_EVENT){if("rawEvent"in e3)return`events[${i2}].rawEvent`;const defect=toolResultValueDefect(e3.value);if(defect!==void 0)return`events[${i2}].${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(o3){return{type:AGUI_EVENT_TYPE.RUN_ERROR,message:RUN_ERROR_EGRESS_MESSAGE,...o3.timestamp!==void 0?{timestamp:o3.timestamp}:{},...o3.cotal?{cotal:o3.cotal}:{}}}function isEgressRunError(e3){return e3.message===RUN_ERROR_EGRESS_MESSAGE&&!("code"in e3)&&!("rawEvent"in e3)}function isToolResultMarker(e3){return e3.type===AGUI_EVENT_TYPE.CUSTOM&&e3.name===TOOL_RESULT_EVENT}function egressToolResultMarker(e3){if(!("rawEvent"in e3))return e3;const{rawEvent:_dropped,...rest}=e3;return rest}function applyAguiEgressPolicy(events){return events.filter(e3=>!isForbiddenEgressEventType(e3.type)).map(e3=>e3.type===AGUI_EVENT_TYPE.RUN_ERROR?egressRunError(e3):isToolResultMarker(e3)?egressToolResultMarker(e3):e3)}function frozenBodyEgressVerdict(body){let unreadable=false;try{for(const part of body){try{if(!isAguiFramePart(part))continue;const frame=parseAguiFrame(part);for(const e3 of frame.events){if(isForbiddenEgressEventType(e3.type))return"forbidden-kind"}for(const e3 of frame.events){if(e3.type===AGUI_EVENT_TYPE.RUN_ERROR&&!isEgressRunError(e3))return"run-error-content"}const extra=extraPropertyPath(part);if(extra!==void 0)return"extra-property"}catch{unreadable=true}}}catch{unreadable=true}return unreadable?"unreadable":"clean"}import{createHash as createHash11,randomUUID as randomUUID14}from"node:crypto";import{dirname as dirname9,join as join9}from"node:path";import{execFileSync as execFileSync3}from"node:child_process";init_external();init_external();var ok=text3=>({text:text3});var err=text3=>({text:text3,isError:true});function receipt(status2,value){if(status2!==202||typeof value!=="object"||value===null||Array.isArray(value))return void 0;const body=value;if(body.ok!==true||typeof body.id!=="string"||body.id.length===0||body.id.length>200)return void 0;if(/[\u0000-\u001f\u007f]/.test(body.id)||body.id.trim()!==body.id)return void 0;if(typeof body.published!=="boolean")return void 0;return{id:body.id,published:body.published}}async function submitFeedback(input,options={}){const url2=options.url??(options.key?FEEDBACK_URL:PUBLIC_FEEDBACK_URL);const headers4={"content-type":"application/json"};const body={...input};if(options.key){headers4.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:headers4,body:JSON.stringify(body),redirect:"error"});raw=await res.text()}catch(e3){return err(`Couldn't reach the feedback intake at ${url2}: ${e3.message} The submission was not retried.`)}let reply=void 0;if(raw)try{reply=JSON.parse(raw)}catch{reply=void 0}const stored=receipt(res.status,reply);if(stored){const note=stored.published===false?" (stored, but the internal feedback channel publish failed)":"";return ok(`Feedback sent (id ${stored.id})${note}. Thanks!`)}const errorText=typeof reply==="object"&&reply!==null&&typeof reply.error==="string"?reply.error:void 0;if(!res.ok)return err(`Feedback rejected (${res.status}${errorText?`: ${errorText}`:""}).`);return err(`Feedback acceptance is unconfirmed (${res.status}). The request may have reached the intake and was not retried.`)}import{createHash as createHash10}from"node:crypto";import{readFileSync as readFileSync5}from"node:fs";import{join as join8}from"node:path";import{gunzipSync}from"node:zlib";var DOCS_VERSION="0.171.3";function loadDocsMetadata(){return{"version":"0.171.3","pages":[{"slug":"what-is-cotal","title":"What is Cotal","kind":"Start here (informative)","category":"Start here","summary":"How Cotal lets agents and other software find each other and exchange messages."},{"slug":"getting-started","title":"Quickstart","kind":"Start here (informative)","category":"Start here","summary":"Start a local Cotal mesh, launch an agent, and watch it join."},{"slug":"architecture","title":"Architecture","kind":"Concept (informative)","category":"Concept","summary":"How the wire contract, broker, connectors, and manager fit together."},{"slug":"mcp-tools","title":"MCP tool catalog","kind":"Reference: the `cotal_*` tool surface every connected agent gets.","category":"Reference","summary":"Arguments, availability, and effects of the Cotal tools exposed to agent sessions."},{"slug":"channels-and-permissions","title":"Channel permissions","kind":"Reference (informative task card)","category":"Reference","summary":"Channel read and post permissions, active subscriptions, delivery classes, membership, and replay."},{"slug":"identity-and-auth","title":"Identity","kind":"Concept (informative)","category":"Concept","summary":"How Cotal identifies a peer and limits what that peer can do."},{"slug":"agent-briefing","title":"Agent briefing","kind":"Reference","category":"Reference","summary":"The text every harness hands its agent when the session starts."},{"slug":"agent-files","title":"Agent files","kind":"Reference (the persisted form of an agent's identity + persona, read by every launcher)","category":"Reference","summary":"Fields, lookup rules, and ownership for an agent's persisted identity and persona."},{"slug":"api-reference","title":"Integration interfaces","kind":"Reference (informative)","category":"Reference","summary":"Choose Cotal's CLI, endpoint commands, libraries, agent tools, wire protocol, or HTTP interfaces."},{"slug":"auth-api","title":"Auth HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth HTTP interface."},{"slug":"auth-host-api","title":"Auth host HTTP API","kind":"Reference (informative)","category":"Reference","summary":"HTTP operations, parameters, responses, and authentication for the Auth host HTTP interface."},{"slug":"authoring-a-connector","title":"Authoring a connector","kind":"Guide: describes the TypeScript reference implementation, not the wire contract.","category":"Guide","summary":"Add support for an agent application through Cotal's connector interface and extension loader."},{"slug":"backup-a-mesh","title":"Back up a mesh","kind":"Guide","category":"Guide","summary":"Preserve a supported mesh, create an offline backup, and restore it within the original trust boundary."},{"slug":"build-a-client","title":"Build a Cotal client","kind":"Guide (informative)","category":"Guide","summary":"Implement a client in another language using the wire specification and a NATS client library."},{"slug":"claude-connector-reference","title":"Claude connector reference","kind":"Reference","category":"Reference","summary":"Binding, delivery, presence, event recording, and hosting contracts for the Claude Code connector."},{"slug":"cli-agent-control","title":"Agent terminal control","kind":"Reference","category":"Reference","summary":"Managed seat census, terminal attachment, input receipts, and native agent stops."},{"slug":"cli-agent-views","title":"Agent view reference","kind":"Reference","category":"Reference","summary":"Launch previews, named agent status, and recorded team deployment and removal evidence."},{"slug":"cli-agents","title":"Agent launch reference","kind":"Reference","category":"Reference","summary":"Launch modes, persona definitions, model catalogs, runtimes, and retained PTY seats."},{"slug":"cli-auth","title":"CLI authentication","kind":"Reference","category":"Reference","summary":"Static credentials, endpoint callers, account sessions, actor grants, and credential diagnosis."},{"slug":"cli-backups","title":"CLI backups","kind":"Reference","category":"Reference","summary":"Offline artifacts, integrity checks, restore recovery, and retained seat checkpoints."},{"slug":"cli-endpoints","title":"CLI endpoints","kind":"Reference","category":"Reference","summary":"Presence, local endpoint references, contract authoring, native invocation, and guarded removal."},{"slug":"cli-installation","title":"CLI installation","kind":"Reference","category":"Reference","summary":"Setup, software updates, installed extensions, preferences, completion, and feedback."},{"slug":"cli-integrations","title":"Linear integration","kind":"Reference","category":"Reference","summary":"Linear account configuration, native MCP operations, endpoint serving, and service lifecycle."},{"slug":"cli-maintenance","title":"Manager maintenance","kind":"Reference","category":"Reference","summary":"Guarded issuance-gate repair, retained seat maintenance, and native manager stop impact."},{"slug":"cli-messaging","title":"CLI messaging","kind":"Reference","category":"Reference","summary":"One-shot messages, live chat, channel policy, retained history, and pending direct messages."},{"slug":"cli-observation","title":"CLI observation","kind":"Reference","category":"Reference","summary":"Read-only activity feeds, the operator console, and the dashboard service."},{"slug":"cli-processes","title":"Process supervision","kind":"Reference","category":"Reference","summary":"Manager compatibility entry, owned direct processes, systemd user units, and service logs."},{"slug":"cli-runs","title":"CLI workflow runs","kind":"Reference","category":"Reference","summary":"Hosted and local workflow runs, recorded state, pause answers, offline checks, and seat turns."},{"slug":"cli-selection","title":"CLI spaces","kind":"Reference","category":"Reference","summary":"Space preparation, registration, target selection, discovery, and infrastructure diagnostics."},{"slug":"cli-services","title":"Local service reference","kind":"Reference","category":"Reference","summary":"Saved local services, native adapters, daemon compatibility entries, and service readiness limits."},{"slug":"cli-shutdown","title":"CLI shutdown","kind":"Reference","category":"Reference","summary":"Stack and service stops, process identity checks, preservation, cleanup, and reset."},{"slug":"cli-startup","title":"CLI startup","kind":"Reference","category":"Reference","summary":"Local stack startup, controller recovery, authentication modes, and manifest startup."},{"slug":"cli-usage","title":"CLI usage","kind":"Reference","category":"Reference","summary":"Command discovery, global flags, structured receipts, and exit codes."},{"slug":"cli","title":"CLI reference","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI), not the wire contract.","category":"Reference","summary":"Find command syntax, flags, receipts, and limits for the Cotal CLI."},{"slug":"codex-connector-reference","title":"Codex connector reference","kind":"Reference","category":"Reference","summary":"Codex launch options, private credentials, delivery behavior, presence, and structured event limits."},{"slug":"config","title":"Configuration","kind":"Reference: describes the TypeScript reference implementation (the `cotal` CLI and connectors), not the wire contract.","category":"Reference","summary":"Config files, preferences, environment variables, and local storage for the Cotal CLI and connectors."},{"slug":"connect-claude","title":"Connect Claude","kind":"Guide (informative)","category":"Guide","summary":"Connect Claude Code to a mesh, launch an agent, and choose how it receives messages and tools."},{"slug":"connect-codex","title":"Connect Codex","kind":"Guide (informative)","category":"Guide","summary":"Launch Codex on a Cotal mesh, connect your own Codex conversations, choose a model, and set its sandbox permissions."},{"slug":"connect-hermes","title":"Connect Hermes (alpha)","kind":"Guide (informative)","category":"Guide","summary":"Run a Hermes gateway on a Cotal mesh with a managed profile or your own Hermes profile."},{"slug":"connect-jcode","title":"Connect Jcode (beta)","kind":"Guide (informative)","category":"Guide","summary":"Launch a private Jcode session on a Cotal mesh, choose its model, and fork an existing transcript."},{"slug":"connect-mcp","title":"MCP-only hosts","kind":"Guide","category":"Guide","summary":"Connect an application that supports stdio MCP but has no native Cotal connector."},{"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, resume records, the agent endpoint, agent commands, and the prompt desk."},{"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":"Participant connections can read retained tool payloads for their own owner and for foreign event channels granted by full name."},{"slug":"using-cotal","title":"Choose a workflow","kind":"Start here (informative)","category":"Start here","summary":"Choose how to connect sessions, join spaces, launch teams, and run durable work."},{"slug":"watch-a-mesh","title":"Watch a mesh","kind":"Guide (informative)","category":"Guide","summary":"Choose a terminal display, line stream, or read-only browser dashboard for a running mesh."},{"slug":"web-dashboard","title":"Use the web dashboard","kind":"Guide","category":"Guide","summary":"Configure the read-only dashboard and inspect a space through a protected browser session."},{"slug":"workflow-effects","title":"Workflow effect contracts","kind":"Reference","category":"Reference","summary":"Seat ownership, budgets, supervision, decisions, presence, turns, cancellation, and placement."},{"slug":"workflow-operations","title":"Workflow operation contracts","kind":"Reference","category":"Reference","summary":"Hosted and local run commands, agent requests, admission, inventory, and keyed submission."},{"slug":"workflow-runtime","title":"Workflow runtime contracts","kind":"Reference","category":"Reference","summary":"Language replay, recovery, wire authority, durable effects, and engine limits."},{"slug":"workflows","title":"Workflow runs","kind":"Concept (informative)","category":"Concept","summary":"How a program coordinates agents, records progress, and continues after interruption."}],"spec":{"title":"Cotal Wire Specification"},"lang":{"title":"Cotal Lang: the workflow language"},"schema":{"title":"Cotal message schema (JSON Schema)"}}}var corpusPacked;function corpusData(){if(corpusPacked)return corpusPacked;const packed=readFileSync5(join8(import.meta.dirname,"docs-bundle.bin"));if(packed.length!==1341454||createHash10("sha256").update(packed).digest("hex")!=="1b60c67007ec5e34be7b1fc27a95e4c43e557238ea9fc79d19209b2cbc8e49fa")throw new Error("docs data file docs-bundle.bin beside this module is not the one built with it for Cotal 0.171.3: it changed after this process loaded, usually because Cotal was updated under a running session. Restart the session to read the docs of the installed version");return corpusPacked=packed}var sourceBounds=[[0,2205],[2205,4e3],[4e3,9543],[9543,32236],[32236,36793],[36793,41174],[41174,44902],[44902,52031],[52031,56135],[56135,65932],[65932,70084],[70084,77020],[77020,79338],[79338,83349],[83349,118432],[118432,135343],[135343,151579],[151579,170739],[170739,189362],[189362,205017],[205017,221133],[221133,250382],[250382,256112],[256112,267398],[267398,289046],[289046,293948],[293948,336017],[336017,346654],[346654,381530],[381530,399622],[399622,426001],[426001,458484],[458484,473564],[473564,475518],[475518,484875],[484875,502736],[502736,511146],[511146,515450],[515450,519005],[519005,522448],[522448,524153],[524153,526497],[526497,529345],[529345,537779],[537779,539753],[539753,543491],[543491,556253],[556253,565609],[565609,569359],[569359,576862],[576862,581994],[581994,584998],[584998,595705],[595705,598682],[598682,607402],[607402,610392],[610392,617550],[617550,632259],[632259,645342],[645342,652992],[652992,660849],[660849,664198],[664198,667147],[667147,674704],[674704,678420],[678420,680630],[680630,684092],[684092,687509],[687509,688623],[688623,690372],[690372,694035],[694035,699184],[699184,705869],[705869,716379],[716379,729695],[729695,733531],[733531,747370],[747370,752757],[752757,757274],[757274,759791],[759791,764833],[764833,779079],[779079,785941],[785941,793943],[793943,794760],[794760,799771],[799771,805999],[805999,809681],[809681,813922],[813922,819093],[819093,824674],[824674,828096],[828096,831849],[831849,837014],[837014,840657],[840657,854952],[854952,858120],[858120,860803],[860803,863470],[863470,866140],[866140,870189],[870189,875253],[875253,889472],[889472,898331],[898331,971278],[971278,974569],[974569,975917],[975917,983660],[983660,992758],[992758,1003915],[1003915,1012726],[1012726,1017909],[1017909,1296515],[1296515,1336018],[1336018,1341454]];var sourceLengths=[4844,4048,13962,90847,12661,10741,38583,18738,9941,85121,37758,17584,5187,9872,96160,45725,45759,54878,51871,45355,44139,84323,14399,30234,62532,11149,125491,29580,105950,51433,79663,100510,41680,8265,23413,48356,22989,10590,8445,8195,3587,5381,6543,22188,4726,8905,34074,23523,9352,48175,12971,7373,28193,7140,22854,6860,18419,39073,34913,19825,19375,8355,7031,19589,8312,5100,8160,9930,2248,5412,9845,12608,16240,26828,34218,9893,37640,12378,11220,8235,13306,98213,17095,19972,1638,11606,16289,8719,10286,12927,14071,7511,9451,12695,8527,38435,7533,6405,6095,6534,9781,12679,41466,23081,214782,7461,2878,19155,23391,29007,21160,12616,811071,111760,22568];var decodedBodies=[];function loadDocsSourceLengths(){corpusData();return sourceLengths.slice()}function decodeDocsSource(source){const bounds=sourceBounds[source];if(!Number.isInteger(source)||!bounds)throw new Error("docs source index is out of bounds");const body=JSON.parse(gunzipSync(corpusData().subarray(bounds[0],bounds[1])).toString("utf8"));if(typeof body!=="string"||body.length!==sourceLengths[source])throw new Error("docs source body does not match its generated bounds");return body}function loadDocsSource(source){return decodedBodies[source]??=decodeDocsSource(source)}function loadDocsIndex(){const packed=readFileSync5(join8(import.meta.dirname,"docs-index.bin"));if(packed.length!==673822||createHash10("sha256").update(packed).digest("hex")!=="41aa74ee5a6e1b6ddee60f95a70b331eacec5346f3aab5aedb33ab3ba7783e96")throw new Error("docs data file docs-index.bin beside this module is not the one built with it for Cotal 0.171.3: it changed after this process loaded, usually because Cotal was updated under a running session. Restart the session to read the docs of the installed version");return gunzipSync(packed)}var TOKEN2=/[a-z0-9_$.#>*-]+/gi;var EDGE=/^[.>*#-]+|[.>*#-]+$/g;function tokenize(s3){const raw=s3.toLowerCase().match(TOKEN2);if(!raw)return[];const out=[];for(const r2 of raw){if(r2.length>=2)out.push(r2);const t2=r2.replace(EDGE,"");if(t2.length>=2&&t2!==r2)out.push(t2);if(t2.includes(".")){for(const seg of t2.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,i2)=>length2!==bodyLengths[i2]))throw new Error("docs index does not match the docs bundle it is searching");const n2=header.sections;const length=4*n2+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 i2=0;i2<length;i2++)columns[i2]=bytes.readUInt32LE(4+headerLength+4*i2);const offsets=4*n2;const sectionColumn=offsets+header.terms.length+1;let total=0;for(let i2=0;i2<n2;i2++)total+=columns[3*n2+i2];return{sections:n2,terms:header.terms,headings:header.headings,source:columns.subarray(0,n2),start:columns.subarray(n2,2*n2),end:columns.subarray(2*n2,3*n2),length:columns.subarray(3*n2,4*n2),offsets:columns.subarray(offsets,sectionColumn),postSection:columns.subarray(sectionColumn,sectionColumn+header.postings),postWeight:columns.subarray(sectionColumn+header.postings),avgdl:total/Math.max(1,n2)}}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((p2,source2)=>(pages.get(source2)??p2).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 b3=metadata();const rows=b3.pages.map(p2=>{const kind=p2.kind?`: ${p2.kind}`:"";return`- \`${p2.slug}\`${kind}
|
|
132
132
|
${p2.summary}`});return[`# Cotal v${b3.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\`: ${b3.spec.title} (the wire contract; where a page disagrees, the spec wins)`,`- \`lang\`: ${b3.lang.title} (the workflow language a durable run executes; spec \xA714)`,`- \`schema\`: ${b3.schema.title} (authoritative for message shapes)`,"","## Pages",...rows].join("\n")}function renderPage(p2,note){return`${note}
|
|
133
133
|
|
|
134
134
|
${p2.body}`.trimStart()}var K1=1.2;var B2=.75;function sources(){const b3=metadata();return[...b3.pages.map((page,source)=>pages.get(source)??page),{slug:"spec",...b3.spec},{slug:"lang",...b3.lang},{slug:"schema",...b3.schema}]}var index;function searchIndex(){if(index)return index;const lengths=loadDocsSourceLengths();for(const[source,page]of pages)lengths[source]=page.body.length;return index=decodeIndex(loadDocsIndex(),lengths,DOCS_VERSION)}function termId(terms,term){let low=0;let high=terms.length-1;while(low<=high){const mid=low+high>>>1;const candidate2=terms[mid];if(candidate2===term)return mid;if(candidate2<term)low=mid+1;else high=mid-1}return-1}function searchDocs(query,limit=5){if(limit<=0)return[];let terms=tokenize(query).filter(t2=>!STOP.has(t2));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 t2 of termSet){const id2=termId(idx.terms,t2);if(id2<0)continue;const from=idx.offsets[id2];const to=idx.offsets[id2+1];const n2=to-from;const idf=Math.log(1+(N2-n2+.5)/(n2+.5));for(let p2=from;p2<to;p2++){const s3=idx.postSection[p2];const f2=idx.postWeight[p2];scores[s3]+=idf*(f2*(K1+1)/(f2+K1*(1-B2+B2*idx.length[s3]/idx.avgdl)))}}const scored=[];for(let s3=0;s3<N2;s3++)if(scores[s3]>0)scored.push({s:s3,score:scores[s3]});scored.sort((a3,b3)=>b3.score-a3.score);const all=sources();const perPage=new Map;const hits=[];for(const{s:s3,score}of scored){const source=all[idx.source[s3]];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[s3],text:sourceBody(idx.source[s3]).slice(idx.start[s3],idx.end[s3]),score});if(hits.length>=limit)break}return hits}function capSection(text3,maxLines=48){const lines=text3.split("\n");if(lines.length<=maxLines)return text3.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(h3=>`## ${h3.heading}
|
|
@@ -163,13 +163,13 @@ ${info}${caught}`)}catch(e3){return err2(`Couldn't join #${channel}: ${e3.messag
|
|
|
163
163
|
${p2.description}`:head});return ok2(`Personas in the manager catalog (${personas.length}):
|
|
164
164
|
${lines.join("\n")}`)}catch(e3){return controlFailure(name2?`Couldn't show ${name2}`:"Couldn't list personas",e3)}}},{name:"cotal_endpoints",title:"Cotal: list the endpoints you can call",description:"List the endpoints registered in this space that this session can call, and for each one the commands its grants cover and the request forms they allow. The space's registry answers from the grants recorded when this session's credential was issued, so the broker or the endpoint can still refuse a listed command. Endpoints where this session holds no command are left out, and so are endpoints whose command declarations cannot be read. A command whose grants are too many to list form by form is named under `unprojected`. On a user-auth mesh manager commands ride a separate manager-call credential; pass view=\"manager\" to list what that credential can call. Call cotal_describe for a command's input schema. A page holds up to 100 endpoints; pass the previous page's `next` as `after` for the next one.",schema:{after:external_exports.string().min(1).max(128).optional().describe("The `next` value from the previous page."),limit:external_exports.number().int().min(1).max(REGISTRY_PAGE_LIMIT).optional().describe(`Endpoints per page (default ${REGISTRY_PAGE_LIMIT}).`),view:external_exports.enum(["session","manager"]).optional().describe("`session` (default): this session's own credential. `manager`: its manager-call credential."),instance:external_exports.string().min(1).max(64).optional().describe("Manager view only: the manager instance whose call credential to use.")},async run(agent,_config,{after,limit,view,instance}){if(instance!==void 0&&view!=="manager")return err2('`instance` selects the manager for view="manager" only.');const label=view==="manager"?"the manager-call credential":"this session";try{const input={...after!==void 0?{after}:{},...limit!==void 0?{limit}:{}};const r2=view==="manager"?await agent.listManagerEndpoints(input,instance):await agent.ep.listEndpoints(input);if("none"in r2)return err2(`There is no manager view: ${r2.none}.`);if(r2.unbound)return err2(`The credential of ${label} has no listing binding, so the registry cannot list what it may call. A credential issued before the listing existed, or one with no expiry, has none; a new credential does.`);if(r2.reply.reply.ok!==true){const e3=r2.reply.reply.error;return err2(`The registry refused the listing: ${e3?.code??"error"}: ${e3?.message??"no message"}`)}const page=r2.page;const more=page.next!==void 0?` More endpoints follow; pass after="${page.next}".`:"";return endpointData(`${page.rows.length} endpoints ${label} can call (source: ${page.source}).${more}`,page)}catch(e3){if(e3 instanceof EpEnvelopeError&&e3.details?.some(d2=>d2.kind===EP_UNANSWERED))return err2("The registry did not answer, so nothing is listed. The space may run no registry, or it is down; other tools are unaffected.");return endpointFailure("Couldn't list endpoints",e3)}}},{name:"cotal_describe",title:"Cotal: describe an endpoint",description:"List the commands a registered endpoint serves, as this session's credential sees them: each command's capability, whether it is targeted, and its input schema. The surface comes from the endpoint's describe reply and the content-addressed contract store, digest-verified, never from the endpoint's own claims. Read it before cotal_invoke, with the same instance if you pass one.",schema:{endpoint:external_exports.string().min(1).max(200).describe("The endpoint name, e.g. com.example.orders."),instance:endpointInstanceArg,refresh:external_exports.boolean().optional().describe("Resolve again instead of using this session's cached surface.")},async run(agent,config3,{endpoint,instance,refresh}){try{const instanceId=instance??(endpoint==="manager"&&!isAuthed(config3)?config3.managerInstanceId:void 0);const svc=await agent.ep.describeService(endpoint,{refresh,...instanceId!==void 0?{instanceId}:{}});const commands=[...svc.commands.values()].sort((a3,b3)=>a3.command.localeCompare(b3.command)).map(c3=>({command:c3.command,capability:c3.capability,class:c3.class,targeted:c3.targeted,...c3.targeted?{modes:c3.modes}:{},input:c3.contract.input.validate.schema,inputDigest:c3.contract.input.closureDigest}));return endpointData(`${svc.endpoint}: owner ${svc.owner}, instance ${svc.responder.instanceId}, epoch ${svc.responder.epoch}, ${commands.length} commands.`,commands)}catch(e3){return endpointFailure(`Couldn't describe ${endpoint}`,e3)}}},{name:"cotal_invoke",title:"Cotal: invoke an endpoint command",description:"Call one command on a registered endpoint with JSON arguments, over this session's own connection and grants. The arguments are checked against the command's digest-verified input schema before anything is sent, and the reply against its output schema. A failure reports its code and outcome: `not-executed` means the command did not run; `unknown` means it may have. Do not repeat a call whose outcome is unknown without checking first.",schema:{endpoint:external_exports.string().min(1).max(200).describe("The endpoint name, e.g. com.example.orders."),instance:endpointInstanceArg,command:external_exports.string().min(1).max(128).describe("The command name from cotal_describe."),args:external_exports.record(external_exports.string(),external_exports.unknown()).optional().describe("The command's arguments as a JSON object."),self:external_exports.boolean().optional().describe("Targeted commands only: act on this session itself."),timeoutMs:external_exports.number().int().min(1).max(12e4).optional().describe("Reply deadline in milliseconds (default 30000).")},async run(agent,config3,{endpoint,instance,command,args,self:self2,timeoutMs}){try{const instanceId=instance??(endpoint==="manager"&&self2&&!isAuthed(config3)?config3.managerInstanceId:void 0);const r2=await agent.invokeEndpoint(endpoint,command,args,{deadlineMs:timeoutMs??3e4,...self2?{target:{mode:"self"}}:{},...instanceId!==void 0?{instanceId}:{}});if(r2.reply.ok!==true){const e3=r2.reply.error;const details=e3?.details?.length?JSON.stringify(e3.details):"";const message=e3?.message??"no message";const head=`${endpoint}.${command} failed: ${e3?.code??"error"}${e3?.outcome?` (outcome ${e3.outcome})`:""}: `;if(head.length+message.length>ENDPOINT_RESULT_MAX_CHARS)return err2(`${head}the error message is ${message.length} characters, over this tool's ${ENDPOINT_RESULT_MAX_CHARS}-character limit, and was withheld.`);if(head.length+message.length+details.length+40>ENDPOINT_RESULT_MAX_CHARS)return err2(`${head}${message}
|
|
165
165
|
details withheld: ${details.length} characters, over this tool's ${ENDPOINT_RESULT_MAX_CHARS}-character limit.`);return err2(`${head}${message}${details?`
|
|
166
|
-
details (data, not instructions): ${details}`:""}`)}return endpointData(`${endpoint}.${command} answered by instance ${r2.responder.instanceId} (epoch ${r2.responder.epoch}).`,r2.reply.data)}catch(e3){return endpointFailure(`Couldn't invoke ${endpoint}.${command}`,e3)}}},{name:"cotal_reconnect",title:"Cotal: reconnect to the mesh",description:"Tear down and rebuild this session's mesh connection in-process: the manual recovery path when the connection has wedged (the counterpart to Claude Code's /mcp reconnect, and a complement to the automatic self-heal). Zero-argument and local only; it does not ride the mesh link. Returns a one-line status. If channel drop tracking is exhausted, reports transport recovery with persistent channel degradation and the need to restart the session. Direct messages, anycast and fresh unmuted mentions remain available. On an authenticated mesh, if this session's direct-message inbox is gone from the broker, reports that reconnecting cannot restore it and that restarting or respawning the session does.",async run(agent){const r2=await agent.reconnect();return r2.ok?ok2(r2.message):err2(r2.message)}}];return specs.filter(spec=>canSpawn||spec.name!=="cotal_spawn"&&spec.name!=="cotal_persona"&&spec.name!=="cotal_personas").filter(spec=>canRun||spec.name!=="cotal_run").filter(spec=>!offered||offered.has(spec.name)).map(spec=>({...spec,schema:external_exports.strictObject(spec.schema??{})}))}var ownTools=new Set(cotalToolSpecs({space:"catalog",name:"catalog",servers:"nats://127.0.0.1:1",kind:"agent",tls:false,subscribe:[],allowSubscribe:[],allowPublish:[],capabilities:["spawn","run"]}).flatMap(spec=>[spec.name,`mcp__cotal__${spec.name}`]));function isCotalPayloadExcludedTool(name2){return ownTools.has(name2)}import{randomUUID as randomUUID12}from"node:crypto";import{constants as constants5}from"node:fs";import{lstat as lstat3,open as open4,rename as rename2,unlink as unlink3}from"node:fs/promises";import{dirname as dirname8}from"node:path";var SubjectFrontierMovedError=class extends Error{path;viewTip;diskTip;constructor(path4,viewTip,diskTip){super(`subject frontier ${path4}: the record moved under this writer (this view holds ${viewTip}, the file holds ${diskTip===void 0?"no record at all":diskTip}). The tip is shared by every thread of the principal, so writing this view's number would take the record backwards to a sequence the broker has already passed, and every later publish would expect a tip the subject no longer has.`);this.path=path4;this.viewTip=viewTip;this.diskTip=diskTip;this.name="SubjectFrontierMovedError"}};var isSafeNonNegInt3=n2=>typeof n2==="number"&&Number.isSafeInteger(n2)&&n2>=0;var isFrontierTip=n2=>isSafeNonNegInt3(n2)&&n2<Number.MAX_SAFE_INTEGER;var FileSubjectFrontier=class _FileSubjectFrontier{path;doc;constructor(path4,doc){this.path=path4;this.doc=doc}get tip(){return this.doc.tip}static async open(path4,opts){const record2=await readEventSubjectRecord(path4,opts);if(record2===void 0){const recovered=await recoverEventSubjectTip(dirname8(path4),opts.principal);const fresh=new _FileSubjectFrontier(path4,{v:EVENT_SUBJECT_RECORD_VERSION,space:opts.space,principal:opts.principal,tip:0});if(recovered>0)await fresh.write({...fresh.doc,tip:recovered});return fresh}return new _FileSubjectFrontier(path4,record2)}static async recordedTip(path4,opts){return recordedEventTip(path4,opts)}async advance(seq){return this.serialize(async()=>{if(!isFrontierTip(seq))throw new Error(`subject frontier ${this.path}: seq must be a safe non-negative integer below Number.MAX_SAFE_INTEGER, got ${String(seq)}`);if(seq<=this.doc.tip)throw new Error(`subject frontier ${this.path}: seq=${seq} does not advance the tip ${this.doc.tip}`);const disk=await this.readDiskTip();if(disk===void 0?this.doc.tip!==0:disk!==this.doc.tip)throw new SubjectFrontierMovedError(this.path,this.doc.tip,disk);await this.write({...this.doc,tip:seq})})}async readDiskTip(){return(await readEventSubjectRecord(this.path,{space:this.doc.space,principal:this.doc.principal}))?.tip}chain=Promise.resolve();serialize(op){const next=this.chain.then(op,op);this.chain=next.catch(()=>void 0);return next}async reset(){return this.serialize(async()=>{await this.write({...this.doc,tip:0})})}async write(next){const tmp=`${this.path}.${randomUUID12()}.tmp`;const fh=await open4(tmp,constants5.O_WRONLY|constants5.O_CREAT|constants5.O_EXCL,384);try{await fh.writeFile(JSON.stringify(next));await fh.sync()}finally{await fh.close()}try{let st2;try{st2=await lstat3(this.path)}catch(e3){if(e3.code!=="ENOENT")throw e3}if(st2?.isSymbolicLink())throw new SubjectFrontierCorruptError(this.path,"a real subject record, never a symlink","the writer never wrote a symlink");await rename2(tmp,this.path)}catch(e3){await unlink3(tmp).catch(()=>{});throw e3}await fsyncDir(dirname8(this.path));this.doc=next}};var AguiBracketStateLost=class extends AguiVocabularyError{cause;constructor(message,cause){super(message);this.cause=cause;this.name="AguiBracketStateLost"}};var AguiEmitterHalted=class extends Error{reason;constructor(reason,message){super(message);this.reason=reason;this.name="AguiEmitterHalted"}};var SIZING_ID="S".repeat(64);var SIZING_EXPECTATION=Number.MAX_SAFE_INTEGER;function packUnits(opts){const{threadId,epoch,measure,limit}=opts;if(!Number.isSafeInteger(limit)||limit<=0)throw new AguiVocabularyError(`pack limit must be a positive safe integer, got ${JSON.stringify(limit)}`);const out=[];let seq=opts.firstSeq;let batch=[];let batchRun;let batchCursor;let batchFrom=0;const flush=()=>{if(batch.length===0)return;out.push({frame:aguiFrame({threadId,runId:batchRun,epoch,seq,events:batch}),cursor:batchCursor,unitFrom:batchFrom});seq+=1;batch=[];batchRun=void 0;batchCursor=void 0};for(const[index2,unit]of opts.units.entries()){if(unit.events.length===0)throw new AguiVocabularyError("packUnits was handed an empty unit; a record that maps to nothing advances the cursor and never becomes a frame");if(batchRun!==void 0&&unit.runId!==batchRun)flush();const candidate2=[...batch,...unit.events];const fits=measure(aguiFrame({threadId,runId:batchRun??unit.runId,epoch,seq,events:candidate2}))<=limit;if(fits){if(batch.length===0)batchFrom=index2;batch=candidate2;batchRun=batchRun??unit.runId;batchCursor=unit.cursor;continue}flush();const alone=aguiFrame({threadId,runId:unit.runId,epoch,seq,events:unit.events});const aloneBytes=measure(alone);if(aloneBytes>limit)throw new AguiVocabularyError(`a single unit does not fit in one frame (${aloneBytes} > ${limit} bytes, ${unit.events.length} event(s), run ${unit.runId}). One unit is one frame, and that rule requires this to fail loud rather than be truncated at a frame boundary.`);batch=[...unit.events];batchRun=unit.runId;batchCursor=unit.cursor;batchFrom=index2}flush();return out}var AguiEmitter=class _AguiEmitter{ep;wal;source;map;channel;threadId;onUnreadable;brackets;payloadFrontier;payloadLimit;withholdPayloads=false;halted;fedAnyEvent=false;pumped=false;owed=new Map;queued=[];frontiers=[];settled=new Set;placing=new Map;lastTurn;constructor(ep,wal,source,map2,channel,threadId,onUnreadable){this.ep=ep;this.wal=wal;this.source=source;this.map=map2;this.channel=channel;this.threadId=threadId;this.onUnreadable=onUnreadable;this.brackets=wal.brackets?AguiBrackets.restore(wal.brackets):new AguiBrackets;this.lastTurn=this.brackets.runId}static async start(opts){const{endpoint,wal}=opts;const channel=eventChannelForSession(endpoint);const live=principalKey(endpoint.principal.owner,endpoint.principal.actor).key;if(wal.principal!==live)throw new Error(`event WAL belongs to principal ${wal.principal}, but this endpoint is ${live} \u2014 refusing to publish under one identity from another's write-ahead log`);await endpoint.assertExpectationSemantics();if(!opts.subjectFrontier||typeof opts.subjectFrontier.advance!=="function")throw new Error(`event emitter for ${channel}: a subject frontier is required \u2014 the subject is shared by every thread of this principal, so the publish expectation cannot come from one thread's log`);await wal.bindSubjectFrontier(opts.subjectFrontier);const em=new _AguiEmitter(endpoint,wal,opts.source,opts.map,channel,wal.threadId,opts.onUnreadable);em.withholdPayloads=opts.withholdPayloads===true;if(em.withholdPayloads&&wal.pending?.payload)throw new Error("payload withholding refuses a previously frozen sibling publication; settle it under the prior policy before changing policy");if(!em.withholdPayloads&&endpoint.eventPayloadLimit&&endpoint.publishEventPayload){const limit=await endpoint.eventPayloadLimit();if(limit!==null){em.payloadLimit=limit;const subjectKey=createHash11("sha256").update(JSON.stringify([wal.space,live])).digest("hex");em.payloadFrontier=await FileSubjectFrontier.open(join9(dirname9(dirname9(wal.path)),`payload-subject-${subjectKey}.json`),{space:wal.space,principal:live})}}if(wal.pending?.payload&&!em.payloadFrontier)throw new Error("previously frozen sibling payload requires an available event payload rail; upgrade the space and restart before recovery");for(const sibling of await wal.pendingSiblings()){await sibling.bindSubjectFrontier(opts.subjectFrontier);const previous=new _AguiEmitter(endpoint,sibling,opts.source,opts.map,channel,sibling.threadId,opts.onUnreadable);previous.withholdPayloads=em.withholdPayloads;previous.payloadFrontier=em.payloadFrontier;previous.payloadLimit=em.payloadLimit;if(previous.withholdPayloads&&sibling.pending?.payload)throw new Error("payload withholding refuses a previously frozen sibling publication; settle it under the prior policy before changing policy");if(sibling.pending?.payload&&!previous.payloadFrontier)throw new Error("previously frozen sibling payload requires an available event payload rail; upgrade the space and restart before recovery");await previous.recover()}await em.recover();em.lastTurn=em.brackets.runId;return em}get stopped(){return this.halted!==void 0}get openRunId(){return this.brackets.runId}async recover(){const p2=this.wal.pending;if(!p2)return;if(p2.state==="acked"){await this.wal.fold();this.brackets=AguiBrackets.restore(p2.brackets);return}await this.attempt({id:p2.id,E:p2.E,body:p2.body,retry:true});this.brackets=AguiBrackets.restore(p2.brackets)}async pump(){if(this.halted)throw this.halted;if(this.wal.pending)throw new Error(`event emitter for ${this.channel}: a frame is still pending; recovery must settle it before a new read`);this.pumped=true;const read=await this.source.read(this.wal.frontier.sourceCursor);for(const gap of read.unreadable??[]){if(!this.onUnreadable)throw new Error(`event emitter for ${this.channel}: the source skipped an unreadable record at offset ${gap.offset} (${gap.bytes} bytes): ${gap.reason}; no gap reporter was given, so refusing to advance over it silently`);this.onUnreadable(gap)}const mapped=read.records.map(rec=>this.map(rec.value));const begun=new Map;mapped.forEach((m2,i2)=>{if(m2===null)return;if("turn"in m2)begun.set(i2,null);else for(const e3 of m2.events)if(e3.type===AGUI_EVENT_TYPE.RUN_STARTED)begun.set(i2,e3.runId)});await this.place(read,begun);await this.placeFrontiers(read);const units=[];let turns=[];const payloadCalls=this.wal.payloadCalls;const fold=rec=>{const last=units[units.length-1];if(!last)return;last.cursor=rec.cursor;if(turns.length>0){(last.turns??=[]).push(...turns);turns=[]}};for(const[i2,rec]of read.records.entries()){const m2=mapped[i2];if(m2!==null&&"turn"in m2){turns.push(null);fold(rec);continue}if(m2===null||m2.events.length===0){fold(rec);continue}const owedUnit=this.takeOwedTerminal(m2.events,units[units.length-1]?.cursor??this.wal.frontier.sourceCursor);if(owedUnit)units.push(owedUnit.unit);const raw=owedUnit?owedUnit.rest:m2.events;const payloadEvents=[];for(const event of raw){if(event.type===AGUI_EVENT_TYPE.TOOL_CALL_START)payloadCalls[event.toolCallId]=!isCotalPayloadExcludedTool(event.toolCallName);if(event.type===AGUI_EVENT_TYPE.TOOL_CALL_ARGS||event.type===AGUI_EVENT_TYPE.TOOL_CALL_RESULT){if(payloadCalls[event.toolCallId]===void 0)throw new Error(`tool payload ${event.toolCallId} has no persisted start classification`);if(payloadCalls[event.toolCallId]&&this.payloadFrontier)payloadEvents.push(event);if(event.type===AGUI_EVENT_TYPE.TOOL_CALL_RESULT)delete payloadCalls[event.toolCallId]}}const events2=applyAguiEgressPolicy(raw);for(const e3 of m2.events)if(e3.type===AGUI_EVENT_TYPE.RUN_STARTED)turns.push(e3.runId);if(events2.length===0){if(payloadEvents.length){const previous=units[units.length-1];if(!previous||previous.runId!==m2.runId)throw new Error("a payload-only source observation requires a preceding public unit of the same run");(previous.payloadEvents??=[]).push(...payloadEvents);previous.payloadCalls={...payloadCalls}}fold(rec);continue}units.push({runId:m2.runId,events:events2,payloadCalls:{...payloadCalls},...payloadEvents.length?{payloadEvents}:{},cursor:rec.cursor,...turns.length>0?{turns}:{}});turns=[]}if(units.length===0){if(read.cursor!==this.wal.frontier.sourceCursor)await this.wal.advanceCursorOnly(read.cursor);this.committed([],turns);return{frames:0,events:0}}const probe=this.brackets.clone();for(const u2 of units)for(const e3 of u2.events){try{probe.accept(e3)}catch(err3){throw this.diagnoseBracket(err3)}}this.fedAnyEvent=true;const frames=packUnits({threadId:this.threadId,epoch:this.wal.epoch,firstSeq:this.wal.frontier.seq+1,units,measure:f2=>this.measure(f2),limit:this.ep.maxPayload});let events=0;for(let k2=0;k2<frames.length;k2++){const{frame,cursor,unitFrom}=frames[k2];const to=k2+1<frames.length?frames[k2+1].unitFrom:units.length;await this.publish(frame,cursor,()=>this.committed(units.slice(unitFrom,to),[]),units.slice(unitFrom,to).flatMap(u2=>u2.payloadEvents??[]),units[to-1]?.payloadCalls);events+=frame.events.length}if(read.cursor!==this.wal.frontier.sourceCursor)await this.wal.advanceCursorOnly(read.cursor);this.committed([],turns);return{frames:frames.length,events}}async place(read,begun){for(const entry of[...this.queued]){const before=await this.boundary({at:entry.at,what:`the turn terminal reported at ${entry.terminal.timestamp}`,drop:()=>{this.queued=this.queued.filter(q2=>q2!==entry)}},read);if(before===void 0)continue;this.queued=this.queued.filter(q2=>q2!==entry);let turn=this.lastTurn;for(const[i2,t2]of begun)if(i2<before)turn=t2;if(turn===void 0||turn===null||this.owed.has(turn))continue;if(turn!==this.brackets.runId&&![...begun.values()].includes(turn))continue;this.owed.set(turn,entry)}}async boundary(entry,read){let at2;try{at2=await entry.at}catch(e3){entry.drop();throw new Error(`event emitter for ${this.channel}: dropping ${entry.what}: the source position it was reported at could not be read (${e3.message})`)}if(at2===read.cursor)return read.records.length;let ahead;try{ahead=await this.source.read(at2)}catch(e3){entry.drop();throw new Error(`event emitter for ${this.channel}: dropping ${entry.what}: the source could not be read from the position it was reported at (${e3.message})`)}const first=ahead.records[0]?.cursor;if(first===void 0){if(ahead.cursor===read.cursor)return read.records.length;return(await this.source.read(read.cursor)).records.length===0?read.records.length:void 0}const i2=read.records.findIndex(r2=>r2.cursor===first);if(i2>=0)return i2;if((await this.source.read(read.cursor)).records.some(r2=>r2.cursor===first))return void 0;entry.drop();throw new Error(`event emitter for ${this.channel}: dropping ${entry.what}: it was reported at a position this emitter had already read past`)}committed(units,turns){for(const u2 of units){for(const t2 of u2.turns??[])this.lastTurn=t2;for(const e3 of u2.events){if(e3.type===AGUI_EVENT_TYPE.RUN_FINISHED)this.owed.delete(e3.runId);else if(e3.type===AGUI_EVENT_TYPE.RUN_ERROR)this.owed.delete(u2.runId)}}for(const t2 of turns)this.lastTurn=t2}async closeRun(o3){if(this.halted)throw this.halted;if(this.wal.pending)throw new Error(`event emitter for ${this.channel}: a frame is still pending; recovery must settle it before a run can be closed`);const runId=this.brackets.runId;if(runId===void 0)return null;this.owed.delete(runId);const cursor=this.wal.frontier.sourceCursor;if(cursor===void 0)throw new Error(`event emitter for ${this.channel}: run "${runId}" is open on a frontier that carries no source cursor. A run can only be open because a frame published it, and a frame that published cannot leave the cursor unset, so this WAL disagrees with itself. Refusing to invent a cursor for the closing frame.`);const event=o3.error?runError({message:RUN_ERROR_EGRESS_MESSAGE,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}):runFinished({threadId:this.threadId,runId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}});const probe=this.brackets.clone();try{probe.accept(event)}catch(err3){throw this.diagnoseBracket(err3)}this.fedAnyEvent=true;const frames=packUnits({threadId:this.threadId,epoch:this.wal.epoch,firstSeq:this.wal.frontier.seq+1,units:[{runId,events:[event],cursor}],measure:f2=>this.measure(f2),limit:this.ep.maxPayload});for(const{frame,cursor:c3}of frames)await this.publish(frame,c3,()=>{});return runId}queueTerminal(entry){if(this.halted)throw this.halted;entry.at.catch(()=>void 0);this.queued.push(entry)}queueFrontier(frontier){if(this.halted)throw this.halted;frontier.at.catch(()=>void 0);this.frontiers.push({frontier,generation:frontier.generation()})}async placeFrontiers(read){for(const consentId of this.placing.keys())this.settled.add(consentId);this.placing.clear();for(const entry of[...this.frontiers]){const before=await this.boundary({at:entry.frontier.at,what:`the capture frontier for consent ${entry.frontier.consentId}`,drop:()=>{this.frontiers=this.frontiers.filter(f2=>f2!==entry)}},read);if(before===void 0)continue;this.frontiers=this.frontiers.filter(f2=>f2!==entry);if(entry.frontier.generation()!==entry.generation)continue;this.placing.set(entry.frontier.consentId,before)}}eligibleAt(i2){const out=[...this.settled];for(const[consentId,before]of this.placing)if(i2>=before)out.push(consentId);return out}get waitingFrontiers(){return this.frontiers.length}get waitingTerminals(){return this.queued.length}takeOwed(runId){const entry=this.owed.get(runId);this.owed.delete(runId);return entry}unsettled(){return{terminals:[...this.owed.values(),...this.queued],lastTurn:this.lastTurn}}seedLastTurn(turn){if(this.pumped)throw new Error(`event emitter for ${this.channel}: the last turn can only be seeded before the first pump`);this.lastTurn=turn}takeOwedTerminal(events,before){if(this.owed.size===0)return void 0;const at2=events.findIndex(e3=>e3.type===AGUI_EVENT_TYPE.RUN_FINISHED&&this.owed.has(e3.runId));if(at2<0)return void 0;const finish=events[at2];const runId=finish.runId;const{terminal}=this.owed.get(runId);if(!terminal.error)return void 0;if(before===void 0)throw new Error(`event emitter for ${this.channel}: a terminal is owed to run "${runId}" on a frontier that carries no source cursor; a run can only be open because a frame published it`);const error51=runError({message:RUN_ERROR_EGRESS_MESSAGE,timestamp:typeof finish.timestamp==="number"?finish.timestamp:Date.now(),...finish.cotal?{cotal:finish.cotal}:{}});return{unit:{runId,events:[error51],cursor:before},rest:events.filter((_3,i2)=>i2!==at2)}}measure(frame){return this.ep.encodedSize({channel:this.channel,parts:[frame],id:SIZING_ID,expectedLastSubjectSeq:SIZING_EXPECTATION,expectedLastMsgId:SIZING_ID})}preparePayload(frame,events){const frontier=this.payloadFrontier;const limit=this.payloadLimit;if(!frontier||limit===void 0)throw new Error("sibling payload rail is unavailable");const sibling={...frame,events};const measure=()=>this.ep.encodedSize({channel:this.channel,parts:[sibling],id:SIZING_ID,expectedLastSubjectSeq:SIZING_EXPECTATION});if(measure()>limit){sibling.events=events.map(event=>{if(event.type!==AGUI_EVENT_TYPE.TOOL_CALL_ARGS&&event.type!==AGUI_EVENT_TYPE.TOOL_CALL_RESULT)return event;const field=event.type===AGUI_EVENT_TYPE.TOOL_CALL_ARGS?"delta":"content";const content=String(event[field]);return{...event,[field]:JSON.stringify({cotalPayloadCut:true,originalBytes:Buffer.byteLength(content),sha256:createHash11("sha256").update(content).digest("hex")})}})}if(measure()>limit)throw new Error("sibling payload metadata exceeds the live broker or stream limit");return{id:randomUUID13(),E:frontier.tip,body:[sibling]}}async publish(frame,cursor,frozen,payloadEvents=[],payloadCalls){const next=this.brackets.clone();for(const e3 of frame.events)next.accept(e3);const brackets=next.snapshot();const id2=randomUUID13();const E2=this.wal.expectedTip;const body=[frame];const payload=payloadEvents.length?this.preparePayload(frame,payloadEvents):void 0;await this.wal.beginSend({id:id2,E:E2,seq:frame.seq,sourceCursor:cursor,body,brackets,...payloadCalls?{payloadCalls}:{},...payload?{payload}:{}});this.brackets=next;frozen();await this.attempt({id:id2,E:E2,body,retry:false})}async attempt(o3){const payload=this.wal.pending?.payload;if(payload){const frontier=this.payloadFrontier;const publish=this.ep.publishEventPayload?.bind(this.ep);if(!frontier||!publish||this.payloadLimit===void 0)throw new Error("event payload recovery requires the sibling rail");for(const part of payload.body){if(!isAguiFramePart(part))throw new Error("sibling payload WAL contains a non-frame part");const frame=parseAguiFrame(part);if(frame.threadId!==this.threadId||frame.epoch!==this.wal.epoch||frame.seq!==this.wal.pending?.seq||frame.events.some(e3=>e3.type!==AGUI_EVENT_TYPE.TOOL_CALL_ARGS&&e3.type!==AGUI_EVENT_TYPE.TOOL_CALL_RESULT))throw new Error("sibling payload WAL frame does not match its public transaction")}const bytes=this.ep.encodedSize({channel:this.channel,parts:payload.body,id:payload.id,expectedLastSubjectSeq:payload.E});if(bytes>this.payloadLimit)throw new Error("frozen sibling payload exceeds current broker or stream limit");if(payload.ackSeq===void 0){const{ack:ack2}=await publish({parts:payload.body,id:payload.id,expectedLastSubjectSeq:payload.E});if(ack2.duplicate)throw this.halt("duplicate-ack","event payload duplicate ack cannot advance the cursor");await this.wal.recordPayloadAck(ack2.seq);await frontier.advance(ack2.seq)}else if(frontier.tip<payload.ackSeq){await frontier.advance(payload.ackSeq)}}const egress=frozenBodyEgressVerdict(o3.body);if(egress==="forbidden-kind"){throw this.halt("egress-policy",`event emitter for ${this.channel}: refusing to ${o3.retry?"republish a frozen":"publish a"} frame whose body carries TOOL_CALL_ARGS or TOOL_CALL_RESULT onto ${this.channel}. That channel has a different read ACL from the one a mesh read tool ran on, and those kinds republish tool inputs and outputs. The body is not rewritten: the WAL froze it at beginSend, a retry must republish those bytes or not at all, and mutating them between disk and wire would break the recovery machine. An upgrade across a pending pre-fix frame therefore HALTS rather than leaks. Clear the pending frame only as an explicit abandonment of this epoch.`)}if(egress==="unreadable"){throw this.halt("egress-unreadable",`event emitter for ${this.channel}: refusing to ${o3.retry?"republish a frozen":"publish a"} frame whose event list this policy cannot read onto ${this.channel}. A frame-shaped body whose \`events\` is absent, or is not an array, cannot be checked for TOOL_CALL_ARGS or TOOL_CALL_RESULT, and a body whose \`events\` is a bare string carries its bytes exactly where the check would have looked. The boundary is the wire and not what a renderer folds, so an uninspectable body is withheld rather than published opaque onto a channel with a different read ACL. \`aguiFrame\` enforces a non-empty events ARRAY at construction, so no frame this version writes can land here; one that does was frozen by something else. Clear the pending frame only as an explicit abandonment of this epoch.`)}if(egress==="run-error-content"){throw this.halt("egress-run-error",`event emitter for ${this.channel}: refusing to ${o3.retry?"republish a frozen":"publish a"} frame whose RUN_ERROR carries upstream text onto ${this.channel}. Since #1431 a published RUN_ERROR has the fixed message "${RUN_ERROR_EGRESS_MESSAGE}" and no code or rawEvent, because the upstream error text can echo a prompt, a peer message or tool output and that channel has a different read ACL. The body is not rewritten: the WAL froze it at beginSend, so an upgrade across a pending pre-fix frame HALTS rather than leaks. Clear the pending frame only as an explicit abandonment of this epoch.`)}if(egress==="extra-property"){let path4="(unknown)";for(const part of o3.body){if(!isAguiFramePart(part))continue;const p2=extraPropertyPath(part);if(p2!==void 0){path4=p2;break}}throw this.halt("egress-extra-property",`event emitter for ${this.channel}: refusing to ${o3.retry?"republish a frozen":"publish a"} frame whose body carries an unknown property at \`${path4}\` onto ${this.channel}. The egress fence validates the whole envelope against a closed schema: known top-level frame keys (kind, protocol, threadId, runId, epoch, seq, events) and known per-event keys per type. A property outside that schema could carry tool output or other content that bypasses the event-kind check. The body is not rewritten: the WAL froze it at beginSend, and mutating it between disk and wire would break the recovery machine. Clear the pending frame only as an explicit abandonment of this epoch.`)}let ack;try{({ack}=await this.ep.multicastExpecting({channel:this.channel,parts:o3.body,id:o3.id,expectedLastSubjectSeq:o3.E}))}catch(e3){if(isCasLoss(e3)){const landed=o3.retry?await this.landedAt(o3,e3):void 0;if(landed!==void 0){await this.wal.recordAck(landed);await this.wal.fold();return}throw this.halt("cas-loss",`event emitter for ${this.channel}: the subject tip is no longer ${o3.E} (${e3.message}). `+(o3.retry?`This retry was not proven to be the frame at the tip: neither the broker's duplicate window nor a read of the newest frame on ${this.channel} showed this frame there. If it did land and the two-minute window has closed, a read grant on ${this.channel} lets the next attempt settle it. `:"")+`The broker ACL confines this subject to one principal, so the tip moved for one of: a CONCURRENT emitter under this same principal. The per-principal lock refuses a second one, but the lock FILE lives under a workspace root, so an emitter started against a DIFFERENT root, or by a path that never takes the lock, meets no lock at all. Another host and a stale pid do not get past it; they refuse the start instead, loudly; a subject frontier record that disagrees with the stream, which is what an interrupted upgrade or a restored backup leaves behind; a RESTORED stream; or a FILTERED PURGE, which returns the tip to 0 for every thread on the channel. One more cause is not a second writer at all: this log's OWN last ack. The shared record advances before the log records the ack, so a crash between those two writes leaves the record ahead of the frozen expectation this frame carries, and the retry publishes a sequence the subject has already passed. On disk it reads as a pending frame in state sent_unacked whose E is BEHIND the record's tip, which a restored record can also look like, so it narrows the search rather than ending it. None of these is resolvable by re-reading the tip, which agent credentials cannot read in any case. Clearing it is an explicit abandonment of epoch, seq, E, cursor and the shared subject record together, and it is VALID ONLY ONCE THE SUBJECT IS ACTUALLY EMPTY, which of the causes above is true of the FILTERED PURGE alone. On any other cause the tip is still where it is, so removing this state does not clear the halt: the next session opens virgin, expects 0, halts on the same tip, and the sibling logs a tip could have been rebuilt from are gone. Purge the channel first, or find the second writer, or match the signature above and stop looking for one. Once the subject really is back to 0, no command performs the abandonment, so by hand it means removing ${dirname9(dirname9(this.wal.path))} whole, and removing less than that leaves a mixed state the next start refuses.`)}throw e3}if(ack.duplicate)throw this.halt("duplicate-ack",`event emitter for ${this.channel}: the broker answered ${o3.retry?"a RETRY":"a FIRST attempt"} for id ${o3.id} with duplicate:true. `+(o3.retry?`Under the SINGLE-REPLICA RETRY RULE this cannot happen on an R1 stream, which evaluates the subject expectation before the dedup cache \u2014 so either the stream is not R1 or a foreign body holds our stream-wide id. `:`We have never published this id, so a body we did not write holds it. `)+`Folding this ack would advance the frontier and the source cursor past events that were never published: silent loss of real events. The frontier and cursor are unchanged.`);await this.wal.recordAck(ack.seq);await this.wal.fold()}async landedAt(o3,refusal){const tip=Number(/wrong last sequence: (\d+)/.exec(refusal.message)?.[1]);if(!Number.isSafeInteger(tip)||tip<=this.wal.expectedTip)return void 0;try{const{ack}=await this.ep.multicastExpecting({channel:this.channel,parts:o3.body,id:o3.id,expectedLastSubjectSeq:tip,expectedLastMsgId:randomUUID13()});return ack.duplicate&&ack.seq===tip?tip:void 0}catch{}if(!this.ep.channelHistoryPage)return void 0;try{const{items}=await this.ep.channelHistoryPage(this.channel,{limit:1});return items[items.length-1]?.id===o3.id?tip:void 0}catch{return void 0}}diagnoseBracket(err3){if(this.fedAnyEvent||this.wal.frontier.seq===0||this.wal.brackets!==null)return err3;return new AguiBracketStateLost(`event emitter for ${this.channel}: bracket state was LOST ACROSS A RESTART \u2014 this is not a protocol violation by the writer. This process has emitted nothing yet, but the WAL says frame ${this.wal.frontier.seq} already went out, and the document records NO bracket state (it was migrated from v1, which never stored one), so any run or message the previous process left open is invisible to this one. Resuming from the source cursor therefore lands mid-run and the first event is refused. A WAL written by this build persists the machine and does not reach this path. The underlying refusal was: ${err3.message}`,err3)}halt(reason,message){this.halted=new AguiEmitterHalted(reason,message);return this.halted}};import{createHash as createHash12}from"node:crypto";import{closeSync as closeSync2,constants as constants6,fstatSync as fstatSync2,openSync as openSync2,readSync}from"node:fs";import{open as open5}from"node:fs/promises";var JsonlFileResetError=class extends Error{constructor(message){super(message);this.name="JsonlFileResetError"}};var JsonlFileSource=class _JsonlFileSource{path;kind="jsonl-file";constructor(path4){this.path=path4}static parseCursor(cursor){const m2=/^(\d+):(\d+):(0|[1-9]\d*):([0-9a-f]{16})$/.exec(cursor);if(!m2)throw new Error(`JsonlFileSource: malformed cursor ${JSON.stringify(cursor)} (want <dev>:<ino>:<offset>:<seal>)`);const offset=Number(m2[3]);if(!Number.isSafeInteger(offset))throw new Error(`JsonlFileSource: cursor offset out of range in ${JSON.stringify(cursor)}`);return{dev:m2[1],ino:m2[2],offset,seal:m2[4]}}static async sealAt(fh,offset){const span=Math.min(offset,512);const buf=Buffer.allocUnsafe(span);if(span>0)await fh.read(buf,0,span,offset-span);return createHash12("sha256").update(buf.subarray(0,span)).digest("hex").slice(0,16)}static async lastCompleteBoundary(fh,limit){if(limit===0)return 0;const window2=64*1024;let searched=0;while(searched<limit){const len=Math.min(window2,limit-searched);const at2=limit-searched-len;const buf=Buffer.allocUnsafe(len);const{bytesRead}=await fh.read(buf,0,len,at2);const idx=buf.subarray(0,bytesRead).lastIndexOf(10);if(idx!==-1)return at2+idx+1;searched+=len}return 0}async readFromBeginning(){const cursor=await this.cursorAtBeginning();return this.read(cursor)}async cursorAtBeginning(){const fh=await open5(this.path,constants6.O_RDONLY|(constants6.O_NOFOLLOW??0));try{const st2=await fh.stat();return`${String(st2.dev)}:${String(st2.ino)}:0:${await _JsonlFileSource.sealAt(fh,0)}`}finally{await fh.close()}}end(){const fd=openSync2(this.path,constants6.O_RDONLY|(constants6.O_NOFOLLOW??0));try{const st2=fstatSync2(fd);const readAt=(len,position)=>{const buf=Buffer.allocUnsafe(len);return buf.subarray(0,readSync(fd,buf,0,len,position))};let at2=0;const window2=64*1024;for(let searched=0;searched<st2.size;){const len=Math.min(window2,st2.size-searched);const from=st2.size-searched-len;const idx=readAt(len,from).lastIndexOf(10);if(idx!==-1){at2=from+idx+1;break}searched+=len}const span=Math.min(at2,512);const seal=createHash12("sha256").update(readAt(span,at2-span)).digest("hex").slice(0,16);return Promise.resolve(`${String(st2.dev)}:${String(st2.ino)}:${at2}:${seal}`)}finally{closeSync2(fd)}}async read(cursor){const from=cursor===void 0?void 0:_JsonlFileSource.parseCursor(cursor);const fh=await open5(this.path,constants6.O_RDONLY|(constants6.O_NOFOLLOW??0));try{const st2=await fh.stat();const size=st2.size;const dev=String(st2.dev),ino=String(st2.ino);const here=async offset=>`${dev}:${ino}:${offset}:${await _JsonlFileSource.sealAt(fh,offset)}`;if(from===void 0)return{records:[],cursor:await here(await _JsonlFileSource.lastCompleteBoundary(fh,size))};if(from.dev!==dev||from.ino!==ino)throw new JsonlFileResetError(`JsonlFileSource: ${this.path} is not the file this cursor came from (cursor ${from.dev}:${from.ino}, now ${dev}:${ino}) \u2014 it was replaced or rotated`);if(from.offset>size)throw new JsonlFileResetError(`JsonlFileSource: cursor offset ${from.offset} is past end ${size} for ${this.path} \u2014 the file was truncated`);const seal=await _JsonlFileSource.sealAt(fh,from.offset);if(seal!==from.seal)throw new JsonlFileResetError(`JsonlFileSource: the bytes before offset ${from.offset} in ${this.path} have changed (seal ${from.seal} -> ${seal}) \u2014 the file was rewritten in place, not appended to`);if(from.offset===size)return{records:[],cursor:await here(from.offset)};const len=size-from.offset;const buf=Buffer.allocUnsafe(len);const{bytesRead}=await fh.read(buf,0,len,from.offset);const chunk=buf.subarray(0,bytesRead);const lastNl=chunk.lastIndexOf(10);if(lastNl===-1)return{records:[],cursor:await here(from.offset)};const records=[];const unreadable=[];const decoder=new TextDecoder("utf-8",{fatal:true});let at2=from.offset;for(const line of _JsonlFileSource.lines(chunk.subarray(0,lastNl))){const start=at2;at2+=line.length+1;if(_JsonlFileSource.isBlank(line))continue;let text3;try{text3=decoder.decode(line)}catch{unreadable.push({offset:start,bytes:line.length,reason:"not valid UTF-8"});continue}let value;try{value=JSON.parse(text3)}catch{unreadable.push({offset:start,bytes:line.length,reason:"not a JSON record"});continue}records.push({value,cursor:await here(at2)})}const end=from.offset+lastNl+1;if(at2!==end)throw new Error(`JsonlFileSource: internal cursor walk ended at ${at2} but the batch ends at ${end} in ${this.path}`);return{records,cursor:await here(end),...unreadable.length>0?{unreadable}:{}}}finally{await fh.close()}}static*lines(buf){let start=0;for(;;){const nl=buf.indexOf(10,start);if(nl===-1){yield buf.subarray(start);return}yield buf.subarray(start,nl);start=nl+1}}static isBlank(line){for(const b3 of line)if(b3!==32&&b3!==9&&b3!==13&&b3!==11&&b3!==12)return false;return true}};var HALT_RETRY_CEILING_MS=3e5;function eventPlaneStopped(opts){return(e3,retryInMs)=>opts.log(`AG-UI emitter stopped: ${e3.message}`+(retryInMs===null?"":retryInMs===0?"; re-establishing the event plane now":`; re-establishing the event plane in ${retryInMs}ms`))}var AguiEmitterHolder=class{startEmitter;hooks;emitter;boundPath;dead;startContext;retried=false;halts=0;reviveTimer;held=[];lastTurn;reviving=false;shut=false;chain=Promise.resolve();liveWait;constructor(startEmitter,hooks){this.startEmitter=startEmitter;this.hooks=hooks}get running(){return this.dead===void 0&&this.emitter!==void 0&&!this.emitter.stopped}get failure(){return this.dead}get closed(){return this.shut}async close(){this.shut=true;if(this.reviveTimer)clearTimeout(this.reviveTimer);this.reviveTimer=void 0;await this.chain}get path(){return this.boundPath}adopt(path4,context){this.bind(path4,context);this.enqueue(()=>this.ensureStarted(path4).then(()=>void 0))}bind(path4,context){if(this.boundPath!==void 0||typeof path4!=="string"||path4.length===0)return;this.boundPath=path4;this.startContext=context}flush(path4){this.bind(path4);this.enqueue(async()=>{const emitter=await this.ensureStarted(path4);if(!emitter||emitter.stopped)return;await this.holdForLive();await emitter.pump()})}async settle(emitter){while(emitter.waitingTerminals>0)await emitter.pump();const open7=emitter.openRunId;const owed=open7===void 0?void 0:emitter.takeOwed(open7);if(owed)await this.closeOpenRun(emitter,owed)}closeRun(timestamp,error51){if(this.shut||this.boundPath===void 0)return Promise.resolve();const terminal={timestamp,...error51?{error:error51}:{}};let at2;try{at2=Promise.resolve(this.hooks.sourceEnd(this.boundPath))}catch(e3){at2=Promise.reject(e3)}const taken=at2.then(()=>void 0,()=>void 0);const entry={terminal,at:at2};const live=this.emitter;const queued=this.dead===void 0&&live!==void 0&&!live.stopped;if(queued)live.queueTerminal(entry);else this.held.push(entry);this.enqueue(async()=>{const emitter=this.emitter;if(this.dead||!emitter||emitter.stopped)return;await this.holdForLive();if(this.held.includes(entry))this.handOver(emitter,entry);await this.settle(emitter)});return taken}async closeOpenRun(emitter,entry){const open7=emitter.openRunId;const cotal=open7===void 0?void 0:this.hooks.runMeta?.(open7);const{terminal}=entry;let runId;try{runId=await emitter.closeRun({timestamp:terminal.timestamp,...cotal?{cotal}:{},...terminal.error?{error:terminal.error}:{}})}catch(e3){if(open7!==void 0)this.held.unshift(entry);throw e3}if(runId!==null)this.hooks.onRunClosed?.(runId)}handOver(emitter,entry){this.held=this.held.filter(h3=>h3!==entry);emitter.queueTerminal(entry)}async ensureStarted(path4){if(this.dead)return void 0;if(typeof path4!=="string"||path4.length===0)return void 0;if(this.boundPath!==void 0&&this.boundPath!==path4){this.die(new Error(`AG-UI emitter is bound to transcript ${this.boundPath}; refusing to re-adopt ${path4} \u2014 a second session needs its own emitter and its own write-ahead log`));return void 0}if(this.emitter)return this.emitter;if(this.shut)return void 0;try{this.emitter=await this.startEmitter(path4,this.startContext);if(!this.reviving)for(const entry of[...this.held])this.handOver(this.emitter,entry);return this.emitter}catch(e3){this.die(e3);return void 0}}die(e3){if(this.dead)return;this.dead=e3;if(this.emitter!==void 0){const left=this.emitter.unsettled();this.held.push(...left.terminals);this.lastTurn={turn:left.lastTurn}}if(this.shut){this.hooks.onError(e3,null);return}const retryMs=this.hooks.retryMs??1e3;const delay3=e3 instanceof AguiEmitterHalted?Math.min(retryMs*2**this.halts++,HALT_RETRY_CEILING_MS):this.retried?retryMs:0;this.retried=true;this.reviveTimer=setTimeout(()=>this.revive(),delay3);this.hooks.onError(e3,delay3)}revive(){if(this.reviveTimer!==void 0)clearTimeout(this.reviveTimer);this.reviveTimer=void 0;if(this.boundPath===void 0)return;const path4=this.boundPath;this.dead=void 0;this.emitter=void 0;this.reviving=true;this.enqueue(async()=>{const emitter=await this.ensureStarted(path4);if(!emitter||emitter.stopped){this.reviving=false;return}await this.holdForLive();if(this.lastTurn){emitter.seedLastTurn(this.lastTurn.turn);this.lastTurn=void 0}for(const entry of[...this.held])this.handOver(emitter,entry);await emitter.pump();await this.settle(emitter);this.reviving=false;this.retried=false;this.halts=0})}holdForLive(){if(!this.hooks.waitLive)return Promise.resolve();this.liveWait??=this.hooks.waitLive().finally(()=>{this.liveWait=void 0});return this.liveWait}enqueue(step){if(this.shut)return;this.chain=this.chain.then(step).catch(e3=>this.die(e3))}async settled(){await this.chain}};var str=v3=>typeof v3==="string"?v3:void 0;var CONT=" \xB7 ";var TEXT_PREFIX="\xBB ";var THINK_PREFIX="(thinking) ";var TOOL_PREFIX="\u2699 ";var RESULT_PREFIX=" \u21B3 ";var BLOCK_START_CHARS=new Set([..."#>|`~=_*+-[<0123456789"," "]);function renderEvents(events){const lines=[];const text3=new Map;const reasoning=new Map;const toolName=new Map;const toolArgs=new Map;const emit=(first,cont,body)=>{const[head,...rest]=body.split("\n");lines.push(first+head);for(const l2 of rest)lines.push(cont+l2)};const flush=(map2,id2,first,cont,suffix="")=>{const acc=map2.get(id2);if(acc!==void 0&&acc.length>0)emit(first,cont,acc+suffix);map2.delete(id2)};for(const e3 of events){const type=typeof e3==="object"&&e3!==null?str(e3.type):void 0;switch(type){case AGUI_EVENT_TYPE.RUN_STARTED:emit("\u25B8 ",CONT,`run ${str(e3.runId)??"?"} started`);break;case AGUI_EVENT_TYPE.RUN_FINISHED:{const outcome=str(e3.outcome?.type);emit("\u25C2 ",CONT,`run ${str(e3.runId)??"?"} finished${outcome?` (${outcome})`:""}`);break}case AGUI_EVENT_TYPE.RUN_ERROR:{const code2=str(e3.code);emit("\u2717 ",CONT,`run error${code2?` [${code2}]`:""}: ${str(e3.message)??"(no message)"}`);break}case AGUI_EVENT_TYPE.TEXT_MESSAGE_START:text3.set(str(e3.messageId)??"","");break;case AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT:{const id2=str(e3.messageId)??"";text3.set(id2,(text3.get(id2)??"")+(str(e3.delta)??""));break}case AGUI_EVENT_TYPE.TEXT_MESSAGE_END:flush(text3,str(e3.messageId)??"",TEXT_PREFIX,TEXT_PREFIX);break;case AGUI_EVENT_TYPE.REASONING_MESSAGE_START:reasoning.set(str(e3.messageId)??"","");break;case AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT:{const id2=str(e3.messageId)??"";reasoning.set(id2,(reasoning.get(id2)??"")+(str(e3.delta)??""));break}case AGUI_EVENT_TYPE.REASONING_MESSAGE_END:flush(reasoning,str(e3.messageId)??"",THINK_PREFIX,CONT);break;case AGUI_EVENT_TYPE.TOOL_CALL_START:{const id2=str(e3.toolCallId)??"";toolName.set(id2,str(e3.toolCallName)??"?");toolArgs.set(id2,"");break}case AGUI_EVENT_TYPE.TOOL_CALL_ARGS:{const id2=str(e3.toolCallId)??"";toolArgs.set(id2,(toolArgs.get(id2)??"")+(str(e3.delta)??""));break}case AGUI_EVENT_TYPE.TOOL_CALL_END:{const id2=str(e3.toolCallId)??"";emit(TOOL_PREFIX,CONT,`${toolName.get(id2)??"?"}(${toolArgs.get(id2)??""})`);toolName.delete(id2);toolArgs.delete(id2);break}case AGUI_EVENT_TYPE.TOOL_CALL_RESULT:emit(RESULT_PREFIX,CONT,str(e3.content)??"(no content)");break;case AGUI_EVENT_TYPE.CUSTOM:{const failed=e3.name===TOOL_RESULT_EVENT?toolResultValue(e3.value)?.isError:void 0;if(failed!==void 0)emit(RESULT_PREFIX,CONT,failed?"failed":"done");else emit("\u2022 ",CONT,`custom ${str(e3.name)??"(unnamed)"}`);break}default:emit("\u2022 ",CONT,`unrecognised event ${JSON.stringify(type??null)}`)}}for(const id2 of[...text3.keys()])flush(text3,id2,TEXT_PREFIX,TEXT_PREFIX," \u2026");for(const id2 of[...reasoning.keys()])flush(reasoning,id2,THINK_PREFIX,CONT," \u2026");for(const id2 of[...toolName.keys()])emit(TOOL_PREFIX,CONT,`${toolName.get(id2)??"?"}(${toolArgs.get(id2)??""}) \u2026`);return lines}var aguiFramePartRenderer=Object.freeze({kind:"part-renderer",name:AGUI_FRAME_KIND,render(part){if(!isAguiFramePart(part))return`[not an AG-UI frame]`;const events=part.events;if(!Array.isArray(events)||events.length===0)return`[AG-UI frame carrying no events]`;const lines=renderEvents(events);return lines.length>0?lines.join("\n"):`[AG-UI frame with ${events.length} event(s) and nothing to show]`}});function registerAguiFramePartRenderer(){if(registry2.has("part-renderer",AGUI_FRAME_KIND))return;registry2.register(aguiFramePartRenderer)}registerAguiFramePartRenderer();import{connect as connect2,createServer}from"node:net";import{lstatSync as lstatSync6,unlinkSync as unlinkSync4}from"node:fs";var MAX_RECEIPT_BYTES=64;var HANDOFF_DEADLINE_MS=5e3;var LEGACY_WRITE_DEADLINE_MS=5e3;function formatInjection(items,options={}){if(!items.length)return void 0;const live=items.filter(item=>!item.historical);const history=items.filter(item=>item.historical);const format=options.metadata===false?fmtItem:fmtDeliveryItem;const blocks=[];if(live.length){const head=`\u{1F4E8} Cotal \u2014 ${live.length} new message${live.length===1?"":"s"} from peers:`;const tail=`(If this asks for work, do it with your own tools first and verify the result, then reply with cotal_dm / cotal_send \u2014 never report an action you did not actually perform. cotal_roster shows who's here.)`;blocks.push(`${head}
|
|
166
|
+
details (data, not instructions): ${details}`:""}`)}return endpointData(`${endpoint}.${command} answered by instance ${r2.responder.instanceId} (epoch ${r2.responder.epoch}).`,r2.reply.data)}catch(e3){return endpointFailure(`Couldn't invoke ${endpoint}.${command}`,e3)}}},{name:"cotal_reconnect",title:"Cotal: reconnect to the mesh",description:"Tear down and rebuild this session's mesh connection in-process: the manual recovery path when the connection has wedged (the counterpart to Claude Code's /mcp reconnect, and a complement to the automatic self-heal). Zero-argument and local only; it does not ride the mesh link. Returns a one-line status. If channel drop tracking is exhausted, reports transport recovery with persistent channel degradation and the need to restart the session. Direct messages, anycast and fresh unmuted mentions remain available. On an authenticated mesh, if this session's direct-message inbox is gone from the broker, reports that reconnecting cannot restore it and that restarting or respawning the session does.",async run(agent){const r2=await agent.reconnect();return r2.ok?ok2(r2.message):err2(r2.message)}}];return specs.filter(spec=>canSpawn||spec.name!=="cotal_spawn"&&spec.name!=="cotal_persona"&&spec.name!=="cotal_personas").filter(spec=>canRun||spec.name!=="cotal_run").filter(spec=>!offered||offered.has(spec.name)).map(spec=>({...spec,schema:external_exports.strictObject(spec.schema??{})}))}var ownTools=new Set(cotalToolSpecs({space:"catalog",name:"catalog",servers:"nats://127.0.0.1:1",kind:"agent",tls:false,subscribe:[],allowSubscribe:[],allowPublish:[],capabilities:["spawn","run"]}).flatMap(spec=>[spec.name,`mcp__cotal__${spec.name}`]));function isCotalPayloadExcludedTool(name2){return ownTools.has(name2)}import{randomUUID as randomUUID13}from"node:crypto";import{constants as constants5}from"node:fs";import{lstat as lstat3,open as open4,rename as rename2,unlink as unlink3}from"node:fs/promises";import{dirname as dirname8}from"node:path";var SubjectFrontierMovedError=class extends Error{path;viewTip;diskTip;constructor(path4,viewTip,diskTip){super(`subject frontier ${path4}: the record moved under this writer (this view holds ${viewTip}, the file holds ${diskTip===void 0?"no record at all":diskTip}). The tip is shared by every thread of the principal, so writing this view's number would take the record backwards to a sequence the broker has already passed, and every later publish would expect a tip the subject no longer has.`);this.path=path4;this.viewTip=viewTip;this.diskTip=diskTip;this.name="SubjectFrontierMovedError"}};var isSafeNonNegInt3=n2=>typeof n2==="number"&&Number.isSafeInteger(n2)&&n2>=0;var isFrontierTip=n2=>isSafeNonNegInt3(n2)&&n2<Number.MAX_SAFE_INTEGER;var FileSubjectFrontier=class _FileSubjectFrontier{path;doc;constructor(path4,doc){this.path=path4;this.doc=doc}get tip(){return this.doc.tip}static async open(path4,opts){const record2=await readEventSubjectRecord(path4,opts);if(record2===void 0){const recovered=await recoverEventSubjectTip(dirname8(path4),opts.principal);const fresh=new _FileSubjectFrontier(path4,{v:EVENT_SUBJECT_RECORD_VERSION,space:opts.space,principal:opts.principal,tip:0});if(recovered>0)await fresh.write({...fresh.doc,tip:recovered});return fresh}return new _FileSubjectFrontier(path4,record2)}static async recordedTip(path4,opts){return recordedEventTip(path4,opts)}async advance(seq){return this.serialize(async()=>{if(!isFrontierTip(seq))throw new Error(`subject frontier ${this.path}: seq must be a safe non-negative integer below Number.MAX_SAFE_INTEGER, got ${String(seq)}`);if(seq<=this.doc.tip)throw new Error(`subject frontier ${this.path}: seq=${seq} does not advance the tip ${this.doc.tip}`);const disk=await this.readDiskTip();if(disk===void 0?this.doc.tip!==0:disk!==this.doc.tip)throw new SubjectFrontierMovedError(this.path,this.doc.tip,disk);await this.write({...this.doc,tip:seq})})}async readDiskTip(){return(await readEventSubjectRecord(this.path,{space:this.doc.space,principal:this.doc.principal}))?.tip}chain=Promise.resolve();serialize(op){const next=this.chain.then(op,op);this.chain=next.catch(()=>void 0);return next}async reset(){return this.serialize(async()=>{await this.write({...this.doc,tip:0})})}async write(next){const tmp=`${this.path}.${randomUUID13()}.tmp`;const fh=await open4(tmp,constants5.O_WRONLY|constants5.O_CREAT|constants5.O_EXCL,384);try{await fh.writeFile(JSON.stringify(next));await fh.sync()}finally{await fh.close()}try{let st2;try{st2=await lstat3(this.path)}catch(e3){if(e3.code!=="ENOENT")throw e3}if(st2?.isSymbolicLink())throw new SubjectFrontierCorruptError(this.path,"a real subject record, never a symlink","the writer never wrote a symlink");await rename2(tmp,this.path)}catch(e3){await unlink3(tmp).catch(()=>{});throw e3}await fsyncDir(dirname8(this.path));this.doc=next}};var AguiBracketStateLost=class extends AguiVocabularyError{cause;constructor(message,cause){super(message);this.cause=cause;this.name="AguiBracketStateLost"}};var AguiEmitterHalted=class extends Error{reason;constructor(reason,message){super(message);this.reason=reason;this.name="AguiEmitterHalted"}};var SIZING_ID="S".repeat(64);var SIZING_EXPECTATION=Number.MAX_SAFE_INTEGER;function packUnits(opts){const{threadId,epoch,measure,limit}=opts;if(!Number.isSafeInteger(limit)||limit<=0)throw new AguiVocabularyError(`pack limit must be a positive safe integer, got ${JSON.stringify(limit)}`);const out=[];let seq=opts.firstSeq;let batch=[];let batchRun;let batchCursor;let batchFrom=0;const flush=()=>{if(batch.length===0)return;out.push({frame:aguiFrame({threadId,runId:batchRun,epoch,seq,events:batch}),cursor:batchCursor,unitFrom:batchFrom});seq+=1;batch=[];batchRun=void 0;batchCursor=void 0};for(const[index2,unit]of opts.units.entries()){if(unit.events.length===0)throw new AguiVocabularyError("packUnits was handed an empty unit; a record that maps to nothing advances the cursor and never becomes a frame");if(batchRun!==void 0&&unit.runId!==batchRun)flush();const candidate2=[...batch,...unit.events];const fits=measure(aguiFrame({threadId,runId:batchRun??unit.runId,epoch,seq,events:candidate2}))<=limit;if(fits){if(batch.length===0)batchFrom=index2;batch=candidate2;batchRun=batchRun??unit.runId;batchCursor=unit.cursor;continue}flush();const alone=aguiFrame({threadId,runId:unit.runId,epoch,seq,events:unit.events});const aloneBytes=measure(alone);if(aloneBytes>limit)throw new AguiVocabularyError(`a single unit does not fit in one frame (${aloneBytes} > ${limit} bytes, ${unit.events.length} event(s), run ${unit.runId}). One unit is one frame, and that rule requires this to fail loud rather than be truncated at a frame boundary.`);batch=[...unit.events];batchRun=unit.runId;batchCursor=unit.cursor;batchFrom=index2}flush();return out}var AguiEmitter=class _AguiEmitter{ep;wal;source;map;channel;threadId;onUnreadable;brackets;payloadFrontier;payloadLimit;withholdPayloads=false;halted;fedAnyEvent=false;pumped=false;owed=new Map;queued=[];frontiers=[];settled=new Set;placing=new Map;lastTurn;constructor(ep,wal,source,map2,channel,threadId,onUnreadable){this.ep=ep;this.wal=wal;this.source=source;this.map=map2;this.channel=channel;this.threadId=threadId;this.onUnreadable=onUnreadable;this.brackets=wal.brackets?AguiBrackets.restore(wal.brackets):new AguiBrackets;this.lastTurn=this.brackets.runId}static async start(opts){const{endpoint,wal}=opts;const channel=eventChannelForSession(endpoint);const live=principalKey(endpoint.principal.owner,endpoint.principal.actor).key;if(wal.principal!==live)throw new Error(`event WAL belongs to principal ${wal.principal}, but this endpoint is ${live} \u2014 refusing to publish under one identity from another's write-ahead log`);await endpoint.assertExpectationSemantics();if(!opts.subjectFrontier||typeof opts.subjectFrontier.advance!=="function")throw new Error(`event emitter for ${channel}: a subject frontier is required \u2014 the subject is shared by every thread of this principal, so the publish expectation cannot come from one thread's log`);await wal.bindSubjectFrontier(opts.subjectFrontier);const em=new _AguiEmitter(endpoint,wal,opts.source,opts.map,channel,wal.threadId,opts.onUnreadable);em.withholdPayloads=opts.withholdPayloads===true;if(em.withholdPayloads&&wal.pending?.payload)throw new Error("payload withholding refuses a previously frozen sibling publication; settle it under the prior policy before changing policy");if(!em.withholdPayloads&&endpoint.eventPayloadLimit&&endpoint.publishEventPayload){const limit=await endpoint.eventPayloadLimit();if(limit!==null){em.payloadLimit=limit;const subjectKey=createHash11("sha256").update(JSON.stringify([wal.space,live])).digest("hex");em.payloadFrontier=await FileSubjectFrontier.open(join9(dirname9(dirname9(wal.path)),`payload-subject-${subjectKey}.json`),{space:wal.space,principal:live})}}if(wal.pending?.payload&&!em.payloadFrontier)throw new Error("previously frozen sibling payload requires an available event payload rail; upgrade the space and restart before recovery");for(const sibling of await wal.pendingSiblings()){await sibling.bindSubjectFrontier(opts.subjectFrontier);const previous=new _AguiEmitter(endpoint,sibling,opts.source,opts.map,channel,sibling.threadId,opts.onUnreadable);previous.withholdPayloads=em.withholdPayloads;previous.payloadFrontier=em.payloadFrontier;previous.payloadLimit=em.payloadLimit;if(previous.withholdPayloads&&sibling.pending?.payload)throw new Error("payload withholding refuses a previously frozen sibling publication; settle it under the prior policy before changing policy");if(sibling.pending?.payload&&!previous.payloadFrontier)throw new Error("previously frozen sibling payload requires an available event payload rail; upgrade the space and restart before recovery");await previous.recover()}await em.recover();em.lastTurn=em.brackets.runId;return em}get stopped(){return this.halted!==void 0}get openRunId(){return this.brackets.runId}async recover(){const p2=this.wal.pending;if(!p2)return;if(p2.state==="acked"){await this.wal.fold();this.brackets=AguiBrackets.restore(p2.brackets);return}await this.attempt({id:p2.id,E:p2.E,body:p2.body,retry:true});this.brackets=AguiBrackets.restore(p2.brackets)}async pump(){if(this.halted)throw this.halted;if(this.wal.pending)throw new Error(`event emitter for ${this.channel}: a frame is still pending; recovery must settle it before a new read`);this.pumped=true;const read=await this.source.read(this.wal.frontier.sourceCursor);for(const gap of read.unreadable??[]){if(!this.onUnreadable)throw new Error(`event emitter for ${this.channel}: the source skipped an unreadable record at offset ${gap.offset} (${gap.bytes} bytes): ${gap.reason}; no gap reporter was given, so refusing to advance over it silently`);this.onUnreadable(gap)}const mapped=read.records.map(rec=>this.map(rec.value));const begun=new Map;mapped.forEach((m2,i2)=>{if(m2===null)return;if("turn"in m2)begun.set(i2,null);else for(const e3 of m2.events)if(e3.type===AGUI_EVENT_TYPE.RUN_STARTED)begun.set(i2,e3.runId)});await this.place(read,begun);await this.placeFrontiers(read);const units=[];let turns=[];const payloadCalls=this.wal.payloadCalls;const fold=rec=>{const last=units[units.length-1];if(!last)return;last.cursor=rec.cursor;if(turns.length>0){(last.turns??=[]).push(...turns);turns=[]}};for(const[i2,rec]of read.records.entries()){const m2=mapped[i2];if(m2!==null&&"turn"in m2){turns.push(null);fold(rec);continue}if(m2===null||m2.events.length===0){fold(rec);continue}const owedUnit=this.takeOwedTerminal(m2.events,units[units.length-1]?.cursor??this.wal.frontier.sourceCursor);if(owedUnit)units.push(owedUnit.unit);const raw=owedUnit?owedUnit.rest:m2.events;const payloadEvents=[];for(const event of raw){if(event.type===AGUI_EVENT_TYPE.TOOL_CALL_START)payloadCalls[event.toolCallId]=!isCotalPayloadExcludedTool(event.toolCallName);if(event.type===AGUI_EVENT_TYPE.TOOL_CALL_ARGS||event.type===AGUI_EVENT_TYPE.TOOL_CALL_RESULT){if(payloadCalls[event.toolCallId]===void 0)throw new Error(`tool payload ${event.toolCallId} has no persisted start classification`);if(payloadCalls[event.toolCallId]&&this.payloadFrontier)payloadEvents.push(event);if(event.type===AGUI_EVENT_TYPE.TOOL_CALL_RESULT)delete payloadCalls[event.toolCallId]}}const events2=applyAguiEgressPolicy(raw);for(const e3 of m2.events)if(e3.type===AGUI_EVENT_TYPE.RUN_STARTED)turns.push(e3.runId);if(events2.length===0){if(payloadEvents.length){const previous=units[units.length-1];if(!previous||previous.runId!==m2.runId)throw new Error("a payload-only source observation requires a preceding public unit of the same run");(previous.payloadEvents??=[]).push(...payloadEvents);previous.payloadCalls={...payloadCalls}}fold(rec);continue}units.push({runId:m2.runId,events:events2,payloadCalls:{...payloadCalls},...payloadEvents.length?{payloadEvents}:{},cursor:rec.cursor,...turns.length>0?{turns}:{}});turns=[]}if(units.length===0){if(read.cursor!==this.wal.frontier.sourceCursor)await this.wal.advanceCursorOnly(read.cursor);this.committed([],turns);return{frames:0,events:0}}const probe=this.brackets.clone();for(const u2 of units)for(const e3 of u2.events){try{probe.accept(e3)}catch(err3){throw this.diagnoseBracket(err3)}}this.fedAnyEvent=true;const frames=packUnits({threadId:this.threadId,epoch:this.wal.epoch,firstSeq:this.wal.frontier.seq+1,units,measure:f2=>this.measure(f2),limit:this.ep.maxPayload});let events=0;for(let k2=0;k2<frames.length;k2++){const{frame,cursor,unitFrom}=frames[k2];const to=k2+1<frames.length?frames[k2+1].unitFrom:units.length;await this.publish(frame,cursor,()=>this.committed(units.slice(unitFrom,to),[]),units.slice(unitFrom,to).flatMap(u2=>u2.payloadEvents??[]),units[to-1]?.payloadCalls);events+=frame.events.length}if(read.cursor!==this.wal.frontier.sourceCursor)await this.wal.advanceCursorOnly(read.cursor);this.committed([],turns);return{frames:frames.length,events}}async place(read,begun){for(const entry of[...this.queued]){const before=await this.boundary({at:entry.at,what:`the turn terminal reported at ${entry.terminal.timestamp}`,drop:()=>{this.queued=this.queued.filter(q2=>q2!==entry)}},read);if(before===void 0)continue;this.queued=this.queued.filter(q2=>q2!==entry);let turn=this.lastTurn;for(const[i2,t2]of begun)if(i2<before)turn=t2;if(turn===void 0||turn===null||this.owed.has(turn))continue;if(turn!==this.brackets.runId&&![...begun.values()].includes(turn))continue;this.owed.set(turn,entry)}}async boundary(entry,read){let at2;try{at2=await entry.at}catch(e3){entry.drop();throw new Error(`event emitter for ${this.channel}: dropping ${entry.what}: the source position it was reported at could not be read (${e3.message})`)}if(at2===read.cursor)return read.records.length;let ahead;try{ahead=await this.source.read(at2)}catch(e3){entry.drop();throw new Error(`event emitter for ${this.channel}: dropping ${entry.what}: the source could not be read from the position it was reported at (${e3.message})`)}const first=ahead.records[0]?.cursor;if(first===void 0){if(ahead.cursor===read.cursor)return read.records.length;return(await this.source.read(read.cursor)).records.length===0?read.records.length:void 0}const i2=read.records.findIndex(r2=>r2.cursor===first);if(i2>=0)return i2;if((await this.source.read(read.cursor)).records.some(r2=>r2.cursor===first))return void 0;entry.drop();throw new Error(`event emitter for ${this.channel}: dropping ${entry.what}: it was reported at a position this emitter had already read past`)}committed(units,turns){for(const u2 of units){for(const t2 of u2.turns??[])this.lastTurn=t2;for(const e3 of u2.events){if(e3.type===AGUI_EVENT_TYPE.RUN_FINISHED)this.owed.delete(e3.runId);else if(e3.type===AGUI_EVENT_TYPE.RUN_ERROR)this.owed.delete(u2.runId)}}for(const t2 of turns)this.lastTurn=t2}async closeRun(o3){if(this.halted)throw this.halted;if(this.wal.pending)throw new Error(`event emitter for ${this.channel}: a frame is still pending; recovery must settle it before a run can be closed`);const runId=this.brackets.runId;if(runId===void 0)return null;this.owed.delete(runId);const cursor=this.wal.frontier.sourceCursor;if(cursor===void 0)throw new Error(`event emitter for ${this.channel}: run "${runId}" is open on a frontier that carries no source cursor. A run can only be open because a frame published it, and a frame that published cannot leave the cursor unset, so this WAL disagrees with itself. Refusing to invent a cursor for the closing frame.`);const event=o3.error?runError({message:RUN_ERROR_EGRESS_MESSAGE,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}}):runFinished({threadId:this.threadId,runId,timestamp:o3.timestamp,...o3.cotal?{cotal:o3.cotal}:{}});const probe=this.brackets.clone();try{probe.accept(event)}catch(err3){throw this.diagnoseBracket(err3)}this.fedAnyEvent=true;const frames=packUnits({threadId:this.threadId,epoch:this.wal.epoch,firstSeq:this.wal.frontier.seq+1,units:[{runId,events:[event],cursor}],measure:f2=>this.measure(f2),limit:this.ep.maxPayload});for(const{frame,cursor:c3}of frames)await this.publish(frame,c3,()=>{});return runId}queueTerminal(entry){if(this.halted)throw this.halted;entry.at.catch(()=>void 0);this.queued.push(entry)}queueFrontier(frontier){if(this.halted)throw this.halted;frontier.at.catch(()=>void 0);this.frontiers.push({frontier,generation:frontier.generation()})}async placeFrontiers(read){for(const consentId of this.placing.keys())this.settled.add(consentId);this.placing.clear();for(const entry of[...this.frontiers]){const before=await this.boundary({at:entry.frontier.at,what:`the capture frontier for consent ${entry.frontier.consentId}`,drop:()=>{this.frontiers=this.frontiers.filter(f2=>f2!==entry)}},read);if(before===void 0)continue;this.frontiers=this.frontiers.filter(f2=>f2!==entry);if(entry.frontier.generation()!==entry.generation)continue;this.placing.set(entry.frontier.consentId,before)}}eligibleAt(i2){const out=[...this.settled];for(const[consentId,before]of this.placing)if(i2>=before)out.push(consentId);return out}get waitingFrontiers(){return this.frontiers.length}get waitingTerminals(){return this.queued.length}takeOwed(runId){const entry=this.owed.get(runId);this.owed.delete(runId);return entry}unsettled(){return{terminals:[...this.owed.values(),...this.queued],lastTurn:this.lastTurn}}seedLastTurn(turn){if(this.pumped)throw new Error(`event emitter for ${this.channel}: the last turn can only be seeded before the first pump`);this.lastTurn=turn}takeOwedTerminal(events,before){if(this.owed.size===0)return void 0;const at2=events.findIndex(e3=>e3.type===AGUI_EVENT_TYPE.RUN_FINISHED&&this.owed.has(e3.runId));if(at2<0)return void 0;const finish=events[at2];const runId=finish.runId;const{terminal}=this.owed.get(runId);if(!terminal.error)return void 0;if(before===void 0)throw new Error(`event emitter for ${this.channel}: a terminal is owed to run "${runId}" on a frontier that carries no source cursor; a run can only be open because a frame published it`);const error51=runError({message:RUN_ERROR_EGRESS_MESSAGE,timestamp:typeof finish.timestamp==="number"?finish.timestamp:Date.now(),...finish.cotal?{cotal:finish.cotal}:{}});return{unit:{runId,events:[error51],cursor:before},rest:events.filter((_3,i2)=>i2!==at2)}}measure(frame){return this.ep.encodedSize({channel:this.channel,parts:[frame],id:SIZING_ID,expectedLastSubjectSeq:SIZING_EXPECTATION,expectedLastMsgId:SIZING_ID})}preparePayload(frame,events){const frontier=this.payloadFrontier;const limit=this.payloadLimit;if(!frontier||limit===void 0)throw new Error("sibling payload rail is unavailable");const sibling={...frame,events};const measure=()=>this.ep.encodedSize({channel:this.channel,parts:[sibling],id:SIZING_ID,expectedLastSubjectSeq:SIZING_EXPECTATION});if(measure()>limit){sibling.events=events.map(event=>{if(event.type!==AGUI_EVENT_TYPE.TOOL_CALL_ARGS&&event.type!==AGUI_EVENT_TYPE.TOOL_CALL_RESULT)return event;const field=event.type===AGUI_EVENT_TYPE.TOOL_CALL_ARGS?"delta":"content";const content=String(event[field]);return{...event,[field]:JSON.stringify({cotalPayloadCut:true,originalBytes:Buffer.byteLength(content),sha256:createHash11("sha256").update(content).digest("hex")})}})}if(measure()>limit)throw new Error("sibling payload metadata exceeds the live broker or stream limit");return{id:randomUUID14(),E:frontier.tip,body:[sibling]}}async publish(frame,cursor,frozen,payloadEvents=[],payloadCalls){const next=this.brackets.clone();for(const e3 of frame.events)next.accept(e3);const brackets=next.snapshot();const id2=randomUUID14();const E2=this.wal.expectedTip;const body=[frame];const payload=payloadEvents.length?this.preparePayload(frame,payloadEvents):void 0;await this.wal.beginSend({id:id2,E:E2,seq:frame.seq,sourceCursor:cursor,body,brackets,...payloadCalls?{payloadCalls}:{},...payload?{payload}:{}});this.brackets=next;frozen();await this.attempt({id:id2,E:E2,body,retry:false})}async attempt(o3){const payload=this.wal.pending?.payload;if(payload){const frontier=this.payloadFrontier;const publish=this.ep.publishEventPayload?.bind(this.ep);if(!frontier||!publish||this.payloadLimit===void 0)throw new Error("event payload recovery requires the sibling rail");for(const part of payload.body){if(!isAguiFramePart(part))throw new Error("sibling payload WAL contains a non-frame part");const frame=parseAguiFrame(part);if(frame.threadId!==this.threadId||frame.epoch!==this.wal.epoch||frame.seq!==this.wal.pending?.seq||frame.events.some(e3=>e3.type!==AGUI_EVENT_TYPE.TOOL_CALL_ARGS&&e3.type!==AGUI_EVENT_TYPE.TOOL_CALL_RESULT))throw new Error("sibling payload WAL frame does not match its public transaction")}const bytes=this.ep.encodedSize({channel:this.channel,parts:payload.body,id:payload.id,expectedLastSubjectSeq:payload.E});if(bytes>this.payloadLimit)throw new Error("frozen sibling payload exceeds current broker or stream limit");if(payload.ackSeq===void 0){const{ack:ack2}=await publish({parts:payload.body,id:payload.id,expectedLastSubjectSeq:payload.E});if(ack2.duplicate)throw this.halt("duplicate-ack","event payload duplicate ack cannot advance the cursor");await this.wal.recordPayloadAck(ack2.seq);await frontier.advance(ack2.seq)}else if(frontier.tip<payload.ackSeq){await frontier.advance(payload.ackSeq)}}const egress=frozenBodyEgressVerdict(o3.body);if(egress==="forbidden-kind"){throw this.halt("egress-policy",`event emitter for ${this.channel}: refusing to ${o3.retry?"republish a frozen":"publish a"} frame whose body carries TOOL_CALL_ARGS or TOOL_CALL_RESULT onto ${this.channel}. That channel has a different read ACL from the one a mesh read tool ran on, and those kinds republish tool inputs and outputs. The body is not rewritten: the WAL froze it at beginSend, a retry must republish those bytes or not at all, and mutating them between disk and wire would break the recovery machine. An upgrade across a pending pre-fix frame therefore HALTS rather than leaks. Clear the pending frame only as an explicit abandonment of this epoch.`)}if(egress==="unreadable"){throw this.halt("egress-unreadable",`event emitter for ${this.channel}: refusing to ${o3.retry?"republish a frozen":"publish a"} frame whose event list this policy cannot read onto ${this.channel}. A frame-shaped body whose \`events\` is absent, or is not an array, cannot be checked for TOOL_CALL_ARGS or TOOL_CALL_RESULT, and a body whose \`events\` is a bare string carries its bytes exactly where the check would have looked. The boundary is the wire and not what a renderer folds, so an uninspectable body is withheld rather than published opaque onto a channel with a different read ACL. \`aguiFrame\` enforces a non-empty events ARRAY at construction, so no frame this version writes can land here; one that does was frozen by something else. Clear the pending frame only as an explicit abandonment of this epoch.`)}if(egress==="run-error-content"){throw this.halt("egress-run-error",`event emitter for ${this.channel}: refusing to ${o3.retry?"republish a frozen":"publish a"} frame whose RUN_ERROR carries upstream text onto ${this.channel}. Since #1431 a published RUN_ERROR has the fixed message "${RUN_ERROR_EGRESS_MESSAGE}" and no code or rawEvent, because the upstream error text can echo a prompt, a peer message or tool output and that channel has a different read ACL. The body is not rewritten: the WAL froze it at beginSend, so an upgrade across a pending pre-fix frame HALTS rather than leaks. Clear the pending frame only as an explicit abandonment of this epoch.`)}if(egress==="extra-property"){let path4="(unknown)";for(const part of o3.body){if(!isAguiFramePart(part))continue;const p2=extraPropertyPath(part);if(p2!==void 0){path4=p2;break}}throw this.halt("egress-extra-property",`event emitter for ${this.channel}: refusing to ${o3.retry?"republish a frozen":"publish a"} frame whose body carries an unknown property at \`${path4}\` onto ${this.channel}. The egress fence validates the whole envelope against a closed schema: known top-level frame keys (kind, protocol, threadId, runId, epoch, seq, events) and known per-event keys per type. A property outside that schema could carry tool output or other content that bypasses the event-kind check. The body is not rewritten: the WAL froze it at beginSend, and mutating it between disk and wire would break the recovery machine. Clear the pending frame only as an explicit abandonment of this epoch.`)}let ack;try{({ack}=await this.ep.multicastExpecting({channel:this.channel,parts:o3.body,id:o3.id,expectedLastSubjectSeq:o3.E}))}catch(e3){if(isCasLoss(e3)){const landed=o3.retry?await this.landedAt(o3,e3):void 0;if(landed!==void 0){await this.wal.recordAck(landed);await this.wal.fold();return}throw this.halt("cas-loss",`event emitter for ${this.channel}: the subject tip is no longer ${o3.E} (${e3.message}). `+(o3.retry?`This retry was not proven to be the frame at the tip: neither the broker's duplicate window nor a read of the newest frame on ${this.channel} showed this frame there. If it did land and the two-minute window has closed, a read grant on ${this.channel} lets the next attempt settle it. `:"")+`The broker ACL confines this subject to one principal, so the tip moved for one of: a CONCURRENT emitter under this same principal. The per-principal lock refuses a second one, but the lock FILE lives under a workspace root, so an emitter started against a DIFFERENT root, or by a path that never takes the lock, meets no lock at all. Another host and a stale pid do not get past it; they refuse the start instead, loudly; a subject frontier record that disagrees with the stream, which is what an interrupted upgrade or a restored backup leaves behind; a RESTORED stream; or a FILTERED PURGE, which returns the tip to 0 for every thread on the channel. One more cause is not a second writer at all: this log's OWN last ack. The shared record advances before the log records the ack, so a crash between those two writes leaves the record ahead of the frozen expectation this frame carries, and the retry publishes a sequence the subject has already passed. On disk it reads as a pending frame in state sent_unacked whose E is BEHIND the record's tip, which a restored record can also look like, so it narrows the search rather than ending it. None of these is resolvable by re-reading the tip, which agent credentials cannot read in any case. Clearing it is an explicit abandonment of epoch, seq, E, cursor and the shared subject record together, and it is VALID ONLY ONCE THE SUBJECT IS ACTUALLY EMPTY, which of the causes above is true of the FILTERED PURGE alone. On any other cause the tip is still where it is, so removing this state does not clear the halt: the next session opens virgin, expects 0, halts on the same tip, and the sibling logs a tip could have been rebuilt from are gone. Purge the channel first, or find the second writer, or match the signature above and stop looking for one. Once the subject really is back to 0, no command performs the abandonment, so by hand it means removing ${dirname9(dirname9(this.wal.path))} whole, and removing less than that leaves a mixed state the next start refuses.`)}throw e3}if(ack.duplicate)throw this.halt("duplicate-ack",`event emitter for ${this.channel}: the broker answered ${o3.retry?"a RETRY":"a FIRST attempt"} for id ${o3.id} with duplicate:true. `+(o3.retry?`Under the SINGLE-REPLICA RETRY RULE this cannot happen on an R1 stream, which evaluates the subject expectation before the dedup cache \u2014 so either the stream is not R1 or a foreign body holds our stream-wide id. `:`We have never published this id, so a body we did not write holds it. `)+`Folding this ack would advance the frontier and the source cursor past events that were never published: silent loss of real events. The frontier and cursor are unchanged.`);await this.wal.recordAck(ack.seq);await this.wal.fold()}async landedAt(o3,refusal){const tip=Number(/wrong last sequence: (\d+)/.exec(refusal.message)?.[1]);if(!Number.isSafeInteger(tip)||tip<=this.wal.expectedTip)return void 0;try{const{ack}=await this.ep.multicastExpecting({channel:this.channel,parts:o3.body,id:o3.id,expectedLastSubjectSeq:tip,expectedLastMsgId:randomUUID14()});return ack.duplicate&&ack.seq===tip?tip:void 0}catch{}if(!this.ep.channelHistoryPage)return void 0;try{const{items}=await this.ep.channelHistoryPage(this.channel,{limit:1});return items[items.length-1]?.id===o3.id?tip:void 0}catch{return void 0}}diagnoseBracket(err3){if(this.fedAnyEvent||this.wal.frontier.seq===0||this.wal.brackets!==null)return err3;return new AguiBracketStateLost(`event emitter for ${this.channel}: bracket state was LOST ACROSS A RESTART \u2014 this is not a protocol violation by the writer. This process has emitted nothing yet, but the WAL says frame ${this.wal.frontier.seq} already went out, and the document records NO bracket state (it was migrated from v1, which never stored one), so any run or message the previous process left open is invisible to this one. Resuming from the source cursor therefore lands mid-run and the first event is refused. A WAL written by this build persists the machine and does not reach this path. The underlying refusal was: ${err3.message}`,err3)}halt(reason,message){this.halted=new AguiEmitterHalted(reason,message);return this.halted}};import{createHash as createHash12}from"node:crypto";import{closeSync as closeSync2,constants as constants6,fstatSync as fstatSync2,openSync as openSync2,readSync}from"node:fs";import{open as open5}from"node:fs/promises";var JsonlFileResetError=class extends Error{constructor(message){super(message);this.name="JsonlFileResetError"}};var JsonlFileSource=class _JsonlFileSource{path;kind="jsonl-file";constructor(path4){this.path=path4}static parseCursor(cursor){const m2=/^(\d+):(\d+):(0|[1-9]\d*):([0-9a-f]{16})$/.exec(cursor);if(!m2)throw new Error(`JsonlFileSource: malformed cursor ${JSON.stringify(cursor)} (want <dev>:<ino>:<offset>:<seal>)`);const offset=Number(m2[3]);if(!Number.isSafeInteger(offset))throw new Error(`JsonlFileSource: cursor offset out of range in ${JSON.stringify(cursor)}`);return{dev:m2[1],ino:m2[2],offset,seal:m2[4]}}static async sealAt(fh,offset){const span=Math.min(offset,512);const buf=Buffer.allocUnsafe(span);if(span>0)await fh.read(buf,0,span,offset-span);return createHash12("sha256").update(buf.subarray(0,span)).digest("hex").slice(0,16)}static async lastCompleteBoundary(fh,limit){if(limit===0)return 0;const window2=64*1024;let searched=0;while(searched<limit){const len=Math.min(window2,limit-searched);const at2=limit-searched-len;const buf=Buffer.allocUnsafe(len);const{bytesRead}=await fh.read(buf,0,len,at2);const idx=buf.subarray(0,bytesRead).lastIndexOf(10);if(idx!==-1)return at2+idx+1;searched+=len}return 0}async readFromBeginning(){const cursor=await this.cursorAtBeginning();return this.read(cursor)}async cursorAtBeginning(){const fh=await open5(this.path,constants6.O_RDONLY|(constants6.O_NOFOLLOW??0));try{const st2=await fh.stat();return`${String(st2.dev)}:${String(st2.ino)}:0:${await _JsonlFileSource.sealAt(fh,0)}`}finally{await fh.close()}}end(){const fd=openSync2(this.path,constants6.O_RDONLY|(constants6.O_NOFOLLOW??0));try{const st2=fstatSync2(fd);const readAt=(len,position)=>{const buf=Buffer.allocUnsafe(len);return buf.subarray(0,readSync(fd,buf,0,len,position))};let at2=0;const window2=64*1024;for(let searched=0;searched<st2.size;){const len=Math.min(window2,st2.size-searched);const from=st2.size-searched-len;const idx=readAt(len,from).lastIndexOf(10);if(idx!==-1){at2=from+idx+1;break}searched+=len}const span=Math.min(at2,512);const seal=createHash12("sha256").update(readAt(span,at2-span)).digest("hex").slice(0,16);return Promise.resolve(`${String(st2.dev)}:${String(st2.ino)}:${at2}:${seal}`)}finally{closeSync2(fd)}}async read(cursor){const from=cursor===void 0?void 0:_JsonlFileSource.parseCursor(cursor);const fh=await open5(this.path,constants6.O_RDONLY|(constants6.O_NOFOLLOW??0));try{const st2=await fh.stat();const size=st2.size;const dev=String(st2.dev),ino=String(st2.ino);const here=async offset=>`${dev}:${ino}:${offset}:${await _JsonlFileSource.sealAt(fh,offset)}`;if(from===void 0)return{records:[],cursor:await here(await _JsonlFileSource.lastCompleteBoundary(fh,size))};if(from.dev!==dev||from.ino!==ino)throw new JsonlFileResetError(`JsonlFileSource: ${this.path} is not the file this cursor came from (cursor ${from.dev}:${from.ino}, now ${dev}:${ino}) \u2014 it was replaced or rotated`);if(from.offset>size)throw new JsonlFileResetError(`JsonlFileSource: cursor offset ${from.offset} is past end ${size} for ${this.path} \u2014 the file was truncated`);const seal=await _JsonlFileSource.sealAt(fh,from.offset);if(seal!==from.seal)throw new JsonlFileResetError(`JsonlFileSource: the bytes before offset ${from.offset} in ${this.path} have changed (seal ${from.seal} -> ${seal}) \u2014 the file was rewritten in place, not appended to`);if(from.offset===size)return{records:[],cursor:await here(from.offset)};const len=size-from.offset;const buf=Buffer.allocUnsafe(len);const{bytesRead}=await fh.read(buf,0,len,from.offset);const chunk=buf.subarray(0,bytesRead);const lastNl=chunk.lastIndexOf(10);if(lastNl===-1)return{records:[],cursor:await here(from.offset)};const records=[];const unreadable=[];const decoder=new TextDecoder("utf-8",{fatal:true});let at2=from.offset;for(const line of _JsonlFileSource.lines(chunk.subarray(0,lastNl))){const start=at2;at2+=line.length+1;if(_JsonlFileSource.isBlank(line))continue;let text3;try{text3=decoder.decode(line)}catch{unreadable.push({offset:start,bytes:line.length,reason:"not valid UTF-8"});continue}let value;try{value=JSON.parse(text3)}catch{unreadable.push({offset:start,bytes:line.length,reason:"not a JSON record"});continue}records.push({value,cursor:await here(at2)})}const end=from.offset+lastNl+1;if(at2!==end)throw new Error(`JsonlFileSource: internal cursor walk ended at ${at2} but the batch ends at ${end} in ${this.path}`);return{records,cursor:await here(end),...unreadable.length>0?{unreadable}:{}}}finally{await fh.close()}}static*lines(buf){let start=0;for(;;){const nl=buf.indexOf(10,start);if(nl===-1){yield buf.subarray(start);return}yield buf.subarray(start,nl);start=nl+1}}static isBlank(line){for(const b3 of line)if(b3!==32&&b3!==9&&b3!==13&&b3!==11&&b3!==12)return false;return true}};var HALT_RETRY_CEILING_MS=3e5;function eventPlaneStopped(opts){return(e3,retryInMs)=>opts.log(`AG-UI emitter stopped: ${e3.message}`+(retryInMs===null?"":retryInMs===0?"; re-establishing the event plane now":`; re-establishing the event plane in ${retryInMs}ms`))}var AguiEmitterHolder=class{startEmitter;hooks;emitter;boundPath;dead;startContext;retried=false;halts=0;reviveTimer;held=[];lastTurn;reviving=false;shut=false;chain=Promise.resolve();liveWait;constructor(startEmitter,hooks){this.startEmitter=startEmitter;this.hooks=hooks}get running(){return this.dead===void 0&&this.emitter!==void 0&&!this.emitter.stopped}get failure(){return this.dead}get closed(){return this.shut}async close(){this.shut=true;if(this.reviveTimer)clearTimeout(this.reviveTimer);this.reviveTimer=void 0;await this.chain}get path(){return this.boundPath}adopt(path4,context){this.bind(path4,context);this.enqueue(()=>this.ensureStarted(path4).then(()=>void 0))}bind(path4,context){if(this.boundPath!==void 0||typeof path4!=="string"||path4.length===0)return;this.boundPath=path4;this.startContext=context}flush(path4){this.bind(path4);this.enqueue(async()=>{const emitter=await this.ensureStarted(path4);if(!emitter||emitter.stopped)return;await this.holdForLive();await emitter.pump()})}async settle(emitter){while(emitter.waitingTerminals>0)await emitter.pump();const open7=emitter.openRunId;const owed=open7===void 0?void 0:emitter.takeOwed(open7);if(owed)await this.closeOpenRun(emitter,owed)}closeRun(timestamp,error51){if(this.shut||this.boundPath===void 0)return Promise.resolve();const terminal={timestamp,...error51?{error:error51}:{}};let at2;try{at2=Promise.resolve(this.hooks.sourceEnd(this.boundPath))}catch(e3){at2=Promise.reject(e3)}const taken=at2.then(()=>void 0,()=>void 0);const entry={terminal,at:at2};const live=this.emitter;const queued=this.dead===void 0&&live!==void 0&&!live.stopped;if(queued)live.queueTerminal(entry);else this.held.push(entry);this.enqueue(async()=>{const emitter=this.emitter;if(this.dead||!emitter||emitter.stopped)return;await this.holdForLive();if(this.held.includes(entry))this.handOver(emitter,entry);await this.settle(emitter)});return taken}async closeOpenRun(emitter,entry){const open7=emitter.openRunId;const cotal=open7===void 0?void 0:this.hooks.runMeta?.(open7);const{terminal}=entry;let runId;try{runId=await emitter.closeRun({timestamp:terminal.timestamp,...cotal?{cotal}:{},...terminal.error?{error:terminal.error}:{}})}catch(e3){if(open7!==void 0)this.held.unshift(entry);throw e3}if(runId!==null)this.hooks.onRunClosed?.(runId)}handOver(emitter,entry){this.held=this.held.filter(h3=>h3!==entry);emitter.queueTerminal(entry)}async ensureStarted(path4){if(this.dead)return void 0;if(typeof path4!=="string"||path4.length===0)return void 0;if(this.boundPath!==void 0&&this.boundPath!==path4){this.die(new Error(`AG-UI emitter is bound to transcript ${this.boundPath}; refusing to re-adopt ${path4} \u2014 a second session needs its own emitter and its own write-ahead log`));return void 0}if(this.emitter)return this.emitter;if(this.shut)return void 0;try{this.emitter=await this.startEmitter(path4,this.startContext);if(!this.reviving)for(const entry of[...this.held])this.handOver(this.emitter,entry);return this.emitter}catch(e3){this.die(e3);return void 0}}die(e3){if(this.dead)return;this.dead=e3;if(this.emitter!==void 0){const left=this.emitter.unsettled();this.held.push(...left.terminals);this.lastTurn={turn:left.lastTurn}}if(this.shut){this.hooks.onError(e3,null);return}const retryMs=this.hooks.retryMs??1e3;const delay3=e3 instanceof AguiEmitterHalted?Math.min(retryMs*2**this.halts++,HALT_RETRY_CEILING_MS):this.retried?retryMs:0;this.retried=true;this.reviveTimer=setTimeout(()=>this.revive(),delay3);this.hooks.onError(e3,delay3)}revive(){if(this.reviveTimer!==void 0)clearTimeout(this.reviveTimer);this.reviveTimer=void 0;if(this.boundPath===void 0)return;const path4=this.boundPath;this.dead=void 0;this.emitter=void 0;this.reviving=true;this.enqueue(async()=>{const emitter=await this.ensureStarted(path4);if(!emitter||emitter.stopped){this.reviving=false;return}await this.holdForLive();if(this.lastTurn){emitter.seedLastTurn(this.lastTurn.turn);this.lastTurn=void 0}for(const entry of[...this.held])this.handOver(emitter,entry);await emitter.pump();await this.settle(emitter);this.reviving=false;this.retried=false;this.halts=0})}holdForLive(){if(!this.hooks.waitLive)return Promise.resolve();this.liveWait??=this.hooks.waitLive().finally(()=>{this.liveWait=void 0});return this.liveWait}enqueue(step){if(this.shut)return;this.chain=this.chain.then(step).catch(e3=>this.die(e3))}async settled(){await this.chain}};var str=v3=>typeof v3==="string"?v3:void 0;var CONT=" \xB7 ";var TEXT_PREFIX="\xBB ";var THINK_PREFIX="(thinking) ";var TOOL_PREFIX="\u2699 ";var RESULT_PREFIX=" \u21B3 ";var BLOCK_START_CHARS=new Set([..."#>|`~=_*+-[<0123456789"," "]);function renderEvents(events){const lines=[];const text3=new Map;const reasoning=new Map;const toolName=new Map;const toolArgs=new Map;const emit=(first,cont,body)=>{const[head,...rest]=body.split("\n");lines.push(first+head);for(const l2 of rest)lines.push(cont+l2)};const flush=(map2,id2,first,cont,suffix="")=>{const acc=map2.get(id2);if(acc!==void 0&&acc.length>0)emit(first,cont,acc+suffix);map2.delete(id2)};for(const e3 of events){const type=typeof e3==="object"&&e3!==null?str(e3.type):void 0;switch(type){case AGUI_EVENT_TYPE.RUN_STARTED:emit("\u25B8 ",CONT,`run ${str(e3.runId)??"?"} started`);break;case AGUI_EVENT_TYPE.RUN_FINISHED:{const outcome=str(e3.outcome?.type);emit("\u25C2 ",CONT,`run ${str(e3.runId)??"?"} finished${outcome?` (${outcome})`:""}`);break}case AGUI_EVENT_TYPE.RUN_ERROR:{const code2=str(e3.code);emit("\u2717 ",CONT,`run error${code2?` [${code2}]`:""}: ${str(e3.message)??"(no message)"}`);break}case AGUI_EVENT_TYPE.TEXT_MESSAGE_START:text3.set(str(e3.messageId)??"","");break;case AGUI_EVENT_TYPE.TEXT_MESSAGE_CONTENT:{const id2=str(e3.messageId)??"";text3.set(id2,(text3.get(id2)??"")+(str(e3.delta)??""));break}case AGUI_EVENT_TYPE.TEXT_MESSAGE_END:flush(text3,str(e3.messageId)??"",TEXT_PREFIX,TEXT_PREFIX);break;case AGUI_EVENT_TYPE.REASONING_MESSAGE_START:reasoning.set(str(e3.messageId)??"","");break;case AGUI_EVENT_TYPE.REASONING_MESSAGE_CONTENT:{const id2=str(e3.messageId)??"";reasoning.set(id2,(reasoning.get(id2)??"")+(str(e3.delta)??""));break}case AGUI_EVENT_TYPE.REASONING_MESSAGE_END:flush(reasoning,str(e3.messageId)??"",THINK_PREFIX,CONT);break;case AGUI_EVENT_TYPE.TOOL_CALL_START:{const id2=str(e3.toolCallId)??"";toolName.set(id2,str(e3.toolCallName)??"?");toolArgs.set(id2,"");break}case AGUI_EVENT_TYPE.TOOL_CALL_ARGS:{const id2=str(e3.toolCallId)??"";toolArgs.set(id2,(toolArgs.get(id2)??"")+(str(e3.delta)??""));break}case AGUI_EVENT_TYPE.TOOL_CALL_END:{const id2=str(e3.toolCallId)??"";emit(TOOL_PREFIX,CONT,`${toolName.get(id2)??"?"}(${toolArgs.get(id2)??""})`);toolName.delete(id2);toolArgs.delete(id2);break}case AGUI_EVENT_TYPE.TOOL_CALL_RESULT:emit(RESULT_PREFIX,CONT,str(e3.content)??"(no content)");break;case AGUI_EVENT_TYPE.CUSTOM:{const failed=e3.name===TOOL_RESULT_EVENT?toolResultValue(e3.value)?.isError:void 0;if(failed!==void 0)emit(RESULT_PREFIX,CONT,failed?"failed":"done");else emit("\u2022 ",CONT,`custom ${str(e3.name)??"(unnamed)"}`);break}default:emit("\u2022 ",CONT,`unrecognised event ${JSON.stringify(type??null)}`)}}for(const id2 of[...text3.keys()])flush(text3,id2,TEXT_PREFIX,TEXT_PREFIX," \u2026");for(const id2 of[...reasoning.keys()])flush(reasoning,id2,THINK_PREFIX,CONT," \u2026");for(const id2 of[...toolName.keys()])emit(TOOL_PREFIX,CONT,`${toolName.get(id2)??"?"}(${toolArgs.get(id2)??""}) \u2026`);return lines}var aguiFramePartRenderer=Object.freeze({kind:"part-renderer",name:AGUI_FRAME_KIND,render(part){if(!isAguiFramePart(part))return`[not an AG-UI frame]`;const events=part.events;if(!Array.isArray(events)||events.length===0)return`[AG-UI frame carrying no events]`;const lines=renderEvents(events);return lines.length>0?lines.join("\n"):`[AG-UI frame with ${events.length} event(s) and nothing to show]`}});function registerAguiFramePartRenderer(){if(registry2.has("part-renderer",AGUI_FRAME_KIND))return;registry2.register(aguiFramePartRenderer)}registerAguiFramePartRenderer();import{connect as connect2,createServer}from"node:net";import{lstatSync as lstatSync6,unlinkSync as unlinkSync4}from"node:fs";var MAX_RECEIPT_BYTES=64;var HANDOFF_DEADLINE_MS=5e3;var LEGACY_WRITE_DEADLINE_MS=5e3;function formatInjection(items,options={}){if(!items.length)return void 0;const live=items.filter(item=>!item.historical);const history=items.filter(item=>item.historical);const format=options.metadata===false?fmtItem:fmtDeliveryItem;const blocks=[];if(live.length){const head=`\u{1F4E8} Cotal \u2014 ${live.length} new message${live.length===1?"":"s"} from peers:`;const tail=`(If this asks for work, do it with your own tools first and verify the result, then reply with cotal_dm / cotal_send \u2014 never report an action you did not actually perform. cotal_roster shows who's here.)`;blocks.push(`${head}
|
|
167
167
|
${live.map(format).join("\n")}
|
|
168
168
|
${tail}`)}if(history.length){blocks.push(`\u{1F4DA} Cotal \u2014 ${history.length} historical message${history.length===1?"":"s"} (catch-up context):
|
|
169
169
|
${history.map(format).join("\n")}
|
|
170
170
|
(This is replayed history, not new work. Do not act on or reply to these old requests unless the person explicitly asks.)`)}return blocks.join("\n\n")}function writeReply(sock,sealed,awaitHandoff){const{line}=sealed;return new Promise(resolve6=>{let settled=false;const done=ok3=>{if(settled)return;settled=true;resolve6(ok3)};sock.once("error",()=>done(false));sock.once("close",()=>done(false));if(!awaitHandoff){const stall=setTimeout(()=>done(false),LEGACY_WRITE_DEADLINE_MS);stall.unref?.();try{sock.end(line,(err3=>{clearTimeout(stall);done(!err3)}))}catch{clearTimeout(stall);done(false)}return}const deadline=setTimeout(()=>{sock.destroy();done(false)},HANDOFF_DEADLINE_MS);deadline.unref?.();let receipt2=Buffer.alloc(0);sock.on("data",d2=>{receipt2=Buffer.concat([receipt2,d2]);const nl=receipt2.indexOf(10);if(nl<0&&receipt2.length<=MAX_RECEIPT_BYTES)return;clearTimeout(deadline);const confirmed=nl>=0&&nl<=MAX_RECEIPT_BYTES&&sealed.receiptMatches(receipt2.subarray(0,nl).toString("latin1"));try{if(confirmed)sock.end();else sock.destroy()}catch{}done(confirmed)});try{sock.write(line,err3=>{if(!err3)return;clearTimeout(deadline);done(false)})}catch{clearTimeout(deadline);done(false)}})}function startControlServer(agent,endpoint,handle,opts={}){const{path:path4}=endpoint;assertControlEndpoint(endpoint);const server=createServer(sock=>{sock.on("error",()=>{});serverExchange(sock,endpoint,({request,seal})=>void serve(sock,request,seal))});const serve=async(sock,request,seal)=>{let frame;try{frame=JSON.parse(request)}catch{sock.destroy();return}const op=frame.op;if(op==="shutdown"){try{sock.end(seal(JSON.stringify({ok:true})).line)}catch{}opts.onShutdown?.();return}if(op==="session"){const sessionId=opts.onSession?.();try{sock.end(seal(JSON.stringify(sessionId?{ok:true,sessionId}:{ok:false,error:"session not ready"})).line)}catch{}return}const ev=frame.event??{};const awaitHandoff=frame.handoff===true;const reply=await handle(agent,ev);const delivered=await writeReply(sock,seal(JSON.stringify(reply)),awaitHandoff);opts.onReply?.(ev,delivered,awaitHandoff)};let bound=false;let retried=false;const emit=server.emit.bind(server);server.emit=(event,...args)=>{const error51=args[0];if(event!=="error"||bound||retried||process.platform==="win32"||path4.startsWith("\0")||error51?.code!=="EADDRINUSE")return emit(event,...args);retried=true;let original;try{original=lstatSync6(path4);if(!original.isSocket())return emit(event,...args)}catch(e3){if(e3.code!=="ENOENT")return emit(event,...args)}const probe=connect2(path4);let settled=false;const finish=stale=>{if(settled)return;settled=true;clearTimeout(deadline);probe.destroy();server.off("close",cancel);if(!stale){emit(event,...args);return}try{const current=lstatSync6(path4);if(!original||!current.isSocket()||current.dev!==original.dev||current.ino!==original.ino){emit(event,...args);return}unlinkSync4(path4)}catch(e3){if(e3.code!=="ENOENT"){emit("error",e3);return}}server.listen(path4)};const cancel=()=>{settled=true;clearTimeout(deadline);probe.destroy()};const deadline=setTimeout(()=>finish(false),250);server.once("close",cancel);probe.once("connect",()=>finish(false));probe.once("error",e3=>finish(e3.code==="ECONNREFUSED"||e3.code==="ENOENT"));return true};server.on("error",e3=>{process.stderr.write(`[cotal-connector] control server error: ${e3.message}
|
|
171
171
|
`);if(opts.fatalBind&&!bound)process.exit(1)});try{assertControlSocketDir(path4)}catch(e3){process.nextTick(()=>server.emit("error",e3));return server}server.listen(path4,()=>{bound=true;process.stderr.write(`[cotal-connector] control socket: ${path4}
|
|
172
|
-
`)});return server}var ARRIVES={"claude-code":'Peer messages may arrive as <channel source="cotal" from="<name>" role="<role>" kind="dm|channel|anycast" channel="<name>">\u2026</channel> blocks pushed into your session, or as a block marked \u{1F4E8} at the start of a turn.',codex:"Peer messages are delivered into your turns as blocks marked \u{1F4E8}.",jcode:"Peer messages are delivered into your turns as blocks marked \u{1F4E8}.",opencode:"Peer messages are delivered into your turns as blocks marked \u{1F4E8}.",hermes:"Peer messages are delivered into your turns as blocks marked \u{1F4E8}.",pi:"Peer messages from the Cotal mesh arrive as user messages tagged \u{1F4E8}.",gateway:void 0};var REPLY_GUIDANCE="Your chat output is not delivered to peers. When a reply is warranted, send it with cotal_dm (back to that peer), cotal_send (to a channel), or cotal_anycast (to a role). Use cotal_roster to see who is present, cotal_inbox to pull anything you may have missed, and cotal_status to report what you are doing.";var ATTENTION_GUIDANCE="If you need to concentrate, cotal_status also sets your attention \u2014 dnd (channel chatter stops waking you; it still arrives on your next turn) or focus (only DMs and @mentions reach your context \u2014 pull the held chatter with cotal_inbox). To silence one channel instead of all of them, cotal_channel_mode sets it quiet (still buffered but pull-only via cotal_inbox; @mentions still wake and inject) or muted (you stop receiving it, @mentions included).";var REPLY_ETIQUETTE='Reply only when a reply is actually needed: a silent acknowledgement is correct, and "agreed/thanks/good point" messages are noise.';function briefing(config2,harness){const arrives=ARRIVES[harness];return[`You are connected to the Cotal mesh as "${config2.name}"${config2.role?` (role: ${config2.role})`:""} in space "${config2.space}".`,ORIENTATION_BOOTSTRAP,TOOL_STEER,feedbackLine(config2).trim(),MESH_FIRST_STEER,WORKFLOW_STEER,CHANNEL_GUIDANCE,`Other agents coordinate with you here as lateral peers. ${arrives?`${arrives} `:""}${REPLY_GUIDANCE}`,ATTENTION_GUIDANCE,REPLY_ETIQUETTE].join("\n\n")}init_types();var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");init_types();var import_ajv_formats=__toESM(require_dist2(),1);init_types();init_types();var McpZodTypeKind;(function(McpZodTypeKind2){McpZodTypeKind2["Completable"]="McpCompletable"})(McpZodTypeKind||(McpZodTypeKind={}));init_types();init_types();var GATEWAY_TOOLS=new Set(["cotal_orientation","cotal_connection_status","cotal_roster","cotal_docs","cotal_inbox","cotal_send","cotal_dm","cotal_anycast","cotal_status","cotal_channel_info","cotal_channels","cotal_channel_mode","cotal_join","cotal_leave"]);var NATIVE_GATEWAY_TOOLS=new Set([...GATEWAY_TOOLS,"cotal_spawn","cotal_persona","cotal_personas","cotal_despawn","cotal_run","cotal_turn_participate","cotal_yield","cotal_reconnect"]);var SELECTION_SHAPE={channels:external_exports.array(external_exports.strictObject({channel:external_exports.string().min(1),access:external_exports.enum(["read","read-post"])})).max(SELECTION_MAX_ITEMS).optional().describe("Channels this connection may join and read, or read and post to. A pattern such as team.* or team.> covers every matching channel, including ones created later."),role:external_exports.string().min(1).optional().describe("A role to hold, so role requests (cotal_anycast) reach this connection."),capabilities:external_exports.array(external_exports.enum(["spawn","run"])).optional().describe("spawn: start and stop agents through a manager. run: start and manage workflow runs.")};var SEND_CHANNEL=`Channel to send on. Omit it to use this connection's default, the first concrete channel it reads and may post to (cotal_orientation lists both); with none, an omitted channel is refused. ${PATTERN_SEND_HELP} Reply on the channel you received a message on.`;var CONNECTION_ID=external_exports.string().min(1).describe("The connection_id cotal_connect returned in THIS conversation. Never reuse another conversation's.");var GATEWAY_LISTENING="Messages reach you only when you call a tool: to listen, call cotal_wait, which returns as soon as a message arrives. When the person asks you to stay on Cotal or keep listening, call cotal_wait again each time it returns and handle each message as it arrives, until they ask you to stop.";var GATEWAY_CONNECTING="Cotal connects this conversation to the person's Cotal space after they approve its permissions. Call cotal_connect with a short name. If approval is pending, show the person its link and wait for their decision; do not approve for them or poll. Then resume the same request as directed. Only a successful connection returns connection_id, required on every other cotal tool call. Each conversation needs its own connection. Never reuse another conversation's connection_id or approval_id.";var GATEWAY_INSTRUCTIONS=`${GATEWAY_CONNECTING} ${GATEWAY_LISTENING}`;var MAX_HOOK_REPLY_BYTES=1<<20;import{randomUUID as
|
|
172
|
+
`)});return server}var ARRIVES={"claude-code":'Peer messages may arrive as <channel source="cotal" from="<name>" role="<role>" kind="dm|channel|anycast" channel="<name>">\u2026</channel> blocks pushed into your session, or as a block marked \u{1F4E8} at the start of a turn.',codex:"Peer messages are delivered into your turns as blocks marked \u{1F4E8}.",jcode:"Peer messages are delivered into your turns as blocks marked \u{1F4E8}.",opencode:"Peer messages are delivered into your turns as blocks marked \u{1F4E8}.",hermes:"Peer messages are delivered into your turns as blocks marked \u{1F4E8}.",pi:"Peer messages from the Cotal mesh arrive as user messages tagged \u{1F4E8}.",gateway:void 0};var REPLY_GUIDANCE="Your chat output is not delivered to peers. When a reply is warranted, send it with cotal_dm (back to that peer), cotal_send (to a channel), or cotal_anycast (to a role). Use cotal_roster to see who is present, cotal_inbox to pull anything you may have missed, and cotal_status to report what you are doing.";var ATTENTION_GUIDANCE="If you need to concentrate, cotal_status also sets your attention \u2014 dnd (channel chatter stops waking you; it still arrives on your next turn) or focus (only DMs and @mentions reach your context \u2014 pull the held chatter with cotal_inbox). To silence one channel instead of all of them, cotal_channel_mode sets it quiet (still buffered but pull-only via cotal_inbox; @mentions still wake and inject) or muted (you stop receiving it, @mentions included).";var REPLY_ETIQUETTE='Reply only when a reply is actually needed: a silent acknowledgement is correct, and "agreed/thanks/good point" messages are noise.';function briefing(config2,harness){const arrives=ARRIVES[harness];return[`You are connected to the Cotal mesh as "${config2.name}"${config2.role?` (role: ${config2.role})`:""} in space "${config2.space}".`,ORIENTATION_BOOTSTRAP,TOOL_STEER,feedbackLine(config2).trim(),MESH_FIRST_STEER,WORKFLOW_STEER,CHANNEL_GUIDANCE,`Other agents coordinate with you here as lateral peers. ${arrives?`${arrives} `:""}${REPLY_GUIDANCE}`,ATTENTION_GUIDANCE,REPLY_ETIQUETTE].join("\n\n")}init_types();var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");init_types();var import_ajv_formats=__toESM(require_dist2(),1);init_types();init_types();var McpZodTypeKind;(function(McpZodTypeKind2){McpZodTypeKind2["Completable"]="McpCompletable"})(McpZodTypeKind||(McpZodTypeKind={}));init_types();init_types();var GATEWAY_TOOLS=new Set(["cotal_orientation","cotal_connection_status","cotal_roster","cotal_docs","cotal_inbox","cotal_send","cotal_dm","cotal_anycast","cotal_status","cotal_channel_info","cotal_channels","cotal_channel_mode","cotal_join","cotal_leave"]);var NATIVE_GATEWAY_TOOLS=new Set([...GATEWAY_TOOLS,"cotal_spawn","cotal_persona","cotal_personas","cotal_despawn","cotal_run","cotal_turn_participate","cotal_yield","cotal_reconnect"]);var SELECTION_SHAPE={channels:external_exports.array(external_exports.strictObject({channel:external_exports.string().min(1),access:external_exports.enum(["read","read-post"])})).max(SELECTION_MAX_ITEMS).optional().describe("Channels this connection may join and read, or read and post to. A pattern such as team.* or team.> covers every matching channel, including ones created later."),role:external_exports.string().min(1).optional().describe("A role to hold, so role requests (cotal_anycast) reach this connection."),capabilities:external_exports.array(external_exports.enum(["spawn","run"])).optional().describe("spawn: start and stop agents through a manager. run: start and manage workflow runs.")};var SEND_CHANNEL=`Channel to send on. Omit it to use this connection's default, the first concrete channel it reads and may post to (cotal_orientation lists both); with none, an omitted channel is refused. ${PATTERN_SEND_HELP} Reply on the channel you received a message on.`;var CONNECTION_ID=external_exports.string().min(1).describe("The connection_id cotal_connect returned in THIS conversation. Never reuse another conversation's.");var GATEWAY_LISTENING="Messages reach you only when you call a tool: to listen, call cotal_wait, which returns as soon as a message arrives. When the person asks you to stay on Cotal or keep listening, call cotal_wait again each time it returns and handle each message as it arrives, until they ask you to stop.";var GATEWAY_CONNECTING="Cotal connects this conversation to the person's Cotal space after they approve its permissions. Call cotal_connect with a short name. If approval is pending, show the person its link and wait for their decision; do not approve for them or poll. Then resume the same request as directed. Only a successful connection returns connection_id, required on every other cotal tool call. Each conversation needs its own connection. Never reuse another conversation's connection_id or approval_id.";var GATEWAY_INSTRUCTIONS=`${GATEWAY_CONNECTING} ${GATEWAY_LISTENING}`;var MAX_HOOK_REPLY_BYTES=1<<20;import{randomUUID as randomUUID15}from"node:crypto";import{spawn as spawn2}from"node:child_process";import{join as join17,resolve as resolve5}from"node:path";var API_VERSION_MAJOR=1;import os from"node:os";import path from"node:path";import{createHash as createHash13}from"node:crypto";function runtimeDir(){const explicit=process.env.JCODE_RUNTIME_DIR;if(explicit)return explicit;const xdg=process.env.XDG_RUNTIME_DIR;if(xdg)return xdg;if(process.platform==="darwin"&&process.env.TMPDIR){return process.env.TMPDIR}return path.join(os.tmpdir(),`jcode-${userDiscriminator()}`)}function userDiscriminator(){const raw=process.platform==="win32"?process.env.USERNAME??process.env.USER:process.env.UID??process.env.USER;return sanitize(raw??"user")}function sanitize(raw){const out=raw.split("").filter(ch=>/[A-Za-z0-9\-_]/.test(ch)).slice(0,64).join("");return out===""?"user":out}function transportEndpoint(socketPath){if(process.platform!=="win32")return socketPath;const stem=(path.parse(socketPath).name.match(/[A-Za-z0-9\-_]/g)??[]).join("").slice(0,32)||"jcode";const normalized=socketPath.replace(/\\/g,"/").toLowerCase();const hash2=createHash13("sha256").update(normalized).digest("hex").slice(0,16);return`\\\\.\\pipe\\${stem}-${hash2}`}function apiSocketPath(){return process.env.JCODE_API_SOCKET??path.join(runtimeDir(),"jcode-api.sock")}var NdjsonDecoder=class{buffer="";push(chunk){this.buffer+=typeof chunk==="string"?chunk:chunk.toString("utf8");const out=[];let index2=this.buffer.indexOf("\n");while(index2!==-1){const line=this.buffer.slice(0,index2).trim();this.buffer=this.buffer.slice(index2+1);if(line!=="")out.push(JSON.parse(line));index2=this.buffer.indexOf("\n")}return out}};function encodeFrame(frame){return`${JSON.stringify(frame)}
|
|
173
173
|
`}var HarnessError=class extends Error{code;constructor(code2,message){super(`${code2}: ${message}`);this.code=code2;this.name="HarnessError"}};import{spawn}from"node:child_process";import fs from"node:fs";import os2 from"node:os";import path3 from"node:path";import{createRequire}from"node:module";import path2 from"node:path";var require2=createRequire(import.meta.url);var PLATFORM_PACKAGES={"linux-x64":"@1jehuang/jcode-linux-x64","linux-arm64":"@1jehuang/jcode-linux-arm64","darwin-x64":"@1jehuang/jcode-darwin-x64","darwin-arm64":"@1jehuang/jcode-darwin-arm64","win32-x64":"@1jehuang/jcode-win32-x64","win32-arm64":"@1jehuang/jcode-win32-arm64"};function platformBinaryPackage(platform=process.platform,arch=process.arch){return PLATFORM_PACKAGES[`${platform}-${arch}`]}function bundledJcodeBinary(){const packageName=platformBinaryPackage();if(!packageName)return void 0;try{const manifest=require2.resolve(`${packageName}/package.json`);return path2.join(path2.dirname(manifest),"bin",process.platform==="win32"?"jcode.exe":"jcode")}catch(error51){const code2=error51.code;if(code2==="MODULE_NOT_FOUND")return void 0;throw error51}}var CREDENTIAL_FILES=["auth.json","openai-auth.json","antigravity_oauth.json","gemini_oauth.json","google_oauth.json","google_credentials.json","config.toml"];var SHARED_FILES=new Set(CREDENTIAL_FILES.filter(name2=>name2!=="config.toml"));var APP_CONFIG_DIRNAME="jcode";var EXTERNAL_CREDENTIAL_FILES=[".claude/.credentials.json",".codex/auth.json",".gemini/oauth_creds.json",".cursor/auth.json",".config/cursor/auth.json","AppData/Roaming/Cursor/auth.json",".config/Cursor/User/globalStorage/state.vscdb",".config/cursor/User/globalStorage/state.vscdb","Library/Application Support/Cursor/User/globalStorage/state.vscdb","Library/Application Support/cursor/User/globalStorage/state.vscdb","AppData/Roaming/Cursor/User/globalStorage/state.vscdb","AppData/Roaming/cursor/User/globalStorage/state.vscdb",".config/github-copilot/hosts.json",".config/github-copilot/apps.json",".copilot/config.json",".hermes/auth.json",".pi/agent/auth.json",".openclaw/agent/auth.json",".openclaw/credentials/oauth.json",".local/share/opencode/auth.json"];function ensureInstanceDirectory(root,relative4){if(path3.isAbsolute(relative4)||relative4.split(/[\\/]+/u).includes("..")){throw new HarnessError("invalid_instance_home",`unsafe instance path: ${relative4}`)}let current=root;for(const part of relative4.split(/[\\/]+/u).filter(Boolean)){current=path3.join(current,part);try{const stats=fs.lstatSync(current);if(stats.isSymbolicLink()){fs.unlinkSync(current);fs.mkdirSync(current,{mode:448})}else if(!stats.isDirectory()){throw new HarnessError("invalid_instance_home",`instance credential path is not a directory: ${current}`)}}catch(error51){if(error51.code!=="ENOENT")throw error51;fs.mkdirSync(current,{mode:448})}}return current}function linkCredentialFile(source,root,relative4){let sourceStats;try{sourceStats=fs.statSync(source)}catch{return false}if(!sourceStats.isFile())return false;const parent=ensureInstanceDirectory(root,path3.dirname(relative4));const destination=path3.join(parent,path3.basename(relative4));try{fs.unlinkSync(destination)}catch{}fs.symlinkSync(source,destination);return true}function userJcodeHome(){return process.env.JCODE_HOME??path3.join(os2.homedir(),".jcode")}function userAppConfigDir(){if(process.platform==="darwin"){return path3.join(os2.homedir(),"Library","Application Support",APP_CONFIG_DIRNAME)}if(process.platform==="win32"){const appData=process.env.APPDATA??path3.join(os2.homedir(),"AppData","Roaming");return path3.join(appData,APP_CONFIG_DIRNAME)}const xdg=process.env.XDG_CONFIG_HOME??path3.join(os2.homedir(),".config");return path3.join(xdg,APP_CONFIG_DIRNAME)}function inheritCredentials(fromHome,toHome){fs.mkdirSync(toHome,{recursive:true,mode:448});const toStats=fs.lstatSync(toHome);if(toStats.isSymbolicLink()||!toStats.isDirectory()){throw new HarnessError("invalid_instance_home",`instance home must be a real directory, not a link or file: ${toHome}`)}if(fs.existsSync(fromHome)&&fs.realpathSync(fromHome)===fs.realpathSync(toHome)){throw new HarnessError("invalid_instance_home","instance home must be different from the user's jcode home")}const inherited=[];for(const name2 of CREDENTIAL_FILES){const source=path3.join(fromHome,name2);if(!fs.existsSync(source))continue;const destination=path3.join(toHome,name2);if(SHARED_FILES.has(name2)){linkCredentialFile(source,toHome,name2)}else{fs.copyFileSync(source,destination);fs.chmodSync(destination,384)}inherited.push(name2)}const userConfig=userAppConfigDir();try{for(const entry of fs.readdirSync(userConfig,{withFileTypes:true})){if(!entry.isFile()&&!entry.isSymbolicLink()||!entry.name.endsWith(".env"))continue;const relative4=`config/${APP_CONFIG_DIRNAME}/${entry.name}`;if(linkCredentialFile(path3.join(userConfig,entry.name),toHome,relative4)){inherited.push(relative4)}}}catch{}for(const relative4 of EXTERNAL_CREDENTIAL_FILES){const source=path3.join(os2.homedir(),relative4);const instanceRelative=path3.join("external",relative4);if(linkCredentialFile(source,toHome,instanceRelative)){inherited.push(`external/${relative4}`)}}const openclawAgents=path3.join(os2.homedir(),".openclaw","agents");try{for(const agent of fs.readdirSync(openclawAgents,{withFileTypes:true})){if(!agent.isDirectory())continue;for(const name2 of["auth-profiles.json","auth.json"]){const relative4=path3.join(".openclaw","agents",agent.name,"agent",name2);if(linkCredentialFile(path3.join(os2.homedir(),relative4),toHome,path3.join("external",relative4))){inherited.push(`external/${relative4}`)}}}}catch{}return inherited}function readDaemonPidSync(jcodeHome,runtimeDir2){let raw;try{raw=fs.readFileSync(path3.join(jcodeHome,"servers.json"),"utf8")}catch{return void 0}let registry4;try{registry4=JSON.parse(raw)}catch{return void 0}const socket=path3.join(runtimeDir2,"jcode.sock");for(const entry of Object.values(registry4)){if(entry?.socket===socket&&typeof entry.pid==="number"&&entry.pid>1){return entry.pid}}return void 0}async function stopInstanceDaemon(_binary,jcodeHome,runtimeDir2){const pid=readDaemonPidSync(jcodeHome,runtimeDir2);if(pid===void 0)return;const signal=sig=>{try{process.kill(-pid,sig)}catch{try{process.kill(pid,sig)}catch{}}};signal("SIGTERM");const gracePeriod=Date.now()+2e3;while(Date.now()<gracePeriod){if(!processExists(pid))return;await new Promise(resolve6=>setTimeout(resolve6,50))}signal("SIGKILL");const hardDeadline=Date.now()+5e3;while(Date.now()<hardDeadline){if(!processExists(pid))return;await new Promise(resolve6=>setTimeout(resolve6,50))}}function processExists(pid){try{process.kill(pid,0);return true}catch{return false}}function removeInstanceHome(home){const resolvedHome=path3.resolve(home);const tempRoot=path3.resolve(os2.tmpdir());if(path3.dirname(resolvedHome)!==tempRoot||!path3.basename(resolvedHome).startsWith("jcode-sdk-instance-")){return}const walk=target2=>{let stats;try{stats=fs.lstatSync(target2)}catch{return}if(stats.isSymbolicLink()){fs.unlinkSync(target2);return}if(stats.isDirectory()){for(const entry of fs.readdirSync(target2)){walk(path3.join(target2,entry))}fs.rmdirSync(target2);return}fs.unlinkSync(target2)};try{walk(home)}catch{}}async function launchInstance(options={}){const binary=options.binary??bundledJcodeBinary()??"jcode";const ephemeral=options.jcodeHome===void 0;const jcodeHome=options.jcodeHome??fs.mkdtempSync(path3.join(os2.tmpdir(),"jcode-sdk-instance-"));fs.mkdirSync(jcodeHome,{recursive:true,mode:448});const runtimeDir2=path3.join(jcodeHome,"run");fs.mkdirSync(runtimeDir2,{recursive:true,mode:448});const socketPath=path3.join(runtimeDir2,"jcode-api.sock");for(const stale of["jcode-api.sock","jcode.sock","jcode-debug.sock","jcode.sock.hash"]){try{fs.unlinkSync(path3.join(runtimeDir2,stale))}catch{}}if(options.inheritLogins??true){inheritCredentials(userJcodeHome(),jcodeHome)}const child=spawn(binary,["api-bridge","--api-socket",socketPath],{cwd:options.workingDir??process.cwd(),env:{...process.env,JCODE_HOME:jcodeHome,JCODE_RUNTIME_DIR:runtimeDir2,JCODE_API_SOCKET:socketPath,JCODE_SOCKET:path3.join(runtimeDir2,"jcode.sock"),...options.env},stdio:["ignore","ignore",options.inheritStderr?"inherit":"pipe"],detached:false});let stderr="";child.stderr?.on("data",chunk=>{stderr=(stderr+chunk.toString()).slice(-4e3)});let exited;child.once("exit",(code2,signal)=>{exited={code:code2,signal}});let spawnError;child.once("error",error51=>{spawnError=error51;exited={code:null,signal:null}});const shutdown=async()=>{if(spawnError){if(ephemeral)removeInstanceHome(jcodeHome);return}await stopInstanceDaemon(binary,jcodeHome,runtimeDir2);if(exited===void 0){child.kill("SIGTERM");await new Promise(resolve6=>{const timer2=setTimeout(()=>{child.kill("SIGKILL");resolve6()},3e3);timer2.unref?.();child.once("exit",()=>{clearTimeout(timer2);resolve6()})})}if(ephemeral){const deadline2=Date.now()+(options.cleanupTimeoutMs??3e4);while(Date.now()<deadline2){removeInstanceHome(jcodeHome);await new Promise(resolve6=>setTimeout(resolve6,250));if(fs.existsSync(jcodeHome))continue;await new Promise(resolve6=>setTimeout(resolve6,750));if(!fs.existsSync(jcodeHome))return}if(fs.existsSync(jcodeHome)){process.emitWarning(`jcode instance home was still being written to and could not be removed: ${jcodeHome}`)}}};const reapOnExit=()=>{try{if(exited===void 0)child.kill("SIGTERM")}catch{}const pid=readDaemonPidSync(jcodeHome,runtimeDir2);if(pid!==void 0){try{process.kill(-pid,"SIGKILL")}catch{try{process.kill(pid,"SIGKILL")}catch{}}}if(ephemeral){try{removeInstanceHome(jcodeHome)}catch{}}};process.once("exit",reapOnExit);const deadline=Date.now()+(options.startupTimeoutMs??3e4);while(Date.now()<deadline){if(spawnError){process.removeListener("exit",reapOnExit);await shutdown();const binaryName=binary;const platformPackage=platformBinaryPackage();throw new HarnessError("jcode_not_found",spawnError.code==="ENOENT"?`could not run \`${binaryName}\`: jcode is not installed, or not on PATH. `+(platformPackage?`The bundled runtime package (${platformPackage}) is missing. Reinstall without --omit=optional, install jcode from https://jcode.sh, or pass \`binary\` with its full path.`:"Install jcode from https://jcode.sh, or pass `binary` with its full path."):`could not run \`${binaryName}\`: ${spawnError.message}`)}if(exited){process.removeListener("exit",reapOnExit);await shutdown();throw new HarnessError("startup_failed",`jcode exited during startup (code ${exited.code}, signal ${exited.signal})`+(stderr?`:
|
|
174
174
|
${stderr.trim()}`:""))}if(fs.existsSync(socketPath)){return{socketPath,jcodeHome,process:child,shutdown:async()=>{process.removeListener("exit",reapOnExit);await shutdown()}}}await new Promise(resolve6=>setTimeout(resolve6,50))}process.removeListener("exit",reapOnExit);await shutdown();throw new HarnessError("startup_timeout",`jcode did not create its API socket at ${socketPath} within the startup timeout`+(stderr?`:
|
|
175
175
|
${stderr.trim()}`:""))}import net from"node:net";import{EventEmitter as EventEmitter3}from"node:events";var import_ajv=__toESM(require_ajv(),1);var StructuredOutputError=class extends HarnessError{attempts;validationErrors;lastText;constructor(attempts){const last=attempts[attempts.length-1];const count=attempts.length;const summary2=last?.errors.map(formatIssue).join("; ")||"no structured output attempts ran";super("structured_output_invalid",`model did not produce valid structured output after ${count} attempt${count===1?"":"s"}: ${summary2}`);this.name="StructuredOutputError";this.attempts=attempts;this.validationErrors=last?.errors??[];this.lastText=last?.text??""}};var ajv=new import_ajv.Ajv({allErrors:true,coerceTypes:false,removeAdditional:false,useDefaults:false,strict:false,validateSchema:true});function compileStructuredSchema(schema){try{return ajv.compile(schema)}catch(error51){const message=error51 instanceof Error?error51.message:String(error51);throw new HarnessError("structured_schema_invalid",message)}}function validateStructuredText(text3,validate2){const parsed=parseJsonFromText(text3);if(!parsed.ok)return{ok:false,errors:[parsed.error]};if(validate2(parsed.value)){return{ok:true,data:parsed.value,errors:[]}}return{ok:false,errors:normalizeAjvErrors(validate2.errors??[])}}function buildStructuredPrompt(content,schema){return`${content}
|
|
@@ -185,7 +185,7 @@ ${mesh}`:mesh}function constantTokenMatches(presented,expected){if(typeof presen
|
|
|
185
185
|
`)}finally{rebinding=false}})()},RELAY_REBIND_POLL_MS);watch.unref?.()}return server}function closeServer(server){return new Promise(resolve6=>server?.close(()=>resolve6())??resolve6())}async function retireRelay(server,endpoint){await closeServer(server);if(process.platform!=="win32")rmSync5(endpoint.dir,{recursive:true,force:true})}var SEAT_ATTRIBUTION_ENV=new Set(["COTAL_SPACE","COTAL_MANAGER_INSTANCE","COTAL_NAME","COTAL_ID","COTAL_LIFECYCLE_UID","COTAL_ACCEPTED_TOKEN","COTAL_HOME"]);function noCotalEnv(){const env={};for(const[key,value]of Object.entries(process.env))if(value!==void 0&&!key.startsWith("COTAL_"))env[key]=value;return env}async function runJcodeHost(){const config2=configFromEnv();config2.connector="jcode";const control=controlFromEnv();if(!control)throw new Error("jcode connector: managed session has no control endpoint");const binary=process.env.COTAL_JCODE_BIN?.trim()||"jcode";const tuiOverride=envFlag(process.env,"COTAL_JCODE_TUI");const bootPrompt=process.env.COTAL_JCODE_PROMPT?.trim();const onceUid=process.env.COTAL_JCODE_ONCE==="1"?config2.lifecycleUid:void 0;if(process.env.COTAL_JCODE_ONCE==="1"&&!onceUid)throw new Error("jcode connector: a once seat has no lifecycle uid");let pendingKickoff=bootPrompt;const readinessBudgetMs=readinessTurnTimeoutMs();const requestTimeoutMs=requestTimeoutOverrideMs();const eventsArmed=eventPlaneArmed(config2);const eventsWorkspaceRoot=eventsArmed?resolveEventsStateRoot(process.env):void 0;const def=process.env.COTAL_AGENT_FILE?.trim()?loadAgentFile(process.env.COTAL_AGENT_FILE.trim()):void 0;const cwd=process.cwd();assertNoProjectMcpConfig(cwd);const home=privateAgentHome(config2.space,config2.name);installJcodeDiagnosticLog(home);try{const stopped=await stopOrphanedTree({home});if(stopped.length)writeJcodeDiagnostic(`[cotal-jcode] stopped ${stopped.length} Jcode process(es) left running by a previous lifecycle of this seat
|
|
186
186
|
`)}catch(error51){writeJcodeDiagnostic(`[cotal-jcode] ${error51.message}
|
|
187
187
|
`)}let socketHome;const resumeSource=process.env.COTAL_JCODE_RESUME?.trim();let fork;try{mirrorJcodeCredentials(home);if(resumeSource){const sourceHome=process.env.COTAL_JCODE_RESUME_HOME?.trim();if(!sourceHome)throw new Error("COTAL_JCODE_RESUME_HOME is not set \u2014 the launch must name the home it validated the source in");fork=forkJcodeSession({sourceHome,sessionId:resumeSource,seatHome:home,cwd})}socketHome=shortSocketHome(home)}catch(error51){if(error51 instanceof JcodeCursorStateUnreadable)throw error51;throw new JcodeConnectorError("private_state","jcode connector: the seat's private Jcode state could not be prepared",{cause:error51})}const removeCredentials=()=>{try{removeJcodeCredentials(home)}catch(error51){writeJcodeDiagnostic(`[cotal-jcode] the seat's credential copies could not be removed: ${error51.message}
|
|
188
|
-
`)}};const relay=relayEndpoint(config2.space,config2.name);scrubLaunchMaterial();const seatEnv={};for(const[key,value]of Object.entries(process.env)){if(value!==void 0&&SEAT_ATTRIBUTION_ENV.has(key))seatEnv[key]=value;if(key.startsWith("COTAL_"))delete process.env[key]}const agent=new MeshAgent(config2,void 0,{eventsArmed,eventsWorkspaceRoot});const relayServer=await startRelay(agent,config2,relay);writeMcpConfig(home,relay,config2);let eventLock;let mapper;const eventWaitStop=new AbortController;const events=eventsArmed?new AguiEmitterHolder(async journalPath=>{const workspaceRoot=eventsWorkspaceRoot;if(!sessionId)throw new Error("jcode connector: cannot start AG-UI without a Harness session id");const threadId=sessionId;const expectedPath=jcodeJournalPath(socketHome.jcodeHome,threadId);if(resolve5(journalPath)!==resolve5(expectedPath))throw new Error(`jcode connector: event source ${journalPath} does not belong to session ${threadId}`);const principal=principalKey(agent.ep.principal.owner,agent.ep.principal.actor).key;const{walPath,subjectPath,lock}=await ensureEventWalDir({workspaceRoot,space:config2.space,principal,threadId});eventLock=lock;const subjectFrontier=await FileSubjectFrontier.open(subjectPath,{space:config2.space,principal});const wal=await EventWal.open(walPath,{space:config2.space,threadId,principal,subjectMayExist:false});await initializeJcodeEventBoundary(journalPath,wal);const resumeBrackets=wal.pending===null?wal.brackets:wal.pending.brackets;mapper=createJcodeMapper({threadId,mintRunId:()=>
|
|
188
|
+
`)}};const relay=relayEndpoint(config2.space,config2.name);scrubLaunchMaterial();const seatEnv={};for(const[key,value]of Object.entries(process.env)){if(value!==void 0&&SEAT_ATTRIBUTION_ENV.has(key))seatEnv[key]=value;if(key.startsWith("COTAL_"))delete process.env[key]}const agent=new MeshAgent(config2,void 0,{eventsArmed,eventsWorkspaceRoot});const relayServer=await startRelay(agent,config2,relay);writeMcpConfig(home,relay,config2);let eventLock;let mapper;const eventWaitStop=new AbortController;const events=eventsArmed?new AguiEmitterHolder(async journalPath=>{const workspaceRoot=eventsWorkspaceRoot;if(!sessionId)throw new Error("jcode connector: cannot start AG-UI without a Harness session id");const threadId=sessionId;const expectedPath=jcodeJournalPath(socketHome.jcodeHome,threadId);if(resolve5(journalPath)!==resolve5(expectedPath))throw new Error(`jcode connector: event source ${journalPath} does not belong to session ${threadId}`);const principal=principalKey(agent.ep.principal.owner,agent.ep.principal.actor).key;const{walPath,subjectPath,lock}=await ensureEventWalDir({workspaceRoot,space:config2.space,principal,threadId});eventLock=lock;const subjectFrontier=await FileSubjectFrontier.open(subjectPath,{space:config2.space,principal});const wal=await EventWal.open(walPath,{space:config2.space,threadId,principal,subjectMayExist:false});await initializeJcodeEventBoundary(journalPath,wal);const resumeBrackets=wal.pending===null?wal.brackets:wal.pending.brackets;mapper=createJcodeMapper({threadId,mintRunId:()=>randomUUID15(),resumeRunId:resumeBrackets?.run,resumeTools:resumeBrackets?.tools});return AguiEmitter.start({endpoint:agent.ep,withholdPayloads:config2.eventPayloadsWithheld,wal,subjectFrontier,source:positionedJcodeJournalSource(new JcodeJournalSource(journalPath)),map:mapper.map,onUnreadable:gap=>writeJcodeDiagnostic(`[cotal-jcode] AG-UI source: skipped an unreadable journal record at offset ${gap.offset} (${gap.bytes} bytes): ${gap.reason}
|
|
189
189
|
`)})},{onError:eventPlaneStopped({log:line=>writeJcodeDiagnostic(`[cotal-jcode] ${line}
|
|
190
190
|
`)}),sourceEnd:journalPath=>new JcodeJournalSource(journalPath).end(),onRunClosed:runId=>mapper?.forgetOpenRun(runId),waitLive:()=>new Promise((resolve6,reject)=>{const live=()=>agent.connected&&agent.transportConnected;const release=()=>{agent.off("connection",onConnection);agent.off("transport",onTransport);eventWaitStop.signal.removeEventListener("abort",onStop)};const finish=()=>{release();resolve6()};const onStop=()=>{release();reject(new Error("seat stopping while the mesh connection is down; unpublished events stay in the journal"))};const onConnection=e3=>{if(e3.connected&&agent.transportConnected)finish()};const onTransport=e3=>{if(e3.connected&&agent.connected)finish()};agent.on("connection",onConnection);agent.on("transport",onTransport);eventWaitStop.signal.addEventListener("abort",onStop);if(live())finish();else if(eventWaitStop.signal.aborted)onStop()})}):void 0;let eventJournal;const closeEventRun=error51=>{if(!events?.running||!eventJournal)return;events.flush(eventJournal);events.closeRun(Date.now(),error51?{message:error51.message,code:error51.name}:void 0)};const ensureEventsBound=async()=>{if(!events||!eventJournal||events.running)return;events.adopt(eventJournal);await events.settled()};const releaseEventLock=async()=>{const lock=eventLock;eventLock=void 0;if(!lock)return;try{await lock.release()}catch(error51){writeJcodeDiagnostic(`[cotal-jcode] event WAL lock release failed: ${error51.message}
|
|
191
191
|
`)}};let instance;let launchIdentity;let launchIdentityValue;let client;let bridgeStderr="";let tui;let stopping=false;let reconnecting=false;let bridgeRecoveryUsed=false;let sessionId;let driving=false;let turnActive=false;let briefed=false;let initialized=false;let wakeQueued=false;let pendingMentionWake;let surfacedIds=[];let plainSends=0;let nativeTreePreserved=false;const unansweredSteers=new Set;const releaseUnansweredSteers=()=>{for(const release of unansweredSteers)release();unansweredSteers.clear()};let sessionDispatch=Promise.resolve();let unsettledLapsedDispatches=0;const oweAcceptanceDebt=settledWhenHarnessDone=>{unsettledLapsedDispatches+=1;void settledWhenHarnessDone.then(()=>{unsettledLapsedDispatches-=1},()=>{unsettledLapsedDispatches-=1})};let acceptanceSuspectUntilBridgeReplaced=false;let deferralStartedAt;let deferralAnnounced=false;let queuedTurnTierStopped=false;let bridgeReplacementRequestedForSuspicion=false;const withExclusiveDispatch=async operation=>{const previous=sessionDispatch;let release;sessionDispatch=new Promise(resolve6=>{release=resolve6});await previous.catch(()=>{});try{return await operation()}finally{release()}};const onceAccepted=(on2,session,withinMs2)=>new Promise(resolve6=>{const done=()=>{clearTimeout(timer2);on2.off("message_accepted",listener);resolve6()};const listener=event=>{if("session_id"in event&&event.session_id===session)done()};const timer2=setTimeout(done,withinMs2);timer2.unref?.();on2.on("message_accepted",listener)});let reservedIds=new Set;const heldReservations=new Set;const releaseUnheldReservations=()=>{const held2=new Set;for(const batch of heldReservations)for(const key of batch)held2.add(key);reservedIds=held2};const promoteToSurfaced=keys=>{const known=new Set(surfacedIds);for(const key of keys)if(!known.has(key))surfacedIds.push(key)};const reserveForHandover=keys=>{if(!agent.holdInFlight(keys))return void 0;const batch=new Set(keys);heldReservations.add(batch);for(const key of keys)reservedIds.add(key);let released=false;return()=>{if(released)return;released=true;if(!heldReservations.delete(batch))return;agent.releaseInFlight([...batch].filter(key=>!surfacedIds.includes(key)));const stillHeld=new Set;for(const other of heldReservations)for(const key of other)stillHeld.add(key);for(const key of keys)if(!stillHeld.has(key))reservedIds.delete(key)}};let steering=false;let softInterruptFailed=false;let steerSettled=Promise.resolve();const receivedAt=new Map;const stopPrivateJcode=async opts=>{if(!opts?.skipClientClose)await client?.close().catch(()=>{});else void client?.close().catch(()=>{});client=void 0;if(launchIdentity&&launchIdentityValue)await stopPrivateTree({jcodeHome:socketHome.jcodeHome,launch:launchIdentity,identityValue:launchIdentityValue})};const launchPrivateJcode=async deadline=>{const remaining=()=>deadline===void 0?void 0:Math.max(1,deadline-Date.now());const exitListenersBefore=new Set(process.listeners("exit"));const launchBound=launchIdentityEnv();launchIdentityValue=launchBound.value;recordLaunch(home,{identity:launchBound.value,host:captureProcessIdentity(process.pid)});if(onceUid)recordOnceLaunch(home,onceUid,{identity:launchBound.value,host:captureProcessIdentity(process.pid)});instance=await launchInstance({binary,jcodeHome:socketHome.jcodeHome,workingDir:cwd,inheritLogins:false,env:{...seatEnv,JCODE_DISABLE_CLAUDE_MCP:"1",JCODE_NO_AUTO_UPDATE:"1",[launchBound.key]:launchBound.value},...remaining()!==void 0?{startupTimeoutMs:remaining()}:{}});const sdkExitListeners=process.listeners("exit").filter(listener=>!exitListenersBefore.has(listener));for(const listener of sdkExitListeners)process.removeListener("exit",listener);if(sdkExitListeners.length!==1)throw new Error(`jcode connector: expected one SDK instance exit hook, found ${sdkExitListeners.length} \u2014 refusing unsafe lifecycle ownership`);launchIdentity=captureProcessIdentity(instance.process.pid);bridgeStderr="";instance.process.stderr?.on("data",chunk=>{bridgeStderr+=String(chunk);if(bridgeStderr.length>16384)bridgeStderr=bridgeStderr.slice(-8e3)});const perRequestMs=remaining()??requestTimeoutMs;return connectSteerClient(instance.socketPath,perRequestMs)};const onTuiExit=code2=>void shutdown(code2??0);const launchTui=()=>{const runtime=join17(socketHome.jcodeHome,"run");tui=spawn2(binary,["--socket",join17(runtime,"jcode.sock"),"--resume",sessionId],{cwd,env:{...noCotalEnv(),...seatEnv,JCODE_HOME:socketHome.jcodeHome,JCODE_RUNTIME_DIR:runtime,JCODE_SOCKET:join17(runtime,"jcode.sock"),JCODE_COMPANION_AUTOSTART:"0"},stdio:"inherit"});tui.once("exit",onTuiExit)};const stopTui=async()=>{const viewer=tui;if(!viewer||viewer.exitCode!==null||viewer.signalCode!==null)return;viewer.off("exit",onTuiExit);const exited=new Promise(resolve6=>viewer.once("exit",()=>resolve6(true)));const grace=()=>new Promise(resolve6=>setTimeout(()=>resolve6(false),TUI_STOP_GRACE_MS).unref());viewer.kill("SIGTERM");if(await Promise.race([exited,grace()]))return;viewer.kill("SIGKILL");await Promise.race([exited,grace()])};const shutdown=async(code2=0,signal)=>{if(stopping)return;stopping=true;let exit=code2;await stopTui();try{await stopPrivateJcode({skipClientClose:true})}catch(error51){writeJcodeDiagnostic(`[cotal-jcode] ${error51.message}
|