@parlehq/codex 0.58.0 → 0.59.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/parle-mcp.js
CHANGED
|
@@ -7,7 +7,7 @@ import{createRequire}from"node:module";const require=createRequire(import.meta.u
|
|
|
7
7
|
depsCount: ${depsCount},
|
|
8
8
|
deps: ${deps}}`};var def={keyword:"dependencies",type:"object",schemaType:"object",error:exports.error,code(cxt){const[propDeps,schDeps]=splitDependencies(cxt);validatePropertyDeps(cxt,propDeps);validateSchemaDeps(cxt,schDeps)}};function splitDependencies({schema}){const propertyDeps={};const schemaDeps={};for(const key in schema){if(key==="__proto__")continue;const deps=Array.isArray(schema[key])?propertyDeps:schemaDeps;deps[key]=schema[key]}return[propertyDeps,schemaDeps]}function validatePropertyDeps(cxt,propertyDeps=cxt.schema){const{gen,data,it}=cxt;if(Object.keys(propertyDeps).length===0)return;const missing=gen.let("missing");for(const prop in propertyDeps){const deps=propertyDeps[prop];if(deps.length===0)continue;const hasProperty=(0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties);cxt.setParams({property:prop,depsCount:deps.length,deps:deps.join(", ")});if(it.allErrors){gen.if(hasProperty,()=>{for(const depProp of deps){(0,code_1.checkReportMissingProp)(cxt,depProp)}})}else{gen.if((0,codegen_1._)`${hasProperty} && (${(0,code_1.checkMissingProp)(cxt,deps,missing)})`);(0,code_1.reportMissingProp)(cxt,missing);gen.else()}}}exports.validatePropertyDeps=validatePropertyDeps;function validateSchemaDeps(cxt,schemaDeps=cxt.schema){const{gen,data,keyword,it}=cxt;const valid=gen.name("valid");for(const prop in schemaDeps){if((0,util_1.alwaysValidSchema)(it,schemaDeps[prop]))continue;gen.if((0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties),()=>{const schCxt=cxt.subschema({keyword,schemaProp:prop},valid);cxt.mergeValidEvaluated(schCxt,valid)},()=>gen.var(valid,true));cxt.ok(valid)}}exports.validateSchemaDeps=validateSchemaDeps;exports.default=def}});var require_propertyNames=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var error62={message:"property name must be valid",params:({params})=>(0,codegen_1._)`{propertyName: ${params.propertyName}}`};var def={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:error62,code(cxt){const{gen,schema,data,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema))return;const valid=gen.name("valid");gen.forIn("key",data,key=>{cxt.setParams({propertyName:key});cxt.subschema({keyword:"propertyNames",data:key,dataTypes:["string"],propertyName:key,compositeRule:true},valid);gen.if((0,codegen_1.not)(valid),()=>{cxt.error(true);if(!it.allErrors)gen.break()})});cxt.ok(valid)}};exports.default=def}});var require_additionalProperties=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var code_1=require_code2();var codegen_1=require_codegen();var names_1=require_names();var util_1=require_util();var error62={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:error62,code(cxt){const{gen,schema,parentSchema,data,errsCount,it}=cxt;if(!errsCount)throw new Error("ajv implementation error");const{allErrors,opts}=it;it.props=true;if(opts.removeAdditional!=="all"&&(0,util_1.alwaysValidSchema)(it,schema))return;const props=(0,code_1.allSchemaProperties)(parentSchema.properties);const patProps=(0,code_1.allSchemaProperties)(parentSchema.patternProperties);checkAdditionalProperties();cxt.ok((0,codegen_1._)`${errsCount} === ${names_1.default.errors}`);function checkAdditionalProperties(){gen.forIn("key",data,key=>{if(!props.length&&!patProps.length)additionalPropertyCode(key);else gen.if(isAdditional(key),()=>additionalPropertyCode(key))})}function isAdditional(key){let definedProp;if(props.length>8){const propsSchema=(0,util_1.schemaRefOrVal)(it,parentSchema.properties,"properties");definedProp=(0,code_1.isOwnProperty)(gen,propsSchema,key)}else if(props.length){definedProp=(0,codegen_1.or)(...props.map(p=>(0,codegen_1._)`${key} === ${p}`))}else{definedProp=codegen_1.nil}if(patProps.length){definedProp=(0,codegen_1.or)(definedProp,...patProps.map(p=>(0,codegen_1._)`${(0,code_1.usePattern)(cxt,p)}.test(${key})`))}return(0,codegen_1.not)(definedProp)}function deleteAdditional(key){gen.code((0,codegen_1._)`delete ${data}[${key}]`)}function additionalPropertyCode(key){if(opts.removeAdditional==="all"||opts.removeAdditional&&schema===false){deleteAdditional(key);return}if(schema===false){cxt.setParams({additionalProperty:key});cxt.error();if(!allErrors)gen.break();return}if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it,schema)){const valid=gen.name("valid");if(opts.removeAdditional==="failing"){applyAdditionalSchema(key,valid,false);gen.if((0,codegen_1.not)(valid),()=>{cxt.reset();deleteAdditional(key)})}else{applyAdditionalSchema(key,valid);if(!allErrors)gen.if((0,codegen_1.not)(valid),()=>gen.break())}}}function applyAdditionalSchema(key,valid,errors){const subschema={keyword:"additionalProperties",dataProp:key,dataPropType:util_1.Type.Str};if(errors===false){Object.assign(subschema,{compositeRule:true,createErrors:false,allErrors:false})}cxt.subschema(subschema,valid)}}};exports.default=def}});var require_properties=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var validate_1=require_validate();var code_1=require_code2();var util_1=require_util();var additionalProperties_1=require_additionalProperties();var def={keyword:"properties",type:"object",schemaType:"object",code(cxt){const{gen,schema,parentSchema,data,it}=cxt;if(it.opts.removeAdditional==="all"&&parentSchema.additionalProperties===void 0){additionalProperties_1.default.code(new validate_1.KeywordCxt(it,additionalProperties_1.default,"additionalProperties"))}const allProps=(0,code_1.allSchemaProperties)(schema);for(const prop of allProps){it.definedProperties.add(prop)}if(it.opts.unevaluated&&allProps.length&&it.props!==true){it.props=util_1.mergeEvaluated.props(gen,(0,util_1.toHash)(allProps),it.props)}const properties=allProps.filter(p=>!(0,util_1.alwaysValidSchema)(it,schema[p]));if(properties.length===0)return;const valid=gen.name("valid");for(const prop of properties){if(hasDefault(prop)){applyPropertySchema(prop)}else{gen.if((0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties));applyPropertySchema(prop);if(!it.allErrors)gen.else().var(valid,true);gen.endIf()}cxt.it.definedProperties.add(prop);cxt.ok(valid)}function hasDefault(prop){return it.opts.useDefaults&&!it.compositeRule&&schema[prop].default!==void 0}function applyPropertySchema(prop){cxt.subschema({keyword:"properties",schemaProp:prop,dataProp:prop},valid)}}};exports.default=def}});var require_patternProperties=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var code_1=require_code2();var codegen_1=require_codegen();var util_1=require_util();var util_2=require_util();var def={keyword:"patternProperties",type:"object",schemaType:"object",code(cxt){const{gen,schema,data,parentSchema,it}=cxt;const{opts}=it;const patterns=(0,code_1.allSchemaProperties)(schema);const alwaysValidPatterns=patterns.filter(p=>(0,util_1.alwaysValidSchema)(it,schema[p]));if(patterns.length===0||alwaysValidPatterns.length===patterns.length&&(!it.opts.unevaluated||it.props===true)){return}const checkProperties=opts.strictSchema&&!opts.allowMatchingProperties&&parentSchema.properties;const valid=gen.name("valid");if(it.props!==true&&!(it.props instanceof codegen_1.Name)){it.props=(0,util_2.evaluatedPropsToName)(gen,it.props)}const{props}=it;validatePatternProperties();function validatePatternProperties(){for(const pat of patterns){if(checkProperties)checkMatchingProperties(pat);if(it.allErrors){validateProperties(pat)}else{gen.var(valid,true);validateProperties(pat);gen.if(valid)}}}function checkMatchingProperties(pat){for(const prop in checkProperties){if(new RegExp(pat).test(prop)){(0,util_1.checkStrictMode)(it,`property ${prop} matches pattern ${pat} (use allowMatchingProperties)`)}}}function validateProperties(pat){gen.forIn("key",data,key=>{gen.if((0,codegen_1._)`${(0,code_1.usePattern)(cxt,pat)}.test(${key})`,()=>{const alwaysValid=alwaysValidPatterns.includes(pat);if(!alwaysValid){cxt.subschema({keyword:"patternProperties",schemaProp:pat,dataProp:key,dataPropType:util_2.Type.Str},valid)}if(it.opts.unevaluated&&props!==true){gen.assign((0,codegen_1._)`${props}[${key}]`,true)}else if(!alwaysValid&&!it.allErrors){gen.if((0,codegen_1.not)(valid),()=>gen.break())}})})}}};exports.default=def}});var require_not=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var util_1=require_util();var def={keyword:"not",schemaType:["object","boolean"],trackErrors:true,code(cxt){const{gen,schema,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema)){cxt.fail();return}const valid=gen.name("valid");cxt.subschema({keyword:"not",compositeRule:true,createErrors:false,allErrors:false},valid);cxt.failResult(valid,()=>cxt.reset(),()=>cxt.error())},error:{message:"must NOT be valid"}};exports.default=def}});var require_anyOf=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var code_1=require_code2();var def={keyword:"anyOf",schemaType:"array",trackErrors:true,code:code_1.validateUnion,error:{message:"must match a schema in anyOf"}};exports.default=def}});var require_oneOf=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var error62={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:error62,code(cxt){const{gen,schema,parentSchema,it}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");if(it.opts.discriminator&&parentSchema.discriminator)return;const schArr=schema;const valid=gen.let("valid",false);const passing=gen.let("passing",null);const schValid=gen.name("_valid");cxt.setParams({passing});gen.block(validateOneOf);cxt.result(valid,()=>cxt.reset(),()=>cxt.error(true));function validateOneOf(){schArr.forEach((sch,i)=>{let schCxt;if((0,util_1.alwaysValidSchema)(it,sch)){gen.var(schValid,true)}else{schCxt=cxt.subschema({keyword:"oneOf",schemaProp:i,compositeRule:true},schValid)}if(i>0){gen.if((0,codegen_1._)`${schValid} && ${valid}`).assign(valid,false).assign(passing,(0,codegen_1._)`[${passing}, ${i}]`).else()}gen.if(schValid,()=>{gen.assign(valid,true);gen.assign(passing,i);if(schCxt)cxt.mergeEvaluated(schCxt,codegen_1.Name)})})}}};exports.default=def}});var require_allOf=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var util_1=require_util();var def={keyword:"allOf",schemaType:"array",code(cxt){const{gen,schema,it}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");const valid=gen.name("valid");schema.forEach((sch,i)=>{if((0,util_1.alwaysValidSchema)(it,sch))return;const schCxt=cxt.subschema({keyword:"allOf",schemaProp:i},valid);cxt.ok(valid);cxt.mergeEvaluated(schCxt)})}};exports.default=def}});var require_if=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var error62={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:error62,code(cxt){const{gen,parentSchema,it}=cxt;if(parentSchema.then===void 0&&parentSchema.else===void 0){(0,util_1.checkStrictMode)(it,'"if" without "then" and "else" is ignored')}const hasThen=hasSchema(it,"then");const hasElse=hasSchema(it,"else");if(!hasThen&&!hasElse)return;const valid=gen.let("valid",true);const schValid=gen.name("_valid");validateIf();cxt.reset();if(hasThen&&hasElse){const ifClause=gen.let("ifClause");cxt.setParams({ifClause});gen.if(schValid,validateClause("then",ifClause),validateClause("else",ifClause))}else if(hasThen){gen.if(schValid,validateClause("then"))}else{gen.if((0,codegen_1.not)(schValid),validateClause("else"))}cxt.pass(valid,()=>cxt.error(true));function validateIf(){const schCxt=cxt.subschema({keyword:"if",compositeRule:true,createErrors:false,allErrors:false},schValid);cxt.mergeEvaluated(schCxt)}function validateClause(keyword,ifClause){return()=>{const schCxt=cxt.subschema({keyword},schValid);gen.assign(valid,schValid);cxt.mergeValidEvaluated(schCxt,valid);if(ifClause)gen.assign(ifClause,(0,codegen_1._)`${keyword}`);else cxt.setParams({ifClause:keyword})}}}};function hasSchema(it,keyword){const schema=it.schema[keyword];return schema!==void 0&&!(0,util_1.alwaysValidSchema)(it,schema)}exports.default=def}});var require_thenElse=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var util_1=require_util();var def={keyword:["then","else"],schemaType:["object","boolean"],code({keyword,parentSchema,it}){if(parentSchema.if===void 0)(0,util_1.checkStrictMode)(it,`"${keyword}" without "if" is ignored`)}};exports.default=def}});var require_applicator=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var additionalItems_1=require_additionalItems();var prefixItems_1=require_prefixItems();var items_1=require_items();var items2020_1=require_items2020();var contains_1=require_contains();var dependencies_1=require_dependencies();var propertyNames_1=require_propertyNames();var additionalProperties_1=require_additionalProperties();var properties_1=require_properties();var patternProperties_1=require_patternProperties();var not_1=require_not();var anyOf_1=require_anyOf();var oneOf_1=require_oneOf();var allOf_1=require_allOf();var if_1=require_if();var thenElse_1=require_thenElse();function getApplicator(draft2020=false){const applicator=[not_1.default,anyOf_1.default,oneOf_1.default,allOf_1.default,if_1.default,thenElse_1.default,propertyNames_1.default,additionalProperties_1.default,dependencies_1.default,properties_1.default,patternProperties_1.default];if(draft2020)applicator.push(prefixItems_1.default,items2020_1.default);else applicator.push(additionalItems_1.default,items_1.default);applicator.push(contains_1.default);return applicator}exports.default=getApplicator}});var require_format=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/format.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var error62={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:error62,code(cxt,ruleType){const{gen,data,$data,schema,schemaCode,it}=cxt;const{opts,errSchemaPath,schemaEnv,self}=it;if(!opts.validateFormats)return;if($data)validate$DataFormat();else validateFormat();function validate$DataFormat(){const fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats});const fDef=gen.const("fDef",(0,codegen_1._)`${fmts}[${schemaCode}]`);const fType=gen.let("fType");const format=gen.let("format");gen.if((0,codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`,()=>gen.assign(fType,(0,codegen_1._)`${fDef}.type || "string"`).assign(format,(0,codegen_1._)`${fDef}.validate`),()=>gen.assign(fType,(0,codegen_1._)`"string"`).assign(format,fDef));cxt.fail$data((0,codegen_1.or)(unknownFmt(),invalidFmt()));function unknownFmt(){if(opts.strictSchema===false)return codegen_1.nil;return(0,codegen_1._)`${schemaCode} && !${format}`}function invalidFmt(){const callFormat=schemaEnv.$async?(0,codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`:(0,codegen_1._)`${format}(${data})`;const validData=(0,codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;return(0,codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`}}function validateFormat(){const formatDef=self.formats[schema];if(!formatDef){unknownFormat();return}if(formatDef===true)return;const[fmtType,format,fmtRef]=getFormat(formatDef);if(fmtType===ruleType)cxt.pass(validCondition());function unknownFormat(){if(opts.strictSchema===false){self.logger.warn(unknownMsg());return}throw new Error(unknownMsg());function unknownMsg(){return`unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`}}function getFormat(fmtDef){const code=fmtDef instanceof RegExp?(0,codegen_1.regexpCode)(fmtDef):opts.code.formats?(0,codegen_1._)`${opts.code.formats}${(0,codegen_1.getProperty)(schema)}`:void 0;const fmt=gen.scopeValue("formats",{key:schema,ref:fmtDef,code});if(typeof fmtDef=="object"&&!(fmtDef instanceof RegExp)){return[fmtDef.type||"string",fmtDef.validate,(0,codegen_1._)`${fmt}.validate`]}return["string",fmtDef,fmt]}function validCondition(){if(typeof formatDef=="object"&&!(formatDef instanceof RegExp)&&formatDef.async){if(!schemaEnv.$async)throw new Error("async format in sync schema");return(0,codegen_1._)`await ${fmtRef}(${data})`}return typeof format=="function"?(0,codegen_1._)`${fmtRef}(${data})`:(0,codegen_1._)`${fmtRef}.test(${data})`}}}};exports.default=def}});var require_format2=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var format_1=require_format();var format=[format_1.default];exports.default=format}});var require_metadata=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/metadata.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.contentVocabulary=exports.metadataVocabulary=void 0;exports.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];exports.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]}});var require_draft7=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/draft7.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var core_1=require_core2();var validation_1=require_validation();var applicator_1=require_applicator();var format_1=require_format2();var metadata_1=require_metadata();var draft7Vocabularies=[core_1.default,validation_1.default,(0,applicator_1.default)(),format_1.default,metadata_1.metadataVocabulary,metadata_1.contentVocabulary];exports.default=draft7Vocabularies}});var require_types=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DiscrError=void 0;var DiscrError;(function(DiscrError2){DiscrError2["Tag"]="tag";DiscrError2["Mapping"]="mapping"})(DiscrError||(exports.DiscrError=DiscrError={}))}});var require_discriminator=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var types_1=require_types();var compile_1=require_compile();var ref_error_1=require_ref_error();var util_1=require_util();var error62={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:error62,code(cxt){const{gen,data,schema,parentSchema,it}=cxt;const{oneOf:oneOf3}=parentSchema;if(!it.opts.discriminator){throw new Error("discriminator: requires discriminator option")}const tagName=schema.propertyName;if(typeof tagName!="string")throw new Error("discriminator: requires propertyName");if(schema.mapping)throw new Error("discriminator: mapping is not supported");if(!oneOf3)throw new Error("discriminator: requires oneOf keyword");const valid=gen.let("valid",false);const tag=gen.const("tag",(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(tagName)}`);gen.if((0,codegen_1._)`typeof ${tag} == "string"`,()=>validateMapping(),()=>cxt.error(false,{discrError:types_1.DiscrError.Tag,tag,tagName}));cxt.ok(valid);function validateMapping(){const mapping=getMapping();gen.if(false);for(const tagValue in mapping){gen.elseIf((0,codegen_1._)`${tag} === ${tagValue}`);gen.assign(valid,applyTagSchema(mapping[tagValue]))}gen.else();cxt.error(false,{discrError:types_1.DiscrError.Mapping,tag,tagName});gen.endIf()}function applyTagSchema(schemaProp){const _valid=gen.name("valid");const schCxt=cxt.subschema({keyword:"oneOf",schemaProp},_valid);cxt.mergeEvaluated(schCxt,codegen_1.Name);return _valid}function getMapping(){var _a3;const oneOfMapping={};const topRequired=hasRequired(parentSchema);let tagRequired=true;for(let i=0;i<oneOf3.length;i++){let sch=oneOf3[i];if((sch===null||sch===void 0?void 0:sch.$ref)&&!(0,util_1.schemaHasRulesButRef)(sch,it.self.RULES)){const ref=sch.$ref;sch=compile_1.resolveRef.call(it.self,it.schemaEnv.root,it.baseId,ref);if(sch instanceof compile_1.SchemaEnv)sch=sch.schema;if(sch===void 0)throw new ref_error_1.default(it.opts.uriResolver,it.baseId,ref)}const propSch=(_a3=sch===null||sch===void 0?void 0:sch.properties)===null||_a3===void 0?void 0:_a3[tagName];if(typeof propSch!="object"){throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`)}tagRequired=tagRequired&&(topRequired||hasRequired(sch));addMappings(propSch,i)}if(!tagRequired)throw new Error(`discriminator: "${tagName}" must be required`);return oneOfMapping;function hasRequired({required:required2}){return Array.isArray(required2)&&required2.includes(tagName)}function addMappings(sch,i){if(sch.const){addMapping(sch.const,i)}else if(sch.enum){for(const tagValue of sch.enum){addMapping(tagValue,i)}}else{throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`)}}function addMapping(tagValue,i){if(typeof tagValue!="string"||tagValue in oneOfMapping){throw new Error(`discriminator: "${tagName}" values must be unique strings`)}oneOfMapping[tagValue]=i}}}};exports.default=def}});var require_json_schema_draft_07=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports,module){module.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:true,readOnly:{type:"boolean",default:false},examples:{type:"array",items:true},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:true},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:true,enum:{type:"array",items:true,minItems:1,uniqueItems:true},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:true}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:true}}});var require_ajv=__commonJS({"../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/ajv.js"(exports,module){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv=void 0;var core_1=require_core();var draft7_1=require_draft7();var discriminator_1=require_discriminator();var draft7MetaSchema=require_json_schema_draft_07();var META_SUPPORT_DATA=["/properties"];var META_SCHEMA_ID="http://json-schema.org/draft-07/schema";var Ajv2=class extends core_1.default{_addVocabularies(){super._addVocabularies();draft7_1.default.forEach(v=>this.addVocabulary(v));if(this.opts.discriminator)this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();if(!this.opts.meta)return;const metaSchema=this.opts.$data?this.$dataMetaSchema(draft7MetaSchema,META_SUPPORT_DATA):draft7MetaSchema;this.addMetaSchema(metaSchema,META_SCHEMA_ID,false);this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0)}};exports.Ajv=Ajv2;module.exports=exports=Ajv2;module.exports.Ajv=Ajv2;Object.defineProperty(exports,"__esModule",{value:true});exports.default=Ajv2;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:true,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:true,get:function(){return codegen_1._}});Object.defineProperty(exports,"str",{enumerable:true,get:function(){return codegen_1.str}});Object.defineProperty(exports,"stringify",{enumerable:true,get:function(){return codegen_1.stringify}});Object.defineProperty(exports,"nil",{enumerable:true,get:function(){return codegen_1.nil}});Object.defineProperty(exports,"Name",{enumerable:true,get:function(){return codegen_1.Name}});Object.defineProperty(exports,"CodeGen",{enumerable:true,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports,"ValidationError",{enumerable:true,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports,"MissingRefError",{enumerable:true,get:function(){return ref_error_1.default}})}});var require_formats=__commonJS({"../../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/formats.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.formatNames=exports.fastFormats=exports.fullFormats=void 0;function fmtDef(validate2,compare){return{validate:validate2,compare}}exports.fullFormats={date:fmtDef(date5,compareDate),time:fmtDef(getTime(true),compareTime),"date-time":fmtDef(getDateTime(true),compareDateTime),"iso-time":fmtDef(getTime(),compareIsoTime),"iso-date-time":fmtDef(getDateTime(),compareIsoDateTime),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte,int32:{type:"number",validate:validateInt32},int64:{type:"number",validate:validateInt64},float:{type:"number",validate:validateNumber},double:{type:"number",validate:validateNumber},password:true,binary:true};exports.fastFormats={...exports.fullFormats,date:fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,compareDate),time:fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareTime),"date-time":fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareDateTime),"iso-time":fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoTime),"iso-date-time":fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoDateTime),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};exports.formatNames=Object.keys(exports.fullFormats);function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}var DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;var DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31];function date5(str){const matches=DATE.exec(str);if(!matches)return false;const year=+matches[1];const month=+matches[2];const day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month===2&&isLeapYear(year)?29:DAYS[month])}function compareDate(d1,d2){if(!(d1&&d2))return void 0;if(d1>d2)return 1;if(d1<d2)return-1;return 0}var TIME=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function getTime(strictTimeZone){return function time3(str){const matches=TIME.exec(str);if(!matches)return false;const hr=+matches[1];const min=+matches[2];const sec=+matches[3];const tz=matches[4];const tzSign=matches[5]==="-"?-1:1;const tzH=+(matches[6]||0);const tzM=+(matches[7]||0);if(tzH>23||tzM>59||strictTimeZone&&!tz)return false;if(hr<=23&&min<=59&&sec<60)return true;const utcMin=min-tzM*tzSign;const utcHr=hr-tzH*tzSign-(utcMin<0?1:0);return(utcHr===23||utcHr===-1)&&(utcMin===59||utcMin===-1)&&sec<61}}function compareTime(s1,s2){if(!(s1&&s2))return void 0;const t1=new Date("2020-01-01T"+s1).valueOf();const t2=new Date("2020-01-01T"+s2).valueOf();if(!(t1&&t2))return void 0;return t1-t2}function compareIsoTime(t1,t2){if(!(t1&&t2))return void 0;const a1=TIME.exec(t1);const a2=TIME.exec(t2);if(!(a1&&a2))return void 0;t1=a1[1]+a1[2]+a1[3];t2=a2[1]+a2[2]+a2[3];if(t1>t2)return 1;if(t1<t2)return-1;return 0}var DATE_TIME_SEPARATOR=/t|\s/i;function getDateTime(strictTimeZone){const time3=getTime(strictTimeZone);return function date_time(str){const dateTime=str.split(DATE_TIME_SEPARATOR);return dateTime.length===2&&date5(dateTime[0])&&time3(dateTime[1])}}function compareDateTime(dt1,dt2){if(!(dt1&&dt2))return void 0;const d1=new Date(dt1).valueOf();const d2=new Date(dt2).valueOf();if(!(d1&&d2))return void 0;return d1-d2}function compareIsoDateTime(dt1,dt2){if(!(dt1&&dt2))return void 0;const[d1,t1]=dt1.split(DATE_TIME_SEPARATOR);const[d2,t2]=dt2.split(DATE_TIME_SEPARATOR);const res=compareDate(d1,d2);if(res===void 0)return void 0;return res||compareTime(t1,t2)}var NOT_URI_FRAGMENT=/\/|:/;var URI=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function uri(str){return NOT_URI_FRAGMENT.test(str)&&URI.test(str)}var BYTE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function byte(str){BYTE.lastIndex=0;return BYTE.test(str)}var MIN_INT32=-(2**31);var MAX_INT32=2**31-1;function validateInt32(value){return Number.isInteger(value)&&value<=MAX_INT32&&value>=MIN_INT32}function validateInt64(value){return Number.isInteger(value)}function validateNumber(){return true}var Z_ANCHOR=/[^\\]\\Z/;function regex(str){if(Z_ANCHOR.test(str))return false;try{new RegExp(str);return true}catch(e){return false}}}});var require_limit=__commonJS({"../../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/limit.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.formatLimitDefinition=void 0;var ajv_1=require_ajv();var codegen_1=require_codegen();var ops=codegen_1.operators;var KWDs={formatMaximum:{okStr:"<=",ok:ops.LTE,fail:ops.GT},formatMinimum:{okStr:">=",ok:ops.GTE,fail:ops.LT},formatExclusiveMaximum:{okStr:"<",ok:ops.LT,fail:ops.GTE},formatExclusiveMinimum:{okStr:">",ok:ops.GT,fail:ops.LTE}};var error62={message:({keyword,schemaCode})=>(0,codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`,params:({keyword,schemaCode})=>(0,codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`};exports.formatLimitDefinition={keyword:Object.keys(KWDs),type:"string",schemaType:"string",$data:true,error:error62,code(cxt){const{gen,data,schemaCode,keyword,it}=cxt;const{opts,self}=it;if(!opts.validateFormats)return;const fCxt=new ajv_1.KeywordCxt(it,self.RULES.all.format.definition,"format");if(fCxt.$data)validate$DataFormat();else validateFormat();function validate$DataFormat(){const fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats});const fmt=gen.const("fmt",(0,codegen_1._)`${fmts}[${fCxt.schemaCode}]`);cxt.fail$data((0,codegen_1.or)((0,codegen_1._)`typeof ${fmt} != "object"`,(0,codegen_1._)`${fmt} instanceof RegExp`,(0,codegen_1._)`typeof ${fmt}.compare != "function"`,compareCode(fmt)))}function validateFormat(){const format=fCxt.schema;const fmtDef=self.formats[format];if(!fmtDef||fmtDef===true)return;if(typeof fmtDef!="object"||fmtDef instanceof RegExp||typeof fmtDef.compare!="function"){throw new Error(`"${keyword}": format "${format}" does not define "compare" function`)}const fmt=gen.scopeValue("formats",{key:format,ref:fmtDef,code:opts.code.formats?(0,codegen_1._)`${opts.code.formats}${(0,codegen_1.getProperty)(format)}`:void 0});cxt.fail$data(compareCode(fmt))}function compareCode(fmt){return(0,codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`}},dependencies:["format"]};var formatLimitPlugin=ajv=>{ajv.addKeyword(exports.formatLimitDefinition);return ajv};exports.default=formatLimitPlugin}});var require_dist=__commonJS({"../../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/index.js"(exports,module){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var formats_1=require_formats();var limit_1=require_limit();var codegen_1=require_codegen();var fullName=new codegen_1.Name("fullFormats");var fastName=new codegen_1.Name("fastFormats");var formatsPlugin=(ajv,opts={keywords:true})=>{if(Array.isArray(opts)){addFormats(ajv,opts,formats_1.fullFormats,fullName);return ajv}const[formats,exportName]=opts.mode==="fast"?[formats_1.fastFormats,fastName]:[formats_1.fullFormats,fullName];const list=opts.formats||formats_1.formatNames;addFormats(ajv,list,formats,exportName);if(opts.keywords)(0,limit_1.default)(ajv);return ajv};formatsPlugin.get=(name,mode="full")=>{const formats=mode==="fast"?formats_1.fastFormats:formats_1.fullFormats;const f=formats[name];if(!f)throw new Error(`Unknown format "${name}"`);return f};function addFormats(ajv,list,fs,exportName){var _a3;var _b;(_a3=(_b=ajv.opts.code).formats)!==null&&_a3!==void 0?_a3:_b.formats=(0,codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;for(const f of list)ajv.addFormat(f,fs[f])}module.exports=exports=formatsPlugin;Object.defineProperty(exports,"__esModule",{value:true});exports.default=formatsPlugin}});var UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;import{homedir}from"node:os";import{isAbsolute,join}from"node:path";var BUILD_ID="";var BUILD_ENVIRONMENT="production";var BUILD_API="https://api.parle.sh";var BUILD_API_HOSTS=["parle.sh","*.parle.sh"];var BUILD_DESKTOP_CHANNEL="production";var BUILD_HOME=".parle";var BUILD_REPORT_URL="https://intake.parle.sh/v1/reports";function parleHome(env=process.env){const configured=env.PARLE_HOME;if(configured&&isAbsolute(configured))return configured;return join(env.HOME||env.USERPROFILE||homedir(),BUILD_HOME)}import{readFileSync as readFileSync6,existsSync as existsSync5}from"node:fs";import{dirname as dirname6,isAbsolute as isAbsolute4,join as join13}from"node:path";import{randomUUID as randomUUID10}from"node:crypto";function isAddressDeliveryFence(fence){return"kind"in fence&&fence.kind==="address"}function configuredDeliveryRuntime(client){let binding2=client.cfg?.deliveryAddress?.value?client.cfg:void 0;let address2=binding2?.deliveryAddress?.value;let runtime=client.deliveryAddressRuntime();const listeners=new Map;const attachListeners=notify=>{for(const listener of listeners.keys()){listeners.set(listener,runtime?.subscribe(listener));if(notify)listener()}};let epoch=client.addressBindingEpoch??0;const follow=()=>{if(!binding2||!client.cfg.deliveryAddress?.value)return;if((client.addressBindingEpoch??0)!==epoch&&client.cfg!==binding2){for(const off of listeners.values())off?.();binding2=client.cfg;address2=binding2.deliveryAddress?.value;runtime=client.deliveryAddressRuntime();epoch=client.addressBindingEpoch??0;attachListeners(true)}else if(!runtime&&client.cfg===binding2&&client.deliveryAddressRuntime()){runtime=client.deliveryAddressRuntime();attachListeners(true)}};client.onAddressConnection?.(()=>follow());const matchesBinding=()=>{follow();return Boolean(binding2)&&client.cfg===binding2&&client.cfg.deliveryAddress?.value===address2&&(!runtime||client.deliveryAddressRuntime()===runtime)};const current=()=>{if(!matchesBinding()||!runtime)throw new Error("Parle address delivery binding changed; explicitly reconnect and rebuild its controller");return runtime};return{env:client.env,async ensureReady(signal){if(!binding2){await client.ensureAddressConnected(signal);binding2=client.cfg;address2=binding2.deliveryAddress?.value;runtime=client.deliveryAddressRuntime();epoch=client.addressBindingEpoch??0;attachListeners(false)}if(client.disconnected)await client.ensureAddressConnected(signal);if(!matchesBinding())throw new Error("Parle address delivery binding changed; explicitly reconnect");if(!runtime){await client.ensureReadySafe(signal);await client.addressConnectingSettled?.();runtime=client.deliveryAddressRuntime();attachListeners(false)}await current().ensureReady(signal)},bindingCurrent:()=>!binding2||matchesBinding(),currentSourceId:()=>matchesBinding()?runtime?.currentSourceId():void 0,watchAllowed:()=>matchesBinding()&&Boolean(runtime?.watchAllowed()),sources:()=>matchesBinding()?runtime?.sources()??[]:[],subscribe:listener=>{listeners.set(listener,runtime?.subscribe(listener));return()=>{listeners.get(listener)?.();listeners.delete(listener)}},openStream:(signal,lastEventId,reconnectReason)=>current().openStream(signal,lastEventId,reconnectReason),streamKeepaliveSeconds:()=>current().streamKeepaliveSeconds?.(),async noteRoomsChanged(){await client.noteRoomsChanged?.()},async noteStreamClosed(reason){await current().noteStreamClosed(reason)},async noteApprovalDecided(approvalRequestId2,decision){await client.noteApprovalDecided?.(approvalRequestId2,decision)},async notePauseChanged(roomId,paused){await client.notePauseChanged?.(roomId,paused)},async noteInvite(inviteId){await client.noteInvite?.(inviteId)},async noteInviteRevoked(inviteId){await client.noteInviteRevoked?.(inviteId)},async noteRoomNudge(name,ids){await client.noteRoomNudge?.(name,ids)},async noteSeatRightsChanged(roomId,agentId){await client.noteSeatRightsChanged?.(roomId,agentId)},async noteAddressTransferred(addressId){await client.noteAddressTransferred?.(addressId)},async noteAddressAvailability(addressId){await client.noteAddressAvailability?.(addressId)},async recoverMissedNotices(){await client.recoverMissedNotices?.()},noteStreamLive(live){client.noteStreamLive?.(live)},recoverRoom:(roomId,signal)=>current().recoverRoom(roomId,signal),prefetchEveryRoom:(signal,sourceId)=>current().prefetchEveryRoom?.(signal,sourceId)??Promise.resolve(void 0),dropPrefetched:()=>current().dropPrefetched?.(),fetch:(signal,roomId,scope,sourceId)=>current().fetch(signal,roomId,scope,sourceId),fenceCurrent:fence=>matchesBinding()&&Boolean(runtime?.fenceCurrent(fence)),acknowledge:(message,signal,roomId,fence)=>current().acknowledge(message,signal,roomId,fence)}}var ReplyNotSentError=class extends Error{sent=false;code;constructor(code,message,options){super(message,options);this.name="ReplyNotSentError";this.code=code}};import{readdirSync,rmSync}from"node:fs";import{join as join3}from"node:path";import{randomUUID}from"node:crypto";import{chmodSync,closeSync,constants,existsSync,fchmodSync,fsyncSync,fstatSync,lstatSync,linkSync,mkdirSync,openSync,readSync,renameSync,unlinkSync,writeSync}from"node:fs";import{basename,dirname,join as join2}from"node:path";var DEFAULT_FILE_MODE=384;var DEFAULT_DIRECTORY_MODE=448;var MAX_LOCK_BYTES=4096;var DEFAULT_MALFORMED_LOCK_STALE_MS=5*6e4;var NO_FOLLOW=typeof constants.O_NOFOLLOW==="number"?constants.O_NOFOLLOW:0;var SafeFileError=class extends Error{code;constructor(code,message,options){super(message,options);this.name="SafeFileError";this.code=code}};function closeBestEffort(fd){try{closeSync(fd)}catch{}}function systemCode(error62){return typeof error62?.code==="string"?error62.code:void 0}function ownerAndMode(stat,expectedMode,label,kind){if(kind==="file"){if(!stat.isFile())throw new SafeFileError("unsafe_type",`${label} must be a regular file.`)}else if(!stat.isDirectory()){throw new SafeFileError("unsafe_type",`${label} must be a real directory.`)}if(process.platform==="win32")return;if(stat.uid!==process.getuid?.())throw new SafeFileError("unsafe_owner",`${label} must be owned by the current user.`);if((stat.mode&511)!==expectedMode)throw new SafeFileError("unsafe_mode",`${label} must have mode ${expectedMode.toString(8)}.`)}function assertSingleLink(stat,label){if(stat.nlink!==1)throw new SafeFileError("unsafe_links",`${label} must have exactly one filesystem link.`)}function inspectRealDirectory(path,label,mode=DEFAULT_DIRECTORY_MODE){let stat;try{stat=lstatSync(path)}catch(error62){throw new SafeFileError("directory_unavailable",`${label} cannot be inspected: ${path}.`,{cause:error62})}if(stat.isSymbolicLink())throw new SafeFileError("symlink_refused",`${label} must not be a symbolic link: ${path}.`);ownerAndMode(stat,mode,label,"directory");return stat}function ensureOwnerOnlyDirectory(path,options={label:"Owner-only directory"}){const mode=options.mode??DEFAULT_DIRECTORY_MODE;if(!existsSync(path)){if(options.create===false)throw new SafeFileError("directory_missing",`${options.label} is missing: ${path}.`);try{mkdirSync(path,{recursive:true,mode})}catch(error62){throw new SafeFileError("directory_create_failed",`${options.label} could not be created: ${path}.`,{cause:error62})}}let stat;try{stat=lstatSync(path)}catch(error62){throw new SafeFileError("directory_unavailable",`${options.label} cannot be inspected: ${path}.`,{cause:error62})}if(stat.isSymbolicLink())throw new SafeFileError("symlink_refused",`${options.label} must not be a symbolic link: ${path}.`);if(!stat.isDirectory())throw new SafeFileError("unsafe_type",`${options.label} must be a real directory.`);if(process.platform!=="win32"&&stat.uid!==process.getuid?.())throw new SafeFileError("unsafe_owner",`${options.label} must be owned by the current user.`);if(options.repairMode&&process.platform!=="win32"&&(stat.mode&511)!==mode)chmodSync(path,mode);inspectRealDirectory(path,options.label,mode);return path}function inspectOwnerFileShape(path,label,requireSingleLink){let stat;try{stat=lstatSync(path)}catch(error62){throw new SafeFileError("file_unavailable",`${label} cannot be inspected: ${path}.`,{cause:error62})}if(stat.isSymbolicLink())throw new SafeFileError("symlink_refused",`${label} must not be a symbolic link: ${path}.`);if(!stat.isFile())throw new SafeFileError("unsafe_type",`${label} must be a regular file.`);if(process.platform!=="win32"&&stat.uid!==process.getuid?.())throw new SafeFileError("unsafe_owner",`${label} must be owned by the current user.`);if(requireSingleLink)assertSingleLink(stat,label);return stat}function inspectOwnerOnlyPath(path,label,mode,requireSingleLink){const stat=inspectOwnerFileShape(path,label,requireSingleLink);ownerAndMode(stat,mode,label,"file");return stat}function openOwnerOnlyRead(path,options){const mode=options.mode??DEFAULT_FILE_MODE;const requireSingleLink=options.requireSingleLink??true;if(options.modePolicy==="ignore")inspectOwnerFileShape(path,options.label,requireSingleLink);else inspectOwnerOnlyPath(path,options.label,mode,requireSingleLink);let fd;try{fd=openSync(path,constants.O_RDONLY|NO_FOLLOW)}catch(error62){if(systemCode(error62)==="ELOOP")throw new SafeFileError("symlink_refused",`${options.label} must not be a symbolic link: ${path}.`,{cause:error62});throw new SafeFileError("file_open_failed",`${options.label} could not be opened: ${path}.`,{cause:error62})}try{const stat=fstatSync(fd);if(options.modePolicy==="ignore"){if(!stat.isFile())throw new SafeFileError("unsafe_type",`${options.label} must be a regular file.`);if(process.platform!=="win32"&&stat.uid!==process.getuid?.())throw new SafeFileError("unsafe_owner",`${options.label} must be owned by the current user.`)}else ownerAndMode(stat,mode,options.label,"file");if(requireSingleLink)assertSingleLink(stat,options.label);if(stat.size>options.maxBytes)throw new SafeFileError("size_limit",`${options.label} exceeds ${options.maxBytes} bytes.`);return{fd,stat}}catch(error62){closeBestEffort(fd);throw error62}}function readOwnerOnlyFile(path,options){if(!Number.isSafeInteger(options.maxBytes)||options.maxBytes<0)throw new SafeFileError("invalid_limit",`${options.label} requires a non-negative byte limit.`);const{fd}=openOwnerOnlyRead(path,options);try{const output2=Buffer.allocUnsafe(options.maxBytes+1);let offset=0;while(offset<output2.length){const count2=readSync(fd,output2,offset,output2.length-offset,null);if(count2===0)break;offset+=count2}if(offset>options.maxBytes)throw new SafeFileError("size_limit",`${options.label} exceeds ${options.maxBytes} bytes.`);return Buffer.from(output2.subarray(0,offset))}catch(error62){if(error62 instanceof SafeFileError)throw error62;throw new SafeFileError("file_read_failed",`${options.label} could not be read: ${path}.`,{cause:error62})}finally{closeBestEffort(fd)}}function readOwnerOnlyTextFile(path,options){return readOwnerOnlyFile(path,options).toString("utf8")}var UNSUPPORTED_SYNC_CODES=new Set(["EINVAL","ENOTSUP","EOPNOTSUPP","EPERM","EISDIR"]);function syncFile(fd,label,durability){if(durability==="none")return;try{fsyncSync(fd)}catch(error62){if(durability==="best-effort"&&UNSUPPORTED_SYNC_CODES.has(systemCode(error62)||""))return;throw new SafeFileError("file_sync_unsupported",`${label} cannot provide required file durability.`,{cause:error62})}}function syncDirectory(path,label,durability){if(durability==="none")return;let fd;try{fd=openSync(path,constants.O_RDONLY);fsyncSync(fd)}catch(error62){if(durability==="best-effort"&&UNSUPPORTED_SYNC_CODES.has(systemCode(error62)||""))return;throw new SafeFileError("directory_sync_unsupported",`${label} cannot provide required directory durability.`,{cause:error62})}finally{if(fd!==void 0)closeBestEffort(fd)}}function writeAll(fd,value){let offset=0;while(offset<value.length)offset+=writeSync(fd,value,offset,value.length-offset)}function atomicReplaceOwnerOnlyFile(path,value,options){const mode=options.mode??DEFAULT_FILE_MODE;const durability=options.durability;const body=typeof value==="string"?Buffer.from(value,"utf8"):Buffer.from(value);if(options.maxBytes!==void 0&&body.byteLength>options.maxBytes){throw new SafeFileError("size_limit",`${options.label} exceeds ${options.maxBytes} bytes.`)}const directory=dirname(path);const directoryStat=inspectRealDirectory(directory,`${options.label} parent directory`);const inspectExisting=()=>options.existingMode==="replace"?inspectOwnerFileShape(path,options.label,true):inspectOwnerOnlyPath(path,options.label,mode,true);if(existsSync(path))inspectExisting();const temp=join2(directory,`.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);let fd;try{fd=openSync(temp,constants.O_CREAT|constants.O_EXCL|constants.O_WRONLY|NO_FOLLOW,mode);if(process.platform!=="win32")fchmodSync(fd,mode);const tempStat=fstatSync(fd);ownerAndMode(tempStat,mode,`${options.label} temporary file`,"file");assertSingleLink(tempStat,`${options.label} temporary file`);writeAll(fd,body);syncFile(fd,`${options.label} temporary file`,durability);closeSync(fd);fd=void 0;inspectOwnerOnlyPath(temp,`${options.label} temporary file`,mode,true);const currentDirectory=inspectRealDirectory(directory,`${options.label} parent directory`);if(currentDirectory.dev!==directoryStat.dev||currentDirectory.ino!==directoryStat.ino)throw new SafeFileError("directory_changed",`${options.label} parent directory changed during atomic replacement.`);if(existsSync(path))inspectExisting();try{renameSync(temp,path)}catch(error62){const code=systemCode(error62);if(["EXDEV","ENOTSUP","EOPNOTSUPP"].includes(code||"")){throw new SafeFileError("atomic_replace_unsupported",`${options.label} cannot be replaced atomically on this filesystem.`,{cause:error62})}throw error62}inspectOwnerOnlyPath(path,options.label,mode,true);syncDirectory(directory,`${options.label} parent directory`,durability)}catch(error62){if(error62 instanceof SafeFileError)throw error62;throw new SafeFileError("atomic_replace_failed",`${options.label} could not be replaced atomically: ${path}.`,{cause:error62})}finally{if(fd!==void 0)closeBestEffort(fd);try{if(existsSync(temp))unlinkSync(temp)}catch{}body.fill(0)}}function restoreQuarantinedFile(path,quarantine){try{linkSync(quarantine,path);unlinkSync(quarantine)}catch(error62){if(systemCode(error62)==="EEXIST"){try{unlinkSync(quarantine)}catch(unlinkError){if(systemCode(unlinkError)!=="ENOENT")throw unlinkError}return}throw error62}}function removeOwnerOnlyFileIf(path,options){try{inspectOwnerOnlyPath(path,options.label,DEFAULT_FILE_MODE,true);const raw=readOwnerOnlyTextFile(path,{label:options.label,maxBytes:options.maxBytes});if(!options.shouldRemove(raw))return false}catch{return false}const quarantine=join2(dirname(path),`.${basename(path)}.prune.${process.pid}.${randomUUID()}`);try{renameSync(path,quarantine)}catch(error62){if(systemCode(error62)==="ENOENT")return false;throw error62}let remove=false;try{const raw=readOwnerOnlyTextFile(quarantine,{label:options.label,maxBytes:options.maxBytes});remove=options.shouldRemove(raw)}catch{remove=false}if(remove){try{unlinkSync(quarantine)}catch(error62){if(systemCode(error62)!=="ENOENT")throw error62}return true}restoreQuarantinedFile(path,quarantine);return false}function defaultPidIsAlive(pid){try{process.kill(pid,0);return true}catch(error62){return systemCode(error62)!=="ESRCH"}}function parseLockRecord(raw){try{const value=JSON.parse(raw);if(value.version!==1||typeof value.token!=="string"||!/^[0-9a-f-]{36}$/i.test(value.token)||!Number.isSafeInteger(value.pid)||value.pid<=0||typeof value.createdAt!=="string"||!Number.isFinite(Date.parse(value.createdAt)))return void 0;return value}catch{return void 0}}function readLockObservation(path,options){const stat=inspectOwnerFileShape(path,`${options.label} lock`,true);let fd;let raw=Buffer.alloc(0);try{fd=openSync(path,constants.O_RDONLY|NO_FOLLOW);const opened=fstatSync(fd);if(!opened.isFile()||opened.nlink!==1||opened.dev!==stat.dev||opened.ino!==stat.ino)throw new SafeFileError("lock_changed",`${options.label} lock changed during inspection.`);raw=Buffer.allocUnsafe(MAX_LOCK_BYTES+1);let offset=0;while(offset<raw.length){const count2=readSync(fd,raw,offset,raw.length-offset,null);if(count2===0)break;offset+=count2}const record4=offset<=MAX_LOCK_BYTES?parseLockRecord(raw.subarray(0,offset).toString("utf8")):void 0;const stale=record4?!(options.pidIsAlive??defaultPidIsAlive)(record4.pid):(options.now??(()=>new Date))().getTime()-stat.mtimeMs>=(options.malformedStaleAfterMs??DEFAULT_MALFORMED_LOCK_STALE_MS);return{stat:{dev:stat.dev,ino:stat.ino,size:stat.size,mtimeMs:stat.mtimeMs},record:record4,stale}}finally{if(fd!==void 0)closeBestEffort(fd);raw.fill(0)}}function removeStaleLock(path,observed,options){const quarantine=`${path}.stale.${process.pid}.${randomUUID()}`;try{renameSync(path,quarantine)}catch(error62){if(systemCode(error62)==="ENOENT")return;throw new SafeFileError("stale_lock_recovery_failed",`${options.label} stale lock could not be quarantined.`,{cause:error62})}try{const quarantined=readLockObservation(quarantine,options);const sameIdentity=quarantined.stat.dev===observed.stat.dev&&quarantined.stat.ino===observed.stat.ino;const sameRecord=observed.record?quarantined.record?.token===observed.record.token:quarantined.record===void 0;if(!sameIdentity||!sameRecord){if(!existsSync(path))renameSync(quarantine,path);throw new SafeFileError("lock_contended",`${options.label} lock changed during stale recovery.`)}unlinkSync(quarantine);syncDirectory(dirname(path),`${options.label} lock directory`,options.durability??"none")}catch(error62){if(error62 instanceof SafeFileError)throw error62;throw new SafeFileError("stale_lock_recovery_failed",`${options.label} stale lock could not be removed safely.`,{cause:error62})}}function acquireLock(path,record4,options){const body=Buffer.from(`${JSON.stringify(record4)}
|
|
9
9
|
`,"utf8");let fd;try{fd=openSync(path,constants.O_CREAT|constants.O_EXCL|constants.O_WRONLY|NO_FOLLOW,DEFAULT_FILE_MODE);if(process.platform!=="win32")fchmodSync(fd,DEFAULT_FILE_MODE);const stat=fstatSync(fd);ownerAndMode(stat,DEFAULT_FILE_MODE,`${options.label} lock`,"file");assertSingleLink(stat,`${options.label} lock`);writeAll(fd,body);syncFile(fd,`${options.label} lock`,options.durability??"none");closeSync(fd);fd=void 0;syncDirectory(dirname(path),`${options.label} lock directory`,options.durability??"none")}catch(error62){if(fd!==void 0)closeBestEffort(fd);if(systemCode(error62)==="EEXIST")throw new SafeFileError("lock_contended",`${options.label} is locked by another writer: ${path}.`,{cause:error62});if(error62 instanceof SafeFileError)throw error62;throw new SafeFileError("lock_failed",`${options.label} lock could not be acquired: ${path}.`,{cause:error62})}finally{body.fill(0)}}function withOwnerOnlyFileLock(targetPath,options,operation){const lockPath=options.lockPath??`${targetPath}.lock`;inspectRealDirectory(dirname(lockPath),`${options.label} lock directory`);const record4={version:1,token:randomUUID(),pid:process.pid,createdAt:(options.now??(()=>new Date))().toISOString()};try{acquireLock(lockPath,record4,options)}catch(error62){if(!(error62 instanceof SafeFileError)||error62.code!=="lock_contended")throw error62;const observed=readLockObservation(lockPath,options);if(!observed.stale)throw error62;removeStaleLock(lockPath,observed,options);acquireLock(lockPath,record4,options)}let result2;let operationError;let operationFailed=false;try{result2=operation()}catch(error62){operationFailed=true;operationError=error62}let releaseError;try{const current=parseLockRecord(readOwnerOnlyTextFile(lockPath,{label:`${options.label} lock`,maxBytes:MAX_LOCK_BYTES}));if(!current||current.token!==record4.token)throw new SafeFileError("lock_ownership_lost",`${options.label} lock ownership changed before release.`);unlinkSync(lockPath);syncDirectory(dirname(lockPath),`${options.label} lock directory`,options.durability??"none")}catch(error62){releaseError=error62 instanceof SafeFileError?error62:new SafeFileError("lock_release_failed",`${options.label} lock could not be released safely.`,{cause:error62})}if(operationFailed){if(releaseError!==void 0&&operationError instanceof Error)Object.defineProperty(operationError,"lockReleaseError",{value:releaseError,enumerable:false});throw operationError}if(releaseError!==void 0)throw releaseError;return result2}var RUNTIME_SCHEMA_VERSION=2;var RUNTIME_DIR_SEGMENTS=["runtime"];var RUNTIME_PRUNE_LIMIT=32;var RUNTIME_PRUNE_INSPECTION_LIMIT=64;var MAX_RUNTIME_FILE_BYTES=64*1024;var pruneCursor=new Map;function runtimeDirPath(home){return join3(home,...RUNTIME_DIR_SEGMENTS)}function runtimeFilePath(home,pid){return join3(runtimeDirPath(home),`${pid}.json`)}function processStartedAtIso(now=new Date){return new Date(now.getTime()-process.uptime()*1e3).toISOString()}function writeRuntimeFile(home,snapshot){const dir=runtimeDirPath(home);ensureOwnerOnlyDirectory(dir,{label:"Parle runtime directory",repairMode:true});atomicReplaceOwnerOnlyFile(runtimeFilePath(home,snapshot.pid),JSON.stringify(snapshot,null,2)+"\n",{label:"Parle runtime snapshot",maxBytes:MAX_RUNTIME_FILE_BYTES,durability:"none"});try{pruneRuntimeFiles(home,new Date(snapshot.updatedAt),{excludePid:snapshot.pid})}catch{}}function removeRuntimeFile(home,pid){rmSync(runtimeFilePath(home,pid),{force:true})}function pidLiveness(pid){try{process.kill(pid,0);return"alive"}catch(error62){return error62?.code==="ESRCH"?"dead":"uncertain"}}function boundedLimit(value,fallback){const parsed2=Math.trunc(value??fallback);return Number.isFinite(parsed2)?Math.max(0,parsed2):fallback}function rotatedCandidates(dir,names,limit){if(!names.length||limit===0)return[];names.sort();const start=(pruneCursor.get(dir)??0)%names.length;const count2=Math.min(limit,names.length);const selected=Array.from({length:count2},(_,offset)=>names[(start+offset)%names.length]);pruneCursor.set(dir,(start+count2)%names.length);return selected}function pruneRuntimeFiles(home,now=new Date,options={}){const dir=runtimeDirPath(home);let names;try{names=readdirSync(dir).filter(name=>!name.startsWith(".")&&name.endsWith(".json"))}catch{return}const maxInspections=boundedLimit(options.maxInspections,RUNTIME_PRUNE_INSPECTION_LIMIT);const maxRemovals=boundedLimit(options.maxRemovals,RUNTIME_PRUNE_LIMIT);const inspectPid=options.inspectPid??pidLiveness;let removed=0;for(const name of rotatedCandidates(dir,names,maxInspections)){if(removed>=maxRemovals)break;const path=join3(dir,name);if(removeOwnerOnlyFileIf(path,{label:"Parle runtime snapshot",maxBytes:MAX_RUNTIME_FILE_BYTES,shouldRemove:raw=>{let snapshot;try{snapshot=JSON.parse(raw)}catch{return false}if(!snapshot||!Number.isSafeInteger(snapshot.pid)||snapshot.pid<=0||snapshot.pid===process.pid||snapshot.pid===options.excludePid)return false;const expiresAt=Date.parse(snapshot.expiresAt||"");return Number.isFinite(expiresAt)&&expiresAt<=now.getTime()&&inspectPid(snapshot.pid)==="dead"}}))removed+=1}}import{readdirSync as readdirSync2,rmSync as rmSync2}from"node:fs";import{dirname as dirname2,join as join4}from"node:path";function pluginSemver(value){const match=/^(\d+)\.(\d+)\.(\d+)$/.exec(value??"");return match?[Number(match[1]),Number(match[2]),Number(match[3])]:void 0}function comparePluginVersions(left,right){const a=pluginSemver(left);const b=pluginSemver(right);if(!a||!b)return a?1:b?-1:0;for(let index=0;index<3;index+=1)if(a[index]!==b[index])return a[index]-b[index];return 0}var SESSION_REGISTRY_SCHEMA_VERSION=1;var MAX_ENTRY_BYTES=64*1024;var MAX_PRUNE_PER_WRITE=20;function sessionRegistryDir(env=process.env){return join4(parleHome(env),"sessions")}function part(value){return value.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,128)}function sessionRegistryKey(host){return[host.kind,host.sessionId,...host.discriminator?[host.discriminator]:[]].map(part).join("-")}function sessionRegistryPath(dir,host,pid){return join4(dir,`${sessionRegistryKey(host)}.${pid}.json`)}function writeSessionRegistryEntry(path,entry,now=new Date){const dir=dirname2(path);ensureOwnerOnlyDirectory(dir,{label:"Parle session registry",repairMode:true});atomicReplaceOwnerOnlyFile(path,`${JSON.stringify(entry,null,2)}
|
|
10
|
-
`,{label:"Parle session registry entry",maxBytes:MAX_ENTRY_BYTES,durability:"none"});try{pruneSessionRegistry(dir,now,entry.pid)}catch{}}function removeSessionRegistryEntry(path){rmSync2(path,{force:true})}function readSessionRegistry(dir,inspectPid=pidLiveness){let names;try{names=readdirSync2(dir)}catch{return[]}const out=[];for(const name of names){if(name.startsWith(".")||!name.endsWith(".json"))continue;const path=join4(dir,name);try{const entry=JSON.parse(readOwnerOnlyTextFile(path,{label:"Parle session registry entry",maxBytes:MAX_ENTRY_BYTES}));if(!entry||entry.schemaVersion!==SESSION_REGISTRY_SCHEMA_VERSION||typeof entry.pid!=="number"||!entry.host?.kind||!entry.host?.sessionId)continue;out.push({path,entry,live:inspectPid(entry.pid)==="alive"})}catch{}}return out}function liveSessionEntries(dir,host,inspectPid){const key=sessionRegistryKey(host);return readSessionRegistry(dir,inspectPid).filter(record4=>record4.live&&sessionRegistryKey(record4.entry.host)===key)}function pruneSessionRegistry(dir,_now,ownPid){let removed=0;for(const record4 of readSessionRegistry(dir)){if(removed>=MAX_PRUNE_PER_WRITE)return;if(record4.entry.pid===ownPid||record4.live||pidLiveness(record4.entry.pid)!=="dead")continue;rmSync2(record4.path,{force:true});removed+=1}}function newerDeliveringSibling(records,ownPid,ownVersion){if(!pluginSemver(ownVersion))return void 0;return records.filter(({entry,live})=>live&&entry.pid!==ownPid&&entry.delivery?.state==="watching").map(({entry})=>entry).find(entry=>pluginSemver(entry.adapter?.version)&&comparePluginVersions(entry.adapter?.version,ownVersion)>0)}import{randomUUID as randomUUID2}from"node:crypto";var processClientInstance;function processClientInstanceId(){processClientInstance||=randomUUID2();return processClientInstance}var REPORTED_METADATA_LIMIT=96;var SOFTWARE_NAME_RE=/^(?:(?:@?[a-z0-9][a-z0-9._-]*)\/)?[a-z0-9][a-z0-9._-]*$/;var RELEASE_TOKEN_RE=/^[0-9A-Za-z][0-9A-Za-z._+!-]*$/;function assertReportedMetadataBounds(value,label){if(value.length===0||value.length>REPORTED_METADATA_LIMIT||!/^[\x20-\x7e]+$/.test(value)){throw new Error(`Parle ${label} must be 1 to ${REPORTED_METADATA_LIMIT} printable ASCII bytes.`)}}function assertClientName(value){assertReportedMetadataBounds(value,"clientName");if(!SOFTWARE_NAME_RE.test(value))throw new Error("Parle clientName must be a canonical software identifier.");return value}function assertClientVersion(value){assertReportedMetadataBounds(value,"clientVersion");if(!RELEASE_TOKEN_RE.test(value))throw new Error("Parle clientVersion must be a bounded release token.");return value}function assertClientInstanceId(value){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[47][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)){throw new Error("Parle clientInstanceId must be a canonical UUIDv4 or UUIDv7.")}return value.toLowerCase()}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function nonNegative(value){return typeof value==="number"&&Number.isFinite(value)&&value>=0?value:void 0}function retryAfterMsFrom(candidate){const ms=nonNegative(candidate.retry_after_ms);if(ms!==void 0)return Math.trunc(ms);const seconds=nonNegative(candidate.retry_after_seconds);return seconds===void 0?void 0:Math.trunc(seconds*1e3)}function retryAfterHeaderMs(value,nowMs){const text=value?.trim();if(!text)return void 0;if(/^\d+$/.test(text))return Number(text)*1e3;const at=Date.parse(text);return Number.isFinite(at)?Math.max(0,at-nowMs):void 0}function parseErrorEnvelope(value){const outer=value&&typeof value==="object"?value:{};const candidate=outer.error&&typeof outer.error==="object"?outer.error:outer;return{code:nonEmptyString(candidate.code),message:nonEmptyString(candidate.message),action:nonEmptyString(candidate.action),scope:nonEmptyString(candidate.scope),retryable:typeof candidate.retryable==="boolean"?candidate.retryable:void 0,retryAfterMs:retryAfterMsFrom(candidate),limitedBy:nonEmptyString(candidate.limited_by),lastErrorCode:nonEmptyString(candidate.last_error_code),raw:candidate}}var LIMITER_CODES=new Set(["rate_limited","service_unavailable"]);var QUOTA_CODES=new Set(["monthly_quota_exceeded","monthly_room_quota_exceeded","resource_limit_exceeded","invite_allowance_exceeded","approval_request_quota_exceeded","grant_quota_exceeded"]);var LIMITED_BY_WORDS={lease:"this session alone, so slowing this session down is enough",credential:"this agent's key, which its other sessions share; if it keeps happening, tell your principal",agent:"this agent, across all of its sessions",principal:"your principal, across all of their agents and sessions, so slow down everywhere; if it keeps happening, tell your principal",room:"this room, which everyone in it shares, so slow down in this room",ip:"this network address, which everything connecting from it shares"};var LIMITER_THRESHOLD_FIELDS=["burst","submission_rate_per_minute"];function errorObject(details){if(!details||typeof details!=="object")return void 0;const outer=details;return outer.error&&typeof outer.error==="object"?outer.error:outer}function limitRefusalKind(code,details){if(typeof code!=="string")return void 0;if(QUOTA_CODES.has(code))return"quota";if(LIMITER_CODES.has(code))return"limiter";const limitedBy=errorObject(details)?.limited_by;return typeof limitedBy==="string"&&limitedBy.length>0?"limiter":void 0}function limitedByWords(limitedBy){if(typeof limitedBy!=="string"||limitedBy.length===0)return void 0;return LIMITED_BY_WORDS[limitedBy]??`its ${limitedBy}`}function waitWords(retryAfterMs){if(typeof retryAfterMs!=="number"||!Number.isFinite(retryAfterMs)||retryAfterMs<0)return void 0;const seconds=Math.max(1,Math.ceil(retryAfterMs/1e3));if(seconds<120)return`${seconds} second${seconds===1?"":"s"}`;const minutes=Math.ceil(seconds/60);if(minutes<120)return`${minutes} minutes`;return`${Math.ceil(minutes/60)} hours`}var ERROR_CODE=/^[a-z][a-z0-9_]{0,63}$/;function limiterHint(refusal){const error62=errorObject(refusal.details)??{};const code=refusal.code??(typeof error62.code==="string"?error62.code:void 0);const action=refusal.action??(typeof error62.action==="string"?error62.action:void 0);let retryAfterMs=refusal.retryAfterMs;if(retryAfterMs===void 0&&typeof error62.retry_after_ms==="number")retryAfterMs=error62.retry_after_ms;if(retryAfterMs===void 0&&typeof error62.retry_after_seconds==="number")retryAfterMs=error62.retry_after_seconds*1e3;const parts=[];const by=limitedByWords(error62.limited_by);switch(code){case"service_unavailable":parts.push("Parle is briefly unavailable.");break;default:parts.push(by?`Parle limited this request. The limit counts against ${by}.`:"Parle limited this request.")}const lastErrorCode=error62.last_error_code;if(typeof lastErrorCode==="string"&&ERROR_CODE.test(lastErrorCode)){parts.push(`Earlier requests kept failing with ${lastErrorCode}: fix that call before retrying it.`)}const wait=waitWords(retryAfterMs);const resetsAt=typeof error62.resets_at==="string"?error62.resets_at:void 0;if(action==="stop"){parts.push(resetsAt?`Don't retry before ${resetsAt}.`:wait?`Don't retry for ${wait}.`:"Don't retry it now.")}else if(wait){parts.push(`Wait ${wait}, then retry.`)}else{parts.push("Wait a moment, then retry.")}return parts.join(" ")}function withoutLimiterThresholds(details){if(!details||typeof details!=="object")return details;const strip=value=>{const copy={...value};for(const field of LIMITER_THRESHOLD_FIELDS)delete copy[field];return copy};const outer=details;if(outer.error&&typeof outer.error==="object")return{...outer,error:strip(outer.error)};return strip(outer)}var QUOTA_WORDS={owned_active_rooms:"active rooms your principal owns",room_active_participants:"people and agent addresses in this room",active_memberships:"rooms your principal is in",active_delivery_addresses:"your principal's active agent addresses",monthly_room_creations:"rooms your principal may create this month"};function quotaHint(code,details){if(limitRefusalKind(code,details)!=="quota")return void 0;const levels=[details,errorObject(details),errorObject(details)?.details].filter(level=>Boolean(level)&&typeof level==="object");const field=name=>levels.map(level=>level[name]).find(value=>value!==void 0&&value!==null);const cap=field("cap");const used=field("used");const limit=field("limit");const recovery=field("recovery");const resetsAt=field("resets_at");if(!(typeof cap==="string"&&cap)&&typeof limit!=="number")return void 0;const what=typeof cap==="string"&&cap?QUOTA_WORDS[cap]??cap:"a quota";const numbers=typeof used==="number"&&typeof limit==="number"?` (${used} of ${limit})`:typeof limit==="number"?` (limit ${limit})`:"";return[`Parle quota reached: ${what}${numbers}.`,typeof recovery==="string"&&recovery?recovery:void 0,typeof resetsAt==="string"&&resetsAt?`It renews at ${resetsAt}.`:void 0,"Retrying won't help until it frees up; tell your principal if they need to act."].filter(Boolean).join(" ")}import{createHash,createHmac,randomBytes,randomUUID as randomUUID3}from"node:crypto";import{closeSync as closeSync2,constants as constants2,fstatSync as fstatSync2,ftruncateSync,lstatSync as lstatSync2,openSync as openSync2,writeSync as writeSync2}from"node:fs";import{isAbsolute as isAbsolute2,join as join5,resolve}from"node:path";var DEFAULT_VERSION="2026-11-18";var ParleApiError=class extends Error{status;code;action;scope;retryAfterMs;retryable;details;requestId;constructor(message,options={}){super(message);this.name="ParleApiError";this.status=options.status;this.code=options.code;this.action=options.action;this.scope=options.scope;this.retryAfterMs=options.retryAfterMs;this.retryable=options.retryable??false;this.details=options.details;this.requestId=options.requestId}};function parleApiErrorFields(error62){return{code:error62.code,status:error62.status,action:error62.action,scope:error62.scope,retryable:error62.retryable,retryAfterMs:error62.retryAfterMs,...error62.requestId?{requestId:error62.requestId}:{},...error62.details&&typeof error62.details==="object"?{details:error62.details}:{}}}var PARLE_CREDENTIAL_RE=/parle_[a-z]+_[A-Za-z0-9_-]{20,}/g;var PARLE_BEARER_RE=/^parle_[a-z]+_[A-Za-z0-9_-]+$/i;var AUTHORIZATION_CREDENTIAL_RE=/(authorization\\?["']?\s*[:=]\s*\\?["']?\s*(?:bearer|dpop|basic|token)\s+)([A-Za-z0-9_~./+=:-]*[A-Za-z0-9_~+/=:-])/gi;var BEARER_VALUE_RE=/(Bearer\s+)([A-Za-z0-9_~./+=:-]*[A-Za-z0-9_~+/=:-])/gi;var BARE_JWT_RE=/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g;function isBearerTokenShape(value){if(PARLE_BEARER_RE.test(value))return true;return value.length>=20&&/^[A-Za-z]+$/.test(value)||value.length>=6&&/[0-9_~./+=:-]/.test(value)}function redactAuthorizationCredentials(input2){return input2.replace(AUTHORIZATION_CREDENTIAL_RE,"$1<redacted>").replace(BEARER_VALUE_RE,(match,prefix,value)=>isBearerTokenShape(value)?`${prefix}<redacted>`:match).replace(BARE_JWT_RE,value=>value.length>=20?"<redacted-jwt>":value)}function isParleCredential(value){PARLE_CREDENTIAL_RE.lastIndex=0;return PARLE_CREDENTIAL_RE.test(value)}function redactString(input2){const out=redactAuthorizationCredentials(input2).replace(/(__Host-parle_session=)[^;\s]+/g,"$1<redacted>").replace(/(Idempotency-Key\s*[:=]\s*)[A-Za-z0-9._:-]+/gi,"$1<redacted>").replace(/(Parle-Agent-Session\s*[:=]\s*)[A-Za-z0-9._:-]+/gi,"$1<redacted>");PARLE_CREDENTIAL_RE.lastIndex=0;return out.replace(PARLE_CREDENTIAL_RE,"<redacted-token>")}var ADDRESS_HANDLE_MIN_LENGTH=2;var ADDRESS_HANDLE_MAX_LENGTH=24;var SESSION_ALIAS_MAX_LENGTH=32;var ADDRESS_HANDLE_PATTERN=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;var NEW_HANDLE_RULE=`${ADDRESS_HANDLE_MIN_LENGTH} to ${ADDRESS_HANDLE_MAX_LENGTH} lowercase letters, digits and single hyphens, with at least one letter, not a reserved word`;var ANONYMOUS_SESSION_HANDLE_PATTERN=/^[a-z2-7]{16}$/;var RESERVED_ADDRESS_HANDLES=new Set(["admin","agent","agents","api","me","null","parle","room","rooms","root","support","system","www"]);function isValidAddressHandle(value){return value.length>=ADDRESS_HANDLE_MIN_LENGTH&&value.length<=ADDRESS_HANDLE_MAX_LENGTH&&ADDRESS_HANDLE_PATTERN.test(value)&&!RESERVED_ADDRESS_HANDLES.has(value)}function isReadableAddressHandle(value){return value.length>=ADDRESS_HANDLE_MIN_LENGTH&&value.length<=SESSION_ALIAS_MAX_LENGTH&&ADDRESS_HANDLE_PATTERN.test(value)&&!RESERVED_ADDRESS_HANDLES.has(value)}function isValidSessionAlias(value){return value.length>=ADDRESS_HANDLE_MIN_LENGTH&&value.length<=SESSION_ALIAS_MAX_LENGTH&&ADDRESS_HANDLE_PATTERN.test(value)&&!RESERVED_ADDRESS_HANDLES.has(value)&&!ANONYMOUS_SESSION_HANDLE_PATTERN.test(value)}var LEVELS={debug:1,trace:2};var DEBUG_EVENTS=["client_start","http_start","http_response","http_error","http_body_error","delivery_start","delivery_stop","stream_connect","stream_open","stream_eof","stream_error","stream_retry","stream_close","room_error","wake_open","wake_hint","fetch_started","fetch_success","row_fetched","handling_complete","ack_started","ack_success","background_error","mcp_client","mcp_call_meta"];var TRACE_EVENTS=["hook_walk_step","hook_probe_error","hook_host_found","hook_host_missing","hook_bridges_none","hook_bridge_unresponsive"];var EVENTS=new Map([...DEBUG_EVENTS.map(event=>[event,"debug"]),...TRACE_EVENTS.map(event=>[event,"trace"])]);var METHODS=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"]);var REASONS=new Set(["stopped","revision_changed","interrupted","recover","drain","handler","ack","walk_end","self_parent","depth"]);var PROCESS_KINDS=new Set(["codex","codex_refused","shell","other","unknown"]);var TOOLS=new Set(["ps","lsof"]);var BACKGROUND_OPERATIONS=["key_rotation","address_reconnect","room_instructions_refresh","host_session_rebind","address_facts_refresh","room_drain","hook_socket_listen","address_rooms_read","features_read","missed_notices_read","room_set_refresh"];var OPERATIONS=new Set(BACKGROUND_OPERATIONS);var TRIGGERS=new Set(["startup","wake_open","wake_hint","test"]);var TRANSPORT_CODES=new Set(["UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_ABORTED","UND_ERR_DESTROYED","UND_ERR_CLOSED","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","ENOTFOUND","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","ECANCELED","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","CERT_HAS_EXPIRED","ERR_TLS_CERT_ALTNAME_INVALID","UNABLE_TO_GET_ISSUER_CERT_LOCALLY"]);var PROCESS_CODES=new Set(["EAGAIN","ENOMEM","EMFILE","ENFILE","EPERM","EACCES","ENOENT","EIO","ETIMEDOUT"]);var SIGNALS=new Set(["SIGTERM","SIGKILL","SIGINT","SIGHUP"]);var ERROR_NAMES=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","ParleApiError","TokenEndpointError"]);var ACTIONS=new Set(["retry","backoff","retry_with_backoff","reauthorize","fix_client","stop","rebootstrap"]);var SYSCALLS=new Set(["read","write","connect","getaddrinfo"]);var MAX_BYTES=1024*1024;var COMPONENTS=new Set(["client","delivery","account","desktop","approval","oauth","hook"]);var wrappedFetches=new WeakMap;var responseDiagnostics=new WeakMap;var MAX_SINKS=64;var sinks=new Map;var CLIENT_LABEL=/^[A-Za-z0-9 ._@/+:-]{1,64}$/;var META_KEY=/^[A-Za-z0-9_.:/-]{1,64}$/;var META_KEYS_MAX=24;function metaFingerprints(meta3){if(!meta3||typeof meta3!=="object"||Array.isArray(meta3))return void 0;const out={};const add=(key,value)=>{if(Object.keys(out).length>=META_KEYS_MAX||!META_KEY.test(key))return;const type=value===null?"null":Array.isArray(value)?"array":typeof value;let text;try{text=JSON.stringify(value)??String(value)}catch{text=type}out[key]=`${type}:${createHash("sha256").update("parle-debug-meta\0").update(text.slice(0,8192)).digest("hex").slice(0,16)}`};for(const key of Object.keys(meta3)){const value=own(meta3,key);if(value&&typeof value==="object"&&!Array.isArray(value)){for(const inner of Object.keys(value))add(`${key}.${inner}`,own(value,inner))}else add(key,value)}return out}var noop=()=>Object.assign(()=>{},{close:()=>{},nextRequest:()=>0,enabled:false});function own(value,key){if(!value||typeof value!=="object")return void 0;return Object.getOwnPropertyDescriptor(value,key)?.value}function nameOf(error62){const name=own(error62,"name");if(typeof name==="string"&&ERROR_NAMES.has(name))return name;if(error62 instanceof TypeError)return"TypeError";if(error62 instanceof RangeError)return"RangeError";if(error62 instanceof SyntaxError)return"SyntaxError";return"Error"}function debugLevel(env){if(env.PARLE_DEBUG==="1"||env.PARLE_DEBUG==="true")return"debug";if(env.PARLE_DEBUG==="trace")return"trace";return void 0}function debugScope(env,component){if(!COMPONENTS.has(component)||!debugLevel(env))return void 0;const home=parleHome(env);if(!isAbsolute2(home))return void 0;const normalized=resolve(home);return{home:normalized,key:JSON.stringify([component,normalized])}}function createAdapterDebugLog(env,now,component="delivery"){try{const scope=debugScope(env,component);if(!scope)return noop();let sink=sinks.get(scope.key);if(!sink){if(sinks.size>=MAX_SINKS)return noop();sink=createSink(scope.home,component);sinks.set(scope.key,sink)}const shared=sink,logger=shared.nextLogger();const level=LEVELS[debugLevel(env)??"debug"];let closed=false;const log=(event,detail,error62)=>{const eventLevel=EVENTS.get(event);if(closed||!shared.enabled||!eventLevel||LEVELS[eventLevel]>level)return;try{shared.write(Date.prototype.toISOString.call(now()),logger,event,detail,error62)}catch{closed=true}};return Object.defineProperty(Object.assign(log,{close:()=>{closed=true},nextRequest:()=>closed||!shared.enabled?0:shared.nextRequest()}),"enabled",{get:()=>!closed&&shared.enabled})}catch{return noop()}}function createSink(home,component){const root=home;const stem=`${component}-${process.pid}-${randomUUID3()}`;const salt=randomBytes(32);const ref=value=>typeof value==="string"&&value.length>0?createHmac("sha256",salt).update(value.slice(0,8192)).digest("hex").slice(0,24):void 0;let slot=0,bytes=0,failed=false,loggerSequence=0,requestSequence=0;const identities=[];const errorFacts=error62=>{const result2={name:nameOf(error62)};const code=own(error62,"code");if(typeof code==="string"&&(TRANSPORT_CODES.has(code)||PROCESS_CODES.has(code)))result2.code=code;else if(ref(code))result2.codeRef=ref(code);if(Array.isArray(own(error62,"output"))){const signal=own(error62,"signal"),exitStatus=own(error62,"status");if(typeof signal==="string"&&SIGNALS.has(signal))result2.signal=signal;if(typeof exitStatus==="number"&&Number.isInteger(exitStatus)&&exitStatus>=0&&exitStatus<=255)result2.exitStatus=exitStatus}const action=own(error62,"action");if(typeof action==="string"&&ACTIONS.has(action))result2.action=action;if(error62 instanceof ParleApiError){const status=own(error62,"status"),retryAfterMs=own(error62,"retryAfterMs"),retryable=own(error62,"retryable");if(typeof status==="number"&&Number.isInteger(status)&&status>=100&&status<=599)result2.status=status;if(typeof retryAfterMs==="number"&&Number.isInteger(retryAfterMs)&&retryAfterMs>=0&&retryAfterMs<=2**31-1)result2.retryAfterMs=retryAfterMs;if(typeof retryable==="boolean")result2.retryable=retryable}const message=own(error62,"message");if(message==="terminated")result2.reason="terminated";if(message==="Parle agent stream ended unexpectedly")result2.reason="stream_eof";const seen=new Set([error62]);let cause=own(error62,"cause");const causes=[];for(let depth=0;cause&&typeof cause==="object"&&!seen.has(cause)&&depth<3;depth++){seen.add(cause);const facts={name:nameOf(cause)};const code2=own(cause,"code"),syscall=own(cause,"syscall");if(typeof code2==="string"&&TRANSPORT_CODES.has(code2))facts.code=code2;else if(ref(code2))facts.codeRef=ref(code2);if(typeof syscall==="string"&&SYSCALLS.has(syscall))facts.syscall=syscall;causes.push(facts);cause=own(cause,"cause")}if(causes.length)result2.causes=causes;return result2};const write=(at,logger,event,detail,error62)=>{if(failed||!EVENTS.has(event))return;let fd;try{const safe={};for(const key of["attempt","durationMs","retryMs","request","status","seq","rowCount","processId","depth"]){const value=own(detail,key);if(typeof value!=="number"||!Number.isFinite(value)||value<0)continue;if(key==="status"&&(value!==0&&(!Number.isInteger(value)||value<100||value>599)))continue;if(!["durationMs","retryMs"].includes(key)&&!Number.isSafeInteger(value))continue;safe[key]=value}for(const[key,allowed]of[["trigger",TRIGGERS],["reason",REASONS],["method",METHODS],["kind",PROCESS_KINDS],["tool",TOOLS],["operation",OPERATIONS]]){const value=own(detail,key);if(typeof value==="string"&&allowed.has(value))safe[key]=value}for(const key of["clientName","clientVersion"]){const value=own(detail,key);if(typeof value==="string"&&CLIENT_LABEL.test(value))safe[key]=value}const meta3=metaFingerprints(own(detail,"meta"));if(meta3)safe.metaKeys=meta3;for(const key of["roomId","eventId","path"]){const value=ref(own(detail,key));if(value)safe[key==="path"?"routeRef":key==="roomId"?"roomRef":"eventRef"]=value}const line2=JSON.stringify({at,pid:process.pid,component,logger,event,...safe,...error62?{error:errorFacts(error62)}:{}})+"\n";const buffer=Buffer.from(line2);if(buffer.length>MAX_BYTES)return;ensureOwnerOnlyDirectory(root,{label:"Parle state directory"});const directory=ensureOwnerOnlyDirectory(join5(root,"debug"),{label:"Parle debug directory"});const rotate=bytes+buffer.length>MAX_BYTES;if(rotate){slot=1-slot;bytes=0}const path=join5(directory,`${stem}-${slot}.jsonl`);fd=openSync2(path,constants2.O_WRONLY|(identities[slot]?0:constants2.O_CREAT|constants2.O_EXCL)|(constants2.O_NOFOLLOW||0),384);const stat=fstatSync2(fd),link=lstatSync2(path),identity=identities[slot];if(!stat.isFile()||stat.nlink!==1||link.isSymbolicLink()||stat.dev!==link.dev||stat.ino!==link.ino||identity&&(stat.dev!==identity.dev||stat.ino!==identity.ino)||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||(stat.mode&511)!==384))throw new Error("unsafe debug file");identities[slot]={dev:stat.dev,ino:stat.ino};if(rotate&&identity){ftruncateSync(fd,0)}let written=0;while(written<buffer.length){const count2=writeSync2(fd,buffer,written,buffer.length-written,bytes+written);if(count2<=0)throw new Error("debug write made no progress");written+=count2}bytes+=buffer.length}catch{failed=true}finally{if(fd!==void 0){try{closeSync2(fd)}catch{failed=true}}}};return{write,nextLogger:()=>++loggerSequence,nextRequest:()=>++requestSequence,get enabled(){return!failed}}}function createDebugFetch(env,fetchImpl,now,component="client"){const existing=wrappedFetches.get(fetchImpl);let key;try{const scope=debugScope(env,component);if(!scope)return existing?.original||fetchImpl;key=scope.key}catch{return existing?.original||fetchImpl}if(existing?.key===key)return fetchImpl;if(existing)fetchImpl=existing.original;const log=createAdapterDebugLog(env,now,component);if(!log.enabled)return fetchImpl;log("client_start");if(!log.enabled)return fetchImpl;const wrapped=async function(input2,init){if(!log.enabled)return fetchImpl.call(this,input2,init);const request=log.nextRequest();const startedAt=performance.now();let method,path;try{method=init?.method||(input2 instanceof Request?input2.method:"GET");path=typeof input2==="string"?new URL(input2).pathname:input2 instanceof URL?input2.pathname:input2 instanceof Request?new URL(input2.url).pathname:void 0}catch{}log("http_start",{request,method,path});try{const response=await fetchImpl.call(this,input2,init);try{log("http_response",{request,method,path,status:response.status,durationMs:Math.max(0,performance.now()-startedAt)});if(log.enabled)responseDiagnostics.set(response,{log,detail:{request,method,path:path?.slice(0,8192)}})}catch{}return response}catch(error62){log("http_error",{request,method,path,durationMs:Math.max(0,performance.now()-startedAt)},error62);throw error62}};wrappedFetches.set(wrapped,{original:fetchImpl,key});return wrapped}async function readDebugResponse(response,method){try{return await response[method]()}catch(error62){const diagnostics=responseDiagnostics.get(response);diagnostics?.log("http_body_error",diagnostics.detail,error62);throw error62}}var RECORDED_RESPONSE_LIMIT=20;var REQUEST_ID=/^[0-9a-f]{16}$/;var ROUTE_MAX=120;var ROUTE_WORDS=new Set(["accept","accepted","access-grants","account","ack","acknowledge","activity","address-bindings","address-leases","address-waits","address-names","addresses","agent","agents","api-key","approval-requests","approve","attachments","auth","available-updates","begin","check","clear","clones","complete","confirm","counts","decision","decline","delivery","deny","device-authorizations","email","end","enroll","factor-recovery","factors","features","finish","freeze","github","google","handshake-waits","handshakes","history","identities","inbox","instructions","invites","keep","keys","leases","lifetime","link","login","logout","lookup","members","membership","messages","moderation","nudges","offline","offline-messages","onboarding","onboarding-invites","online","organizations","owner","owner-detail","participants","parties","passkey","passkeys","password","pause","person","policies","preferences","presets","preview","primary","principal","projection","providers","publish","read-marks","recovery-codes","regenerate","register","remint","replace","reset","resolve","resume","revisions","rights","room-invites","rooms","ruleset-share-invites","rulesets","scopes","seats","security","sharing","start","stepup","stored","stream","suspend","system-announcement","test","totp","transfer-destinations","transfers","unread","upgrade-notices","usage-consent-decisions","usage-consent-documents","usage-consents","v","verdicts","verify","visibility","wait-reset","waits","whoami","llms","llms.txt","openapi.json","endpoints.md","addresses.md","room-wire.md","responsive-delivery.md","errors.md"]);function requestIdFrom(headers){let value;try{value=headers?.get("x-request-id")}catch{return void 0}return typeof value==="string"&&REQUEST_ID.test(value)?value:void 0}function routeTemplate(method,url2){let pathname;try{pathname=new URL(url2).pathname}catch{return void 0}const path=pathname.split("/").filter(Boolean).map(segment=>ROUTE_WORDS.has(segment)?segment:":id").join("/");const verb=/^[A-Za-z]{1,10}$/.test(method)?method.toUpperCase():"OTHER";return`${verb} /${path}`.slice(0,ROUTE_MAX)}var ApiResponseRecorder=class{entries=[];record(input2,at){const request_id=requestIdFrom(input2.headers);const route=routeTemplate(input2.method,input2.url);if(!request_id||!route||!Number.isInteger(input2.status))return;this.entries.push({request_id,route,status:input2.status,at:at.toISOString()});if(this.entries.length>RECORDED_RESPONSE_LIMIT)this.entries.splice(0,this.entries.length-RECORDED_RESPONSE_LIMIT)}snapshot(){return this.entries.map(entry=>({...entry}))}clear(){this.entries=[]}};var apiResponses=new ApiResponseRecorder;var recordingWrappers=new WeakMap;var wrappers=new WeakSet;function recordResponses(fetchImpl,now,recorder=apiResponses){if(wrappers.has(fetchImpl))return fetchImpl;const existing=recordingWrappers.get(fetchImpl);if(existing)return existing;const wrapped=async function(input2,init){const response=await fetchImpl.call(this,input2,init);try{const request=input2 instanceof Request?input2:void 0;const method=init?.method||request?.method||"GET";const url2=typeof input2==="string"?input2:input2 instanceof URL?input2.href:request?.url??"";recorder.record({method,url:url2,headers:response.headers,status:response.status},now())}catch{}return response};recordingWrappers.set(fetchImpl,wrapped);wrappers.add(wrapped);return wrapped}var UPGRADE_NOTICE_HEADER="Parle-Upgrade-Notice";var HEADER_MAX=2048;var SERVER_LINE_MAX=300;function parseItem(input2){let i=0;const s=input2.replace(/^[ \t]+|[ \t]+$/g,"");const bareItem=()=>{const c=s.charAt(i);if(c==='"'){i++;let out="";while(i<s.length){const ch=s.charAt(i++);if(ch==="\\"){const next=s.charAt(i++);if(next!=='"'&&next!=="\\")return void 0;out+=next}else if(ch==='"'){return out}else{const code=ch.charCodeAt(0);if(code<32||code>126)return void 0;out+=ch}}return void 0}if(c==="?"){const b=s.charAt(i+1);if(b!=="0"&&b!=="1")return void 0;i+=2;return b==="1"}if(/^[A-Za-z*]$/.test(c)){const token=/^[A-Za-z*][!#$%&'*+\-.^_`|~0-9A-Za-z:/]*/.exec(s.slice(i))?.[0]??c;i+=token.length;return{token}}if(/^[-0-9]$/.test(c)){const match=/^-?\d{1,15}(?:\.\d{1,3})?/.exec(s.slice(i));if(!match)return void 0;i+=match[0].length;return Number(match[0])}return void 0};const value=bareItem();if(value===void 0)return void 0;const params=new Map;while(i<s.length){if(s.charAt(i)!==";")return void 0;i++;while(s.charAt(i)===" ")i++;const key=/^[a-z*][a-z0-9_\-.*]*/.exec(s.slice(i));if(!key)return void 0;i+=key[0].length;let paramValue=true;if(s.charAt(i)==="="){i++;const parsed2=bareItem();if(parsed2===void 0)return void 0;paramValue=parsed2}params.set(key[0],paramValue)}return{value,params}}function stringParam(params,name){const value=params.get(name);return typeof value==="string"?value:void 0}function serverLine(value,options={}){if(typeof value!=="string")return void 0;const folded=value.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();const line2=options.redact?options.redact(folded):folded;if(!line2)return void 0;const max=options.max??SERVER_LINE_MAX;return line2.length>max?`${line2.slice(0,max-1)}…`:line2}function sentenceBody(text){return text.replace(/[.!?]+$/,"")}function rfc3339(value){if(!value||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/i.test(value))return void 0;const ms=Date.parse(value);return Number.isFinite(ms)?new Date(ms).toISOString():void 0}function releaseVersion(value){return value&&value.length<=64&&/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/.test(value)?value:void 0}function migrationGuideUrl(value,requestUrl2){if(typeof value!=="string"||!value||value.length>2048)return void 0;try{if(value.startsWith("/")&&!value.startsWith("//"))return requestUrl2?new URL(value,new URL(requestUrl2).origin).href:value;const url2=new URL(value);return url2.protocol==="https:"&&!url2.username&&!url2.password?url2.href:void 0}catch{return void 0}}function parseUpgradeNotice(header,requestUrl2,options={}){try{if(typeof header!=="string"||!header||header.length>HEADER_MAX)return void 0;const item=parseItem(header);if(!item||typeof item.value!=="object")return void 0;const kind=item.value.token;if(kind!=="retiring"&&kind!=="recommended")return void 0;const note=serverLine(stringParam(item.params,"note"),{redact:options.redactNote});const migrationUrl=migrationGuideUrl(stringParam(item.params,"migration-url"),requestUrl2);const retiresAt=kind==="retiring"?rfc3339(stringParam(item.params,"retires-at")):void 0;const recommendedRelease=kind==="recommended"?releaseVersion(stringParam(item.params,"recommended-release")):void 0;return{kind,...retiresAt?{retiresAt}:{},...note?{note}:{},...recommendedRelease?{recommendedRelease}:{},...migrationUrl?{migrationUrl}:{}}}catch{return void 0}}function sameUpgradeNotice(a,b){return a?.kind===b?.kind&&a?.retiresAt===b?.retiresAt&&a?.note===b?.note&&a?.recommendedRelease===b?.recommendedRelease&&a?.migrationUrl===b?.migrationUrl}var MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function retirementDate(retiresAt,now=Date.now()){const at=new Date(retiresAt);const day=`${String(MONTHS[at.getUTCMonth()])} ${at.getUTCDate()}`;const year=at.getUTCFullYear()===new Date(now).getUTCFullYear()?"":`, ${at.getUTCFullYear()}`;const midnight=at.getUTCHours()===0&&at.getUTCMinutes()===0;const time3=midnight?"":` ${String(at.getUTCHours()).padStart(2,"0")}:${String(at.getUTCMinutes()).padStart(2,"0")} UTC`;return`${day}${year}${time3}`}var DAY_MS=24*60*60*1e3;function inFinalDay(retiresAt,now=Date.now()){if(!retiresAt)return false;const at=Date.parse(retiresAt);return now<at&&now>=at-DAY_MS}function parseVersionRefusal(error62,client,options={}){if(typeof error62!=="object"||error62===null)return{};const fields=error62;const lineOptions=options.redact?{redact:options.redact}:{};const required2=fields.required_version;const update=serverLine(typeof fields.update==="object"&&fields.update!==null?fields.update[client]:void 0,lineOptions);const migrationUrl=migrationGuideUrl(fields.migration_url,options.requestUrl);const note=serverLine(fields.note,lineOptions);return{...typeof required2==="string"&&/^\d{4}-\d{2}-\d{2}$/.test(required2)?{requiredVersion:required2}:{},...update?{update}:{},...migrationUrl?{migrationUrl}:{},...note?{note}:{}}}function parseUpgradeNotice2(header,requestUrl2){return parseUpgradeNotice(header,requestUrl2,{redactNote:redactString})}var UpgradeNoticeTracker=class{current;get notice(){return this.current}observe(headers,requestUrl2,options){const raw=headers?.get(UPGRADE_NOTICE_HEADER);if(raw===null||raw===void 0){if(options.clearWhenAbsent)this.current=void 0;return}const parsed2=parseUpgradeNotice2(raw,requestUrl2);if(parsed2)this.current=parsed2}};var GENERIC_UPDATE_STEPS="update the Parle adapter in this host, then restart it.";function upgradeNoticeLine(notice,updateSteps=GENERIC_UPDATE_STEPS,now=Date.now()){const steps=`Update: ${updateSteps.trim()}`;const guide=notice.migrationUrl?` Migration guide: ${notice.migrationUrl}`:"";if(notice.kind==="recommended"){const release=notice.recommendedRelease?` (${notice.recommendedRelease} or newer)`:"";const why2=notice.note?` ${sentenceBody(notice.note)}.`:"";return`An update is recommended${release}.${why2} ${steps}${guide}`}const why=notice.note?`: ${sentenceBody(notice.note)}.`:".";const lead=notice.retiresAt?`Parle stops serving this adapter's version on ${retirementDate(notice.retiresAt,now)}`:"This adapter's Parle version is retiring";return`${lead}${why} ${steps}${guide}`}var DAY_MS2=24*60*60*1e3;var UpgradeNoticeCadence=class{shownFor;lastShownAt;finalDayShown=false;sync(notice){if(sameUpgradeNotice(this.shownFor,notice))return;this.shownFor=notice;this.lastShownAt=void 0;this.finalDayShown=false}due(notice,now){if(!notice)return false;this.sync(notice);if(inFinalDay(notice.retiresAt,now)&&!this.finalDayShown)return true;return this.lastShownAt===void 0||now-this.lastShownAt>=DAY_MS2}shown(notice,now){this.sync(notice);this.lastShownAt=now;if(inFinalDay(notice.retiresAt,now))this.finalDayShown=true}};function parsed(value){return value}function readHandle(raw){const value=raw.trim().toLowerCase();return isValidAddressHandle(value)?value:void 0}function knownHandle(value,sign2){if(typeof value!=="string")return void 0;const bare=value.trim();return(bare.startsWith(sign2)?bare.slice(1):bare).trim().toLowerCase()||void 0}function roomIdInLink(value){let link;try{link=new URL(value.trim())}catch{return void 0}const loopback=link.hostname==="localhost"||link.hostname==="127.0.0.1"||link.hostname==="[::1]";if(link.protocol!=="https:"&&!(link.protocol==="http:"&&loopback)||link.username||link.password)return void 0;const match=link.pathname.match(/^\/rooms\/([0-9a-f-]{36})(?:\/.*)?$/i);return match&&UUID_RE.test(match[1])?match[1].toLowerCase():void 0}function looksLikeLink(value){return typeof value==="string"&&/^[a-z][a-z0-9+.-]*:\/\//i.test(value.trim())}function parseRoomReference(raw){if(typeof raw!=="string")return void 0;const value=raw.trim();if(UUID_RE.test(value))return parsed({kind:"id",id:value.toLowerCase()});if(looksLikeLink(value)){const id=roomIdInLink(value);return id?parsed({kind:"id",id}):void 0}const[room,...owner2]=(value.startsWith("#")?value.slice(1):value).split("@");const handle=readHandle(room);if(!handle)return void 0;if(owner2.length===0)return parsed({kind:"handle",handle});const ownerHandle=owner2.length===1?readHandle(owner2[0]):void 0;return ownerHandle?parsed({kind:"qualified",handle,owner:ownerHandle}):void 0}function roomReferenceText(reference){switch(reference.kind){case"id":return reference.id;case"handle":return reference.handle;case"qualified":return`${reference.handle}@${reference.owner}`}}function roomReferenceLabel(reference){return reference.kind==="id"?reference.id:`#${roomReferenceText(reference)}`}function sameRoomReference(left,right){return left.kind===right.kind&&roomReferenceText(left)===roomReferenceText(right)}function ownedByCaller(ownerId,principalId){const room=typeof ownerId==="string"&&UUID_RE.test(ownerId.trim())?ownerId.trim().toLowerCase():void 0;const caller=typeof principalId==="string"&&UUID_RE.test(principalId.trim())?principalId.trim().toLowerCase():void 0;return room&&caller?room===caller:void 0}function matchRoom(reference,rooms,facts){const seen=new Set;const known=rooms.flatMap(room=>{const fact=facts(room);const id=fact.id.toLowerCase();if(!id||seen.has(id))return[];seen.add(id);return[{room,fact,id}]});if(reference.kind==="id"){const found=known.find(entry=>entry.id===reference.id);return found?{match:found.room}:{none:true}}const named=known.filter(entry=>knownHandle(entry.fact.handle,"#")===reference.handle);if(reference.kind==="qualified"){const owned=named.find(entry=>knownHandle(entry.fact.owner,"@")===reference.owner);if(owned)return{match:owned.room};const unknown2=named.filter(entry=>entry.fact.owner===void 0);return unknown2.length?{ownerUnknown:unknown2.map(entry=>entry.room)}:{none:true}}const own3=named.filter(entry=>entry.fact.own===true);if(own3.length===1)return{match:own3[0].room};if(named.length===1)return{match:named[0].room};return named.length?{ambiguous:named.map(entry=>entry.room)}:{none:true}}function selectRooms(asked2,rooms,facts){const selection={rooms:[],missing:[],ambiguous:[],ownerUnknown:[]};for(const raw of asked2){const written=typeof raw==="string"?raw.trim():String(raw);const reference=parseRoomReference(raw);const result2=reference?matchRoom(reference,rooms,facts):{none:true};if("match"in result2){if(!selection.rooms.includes(result2.match))selection.rooms.push(result2.match)}else if("ambiguous"in result2)selection.ambiguous.push({asked:written,reference,rooms:result2.ambiguous});else if("ownerUnknown"in result2)selection.ownerUnknown.push({asked:written,reference,rooms:result2.ownerUnknown});else selection.missing.push(written)}return selection}function roomHandleAmbiguous(reference,rooms,among,next){const handle=roomReferenceText(reference);const choices=rooms.map(room=>({room_id:room.id.toLowerCase(),owner:room.ownerId?{principal_id:room.ownerId.toLowerCase(),principal_handle:knownHandle(room.owner,"@")??null}:null}));const names=choices.map(choice=>choice.owner?.principal_handle?`#${handle}@${choice.owner.principal_handle}`:choice.room_id);return new ParleApiError(`#${handle} names more than one room ${among}: ${names.join(", ")}. Nothing was chosen. ${next}`,{code:"room_handle_ambiguous",action:"fix_client",scope:"request",details:{room_handle:handle,choices}})}function roomOwnerUnknown(reference,among,next){return new ParleApiError(`${roomReferenceLabel(reference)} names its room by its owner, but Parle doesn't say who owns ${among}, so it can't be checked here. Nothing was chosen. ${next}`,{code:"validation_failed",action:"fix_client",scope:"request",details:{field:"rooms"}})}function parseAgentReference(raw){if(typeof raw!=="string")return void 0;const value=raw.trim();if(UUID_RE.test(value))return parsed({kind:"id",id:value.toLowerCase()});const parts=(value.startsWith("@")?value.slice(1):value).split(".");if(parts.length===1){const handle2=readHandle(parts[0]);return handle2?parsed({kind:"handle",handle:handle2}):void 0}if(parts.length>3||parts.length===3&&!isReadableAddressHandle(parts[2].trim().toLowerCase()))return void 0;const principal=readHandle(parts[0]);const handle=readHandle(parts[1]);return principal&&handle?parsed({kind:"handle",handle,principal}):void 0}function agentReferenceLabel(reference){return reference.kind==="id"?reference.id:`@${reference.principal?`${reference.principal}.`:""}${reference.handle}`}function sameAgentReference(left,right){return agentReferenceLabel(left)===agentReferenceLabel(right)}function agentMatches(reference,agent){if(reference.kind==="id")return typeof agent.id==="string"&&agent.id.trim().toLowerCase()===reference.id;if(knownHandle(agent.handle,"@")!==reference.handle)return false;const principal=knownHandle(agent.principal,"@");return!reference.principal||!principal||principal===reference.principal}function parseAddressReference(raw){if(typeof raw!=="string")return void 0;const value=raw.trim().toLowerCase();if(value.startsWith("@")){const parts=value.slice(1).split(".");return parts.length===3&&readHandle(parts[0])&&readHandle(parts[1])&&isReadableAddressHandle(parts[2])?parsed({kind:"address",address:value}):void 0}return isReadableAddressHandle(value)?parsed({kind:"handle",handle:value}):void 0}function addressMatches(reference,address2){const known=address2.trim().toLowerCase();return reference.kind==="address"?known===reference.address:known.slice(known.lastIndexOf(".")+1)===reference.handle&&known.includes(".")}function agentSelectorIsId(selector){return parseAgentReference(selector)?.kind==="id"}function agentSelectorHandle(selector){const reference=parseAgentReference(selector);return reference?.kind==="handle"?reference.handle:void 0}function agentSelectorMatches(selector,agent){const reference=parseAgentReference(selector);return Boolean(reference&&agentMatches(reference,agent))}function configuredAgentSelectors(get,warnings){const plural2=(get("PARLE_AGENTS")||"").trim();if(plural2)warnings.push(get("PARLE_AGENT")?"PARLE_AGENTS is the old name of PARLE_AGENT and is read beside it; use PARLE_AGENT.":"PARLE_AGENTS is deprecated: use PARLE_AGENT.");const entries=["PARLE_AGENTS","PARLE_AGENT"].flatMap(name=>(get(name)||"").split(",").map(value=>({name,value:value.trim()}))).filter(entry=>entry.value);for(const entry of entries){if(!parseAgentReference(entry.value)){warnings.push(`${entry.name} has ${entry.value}, which is not an agent id, a handle or @principal.agent, so it matches no agent.`)}}const listed=[...new Set(entries.map(entry=>entry.value))];const legacy={id:get("PARLE_AGENT_ID")||void 0,handle:get("PARLE_AGENT_HANDLE")||void 0};const oldNames=[legacy.id?"PARLE_AGENT_ID":void 0,legacy.handle?"PARLE_AGENT_HANDLE":void 0].filter(name=>Boolean(name));if(oldNames.length){warnings.push(listed.length?`${oldNames.join(" and ")} ${oldNames.length===1?"is the old name":"are the old names"} of PARLE_AGENT and ${oldNames.length===1?"is":"are"} ignored because PARLE_AGENT(S) is set. Remove ${oldNames.length===1?"it":"them"}.`:`${oldNames.join(" and ")} ${oldNames.length===1?"is":"are"} deprecated: use PARLE_AGENT (an agent id or handle).`)}if(listed.length)return{selectors:listed,legacy:{}};return{selectors:[legacy.id,legacy.handle].filter(value=>Boolean(value)),legacy}}import{homedir as homedir2}from"node:os";var DEFAULT_API_BASE=BUILD_API;var DESKTOP_CHANNEL=BUILD_DESKTOP_CHANNEL;function hostAllowed(hostname4,hosts=BUILD_API_HOSTS){return hosts.some(host=>host.startsWith("*.")?hostname4.endsWith(host.slice(1)):hostname4===host)}var UNTRUSTED_OPEN="[UNTRUSTED — ";var PARLE_LINE="[PARLE] ";var FENCE_SUFFIX_START="\n[END UNTRUSTED — ";var FENCE_SUFFIX_END=", not by Parle]\n";var FENCE_SUFFIX=`${FENCE_SUFFIX_START}written by another participant${FENCE_SUFFIX_END}`;function truncateText(text,maxBytes){const source=Buffer.from(text,"utf8");const bytes=source.byteLength;if(bytes<=maxBytes)return{text,truncated:false,bytes,returnedBytes:bytes};const suffix=Buffer.from("\n[truncated]","utf8");const limit=Math.max(0,maxBytes-suffix.byteLength);let end=limit;const decoder=new TextDecoder("utf-8",{fatal:true});while(end>0){try{decoder.decode(source.subarray(0,end));break}catch{end-=1}}const slice=source.subarray(0,end);const rendered=Buffer.concat([slice,suffix]).toString("utf8");return{text:rendered,truncated:true,bytes,returnedBytes:Buffer.byteLength(rendered,"utf8")}}function assertSafeBase(base,env=process.env){const url2=new URL(base);const isLocal=["localhost","127.0.0.1","::1","[::1]"].includes(url2.hostname);if(isLocal&&env.PARLE_ALLOW_INSECURE_LOCAL==="1"&&["http:","https:"].includes(url2.protocol)&&!url2.username&&!url2.password)return;if(url2.protocol!=="https:")throw new Error(`Parle API base must use https: ${base}`);if(url2.username||url2.password)throw new Error("Parle API base must not contain credentials.");if(!hostAllowed(url2.hostname))throw new Error(`Parle API base is not allowlisted: ${url2.hostname}`)}function stripServerPreamble(content,preamble){if(!preamble)return content;const prefix=preamble+"\n";if(!content.startsWith(prefix))return content;const rest=content.slice(prefix.length);if(!rest.startsWith(UNTRUSTED_OPEN)&&!rest.startsWith(PARLE_LINE))return content;return rest}function homeRelativePath(path,home=homedir2()){return home&&(path===home||path.startsWith(`${home}/`))?`~${path.slice(home.length)}`:path}import{execFileSync}from"node:child_process";import{existsSync as existsSync2,lstatSync as lstatSync4,readFileSync as readFileSync2,renameSync as renameSync2,statSync}from"node:fs";import{dirname as dirname3,isAbsolute as isAbsolute3,join as join7}from"node:path";function getLineColFromPtr(string5,ptr){let lines=string5.slice(0,ptr).split(/\r?\n/);return[lines.length,lines.pop().length+1]}function makeCodeBlock(string5,line2,column){let lines=string5.split(/\r?\n/);let codeblock="";let numberLen=(Math.log10(line2+1)|0)+1;for(let i=line2-1;i<=line2+1;i++){let l=lines[i-1];if(!l)continue;codeblock+=i.toString().padEnd(numberLen," ");codeblock+=": ";codeblock+=l;codeblock+="\n";if(i===line2){codeblock+=" ".repeat(numberLen+column+2);codeblock+="^\n"}}return codeblock}var TomlError=class _TomlError extends Error{line;column;codeblock;constructor(message,options){const[line2,column]=getLineColFromPtr(options.toml,options.ptr);const codeblock=makeCodeBlock(options.toml,line2,column);super(`Invalid TOML document: ${message}
|
|
10
|
+
`,{label:"Parle session registry entry",maxBytes:MAX_ENTRY_BYTES,durability:"none"});try{pruneSessionRegistry(dir,now,entry.pid)}catch{}}function removeSessionRegistryEntry(path){rmSync2(path,{force:true})}function readSessionRegistry(dir,inspectPid=pidLiveness){let names;try{names=readdirSync2(dir)}catch{return[]}const out=[];for(const name of names){if(name.startsWith(".")||!name.endsWith(".json"))continue;const path=join4(dir,name);try{const entry=JSON.parse(readOwnerOnlyTextFile(path,{label:"Parle session registry entry",maxBytes:MAX_ENTRY_BYTES}));if(!entry||entry.schemaVersion!==SESSION_REGISTRY_SCHEMA_VERSION||typeof entry.pid!=="number"||!entry.host?.kind||!entry.host?.sessionId)continue;out.push({path,entry,live:inspectPid(entry.pid)==="alive"})}catch{}}return out}function liveSessionEntries(dir,host,inspectPid){const key=sessionRegistryKey(host);return readSessionRegistry(dir,inspectPid).filter(record4=>record4.live&&sessionRegistryKey(record4.entry.host)===key)}function pruneSessionRegistry(dir,_now,ownPid){let removed=0;for(const record4 of readSessionRegistry(dir)){if(removed>=MAX_PRUNE_PER_WRITE)return;if(record4.entry.pid===ownPid||record4.live||pidLiveness(record4.entry.pid)!=="dead")continue;rmSync2(record4.path,{force:true});removed+=1}}function newerDeliveringSibling(records,ownPid,ownVersion){if(!pluginSemver(ownVersion))return void 0;return records.filter(({entry,live})=>live&&entry.pid!==ownPid&&entry.delivery?.state==="watching").map(({entry})=>entry).find(entry=>pluginSemver(entry.adapter?.version)&&comparePluginVersions(entry.adapter?.version,ownVersion)>0)}import{randomUUID as randomUUID2}from"node:crypto";var processClientInstance;function processClientInstanceId(){processClientInstance||=randomUUID2();return processClientInstance}var REPORTED_METADATA_LIMIT=96;var SOFTWARE_NAME_RE=/^(?:(?:@?[a-z0-9][a-z0-9._-]*)\/)?[a-z0-9][a-z0-9._-]*$/;var RELEASE_TOKEN_RE=/^[0-9A-Za-z][0-9A-Za-z._+!-]*$/;function assertReportedMetadataBounds(value,label){if(value.length===0||value.length>REPORTED_METADATA_LIMIT||!/^[\x20-\x7e]+$/.test(value)){throw new Error(`Parle ${label} must be 1 to ${REPORTED_METADATA_LIMIT} printable ASCII bytes.`)}}function assertClientName(value){assertReportedMetadataBounds(value,"clientName");if(!SOFTWARE_NAME_RE.test(value))throw new Error("Parle clientName must be a canonical software identifier.");return value}function assertClientVersion(value){assertReportedMetadataBounds(value,"clientVersion");if(!RELEASE_TOKEN_RE.test(value))throw new Error("Parle clientVersion must be a bounded release token.");return value}function assertClientInstanceId(value){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[47][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)){throw new Error("Parle clientInstanceId must be a canonical UUIDv4 or UUIDv7.")}return value.toLowerCase()}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function nonNegative(value){return typeof value==="number"&&Number.isFinite(value)&&value>=0?value:void 0}function retryAfterMsFrom(candidate){const ms=nonNegative(candidate.retry_after_ms);if(ms!==void 0)return Math.trunc(ms);const seconds=nonNegative(candidate.retry_after_seconds);return seconds===void 0?void 0:Math.trunc(seconds*1e3)}function retryAfterHeaderMs(value,nowMs){const text=value?.trim();if(!text)return void 0;if(/^\d+$/.test(text))return Number(text)*1e3;const at=Date.parse(text);return Number.isFinite(at)?Math.max(0,at-nowMs):void 0}function parseErrorEnvelope(value){const outer=value&&typeof value==="object"?value:{};const candidate=outer.error&&typeof outer.error==="object"?outer.error:outer;return{code:nonEmptyString(candidate.code),message:nonEmptyString(candidate.message),action:nonEmptyString(candidate.action),scope:nonEmptyString(candidate.scope),retryable:typeof candidate.retryable==="boolean"?candidate.retryable:void 0,retryAfterMs:retryAfterMsFrom(candidate),limitedBy:nonEmptyString(candidate.limited_by),lastErrorCode:nonEmptyString(candidate.last_error_code),raw:candidate}}var LIMITER_CODES=new Set(["rate_limited","service_unavailable"]);var QUOTA_CODES=new Set(["monthly_quota_exceeded","monthly_room_quota_exceeded","resource_limit_exceeded","invite_allowance_exceeded","approval_request_quota_exceeded","grant_quota_exceeded"]);var LIMITED_BY_WORDS={lease:"this session alone, so slowing this session down is enough",credential:"this agent's key, which its other sessions share; if it keeps happening, tell your principal",agent:"this agent, across all of its sessions",principal:"your principal, across all of their agents and sessions, so slow down everywhere; if it keeps happening, tell your principal",room:"this room, which everyone in it shares, so slow down in this room",ip:"this network address, which everything connecting from it shares"};var LIMITER_THRESHOLD_FIELDS=["burst","submission_rate_per_minute"];function errorObject(details){if(!details||typeof details!=="object")return void 0;const outer=details;return outer.error&&typeof outer.error==="object"?outer.error:outer}function limitRefusalKind(code,details){if(typeof code!=="string")return void 0;if(QUOTA_CODES.has(code))return"quota";if(LIMITER_CODES.has(code))return"limiter";const limitedBy=errorObject(details)?.limited_by;return typeof limitedBy==="string"&&limitedBy.length>0?"limiter":void 0}function limitedByWords(limitedBy){if(typeof limitedBy!=="string"||limitedBy.length===0)return void 0;return LIMITED_BY_WORDS[limitedBy]??`its ${limitedBy}`}function waitWords(retryAfterMs){if(typeof retryAfterMs!=="number"||!Number.isFinite(retryAfterMs)||retryAfterMs<0)return void 0;const seconds=Math.max(1,Math.ceil(retryAfterMs/1e3));if(seconds<120)return`${seconds} second${seconds===1?"":"s"}`;const minutes=Math.ceil(seconds/60);if(minutes<120)return`${minutes} minutes`;return`${Math.ceil(minutes/60)} hours`}var ERROR_CODE=/^[a-z][a-z0-9_]{0,63}$/;function limiterHint(refusal){const error62=errorObject(refusal.details)??{};const code=refusal.code??(typeof error62.code==="string"?error62.code:void 0);const action=refusal.action??(typeof error62.action==="string"?error62.action:void 0);let retryAfterMs=refusal.retryAfterMs;if(retryAfterMs===void 0&&typeof error62.retry_after_ms==="number")retryAfterMs=error62.retry_after_ms;if(retryAfterMs===void 0&&typeof error62.retry_after_seconds==="number")retryAfterMs=error62.retry_after_seconds*1e3;const parts=[];const by=limitedByWords(error62.limited_by);switch(code){case"service_unavailable":parts.push("Parle is briefly unavailable.");break;default:parts.push(by?`Parle limited this request. The limit counts against ${by}.`:"Parle limited this request.")}const lastErrorCode=error62.last_error_code;if(typeof lastErrorCode==="string"&&ERROR_CODE.test(lastErrorCode)){parts.push(`Earlier requests kept failing with ${lastErrorCode}: fix that call before retrying it.`)}const wait=waitWords(retryAfterMs);const resetsAt=typeof error62.resets_at==="string"?error62.resets_at:void 0;if(action==="stop"){parts.push(resetsAt?`Don't retry before ${resetsAt}.`:wait?`Don't retry for ${wait}.`:"Don't retry it now.")}else if(wait){parts.push(`Wait ${wait}, then retry.`)}else{parts.push("Wait a moment, then retry.")}return parts.join(" ")}function withoutLimiterThresholds(details){if(!details||typeof details!=="object")return details;const strip=value=>{const copy={...value};for(const field of LIMITER_THRESHOLD_FIELDS)delete copy[field];return copy};const outer=details;if(outer.error&&typeof outer.error==="object")return{...outer,error:strip(outer.error)};return strip(outer)}var QUOTA_WORDS={owned_active_rooms:"active rooms your principal owns",room_active_participants:"people and agent addresses in this room",active_memberships:"rooms your principal is in",active_delivery_addresses:"your principal's active agent addresses",monthly_room_creations:"rooms your principal may create this month"};function quotaHint(code,details){if(limitRefusalKind(code,details)!=="quota")return void 0;const levels=[details,errorObject(details),errorObject(details)?.details].filter(level=>Boolean(level)&&typeof level==="object");const field=name=>levels.map(level=>level[name]).find(value=>value!==void 0&&value!==null);const cap=field("cap");const used=field("used");const limit=field("limit");const recovery=field("recovery");const resetsAt=field("resets_at");if(!(typeof cap==="string"&&cap)&&typeof limit!=="number")return void 0;const what=typeof cap==="string"&&cap?QUOTA_WORDS[cap]??cap:"a quota";const numbers=typeof used==="number"&&typeof limit==="number"?` (${used} of ${limit})`:typeof limit==="number"?` (limit ${limit})`:"";return[`Parle quota reached: ${what}${numbers}.`,typeof recovery==="string"&&recovery?recovery:void 0,typeof resetsAt==="string"&&resetsAt?`It renews at ${resetsAt}.`:void 0,"Retrying won't help until it frees up; tell your principal if they need to act."].filter(Boolean).join(" ")}import{createHash,createHmac,randomBytes,randomUUID as randomUUID3}from"node:crypto";import{closeSync as closeSync2,constants as constants2,fstatSync as fstatSync2,ftruncateSync,lstatSync as lstatSync2,openSync as openSync2,writeSync as writeSync2}from"node:fs";import{isAbsolute as isAbsolute2,join as join5,resolve}from"node:path";var PARLE_VERSION="2026-11-18";var UPGRADE_NOTICE_HEADER="Parle-Upgrade-Notice";var HEADER_MAX=2048;var SERVER_LINE_MAX=300;function parseItem(input2){let i=0;const s=input2.replace(/^[ \t]+|[ \t]+$/g,"");const bareItem=()=>{const c=s.charAt(i);if(c==='"'){i++;let out="";while(i<s.length){const ch=s.charAt(i++);if(ch==="\\"){const next=s.charAt(i++);if(next!=='"'&&next!=="\\")return void 0;out+=next}else if(ch==='"'){return out}else{const code=ch.charCodeAt(0);if(code<32||code>126)return void 0;out+=ch}}return void 0}if(c==="?"){const b=s.charAt(i+1);if(b!=="0"&&b!=="1")return void 0;i+=2;return b==="1"}if(/^[A-Za-z*]$/.test(c)){const token=/^[A-Za-z*][!#$%&'*+\-.^_`|~0-9A-Za-z:/]*/.exec(s.slice(i))?.[0]??c;i+=token.length;return{token}}if(/^[-0-9]$/.test(c)){const match=/^-?\d{1,15}(?:\.\d{1,3})?/.exec(s.slice(i));if(!match)return void 0;i+=match[0].length;return Number(match[0])}return void 0};const value=bareItem();if(value===void 0)return void 0;const params=new Map;while(i<s.length){if(s.charAt(i)!==";")return void 0;i++;while(s.charAt(i)===" ")i++;const key=/^[a-z*][a-z0-9_\-.*]*/.exec(s.slice(i));if(!key)return void 0;i+=key[0].length;let paramValue=true;if(s.charAt(i)==="="){i++;const parsed2=bareItem();if(parsed2===void 0)return void 0;paramValue=parsed2}params.set(key[0],paramValue)}return{value,params}}function stringParam(params,name){const value=params.get(name);return typeof value==="string"?value:void 0}function serverLine(value,options={}){if(typeof value!=="string")return void 0;const folded=value.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();const line2=options.redact?options.redact(folded):folded;if(!line2)return void 0;const max=options.max??SERVER_LINE_MAX;return line2.length>max?`${line2.slice(0,max-1)}…`:line2}function sentenceBody(text){return text.replace(/[.!?]+$/,"")}function rfc3339(value){if(!value||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/i.test(value))return void 0;const ms=Date.parse(value);return Number.isFinite(ms)?new Date(ms).toISOString():void 0}function releaseVersion(value){return value&&value.length<=64&&/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/.test(value)?value:void 0}function migrationGuideUrl(value,requestUrl2){if(typeof value!=="string"||!value||value.length>2048)return void 0;try{if(value.startsWith("/")&&!value.startsWith("//"))return requestUrl2?new URL(value,new URL(requestUrl2).origin).href:value;const url2=new URL(value);return url2.protocol==="https:"&&!url2.username&&!url2.password?url2.href:void 0}catch{return void 0}}function parseUpgradeNotice(header,requestUrl2,options={}){try{if(typeof header!=="string"||!header||header.length>HEADER_MAX)return void 0;const item=parseItem(header);if(!item||typeof item.value!=="object")return void 0;const kind=item.value.token;if(kind!=="retiring"&&kind!=="recommended")return void 0;const note=serverLine(stringParam(item.params,"note"),{redact:options.redactNote});const migrationUrl=migrationGuideUrl(stringParam(item.params,"migration-url"),requestUrl2);const retiresAt=kind==="retiring"?rfc3339(stringParam(item.params,"retires-at")):void 0;const recommendedRelease=kind==="recommended"?releaseVersion(stringParam(item.params,"recommended-release")):void 0;return{kind,...retiresAt?{retiresAt}:{},...note?{note}:{},...recommendedRelease?{recommendedRelease}:{},...migrationUrl?{migrationUrl}:{}}}catch{return void 0}}function sameUpgradeNotice(a,b){return a?.kind===b?.kind&&a?.retiresAt===b?.retiresAt&&a?.note===b?.note&&a?.recommendedRelease===b?.recommendedRelease&&a?.migrationUrl===b?.migrationUrl}var MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function retirementDate(retiresAt,now=Date.now()){const at=new Date(retiresAt);const day=`${String(MONTHS[at.getUTCMonth()])} ${at.getUTCDate()}`;const year=at.getUTCFullYear()===new Date(now).getUTCFullYear()?"":`, ${at.getUTCFullYear()}`;const midnight=at.getUTCHours()===0&&at.getUTCMinutes()===0;const time3=midnight?"":` ${String(at.getUTCHours()).padStart(2,"0")}:${String(at.getUTCMinutes()).padStart(2,"0")} UTC`;return`${day}${year}${time3}`}var DAY_MS=24*60*60*1e3;function inFinalDay(retiresAt,now=Date.now()){if(!retiresAt)return false;const at=Date.parse(retiresAt);return now<at&&now>=at-DAY_MS}function parseVersionRefusal(error62,client,options={}){if(typeof error62!=="object"||error62===null)return{};const fields=error62;const lineOptions=options.redact?{redact:options.redact}:{};const required2=fields.required_version;const update=serverLine(typeof fields.update==="object"&&fields.update!==null?fields.update[client]:void 0,lineOptions);const migrationUrl=migrationGuideUrl(fields.migration_url,options.requestUrl);const note=serverLine(fields.note,lineOptions);return{...typeof required2==="string"&&/^\d{4}-\d{2}-\d{2}$/.test(required2)?{requiredVersion:required2}:{},...update?{update}:{},...migrationUrl?{migrationUrl}:{},...note?{note}:{}}}var DEFAULT_VERSION=PARLE_VERSION;var ParleApiError=class extends Error{status;code;action;scope;retryAfterMs;retryable;details;requestId;constructor(message,options={}){super(message);this.name="ParleApiError";this.status=options.status;this.code=options.code;this.action=options.action;this.scope=options.scope;this.retryAfterMs=options.retryAfterMs;this.retryable=options.retryable??false;this.details=options.details;this.requestId=options.requestId}};function parleApiErrorFields(error62){return{code:error62.code,status:error62.status,action:error62.action,scope:error62.scope,retryable:error62.retryable,retryAfterMs:error62.retryAfterMs,...error62.requestId?{requestId:error62.requestId}:{},...error62.details&&typeof error62.details==="object"?{details:error62.details}:{}}}var PARLE_CREDENTIAL_RE=/parle_[a-z]+_[A-Za-z0-9_-]{20,}/g;var PARLE_BEARER_RE=/^parle_[a-z]+_[A-Za-z0-9_-]+$/i;var AUTHORIZATION_CREDENTIAL_RE=/(authorization\\?["']?\s*[:=]\s*\\?["']?\s*(?:bearer|dpop|basic|token)\s+)([A-Za-z0-9_~./+=:-]*[A-Za-z0-9_~+/=:-])/gi;var BEARER_VALUE_RE=/(Bearer\s+)([A-Za-z0-9_~./+=:-]*[A-Za-z0-9_~+/=:-])/gi;var BARE_JWT_RE=/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g;function isBearerTokenShape(value){if(PARLE_BEARER_RE.test(value))return true;return value.length>=20&&/^[A-Za-z]+$/.test(value)||value.length>=6&&/[0-9_~./+=:-]/.test(value)}function redactAuthorizationCredentials(input2){return input2.replace(AUTHORIZATION_CREDENTIAL_RE,"$1<redacted>").replace(BEARER_VALUE_RE,(match,prefix,value)=>isBearerTokenShape(value)?`${prefix}<redacted>`:match).replace(BARE_JWT_RE,value=>value.length>=20?"<redacted-jwt>":value)}function isParleCredential(value){PARLE_CREDENTIAL_RE.lastIndex=0;return PARLE_CREDENTIAL_RE.test(value)}function redactString(input2){const out=redactAuthorizationCredentials(input2).replace(/(__Host-parle_session=)[^;\s]+/g,"$1<redacted>").replace(/(Idempotency-Key\s*[:=]\s*)[A-Za-z0-9._:-]+/gi,"$1<redacted>").replace(/(Parle-Agent-Session\s*[:=]\s*)[A-Za-z0-9._:-]+/gi,"$1<redacted>");PARLE_CREDENTIAL_RE.lastIndex=0;return out.replace(PARLE_CREDENTIAL_RE,"<redacted-token>")}var ADDRESS_HANDLE_MIN_LENGTH=2;var ADDRESS_HANDLE_MAX_LENGTH=24;var SESSION_ALIAS_MAX_LENGTH=32;var ADDRESS_HANDLE_PATTERN=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;var NEW_HANDLE_RULE=`${ADDRESS_HANDLE_MIN_LENGTH} to ${ADDRESS_HANDLE_MAX_LENGTH} lowercase letters, digits and single hyphens, with at least one letter, not a reserved word`;var ANONYMOUS_SESSION_HANDLE_PATTERN=/^[a-z2-7]{16}$/;var RESERVED_ADDRESS_HANDLES=new Set(["admin","agent","agents","api","me","null","parle","room","rooms","root","support","system","www"]);function isValidAddressHandle(value){return value.length>=ADDRESS_HANDLE_MIN_LENGTH&&value.length<=ADDRESS_HANDLE_MAX_LENGTH&&ADDRESS_HANDLE_PATTERN.test(value)&&!RESERVED_ADDRESS_HANDLES.has(value)}function isReadableAddressHandle(value){return value.length>=ADDRESS_HANDLE_MIN_LENGTH&&value.length<=SESSION_ALIAS_MAX_LENGTH&&ADDRESS_HANDLE_PATTERN.test(value)&&!RESERVED_ADDRESS_HANDLES.has(value)}function isValidSessionAlias(value){return value.length>=ADDRESS_HANDLE_MIN_LENGTH&&value.length<=SESSION_ALIAS_MAX_LENGTH&&ADDRESS_HANDLE_PATTERN.test(value)&&!RESERVED_ADDRESS_HANDLES.has(value)&&!ANONYMOUS_SESSION_HANDLE_PATTERN.test(value)}var LEVELS={debug:1,trace:2};var DEBUG_EVENTS=["client_start","http_start","http_response","http_error","http_body_error","delivery_start","delivery_stop","stream_connect","stream_open","stream_eof","stream_error","stream_retry","stream_close","room_error","wake_open","wake_hint","fetch_started","fetch_success","row_fetched","handling_complete","ack_started","ack_success","background_error","mcp_client","mcp_call_meta"];var TRACE_EVENTS=["hook_walk_step","hook_probe_error","hook_host_found","hook_host_missing","hook_bridges_none","hook_bridge_unresponsive"];var EVENTS=new Map([...DEBUG_EVENTS.map(event=>[event,"debug"]),...TRACE_EVENTS.map(event=>[event,"trace"])]);var METHODS=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"]);var REASONS=new Set(["stopped","revision_changed","interrupted","recover","drain","handler","ack","walk_end","self_parent","depth"]);var PROCESS_KINDS=new Set(["codex","codex_refused","shell","other","unknown"]);var TOOLS=new Set(["ps","lsof"]);var BACKGROUND_OPERATIONS=["key_rotation","address_reconnect","room_instructions_refresh","host_session_rebind","address_facts_refresh","room_drain","hook_socket_listen","address_rooms_read","features_read","missed_notices_read","room_set_refresh"];var OPERATIONS=new Set(BACKGROUND_OPERATIONS);var TRIGGERS=new Set(["startup","wake_open","wake_hint","test"]);var TRANSPORT_CODES=new Set(["UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_ABORTED","UND_ERR_DESTROYED","UND_ERR_CLOSED","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","ENOTFOUND","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","ECANCELED","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","CERT_HAS_EXPIRED","ERR_TLS_CERT_ALTNAME_INVALID","UNABLE_TO_GET_ISSUER_CERT_LOCALLY"]);var PROCESS_CODES=new Set(["EAGAIN","ENOMEM","EMFILE","ENFILE","EPERM","EACCES","ENOENT","EIO","ETIMEDOUT"]);var SIGNALS=new Set(["SIGTERM","SIGKILL","SIGINT","SIGHUP"]);var ERROR_NAMES=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","ParleApiError","TokenEndpointError"]);var ACTIONS=new Set(["retry","backoff","retry_with_backoff","reauthorize","fix_client","stop","rebootstrap"]);var SYSCALLS=new Set(["read","write","connect","getaddrinfo"]);var MAX_BYTES=1024*1024;var COMPONENTS=new Set(["client","delivery","account","desktop","approval","oauth","hook"]);var wrappedFetches=new WeakMap;var responseDiagnostics=new WeakMap;var MAX_SINKS=64;var sinks=new Map;var CLIENT_LABEL=/^[A-Za-z0-9 ._@/+:-]{1,64}$/;var META_KEY=/^[A-Za-z0-9_.:/-]{1,64}$/;var META_KEYS_MAX=24;function metaFingerprints(meta3){if(!meta3||typeof meta3!=="object"||Array.isArray(meta3))return void 0;const out={};const add=(key,value)=>{if(Object.keys(out).length>=META_KEYS_MAX||!META_KEY.test(key))return;const type=value===null?"null":Array.isArray(value)?"array":typeof value;let text;try{text=JSON.stringify(value)??String(value)}catch{text=type}out[key]=`${type}:${createHash("sha256").update("parle-debug-meta\0").update(text.slice(0,8192)).digest("hex").slice(0,16)}`};for(const key of Object.keys(meta3)){const value=own(meta3,key);if(value&&typeof value==="object"&&!Array.isArray(value)){for(const inner of Object.keys(value))add(`${key}.${inner}`,own(value,inner))}else add(key,value)}return out}var noop=()=>Object.assign(()=>{},{close:()=>{},nextRequest:()=>0,enabled:false});function own(value,key){if(!value||typeof value!=="object")return void 0;return Object.getOwnPropertyDescriptor(value,key)?.value}function nameOf(error62){const name=own(error62,"name");if(typeof name==="string"&&ERROR_NAMES.has(name))return name;if(error62 instanceof TypeError)return"TypeError";if(error62 instanceof RangeError)return"RangeError";if(error62 instanceof SyntaxError)return"SyntaxError";return"Error"}function debugLevel(env){if(env.PARLE_DEBUG==="1"||env.PARLE_DEBUG==="true")return"debug";if(env.PARLE_DEBUG==="trace")return"trace";return void 0}function debugScope(env,component){if(!COMPONENTS.has(component)||!debugLevel(env))return void 0;const home=parleHome(env);if(!isAbsolute2(home))return void 0;const normalized=resolve(home);return{home:normalized,key:JSON.stringify([component,normalized])}}function createAdapterDebugLog(env,now,component="delivery"){try{const scope=debugScope(env,component);if(!scope)return noop();let sink=sinks.get(scope.key);if(!sink){if(sinks.size>=MAX_SINKS)return noop();sink=createSink(scope.home,component);sinks.set(scope.key,sink)}const shared=sink,logger=shared.nextLogger();const level=LEVELS[debugLevel(env)??"debug"];let closed=false;const log=(event,detail,error62)=>{const eventLevel=EVENTS.get(event);if(closed||!shared.enabled||!eventLevel||LEVELS[eventLevel]>level)return;try{shared.write(Date.prototype.toISOString.call(now()),logger,event,detail,error62)}catch{closed=true}};return Object.defineProperty(Object.assign(log,{close:()=>{closed=true},nextRequest:()=>closed||!shared.enabled?0:shared.nextRequest()}),"enabled",{get:()=>!closed&&shared.enabled})}catch{return noop()}}function createSink(home,component){const root=home;const stem=`${component}-${process.pid}-${randomUUID3()}`;const salt=randomBytes(32);const ref=value=>typeof value==="string"&&value.length>0?createHmac("sha256",salt).update(value.slice(0,8192)).digest("hex").slice(0,24):void 0;let slot=0,bytes=0,failed=false,loggerSequence=0,requestSequence=0;const identities=[];const errorFacts=error62=>{const result2={name:nameOf(error62)};const code=own(error62,"code");if(typeof code==="string"&&(TRANSPORT_CODES.has(code)||PROCESS_CODES.has(code)))result2.code=code;else if(ref(code))result2.codeRef=ref(code);if(Array.isArray(own(error62,"output"))){const signal=own(error62,"signal"),exitStatus=own(error62,"status");if(typeof signal==="string"&&SIGNALS.has(signal))result2.signal=signal;if(typeof exitStatus==="number"&&Number.isInteger(exitStatus)&&exitStatus>=0&&exitStatus<=255)result2.exitStatus=exitStatus}const action=own(error62,"action");if(typeof action==="string"&&ACTIONS.has(action))result2.action=action;if(error62 instanceof ParleApiError){const status=own(error62,"status"),retryAfterMs=own(error62,"retryAfterMs"),retryable=own(error62,"retryable");if(typeof status==="number"&&Number.isInteger(status)&&status>=100&&status<=599)result2.status=status;if(typeof retryAfterMs==="number"&&Number.isInteger(retryAfterMs)&&retryAfterMs>=0&&retryAfterMs<=2**31-1)result2.retryAfterMs=retryAfterMs;if(typeof retryable==="boolean")result2.retryable=retryable}const message=own(error62,"message");if(message==="terminated")result2.reason="terminated";if(message==="Parle agent stream ended unexpectedly")result2.reason="stream_eof";const seen=new Set([error62]);let cause=own(error62,"cause");const causes=[];for(let depth=0;cause&&typeof cause==="object"&&!seen.has(cause)&&depth<3;depth++){seen.add(cause);const facts={name:nameOf(cause)};const code2=own(cause,"code"),syscall=own(cause,"syscall");if(typeof code2==="string"&&TRANSPORT_CODES.has(code2))facts.code=code2;else if(ref(code2))facts.codeRef=ref(code2);if(typeof syscall==="string"&&SYSCALLS.has(syscall))facts.syscall=syscall;causes.push(facts);cause=own(cause,"cause")}if(causes.length)result2.causes=causes;return result2};const write=(at,logger,event,detail,error62)=>{if(failed||!EVENTS.has(event))return;let fd;try{const safe={};for(const key of["attempt","durationMs","retryMs","request","status","seq","rowCount","processId","depth"]){const value=own(detail,key);if(typeof value!=="number"||!Number.isFinite(value)||value<0)continue;if(key==="status"&&(value!==0&&(!Number.isInteger(value)||value<100||value>599)))continue;if(!["durationMs","retryMs"].includes(key)&&!Number.isSafeInteger(value))continue;safe[key]=value}for(const[key,allowed]of[["trigger",TRIGGERS],["reason",REASONS],["method",METHODS],["kind",PROCESS_KINDS],["tool",TOOLS],["operation",OPERATIONS]]){const value=own(detail,key);if(typeof value==="string"&&allowed.has(value))safe[key]=value}for(const key of["clientName","clientVersion"]){const value=own(detail,key);if(typeof value==="string"&&CLIENT_LABEL.test(value))safe[key]=value}const meta3=metaFingerprints(own(detail,"meta"));if(meta3)safe.metaKeys=meta3;for(const key of["roomId","eventId","path"]){const value=ref(own(detail,key));if(value)safe[key==="path"?"routeRef":key==="roomId"?"roomRef":"eventRef"]=value}const line2=JSON.stringify({at,pid:process.pid,component,logger,event,...safe,...error62?{error:errorFacts(error62)}:{}})+"\n";const buffer=Buffer.from(line2);if(buffer.length>MAX_BYTES)return;ensureOwnerOnlyDirectory(root,{label:"Parle state directory"});const directory=ensureOwnerOnlyDirectory(join5(root,"debug"),{label:"Parle debug directory"});const rotate=bytes+buffer.length>MAX_BYTES;if(rotate){slot=1-slot;bytes=0}const path=join5(directory,`${stem}-${slot}.jsonl`);fd=openSync2(path,constants2.O_WRONLY|(identities[slot]?0:constants2.O_CREAT|constants2.O_EXCL)|(constants2.O_NOFOLLOW||0),384);const stat=fstatSync2(fd),link=lstatSync2(path),identity=identities[slot];if(!stat.isFile()||stat.nlink!==1||link.isSymbolicLink()||stat.dev!==link.dev||stat.ino!==link.ino||identity&&(stat.dev!==identity.dev||stat.ino!==identity.ino)||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||(stat.mode&511)!==384))throw new Error("unsafe debug file");identities[slot]={dev:stat.dev,ino:stat.ino};if(rotate&&identity){ftruncateSync(fd,0)}let written=0;while(written<buffer.length){const count2=writeSync2(fd,buffer,written,buffer.length-written,bytes+written);if(count2<=0)throw new Error("debug write made no progress");written+=count2}bytes+=buffer.length}catch{failed=true}finally{if(fd!==void 0){try{closeSync2(fd)}catch{failed=true}}}};return{write,nextLogger:()=>++loggerSequence,nextRequest:()=>++requestSequence,get enabled(){return!failed}}}function createDebugFetch(env,fetchImpl,now,component="client"){const existing=wrappedFetches.get(fetchImpl);let key;try{const scope=debugScope(env,component);if(!scope)return existing?.original||fetchImpl;key=scope.key}catch{return existing?.original||fetchImpl}if(existing?.key===key)return fetchImpl;if(existing)fetchImpl=existing.original;const log=createAdapterDebugLog(env,now,component);if(!log.enabled)return fetchImpl;log("client_start");if(!log.enabled)return fetchImpl;const wrapped=async function(input2,init){if(!log.enabled)return fetchImpl.call(this,input2,init);const request=log.nextRequest();const startedAt=performance.now();let method,path;try{method=init?.method||(input2 instanceof Request?input2.method:"GET");path=typeof input2==="string"?new URL(input2).pathname:input2 instanceof URL?input2.pathname:input2 instanceof Request?new URL(input2.url).pathname:void 0}catch{}log("http_start",{request,method,path});try{const response=await fetchImpl.call(this,input2,init);try{log("http_response",{request,method,path,status:response.status,durationMs:Math.max(0,performance.now()-startedAt)});if(log.enabled)responseDiagnostics.set(response,{log,detail:{request,method,path:path?.slice(0,8192)}})}catch{}return response}catch(error62){log("http_error",{request,method,path,durationMs:Math.max(0,performance.now()-startedAt)},error62);throw error62}};wrappedFetches.set(wrapped,{original:fetchImpl,key});return wrapped}async function readDebugResponse(response,method){try{return await response[method]()}catch(error62){const diagnostics=responseDiagnostics.get(response);diagnostics?.log("http_body_error",diagnostics.detail,error62);throw error62}}var RECORDED_RESPONSE_LIMIT=20;var REQUEST_ID=/^[0-9a-f]{16}$/;var ROUTE_MAX=120;var ROUTE_WORDS=new Set(["accept","accepted","access-grants","account","ack","acknowledge","activity","address-bindings","address-leases","address-waits","address-names","addresses","agent","agents","api-key","approval-requests","approve","attachments","auth","available-updates","begin","check","clear","clones","complete","confirm","counts","decision","decline","delivery","deny","device-authorizations","email","end","enroll","factor-recovery","factors","features","finish","freeze","github","google","handshake-waits","handshakes","history","identities","inbox","instructions","invites","keep","keys","leases","legal-documents","lifetime","link","login","logout","lookup","members","membership","messages","moderation","nudges","offline","offline-messages","onboarding","onboarding-invites","online","organizations","owner","owner-detail","participants","parties","passkey","passkeys","password","pause","person","policies","preferences","presets","preview","primary","principal","projection","providers","publish","read-marks","recovery-codes","regenerate","register","remint","replace","reset","resolve","resume","revisions","rights","room-invites","rooms","ruleset-share-invites","rulesets","scopes","seats","security","sharing","start","stepup","stored","stream","suspend","system-announcement","test","totp","transfer-destinations","transfers","unread","upgrade-notices","usage-consent-decisions","usage-consents","v","verdicts","verify","versions","visibility","wait-reset","waits","whoami","llms","llms.txt","openapi.json","endpoints.md","addresses.md","room-wire.md","responsive-delivery.md","errors.md"]);function requestIdFrom(headers){let value;try{value=headers?.get("x-request-id")}catch{return void 0}return typeof value==="string"&&REQUEST_ID.test(value)?value:void 0}function routeTemplate(method,url2){let pathname;try{pathname=new URL(url2).pathname}catch{return void 0}const path=pathname.split("/").filter(Boolean).map(segment=>ROUTE_WORDS.has(segment)?segment:":id").join("/");const verb=/^[A-Za-z]{1,10}$/.test(method)?method.toUpperCase():"OTHER";return`${verb} /${path}`.slice(0,ROUTE_MAX)}var ApiResponseRecorder=class{entries=[];record(input2,at){const request_id=requestIdFrom(input2.headers);const route=routeTemplate(input2.method,input2.url);if(!request_id||!route||!Number.isInteger(input2.status))return;this.entries.push({request_id,route,status:input2.status,at:at.toISOString()});if(this.entries.length>RECORDED_RESPONSE_LIMIT)this.entries.splice(0,this.entries.length-RECORDED_RESPONSE_LIMIT)}snapshot(){return this.entries.map(entry=>({...entry}))}clear(){this.entries=[]}};var apiResponses=new ApiResponseRecorder;var recordingWrappers=new WeakMap;var wrappers=new WeakSet;function recordResponses(fetchImpl,now,recorder=apiResponses){if(wrappers.has(fetchImpl))return fetchImpl;const existing=recordingWrappers.get(fetchImpl);if(existing)return existing;const wrapped=async function(input2,init){const response=await fetchImpl.call(this,input2,init);try{const request=input2 instanceof Request?input2:void 0;const method=init?.method||request?.method||"GET";const url2=typeof input2==="string"?input2:input2 instanceof URL?input2.href:request?.url??"";recorder.record({method,url:url2,headers:response.headers,status:response.status},now())}catch{}return response};recordingWrappers.set(fetchImpl,wrapped);wrappers.add(wrapped);return wrapped}function parseUpgradeNotice2(header,requestUrl2){return parseUpgradeNotice(header,requestUrl2,{redactNote:redactString})}var UpgradeNoticeTracker=class{current;get notice(){return this.current}observe(headers,requestUrl2,options){const raw=headers?.get(UPGRADE_NOTICE_HEADER);if(raw===null||raw===void 0){if(options.clearWhenAbsent)this.current=void 0;return}const parsed2=parseUpgradeNotice2(raw,requestUrl2);if(parsed2)this.current=parsed2}};var GENERIC_UPDATE_STEPS="update the Parle adapter in this host, then restart it.";function upgradeNoticeLine(notice,updateSteps=GENERIC_UPDATE_STEPS,now=Date.now()){const steps=`Update: ${updateSteps.trim()}`;const guide=notice.migrationUrl?` Migration guide: ${notice.migrationUrl}`:"";if(notice.kind==="recommended"){const release=notice.recommendedRelease?` (${notice.recommendedRelease} or newer)`:"";const why2=notice.note?` ${sentenceBody(notice.note)}.`:"";return`An update is recommended${release}.${why2} ${steps}${guide}`}const why=notice.note?`: ${sentenceBody(notice.note)}.`:".";const lead=notice.retiresAt?`Parle stops serving this adapter's version on ${retirementDate(notice.retiresAt,now)}`:"This adapter's Parle version is retiring";return`${lead}${why} ${steps}${guide}`}var DAY_MS2=24*60*60*1e3;var UpgradeNoticeCadence=class{shownFor;lastShownAt;finalDayShown=false;sync(notice){if(sameUpgradeNotice(this.shownFor,notice))return;this.shownFor=notice;this.lastShownAt=void 0;this.finalDayShown=false}due(notice,now){if(!notice)return false;this.sync(notice);if(inFinalDay(notice.retiresAt,now)&&!this.finalDayShown)return true;return this.lastShownAt===void 0||now-this.lastShownAt>=DAY_MS2}shown(notice,now){this.sync(notice);this.lastShownAt=now;if(inFinalDay(notice.retiresAt,now))this.finalDayShown=true}};function parsed(value){return value}function readHandle(raw){const value=raw.trim().toLowerCase();return isValidAddressHandle(value)?value:void 0}function knownHandle(value,sign2){if(typeof value!=="string")return void 0;const bare=value.trim();return(bare.startsWith(sign2)?bare.slice(1):bare).trim().toLowerCase()||void 0}function roomIdInLink(value){let link;try{link=new URL(value.trim())}catch{return void 0}const loopback=link.hostname==="localhost"||link.hostname==="127.0.0.1"||link.hostname==="[::1]";if(link.protocol!=="https:"&&!(link.protocol==="http:"&&loopback)||link.username||link.password)return void 0;const match=link.pathname.match(/^\/rooms\/([0-9a-f-]{36})(?:\/.*)?$/i);return match&&UUID_RE.test(match[1])?match[1].toLowerCase():void 0}function looksLikeLink(value){return typeof value==="string"&&/^[a-z][a-z0-9+.-]*:\/\//i.test(value.trim())}function parseRoomReference(raw){if(typeof raw!=="string")return void 0;const value=raw.trim();if(UUID_RE.test(value))return parsed({kind:"id",id:value.toLowerCase()});if(looksLikeLink(value)){const id=roomIdInLink(value);return id?parsed({kind:"id",id}):void 0}const[room,...owner2]=(value.startsWith("#")?value.slice(1):value).split("@");const handle=readHandle(room);if(!handle)return void 0;if(owner2.length===0)return parsed({kind:"handle",handle});const ownerHandle=owner2.length===1?readHandle(owner2[0]):void 0;return ownerHandle?parsed({kind:"qualified",handle,owner:ownerHandle}):void 0}function roomReferenceText(reference){switch(reference.kind){case"id":return reference.id;case"handle":return reference.handle;case"qualified":return`${reference.handle}@${reference.owner}`}}function roomReferenceLabel(reference){return reference.kind==="id"?reference.id:`#${roomReferenceText(reference)}`}function sameRoomReference(left,right){return left.kind===right.kind&&roomReferenceText(left)===roomReferenceText(right)}function ownedByCaller(ownerId,principalId){const room=typeof ownerId==="string"&&UUID_RE.test(ownerId.trim())?ownerId.trim().toLowerCase():void 0;const caller=typeof principalId==="string"&&UUID_RE.test(principalId.trim())?principalId.trim().toLowerCase():void 0;return room&&caller?room===caller:void 0}function matchRoom(reference,rooms,facts){const seen=new Set;const known=rooms.flatMap(room=>{const fact=facts(room);const id=fact.id.toLowerCase();if(!id||seen.has(id))return[];seen.add(id);return[{room,fact,id}]});if(reference.kind==="id"){const found=known.find(entry=>entry.id===reference.id);return found?{match:found.room}:{none:true}}const named=known.filter(entry=>knownHandle(entry.fact.handle,"#")===reference.handle);if(reference.kind==="qualified"){const owned=named.find(entry=>knownHandle(entry.fact.owner,"@")===reference.owner);if(owned)return{match:owned.room};const unknown2=named.filter(entry=>entry.fact.owner===void 0);return unknown2.length?{ownerUnknown:unknown2.map(entry=>entry.room)}:{none:true}}const own3=named.filter(entry=>entry.fact.own===true);if(own3.length===1)return{match:own3[0].room};if(named.length===1)return{match:named[0].room};return named.length?{ambiguous:named.map(entry=>entry.room)}:{none:true}}function selectRooms(asked2,rooms,facts){const selection={rooms:[],missing:[],ambiguous:[],ownerUnknown:[]};for(const raw of asked2){const written=typeof raw==="string"?raw.trim():String(raw);const reference=parseRoomReference(raw);const result2=reference?matchRoom(reference,rooms,facts):{none:true};if("match"in result2){if(!selection.rooms.includes(result2.match))selection.rooms.push(result2.match)}else if("ambiguous"in result2)selection.ambiguous.push({asked:written,reference,rooms:result2.ambiguous});else if("ownerUnknown"in result2)selection.ownerUnknown.push({asked:written,reference,rooms:result2.ownerUnknown});else selection.missing.push(written)}return selection}function roomHandleAmbiguous(reference,rooms,among,next){const handle=roomReferenceText(reference);const choices=rooms.map(room=>({room_id:room.id.toLowerCase(),owner:room.ownerId?{principal_id:room.ownerId.toLowerCase(),principal_handle:knownHandle(room.owner,"@")??null}:null}));const names=choices.map(choice=>choice.owner?.principal_handle?`#${handle}@${choice.owner.principal_handle}`:choice.room_id);return new ParleApiError(`#${handle} names more than one room ${among}: ${names.join(", ")}. Nothing was chosen. ${next}`,{code:"room_handle_ambiguous",action:"fix_client",scope:"request",details:{room_handle:handle,choices}})}function roomOwnerUnknown(reference,among,next){return new ParleApiError(`${roomReferenceLabel(reference)} names its room by its owner, but Parle doesn't say who owns ${among}, so it can't be checked here. Nothing was chosen. ${next}`,{code:"validation_failed",action:"fix_client",scope:"request",details:{field:"rooms"}})}function parseAgentReference(raw){if(typeof raw!=="string")return void 0;const value=raw.trim();if(UUID_RE.test(value))return parsed({kind:"id",id:value.toLowerCase()});const parts=(value.startsWith("@")?value.slice(1):value).split(".");if(parts.length===1){const handle2=readHandle(parts[0]);return handle2?parsed({kind:"handle",handle:handle2}):void 0}if(parts.length>3||parts.length===3&&!isReadableAddressHandle(parts[2].trim().toLowerCase()))return void 0;const principal=readHandle(parts[0]);const handle=readHandle(parts[1]);return principal&&handle?parsed({kind:"handle",handle,principal}):void 0}function agentReferenceLabel(reference){return reference.kind==="id"?reference.id:`@${reference.principal?`${reference.principal}.`:""}${reference.handle}`}function sameAgentReference(left,right){return agentReferenceLabel(left)===agentReferenceLabel(right)}function agentMatches(reference,agent){if(reference.kind==="id")return typeof agent.id==="string"&&agent.id.trim().toLowerCase()===reference.id;if(knownHandle(agent.handle,"@")!==reference.handle)return false;const principal=knownHandle(agent.principal,"@");return!reference.principal||!principal||principal===reference.principal}function parseAddressReference(raw){if(typeof raw!=="string")return void 0;const value=raw.trim().toLowerCase();if(value.startsWith("@")){const parts=value.slice(1).split(".");return parts.length===3&&readHandle(parts[0])&&readHandle(parts[1])&&isReadableAddressHandle(parts[2])?parsed({kind:"address",address:value}):void 0}return isReadableAddressHandle(value)?parsed({kind:"handle",handle:value}):void 0}function addressMatches(reference,address2){const known=address2.trim().toLowerCase();return reference.kind==="address"?known===reference.address:known.slice(known.lastIndexOf(".")+1)===reference.handle&&known.includes(".")}function agentSelectorIsId(selector){return parseAgentReference(selector)?.kind==="id"}function agentSelectorHandle(selector){const reference=parseAgentReference(selector);return reference?.kind==="handle"?reference.handle:void 0}function agentSelectorMatches(selector,agent){const reference=parseAgentReference(selector);return Boolean(reference&&agentMatches(reference,agent))}function configuredAgentSelectors(get,warnings){const plural2=(get("PARLE_AGENTS")||"").trim();if(plural2)warnings.push(get("PARLE_AGENT")?"PARLE_AGENTS is the old name of PARLE_AGENT and is read beside it; use PARLE_AGENT.":"PARLE_AGENTS is deprecated: use PARLE_AGENT.");const entries=["PARLE_AGENTS","PARLE_AGENT"].flatMap(name=>(get(name)||"").split(",").map(value=>({name,value:value.trim()}))).filter(entry=>entry.value);for(const entry of entries){if(!parseAgentReference(entry.value)){warnings.push(`${entry.name} has ${entry.value}, which is not an agent id, a handle or @principal.agent, so it matches no agent.`)}}const listed=[...new Set(entries.map(entry=>entry.value))];const legacy={id:get("PARLE_AGENT_ID")||void 0,handle:get("PARLE_AGENT_HANDLE")||void 0};const oldNames=[legacy.id?"PARLE_AGENT_ID":void 0,legacy.handle?"PARLE_AGENT_HANDLE":void 0].filter(name=>Boolean(name));if(oldNames.length){warnings.push(listed.length?`${oldNames.join(" and ")} ${oldNames.length===1?"is the old name":"are the old names"} of PARLE_AGENT and ${oldNames.length===1?"is":"are"} ignored because PARLE_AGENT(S) is set. Remove ${oldNames.length===1?"it":"them"}.`:`${oldNames.join(" and ")} ${oldNames.length===1?"is":"are"} deprecated: use PARLE_AGENT (an agent id or handle).`)}if(listed.length)return{selectors:listed,legacy:{}};return{selectors:[legacy.id,legacy.handle].filter(value=>Boolean(value)),legacy}}import{homedir as homedir2}from"node:os";var DEFAULT_API_BASE=BUILD_API;var DESKTOP_CHANNEL=BUILD_DESKTOP_CHANNEL;function hostAllowed(hostname4,hosts=BUILD_API_HOSTS){return hosts.some(host=>host.startsWith("*.")?hostname4.endsWith(host.slice(1)):hostname4===host)}var UNTRUSTED_OPEN="[UNTRUSTED — ";var PARLE_LINE="[PARLE] ";var FENCE_SUFFIX_START="\n[END UNTRUSTED — ";var FENCE_SUFFIX_END=", not by Parle]\n";var FENCE_SUFFIX=`${FENCE_SUFFIX_START}written by another participant${FENCE_SUFFIX_END}`;function truncateText(text,maxBytes){const source=Buffer.from(text,"utf8");const bytes=source.byteLength;if(bytes<=maxBytes)return{text,truncated:false,bytes,returnedBytes:bytes};const suffix=Buffer.from("\n[truncated]","utf8");const limit=Math.max(0,maxBytes-suffix.byteLength);let end=limit;const decoder=new TextDecoder("utf-8",{fatal:true});while(end>0){try{decoder.decode(source.subarray(0,end));break}catch{end-=1}}const slice=source.subarray(0,end);const rendered=Buffer.concat([slice,suffix]).toString("utf8");return{text:rendered,truncated:true,bytes,returnedBytes:Buffer.byteLength(rendered,"utf8")}}function assertSafeBase(base,env=process.env){const url2=new URL(base);const isLocal=["localhost","127.0.0.1","::1","[::1]"].includes(url2.hostname);if(isLocal&&env.PARLE_ALLOW_INSECURE_LOCAL==="1"&&["http:","https:"].includes(url2.protocol)&&!url2.username&&!url2.password)return;if(url2.protocol!=="https:")throw new Error(`Parle API base must use https: ${base}`);if(url2.username||url2.password)throw new Error("Parle API base must not contain credentials.");if(!hostAllowed(url2.hostname))throw new Error(`Parle API base is not allowlisted: ${url2.hostname}`)}function stripServerPreamble(content,preamble){if(!preamble)return content;const prefix=preamble+"\n";if(!content.startsWith(prefix))return content;const rest=content.slice(prefix.length);if(!rest.startsWith(UNTRUSTED_OPEN)&&!rest.startsWith(PARLE_LINE))return content;return rest}function homeRelativePath(path,home=homedir2()){return home&&(path===home||path.startsWith(`${home}/`))?`~${path.slice(home.length)}`:path}import{execFileSync}from"node:child_process";import{existsSync as existsSync2,lstatSync as lstatSync4,readFileSync as readFileSync2,renameSync as renameSync2,statSync}from"node:fs";import{dirname as dirname3,isAbsolute as isAbsolute3,join as join7}from"node:path";function getLineColFromPtr(string5,ptr){let lines=string5.slice(0,ptr).split(/\r?\n/);return[lines.length,lines.pop().length+1]}function makeCodeBlock(string5,line2,column){let lines=string5.split(/\r?\n/);let codeblock="";let numberLen=(Math.log10(line2+1)|0)+1;for(let i=line2-1;i<=line2+1;i++){let l=lines[i-1];if(!l)continue;codeblock+=i.toString().padEnd(numberLen," ");codeblock+=": ";codeblock+=l;codeblock+="\n";if(i===line2){codeblock+=" ".repeat(numberLen+column+2);codeblock+="^\n"}}return codeblock}var TomlError=class _TomlError extends Error{line;column;codeblock;constructor(message,options){const[line2,column]=getLineColFromPtr(options.toml,options.ptr);const codeblock=makeCodeBlock(options.toml,line2,column);super(`Invalid TOML document: ${message}
|
|
11
11
|
|
|
12
12
|
${codeblock}`,options);this.line=line2;this.column=column;this.codeblock=codeblock}static x(message,ctx,ptr){throw new _TomlError(message,{toml:ctx.s,ptr:ptr??ctx.p})}};function parseString(ctx){let startPtr=ctx.p;let c=ctx.s.charCodeAt(ctx.p++);let first=c;let isLiteral=c===39;let isMultiline=c===ctx.s.charCodeAt(ctx.p)&&c===ctx.s.charCodeAt(ctx.p+1);if(isMultiline){if((c=ctx.s.charCodeAt(ctx.p+=2))===10)ctx.p++;else if(c===13&&ctx.s.charCodeAt(ctx.p+1)===10)ctx.p+=2}let parsed2="";let sliceStart=ctx.p;let state=0;for(;ctx.p<ctx.s.length;ctx.p++){c=ctx.s.charCodeAt(ctx.p);if(isMultiline&&(c===10||c===13&&ctx.s.charCodeAt(ctx.p+1)===10)){state=state&&3}else if(c<32&&c!==9||c===127){TomlError.x("control characters are not allowed in strings",ctx)}else if((!state||state===3)&&c===first&&(!isMultiline||ctx.s.charCodeAt(ctx.p+1)===first&&ctx.s.charCodeAt(ctx.p+2)===first)){if(isMultiline){if(ctx.s.charCodeAt(ctx.p+3)===first)ctx.p++;if(ctx.s.charCodeAt(ctx.p+3)===first)ctx.p++}if(!state){let s=ctx.s.slice(sliceStart,ctx.p);parsed2=parsed2?parsed2+s:s}ctx.p+=isMultiline?3:1;return parsed2}else if(!state){if(!isLiteral&&c===92){parsed2+=ctx.s.slice(sliceStart,sliceStart=ctx.p);state=1}}else if(state===1){if(c===120||c===117||c===85){let errPtr=ctx.p++-1;let value=0;let len=c===120?2:c===117?4:8;for(let j=0;j<len;j++,ctx.p++){let hex3=ctx.s.charCodeAt(ctx.p);let digit=hex3>=48&&hex3<=57?hex3-48:hex3>=65&&hex3<=70?hex3-65+10:hex3>=97&&hex3<=102?hex3-97+10:-1;if(digit<0)TomlError.x("invalid non-hex character in unicode escape",ctx);value=value<<4|digit}if(value<0||value>1114111||value>=55296&&value<=57343){TomlError.x("invalid unicode escape",ctx,errPtr)}parsed2+=String.fromCodePoint(value);sliceStart=ctx.p--;state=0}else if(isMultiline&&(c===32||c===9)){state=2}else{if(c===98)parsed2+="\b";else if(c===116)parsed2+=" ";else if(c===110)parsed2+="\n";else if(c===102)parsed2+="\f";else if(c===114)parsed2+="\r";else if(c===101)parsed2+="\x1B";else if(c===34)parsed2+='"';else if(c===92)parsed2+="\\";else TomlError.x("unrecognised escape sequence",ctx);sliceStart=ctx.p+1;state=0}}else if(c!==32&&c!==9){if(state===2)TomlError.x("invalid escape: only line-ending whitespace may be escaped",ctx,sliceStart);state=!isLiteral&&c===92?1:0;sliceStart=ctx.p}}TomlError.x("unfinished string",ctx,startPtr)}var DATE_TIME_RE=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var TomlDate=class _TomlDate extends Date{#hasDate=false;#hasTime=false;#offset=null;constructor(date5,fasttype,unsafeDelim){let hasDate=true;let hasTime=true;let offset="Z";let c;if(typeof date5==="string"){if(fasttype)prep:{if(fasttype<3){if(+date5.slice(11,13)>23){date5="";break prep}if(fasttype===2){offset=null;date5+="Z"}else if((c=date5.charCodeAt(date5.length-1))!==90&&c!==122){offset=date5.slice(date5.length-6)}if(unsafeDelim)date5=date5.slice(0,10)+"T"+date5.slice(11)}else if(fasttype===4){date5=+date5.slice(0,2)>23?"":`0000-01-01T${date5}Z`}hasDate=fasttype!==4;hasTime=fasttype!==3}else{let match=date5.match(DATE_TIME_RE);if(match){if(!match[1]){hasDate=false;date5=`0000-01-01T${date5}`}hasTime=!!match[2];hasTime&&date5[10]===" "&&(date5=date5.replace(" ","T"));if(match[2]&&+match[2]>23){date5=""}else{offset=match[3]||null;if(!offset&&hasTime)date5+="Z"}}else{date5=""}}}super(date5);if(!isNaN(this.getTime())){this.#hasDate=hasDate;this.#hasTime=hasTime;this.#offset=offset}}isDateTime(){return this.#hasDate&&this.#hasTime}isLocal(){return!this.#hasDate||!this.#hasTime||!this.#offset}isDate(){return this.#hasDate&&!this.#hasTime}isTime(){return this.#hasTime&&!this.#hasDate}isValid(){return this.#hasDate||this.#hasTime}toISOString(){let iso=super.toISOString();if(this.isDate())return iso.slice(0,10);if(this.isTime())return iso.slice(11,23);if(this.#offset===null)return iso.slice(0,-1);if(this.#offset==="Z"||this.#offset==="z")return iso;let offset=+this.#offset.slice(1,3)*60+ +this.#offset.slice(4,6);offset=this.#offset[0]==="-"?offset:-offset;let offsetDate=new Date(this.getTime()-offset*6e4);return offsetDate.toISOString().slice(0,-1)+this.#offset}static wrapAsOffsetDateTime(jsDate,offset="Z"){let date5=new _TomlDate(jsDate);date5.#offset=offset;return date5}static wrapAsLocalDateTime(jsDate){let date5=new _TomlDate(jsDate);date5.#offset=null;return date5}static wrapAsLocalDate(jsDate){let date5=new _TomlDate(jsDate);date5.#hasTime=false;date5.#offset=null;return date5}static wrapAsLocalTime(jsDate){let date5=new _TomlDate(jsDate);date5.#hasDate=false;date5.#offset=null;return date5}};function isDigit(char,base=10){return base===16?char>47&&char<58||char>64&&char<71||char>96&&char<103:char>47&&char<48+base}function isEndOfValue(char,delim){return char===32||char===9||char===10||char===13||delim&&(char===delim||char===44)||char===35}function extractValue(ctx,end){let errPtr=ctx.p;let c=ctx.s.charCodeAt(ctx.p);if(c===91||c===123){ctx.d--||TomlError.x("document contains excessively nested structures. aborting.",ctx);let value=c===91?parseArray(ctx):parseInlineTable(ctx);ctx.d++;return value}if(c===34||c===39){return parseString(ctx)}if(c===116){if(ctx.s.charCodeAt(++ctx.p)!==114||ctx.s.charCodeAt(++ctx.p)!==117||ctx.s.charCodeAt(++ctx.p)!==101)TomlError.x("invalid value",ctx,errPtr);return ctx.p++,true}if(c===102){if(ctx.s.charCodeAt(++ctx.p)!==97||ctx.s.charCodeAt(++ctx.p)!==108||ctx.s.charCodeAt(++ctx.p)!==115||ctx.s.charCodeAt(++ctx.p)!==101)TomlError.x("invalid value",ctx,errPtr);return ctx.p++,false}if(c===43||c===45){return parseNumber(ctx,ctx.p,ctx.s.charCodeAt(++ctx.p),44-c,end)}if(ctx.s.charCodeAt(ctx.p+4)===45&&ctx.s.charCodeAt(ctx.p+7)===45){return parseDate(ctx,c,end)}if(ctx.s.charCodeAt(ctx.p+2)===58){return parseTime(ctx,c,end)}return parseNumber(ctx,ctx.p,c,0,end)}function parseNumber(ctx,startPtr,startChr,sign2,endChr){let c=startChr;let state=0;let hasUnderscores=false;if(c===105){if(ctx.s.charCodeAt(++ctx.p)!==110||ctx.s.charCodeAt(++ctx.p)!==102)TomlError.x("invalid value",ctx,startPtr);return ctx.p++,(sign2||1)/0}if(c===110){if(ctx.s.charCodeAt(++ctx.p)!==97||ctx.s.charCodeAt(++ctx.p)!==110)TomlError.x("invalid value",ctx,startPtr);return ctx.p++,NaN}if(c===48){if(++ctx.p>=ctx.s.length||isEndOfValue(c=ctx.s.charCodeAt(ctx.p),endChr))return ctx.bi===true?0n:0;if(!sign2){if(c===120)return parseIntegerBaseN(ctx,startPtr,16,endChr);else if(c===98)return parseIntegerBaseN(ctx,startPtr,2,endChr);else if(c===111)return parseIntegerBaseN(ctx,startPtr,8,endChr)}if(c===46)state=2;else if(c===101||c===69)state=4;else TomlError.x("illegal leading zero",ctx,startPtr)}else if(!isDigit(c))TomlError.x("invalid value",ctx,startPtr);while(++ctx.p<ctx.s.length&&(c=ctx.s.charCodeAt(ctx.p),!isEndOfValue(c,endChr))){if(!state)state=1;if(c===95){if(!(state&1))TomlError.x("illegal underscore",ctx);state+=11;hasUnderscores=true}else if(state===1&&c===46)state=2;else if((state===1||state===3)&&(c===101||c===69))state=4;else if(state===4&&(c===43||c===45)){}else if(!isDigit(c))TomlError.x(`illegal character in numeric literal`,ctx);else if(state>9)state-=11;else if(!(state&1))state++}if(!state){let val=(startChr-48)*(sign2||1);return ctx.bi===true?BigInt(val):val}if(!(state&1))TomlError.x("unfinished numeric value",ctx,startPtr);let str=ctx.s.slice(startPtr,ctx.p);if(hasUnderscores)str=str.replaceAll("_","");return state>1?parseFloat(str):parseInteger(ctx,str,10,startPtr)}function parseIntegerBaseN(ctx,startPtr,base,endChr){let c,underscore=1;while(++ctx.p<ctx.s.length&&(c=ctx.s.charCodeAt(ctx.p),!isEndOfValue(c,endChr))){if(c===95){if(underscore&1)TomlError.x("illegal underscore",ctx);underscore=3}else if(!isDigit(c,base))TomlError.x(`illegal character in numeric literal`,ctx);else if(underscore&1)underscore--}if(underscore&1)TomlError.x("unfinished numeric value",ctx);let str=ctx.s.slice(startPtr+2,ctx.p);if(underscore)str=str.replaceAll("_","");return parseInteger(ctx,str,base,startPtr)}function parseInteger(ctx,str,base,startPtr){if(ctx.bi!==true)int:{let val=parseInt(str,base);if(!Number.isSafeInteger(val)){if(ctx.bi)break int;TomlError.x("integer value cannot be represented losslessly",ctx,startPtr)}return val}return base===10?BigInt(str):BigInt((base===2?"0b":base===8?"0o":"0x")+str)}function parseDate(ctx,c,endChr){let startPtr=ctx.p++,unsafeSeparator;if(!isDigit(c)||!isDigit(ctx.s.charCodeAt(ctx.p++))||!isDigit(ctx.s.charCodeAt(ctx.p++))||!isDigit(ctx.s.charCodeAt(ctx.p++))){return parseNumber(ctx,ctx.p=startPtr,c,0,endChr)}ctx.p+=5;if(!isDigit(ctx.s.charCodeAt(ctx.p++)))TomlError.x("invalid date-time: date part is malformed",ctx,startPtr);if(ctx.p>=ctx.s.length||((c=ctx.s.charCodeAt(ctx.p))!==32||(unsafeSeparator=true,!isDigit(ctx.s.charCodeAt(ctx.p+1))))&&c!==84&&c!==116){let t2=ctx.s.slice(startPtr,ctx.p);return readDate(ctx,t2,3,false,startPtr)}if(ctx.s.charCodeAt(ctx.p+=3)!==58)TomlError.x("invalid date-time: time part is malformed",ctx,startPtr);if(ctx.s.charCodeAt(ctx.p+=3)===58)ctx.p+=3;if(ctx.s.charCodeAt(ctx.p)===46)while(isDigit(ctx.s.charCodeAt(++ctx.p)));if(c=ctx.s.charCodeAt(ctx.p)){if(c===90||c===122){let t2=ctx.s.slice(startPtr,++ctx.p);return readDate(ctx,t2,1,unsafeSeparator,startPtr,"[+00:00]")}if(c===43||c===45){let t2=ctx.s.slice(startPtr,ctx.p+=6);return readDate(ctx,t2,1,unsafeSeparator,startPtr,!ctx.ld&&"["+ctx.s.slice(ctx.p-6,ctx.p)+"]")}}let t=ctx.s.slice(startPtr,ctx.p);return readDate(ctx,t,2,unsafeSeparator,startPtr)}function parseTime(ctx,c,endChr){let start=ctx.p;if(!isDigit(c)||!isDigit(ctx.s.charCodeAt(++ctx.p))){return parseNumber(ctx,--ctx.p,c,0,endChr)}if(ctx.s.charCodeAt(ctx.p+=4)===58)ctx.p+=3;if(ctx.s.charCodeAt(ctx.p)===46)while(isDigit(ctx.s.charCodeAt(++ctx.p)));let t=ctx.s.slice(start,ctx.p);return readDate(ctx,t,4,false,start)}function readDate(ctx,str,type,unsafeDelim,errPtr,temporalSuffix){if(ctx.ld){let date5=new TomlDate(str,type,unsafeDelim);if(!date5.isValid())TomlError.x("invalid date",ctx,errPtr);return date5}try{if(temporalSuffix)str+=temporalSuffix;switch(type){case 1:return Temporal.ZonedDateTime.from(str);case 2:return Temporal.PlainDateTime.from(str);case 3:return Temporal.PlainDate.from(str);case 4:return Temporal.PlainTime.from(str)}}catch(e){TomlError.x(e instanceof Error?e.message:""+e,ctx,errPtr)}}function skipComment(ctx){for(;ctx.p<ctx.s.length;ctx.p++){let c=ctx.s.charCodeAt(ctx.p);if(c===10)break;if(c===13&&ctx.s.charCodeAt(ctx.p+1)===10){ctx.p++;break}if(c<32&&c!==9||c===127){TomlError.x("control characters are not allowed in comments",ctx)}}}function skipVoid(ctx,banNewLines,banComments){let c;while(ctx.p<ctx.s.length){while(ctx.p<ctx.s.length&&((c=ctx.s.charCodeAt(ctx.p))===32||c===9||!banNewLines&&(c===10||c===13&&ctx.s.charCodeAt(ctx.p+1)===10)))ctx.p++;if(banComments||c!==35)break;skipComment(ctx)}}function parseKey(ctx,end=61){let startPtr;let state=0;let parsed2=[];let sliceStart;let c=ctx.s.charCodeAt(startPtr=ctx.p);do{if(c===end){if(!state)TomlError.x("unexpected end of key",ctx);if(state===1)parsed2.push(ctx.s.slice(sliceStart,ctx.p));return ctx.p++,parsed2}else if(c===46){if(!state)TomlError.x("illegal empty bare key",ctx);if(state===1)parsed2.push(ctx.s.slice(sliceStart,ctx.p));state=0}else if(!state&&(c===34||c===39)){if(c===ctx.s.charCodeAt(ctx.p+1)&&c===ctx.s.charCodeAt(ctx.p+2))TomlError.x("illegal quoted key: multiline strings are not allowed",ctx);parsed2.push(parseString(ctx));state=2;ctx.p--}else if(c===32||c===9){if(state===1){parsed2.push(ctx.s.slice(sliceStart,ctx.p));state=2}}else if(state===2||c<48&&c!==45||c>57&&c<65||c>90&&c<97&&c!==95||c>122){TomlError.x("illegal character in key",ctx)}else if(!state){state=1;sliceStart=ctx.p}}while(c=ctx.s.charCodeAt(++ctx.p));TomlError.x("incomplete key-value: cannot find end of key",ctx,startPtr)}function parseInlineTable(ctx){let startPtr=ctx.p++;let res=Object.create(null);let seen=new Set;let c;while(ctx.p<ctx.s.length){skipVoid(ctx);if((c=ctx.s.charCodeAt(ctx.p))===125){ctx.p++;return res}let k;let t=res;let hasOwn=false;let errPtr=ctx.p;let key=parseKey(ctx);for(let i=0;i<key.length;i++){if(i)t=hasOwn?t[k]:t[k]=Object.create(null);k=key[i];if((hasOwn=Object.hasOwn(t,k))&&(typeof t[k]!=="object"||seen.has(t[k]))){TomlError.x("trying to redefine an already defined value",ctx,errPtr)}let unsafe=k==="__proto__";if(ctx.uk&&(unsafe||k==="constructor")){t=ctx.uk!==1&&TomlError.x("document contains an unsafe property",ctx,errPtr);break}if(!hasOwn&&unsafe){Object.defineProperty(t,k,{enumerable:true,configurable:true,writable:true})}}if(hasOwn){TomlError.x("trying to redefine an already defined value",ctx,errPtr)}skipVoid(ctx,true,true);let value=extractValue(ctx,125);if(t&&typeof(t[k]=value)==="object")seen.add(value);skipVoid(ctx);if((c=ctx.s.charCodeAt(ctx.p++))===125){return res}if(c!==44)TomlError.x("expected comma or end of structure",ctx,ctx.p-1)}TomlError.x("unfinished table",ctx,startPtr)}function parseArray(ctx){let startPtr=ctx.p++;let res=[];let c;while(ctx.p<ctx.s.length){skipVoid(ctx);if((c=ctx.s.charCodeAt(ctx.p))===93){ctx.p++;return res}res.push(extractValue(ctx,93));skipVoid(ctx);if((c=ctx.s.charCodeAt(ctx.p++))===93){return res}if(c!==44)TomlError.x("expected comma or end of structure",ctx,ctx.p-1)}TomlError.x("unfinished array",ctx,startPtr)}function peekTable(ctx,key,table,meta3,type){let t=table;let m=meta3;let k;let hasOwn=false;let state;for(let i=0;i<key.length;i++){if(i){t=hasOwn?t[k]:t[k]=Object.create(null);m=(state=m[k]).c;if(type===0&&(state.t===1||state.t===2)){return null}if(state.t===2){let l=t.length-1;t=t[l];m=m[l].c}}k=key[i];if((hasOwn=Object.hasOwn(t,k))&&m[k]?.t===0&&m[k]?.d){return null}if(!hasOwn){let unsafe=k==="__proto__";if(ctx.uk&&(unsafe||k==="constructor"))return false;if(unsafe){Object.defineProperty(t,k,{enumerable:true,configurable:true,writable:true});Object.defineProperty(m,k,{enumerable:true,configurable:true,writable:true})}m[k]={t:i<key.length-1&&type===2?3:type,d:false,i:0,c:Object.create(null)}}}state=m[k];if(state.t!==type&&!(type===1&&state.t===3)){return null}if(type===2){if(!state.d){state.d=true;t[k]=[]}t[k].push(t=Object.create(null));state.c[state.i++]=state={t:1,d:false,i:0,c:Object.create(null)}}if(state.d){return null}state.d=true;if(type===1){t=hasOwn?t[k]:t[k]=Object.create(null)}else if(type===0&&hasOwn){return null}return[k,t,state.c]}function validateTablePeek(ctx,peek,ptr){if(peek===null||ctx.uk===2)TomlError.x(peek===null?"trying to redefine an already defined table or value":"document contains an unsafe property",ctx,ptr)}function parse(toml,options={}){let ctx={s:toml,p:0,d:options.maxDepth??1e3,bi:options.integersAsBigInt??false,ld:options.useLegacyDate??true,uk:options.unsafeKeyBehaviour==="throw"?2:options.unsafeKeyBehaviour==="drop"?1:0};let res=Object.create(null);let meta3=Object.create(null);let tmp;let skipping=false;let tbl=res;let m=meta3;if(toml.charCodeAt(0)===65279)ctx.p++;skipVoid(ctx);while(ctx.p<toml.length){if(toml.charCodeAt(ctx.p)===91){let isTableArray=toml.charCodeAt(++ctx.p)===91;tmp=ctx.p+=+isTableArray;skipping=false;let k=parseKey(ctx,93);if(isTableArray){if(toml.charCodeAt(ctx.p)!==93){TomlError.x("expected end of table array declaration",ctx)}ctx.p++}let p=peekTable(ctx,k,res,meta3,isTableArray?2:1);if(!p){validateTablePeek(ctx,p,tmp);skipping=true}else{m=p[2];tbl=p[1]}}else{tmp=ctx.p;let k=parseKey(ctx);let p=peekTable(ctx,k,tbl,m,0);if(!p&&!skipping)validateTablePeek(ctx,p,tmp);skipVoid(ctx,true,true);let v=extractValue(ctx,void 0);if(p&&!skipping)p[1][p[0]]=v}skipVoid(ctx,true);if(ctx.p<toml.length&&(tmp=toml.charCodeAt(ctx.p))!==10&&(tmp!==13||toml.charCodeAt(ctx.p+1)!==10)){TomlError.x("each key-value declaration must be followed by an end-of-line",ctx)}skipVoid(ctx)}return res}var BARE_KEY=/^[a-z0-9-_]+$/i;var HAS_WELLFORMED=!!"".isWellFormed;function extendedTypeOf(obj){let type=typeof obj;if(type==="object"){if(Array.isArray(obj))return"array";if(typeof obj.getUTCDate==="function"&&obj instanceof Date)return"date";if(globalThis.Temporal){if(obj.until){if(obj instanceof Temporal.ZonedDateTime)return"temporal/tz+uc";if(obj instanceof Temporal.PlainDateTime||obj instanceof Temporal.PlainDate)return"temporal/uc";if(obj instanceof Temporal.PlainTime||obj instanceof Temporal.Instant)return"temporal";if(obj instanceof Temporal.PlainYearMonth)return"temporal/x"}else if(obj.toPlainDate&&obj instanceof Temporal.PlainMonthDay||obj.negated&&obj instanceof Temporal.Duration){return"temporal/x"}}}return type}function isArrayOfTables(obj){for(let i=0;i<obj.length;i++){if(extendedTypeOf(obj[i])!=="object")return false}return obj.length!=0}function formatWellFormedStringUnchecked(s){return JSON.stringify(s).replaceAll("","\\u007f")}function formatString(s){return formatWellFormedStringUnchecked(HAS_WELLFORMED?s.toWellFormed():s)}function formatKey(s){if(BARE_KEY.test(s))return s;if(HAS_WELLFORMED&&!s.isWellFormed())throw new RangeError("key contains illegal lone surrogates");return formatWellFormedStringUnchecked(s)}function stringifyValue(val,type,depth,numberAsFloat,strictTemporal){if(depth===0){throw new Error("Could not stringify the object: maximum object depth exceeded")}switch(type){case"number":if(isNaN(val))return"nan";if(val===Infinity)return"inf";if(val===-Infinity)return"-inf";if(Number.isInteger(val)&&(numberAsFloat||!Number.isSafeInteger(val)))return val.toFixed(1);case"bigint":case"boolean":case"temporal":return val.toString();case"string":return formatString(val);case"date":if(isNaN(val.getTime()))throw new TypeError("cannot serialize invalid date");return val.toISOString();case"object":return stringifyInlineTable(val,depth,numberAsFloat,strictTemporal);case"array":return stringifyArray(val,depth,numberAsFloat,strictTemporal);case"temporal/tz+uc":if(strictTemporal){let tz=val.timeZoneId;let tzc=tz.charCodeAt(0);if(tzc!==43&&tzc!==45&&(tzc!==85&&tzc!==71&&tzc!==90&&tzc!==69||tz!=="UTC"&&tz!=="UCT"&&tz!=="Universal"&&tz!=="Zulu"&&!tz.startsWith("GMT")&&tz!=="Greenwich"&&!tz.startsWith("Etc/"))){throw new TypeError("Temporal objects with an IANA timezone are not allowed in Temporal strict mode")}}case"temporal/uc":if(strictTemporal&&val.calendarId!=="iso8601")throw new TypeError("Temporal objects with a non-default calendar are not allowed in Temporal strict mode");return val.toString({calendarName:"never",timeZoneName:"never"});case"temporal/x":throw new TypeError("Unsupported "+val[Symbol.toStringTag])}}function stringifyInlineTable(obj,depth,numberAsFloat,strictTemporal){let keys=Object.keys(obj);if(keys.length===0)return"{}";let res="{ ";for(let i=0;i<keys.length;i++){let k=keys[i];if(i)res+=", ";res+=formatKey(k)+" = "+stringifyValue(obj[k],extendedTypeOf(obj[k]),depth-1,numberAsFloat,strictTemporal)}return res+" }"}function stringifyArray(array2,depth,numberAsFloat,strictTemporal){if(array2.length===0)return"[]";let res="[ ";for(let i=0;i<array2.length;i++){if(i)res+=", ";if(array2[i]===null||array2[i]===void 0){throw new TypeError("arrays cannot contain null or undefined values")}res+=stringifyValue(array2[i],extendedTypeOf(array2[i]),depth-1,numberAsFloat,strictTemporal)}return res+" ]"}function stringifyArrayTable(array2,key,depth,numberAsFloat,strictTemporal){if(depth===0){throw new Error("Could not stringify the object: maximum object depth exceeded")}let res="";for(let i=0;i<array2.length;i++){res+=`${res&&"\n"}[[${key}]]
|
|
13
13
|
`;res+=stringifyTable(0,array2[i],key,depth,numberAsFloat,strictTemporal)}return res}function stringifyTable(tableKey,obj,prefix,depth,numberAsFloat,strictTemporal){if(depth===0){throw new Error("Could not stringify the object: maximum object depth exceeded")}let preamble="";let tables="";let keys=Object.keys(obj);for(let i=0;i<keys.length;i++){let k=keys[i];if(obj[k]!==null&&obj[k]!==void 0){let type=extendedTypeOf(obj[k]);if(type==="symbol"||type==="function"){throw new TypeError(`cannot serialize values of type '${type}'`)}let key=formatKey(k);if(type==="array"&&isArrayOfTables(obj[k])){tables+=(tables&&"\n")+stringifyArrayTable(obj[k],prefix?`${prefix}.${key}`:key,depth-1,numberAsFloat,strictTemporal)}else if(type==="object"){let tblKey=prefix?`${prefix}.${key}`:key;tables+=(tables&&"\n")+stringifyTable(tblKey,obj[k],tblKey,depth-1,numberAsFloat,strictTemporal)}else{preamble+=key;preamble+=" = ";preamble+=stringifyValue(obj[k],type,depth,numberAsFloat,strictTemporal);preamble+="\n"}}}if(tableKey&&(preamble||!tables))preamble=preamble?`[${tableKey}]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{homedir}from"node:os";import{isAbsolute,join}from"node:path";var BUILD_HOME=".parle";function parleHome(env=process.env){const configured=env.PARLE_HOME;if(configured&&isAbsolute(configured))return configured;return join(env.HOME||env.USERPROFILE||homedir(),BUILD_HOME)}import{createHash,createHmac,randomBytes,randomUUID}from"node:crypto";import{closeSync as closeSync2,constants as constants2,fstatSync as fstatSync2,ftruncateSync,lstatSync as lstatSync2,openSync as openSync2,writeSync as writeSync2}from"node:fs";import{isAbsolute as isAbsolute2,join as join2,resolve}from"node:path";import{chmodSync,closeSync,constants,existsSync,fchmodSync,fsyncSync,fstatSync,lstatSync,linkSync,mkdirSync,openSync,readSync,renameSync,unlinkSync,writeSync}from"node:fs";var DEFAULT_DIRECTORY_MODE=448;var DEFAULT_MALFORMED_LOCK_STALE_MS=5*6e4;var NO_FOLLOW=typeof constants.O_NOFOLLOW==="number"?constants.O_NOFOLLOW:0;var SafeFileError=class extends Error{code;constructor(code,message,options){super(message,options);this.name="SafeFileError";this.code=code}};function ownerAndMode(stat,expectedMode,label,kind){if(kind==="file"){if(!stat.isFile())throw new SafeFileError("unsafe_type",`${label} must be a regular file.`)}else if(!stat.isDirectory()){throw new SafeFileError("unsafe_type",`${label} must be a real directory.`)}if(process.platform==="win32")return;if(stat.uid!==process.getuid?.())throw new SafeFileError("unsafe_owner",`${label} must be owned by the current user.`);if((stat.mode&511)!==expectedMode)throw new SafeFileError("unsafe_mode",`${label} must have mode ${expectedMode.toString(8)}.`)}function inspectRealDirectory(path,label,mode=DEFAULT_DIRECTORY_MODE){let stat;try{stat=lstatSync(path)}catch(error){throw new SafeFileError("directory_unavailable",`${label} cannot be inspected: ${path}.`,{cause:error})}if(stat.isSymbolicLink())throw new SafeFileError("symlink_refused",`${label} must not be a symbolic link: ${path}.`);ownerAndMode(stat,mode,label,"directory");return stat}function ensureOwnerOnlyDirectory(path,options={label:"Owner-only directory"}){const mode=options.mode??DEFAULT_DIRECTORY_MODE;if(!existsSync(path)){if(options.create===false)throw new SafeFileError("directory_missing",`${options.label} is missing: ${path}.`);try{mkdirSync(path,{recursive:true,mode})}catch(error){throw new SafeFileError("directory_create_failed",`${options.label} could not be created: ${path}.`,{cause:error})}}let stat;try{stat=lstatSync(path)}catch(error){throw new SafeFileError("directory_unavailable",`${options.label} cannot be inspected: ${path}.`,{cause:error})}if(stat.isSymbolicLink())throw new SafeFileError("symlink_refused",`${options.label} must not be a symbolic link: ${path}.`);if(!stat.isDirectory())throw new SafeFileError("unsafe_type",`${options.label} must be a real directory.`);if(process.platform!=="win32"&&stat.uid!==process.getuid?.())throw new SafeFileError("unsafe_owner",`${options.label} must be owned by the current user.`);if(options.repairMode&&process.platform!=="win32"&&(stat.mode&511)!==mode)chmodSync(path,mode);inspectRealDirectory(path,options.label,mode);return path}var ParleApiError=class extends Error{status;code;action;scope;retryAfterMs;retryable;details;requestId;constructor(message,options={}){super(message);this.name="ParleApiError";this.status=options.status;this.code=options.code;this.action=options.action;this.scope=options.scope;this.retryAfterMs=options.retryAfterMs;this.retryable=options.retryable??false;this.details=options.details;this.requestId=options.requestId}};var ADDRESS_HANDLE_MIN_LENGTH=2;var ADDRESS_HANDLE_MAX_LENGTH=24;var NEW_HANDLE_RULE=`${ADDRESS_HANDLE_MIN_LENGTH} to ${ADDRESS_HANDLE_MAX_LENGTH} lowercase letters, digits and single hyphens, with at least one letter, not a reserved word`;var LEVELS={debug:1,trace:2};var DEBUG_EVENTS=["client_start","http_start","http_response","http_error","http_body_error","delivery_start","delivery_stop","stream_connect","stream_open","stream_eof","stream_error","stream_retry","stream_close","room_error","wake_open","wake_hint","fetch_started","fetch_success","row_fetched","handling_complete","ack_started","ack_success","background_error","mcp_client","mcp_call_meta"];var TRACE_EVENTS=["hook_walk_step","hook_probe_error","hook_host_found","hook_host_missing","hook_bridges_none","hook_bridge_unresponsive"];var EVENTS=new Map([...DEBUG_EVENTS.map(event=>[event,"debug"]),...TRACE_EVENTS.map(event=>[event,"trace"])]);var METHODS=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"]);var REASONS=new Set(["stopped","revision_changed","interrupted","recover","drain","handler","ack","walk_end","self_parent","depth"]);var PROCESS_KINDS=new Set(["codex","codex_refused","shell","other","unknown"]);var TOOLS=new Set(["ps","lsof"]);var BACKGROUND_OPERATIONS=["key_rotation","address_reconnect","room_instructions_refresh","host_session_rebind","address_facts_refresh","room_drain","hook_socket_listen","address_rooms_read","features_read","missed_notices_read","room_set_refresh"];var OPERATIONS=new Set(BACKGROUND_OPERATIONS);var TRIGGERS=new Set(["startup","wake_open","wake_hint","test"]);var TRANSPORT_CODES=new Set(["UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_ABORTED","UND_ERR_DESTROYED","UND_ERR_CLOSED","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","ENOTFOUND","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","ECANCELED","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","CERT_HAS_EXPIRED","ERR_TLS_CERT_ALTNAME_INVALID","UNABLE_TO_GET_ISSUER_CERT_LOCALLY"]);var PROCESS_CODES=new Set(["EAGAIN","ENOMEM","EMFILE","ENFILE","EPERM","EACCES","ENOENT","EIO","ETIMEDOUT"]);var SIGNALS=new Set(["SIGTERM","SIGKILL","SIGINT","SIGHUP"]);var ERROR_NAMES=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","ParleApiError","TokenEndpointError"]);var ACTIONS=new Set(["retry","backoff","retry_with_backoff","reauthorize","fix_client","stop","rebootstrap"]);var SYSCALLS=new Set(["read","write","connect","getaddrinfo"]);var MAX_BYTES=1024*1024;var COMPONENTS=new Set(["client","delivery","account","desktop","approval","oauth","hook"]);var wrappedFetches=new WeakMap;var responseDiagnostics=new WeakMap;var MAX_SINKS=64;var sinks=new Map;var CLIENT_LABEL=/^[A-Za-z0-9 ._@/+:-]{1,64}$/;var META_KEY=/^[A-Za-z0-9_.:/-]{1,64}$/;var META_KEYS_MAX=24;function metaFingerprints(meta){if(!meta||typeof meta!=="object"||Array.isArray(meta))return void 0;const out={};const add=(key,value)=>{if(Object.keys(out).length>=META_KEYS_MAX||!META_KEY.test(key))return;const type=value===null?"null":Array.isArray(value)?"array":typeof value;let text;try{text=JSON.stringify(value)??String(value)}catch{text=type}out[key]=`${type}:${createHash("sha256").update("parle-debug-meta\0").update(text.slice(0,8192)).digest("hex").slice(0,16)}`};for(const key of Object.keys(meta)){const value=own(meta,key);if(value&&typeof value==="object"&&!Array.isArray(value)){for(const inner of Object.keys(value))add(`${key}.${inner}`,own(value,inner))}else add(key,value)}return out}var noop=()=>Object.assign(()=>{},{close:()=>{},nextRequest:()=>0,enabled:false});function own(value,key){if(!value||typeof value!=="object")return void 0;return Object.getOwnPropertyDescriptor(value,key)?.value}function nameOf(error){const name=own(error,"name");if(typeof name==="string"&&ERROR_NAMES.has(name))return name;if(error instanceof TypeError)return"TypeError";if(error instanceof RangeError)return"RangeError";if(error instanceof SyntaxError)return"SyntaxError";return"Error"}function debugLevel(env){if(env.PARLE_DEBUG==="1"||env.PARLE_DEBUG==="true")return"debug";if(env.PARLE_DEBUG==="trace")return"trace";return void 0}function debugScope(env,component){if(!COMPONENTS.has(component)||!debugLevel(env))return void 0;const home=parleHome(env);if(!isAbsolute2(home))return void 0;const normalized=resolve(home);return{home:normalized,key:JSON.stringify([component,normalized])}}function createAdapterDebugLog(env,now,component="delivery"){try{const scope=debugScope(env,component);if(!scope)return noop();let sink=sinks.get(scope.key);if(!sink){if(sinks.size>=MAX_SINKS)return noop();sink=createSink(scope.home,component);sinks.set(scope.key,sink)}const shared=sink,logger=shared.nextLogger();const level=LEVELS[debugLevel(env)??"debug"];let closed=false;const log=(event,detail,error)=>{const eventLevel=EVENTS.get(event);if(closed||!shared.enabled||!eventLevel||LEVELS[eventLevel]>level)return;try{shared.write(Date.prototype.toISOString.call(now()),logger,event,detail,error)}catch{closed=true}};return Object.defineProperty(Object.assign(log,{close:()=>{closed=true},nextRequest:()=>closed||!shared.enabled?0:shared.nextRequest()}),"enabled",{get:()=>!closed&&shared.enabled})}catch{return noop()}}function createSink(home,component){const root=home;const stem=`${component}-${process.pid}-${randomUUID()}`;const salt=randomBytes(32);const ref=value=>typeof value==="string"&&value.length>0?createHmac("sha256",salt).update(value.slice(0,8192)).digest("hex").slice(0,24):void 0;let slot=0,bytes=0,failed=false,loggerSequence=0,requestSequence=0;const identities=[];const errorFacts=error=>{const result={name:nameOf(error)};const code=own(error,"code");if(typeof code==="string"&&(TRANSPORT_CODES.has(code)||PROCESS_CODES.has(code)))result.code=code;else if(ref(code))result.codeRef=ref(code);if(Array.isArray(own(error,"output"))){const signal=own(error,"signal"),exitStatus=own(error,"status");if(typeof signal==="string"&&SIGNALS.has(signal))result.signal=signal;if(typeof exitStatus==="number"&&Number.isInteger(exitStatus)&&exitStatus>=0&&exitStatus<=255)result.exitStatus=exitStatus}const action=own(error,"action");if(typeof action==="string"&&ACTIONS.has(action))result.action=action;if(error instanceof ParleApiError){const status=own(error,"status"),retryAfterMs=own(error,"retryAfterMs"),retryable=own(error,"retryable");if(typeof status==="number"&&Number.isInteger(status)&&status>=100&&status<=599)result.status=status;if(typeof retryAfterMs==="number"&&Number.isInteger(retryAfterMs)&&retryAfterMs>=0&&retryAfterMs<=2**31-1)result.retryAfterMs=retryAfterMs;if(typeof retryable==="boolean")result.retryable=retryable}const message=own(error,"message");if(message==="terminated")result.reason="terminated";if(message==="Parle agent stream ended unexpectedly")result.reason="stream_eof";const seen=new Set([error]);let cause=own(error,"cause");const causes=[];for(let depth=0;cause&&typeof cause==="object"&&!seen.has(cause)&&depth<3;depth++){seen.add(cause);const facts={name:nameOf(cause)};const code2=own(cause,"code"),syscall=own(cause,"syscall");if(typeof code2==="string"&&TRANSPORT_CODES.has(code2))facts.code=code2;else if(ref(code2))facts.codeRef=ref(code2);if(typeof syscall==="string"&&SYSCALLS.has(syscall))facts.syscall=syscall;causes.push(facts);cause=own(cause,"cause")}if(causes.length)result.causes=causes;return result};const write=(at,logger,event,detail,error)=>{if(failed||!EVENTS.has(event))return;let fd;try{const safe={};for(const key of["attempt","durationMs","retryMs","request","status","seq","rowCount","processId","depth"]){const value=own(detail,key);if(typeof value!=="number"||!Number.isFinite(value)||value<0)continue;if(key==="status"&&(value!==0&&(!Number.isInteger(value)||value<100||value>599)))continue;if(!["durationMs","retryMs"].includes(key)&&!Number.isSafeInteger(value))continue;safe[key]=value}for(const[key,allowed]of[["trigger",TRIGGERS],["reason",REASONS],["method",METHODS],["kind",PROCESS_KINDS],["tool",TOOLS],["operation",OPERATIONS]]){const value=own(detail,key);if(typeof value==="string"&&allowed.has(value))safe[key]=value}for(const key of["clientName","clientVersion"]){const value=own(detail,key);if(typeof value==="string"&&CLIENT_LABEL.test(value))safe[key]=value}const meta=metaFingerprints(own(detail,"meta"));if(meta)safe.metaKeys=meta;for(const key of["roomId","eventId","path"]){const value=ref(own(detail,key));if(value)safe[key==="path"?"routeRef":key==="roomId"?"roomRef":"eventRef"]=value}const line=JSON.stringify({at,pid:process.pid,component,logger,event,...safe,...error?{error:errorFacts(error)}:{}})+"\n";const buffer=Buffer.from(line);if(buffer.length>MAX_BYTES)return;ensureOwnerOnlyDirectory(root,{label:"Parle state directory"});const directory=ensureOwnerOnlyDirectory(join2(root,"debug"),{label:"Parle debug directory"});const rotate=bytes+buffer.length>MAX_BYTES;if(rotate){slot=1-slot;bytes=0}const path=join2(directory,`${stem}-${slot}.jsonl`);fd=openSync2(path,constants2.O_WRONLY|(identities[slot]?0:constants2.O_CREAT|constants2.O_EXCL)|(constants2.O_NOFOLLOW||0),384);const stat=fstatSync2(fd),link=lstatSync2(path),identity=identities[slot];if(!stat.isFile()||stat.nlink!==1||link.isSymbolicLink()||stat.dev!==link.dev||stat.ino!==link.ino||identity&&(stat.dev!==identity.dev||stat.ino!==identity.ino)||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||(stat.mode&511)!==384))throw new Error("unsafe debug file");identities[slot]={dev:stat.dev,ino:stat.ino};if(rotate&&identity){ftruncateSync(fd,0)}let written=0;while(written<buffer.length){const count=writeSync2(fd,buffer,written,buffer.length-written,bytes+written);if(count<=0)throw new Error("debug write made no progress");written+=count}bytes+=buffer.length}catch{failed=true}finally{if(fd!==void 0){try{closeSync2(fd)}catch{failed=true}}}};return{write,nextLogger:()=>++loggerSequence,nextRequest:()=>++requestSequence,get enabled(){return!failed}}}function createDebugFetch(env,fetchImpl,now,component="client"){const existing=wrappedFetches.get(fetchImpl);let key;try{const scope=debugScope(env,component);if(!scope)return existing?.original||fetchImpl;key=scope.key}catch{return existing?.original||fetchImpl}if(existing?.key===key)return fetchImpl;if(existing)fetchImpl=existing.original;const log=createAdapterDebugLog(env,now,component);if(!log.enabled)return fetchImpl;log("client_start");if(!log.enabled)return fetchImpl;const wrapped=async function(input,init){if(!log.enabled)return fetchImpl.call(this,input,init);const request=log.nextRequest();const startedAt=performance.now();let method,path;try{method=init?.method||(input instanceof Request?input.method:"GET");path=typeof input==="string"?new URL(input).pathname:input instanceof URL?input.pathname:input instanceof Request?new URL(input.url).pathname:void 0}catch{}log("http_start",{request,method,path});try{const response=await fetchImpl.call(this,input,init);try{log("http_response",{request,method,path,status:response.status,durationMs:Math.max(0,performance.now()-startedAt)});if(log.enabled)responseDiagnostics.set(response,{log,detail:{request,method,path:path?.slice(0,8192)}})}catch{}return response}catch(error){log("http_error",{request,method,path,durationMs:Math.max(0,performance.now()-startedAt)},error);throw error}};wrappedFetches.set(wrapped,{original:fetchImpl,key});return wrapped}async function readDebugResponse(response,method){try{return await response[method]()}catch(error){const diagnostics=responseDiagnostics.get(response);diagnostics?.log("http_body_error",diagnostics.detail,error);throw error}}export{BACKGROUND_OPERATIONS,createAdapterDebugLog,createDebugFetch,debugLevel,metaFingerprints,readDebugResponse};
|
|
1
|
+
import{homedir}from"node:os";import{isAbsolute,join}from"node:path";var BUILD_HOME=".parle";function parleHome(env=process.env){const configured=env.PARLE_HOME;if(configured&&isAbsolute(configured))return configured;return join(env.HOME||env.USERPROFILE||homedir(),BUILD_HOME)}import{createHash,createHmac,randomBytes,randomUUID}from"node:crypto";import{closeSync as closeSync2,constants as constants2,fstatSync as fstatSync2,ftruncateSync,lstatSync as lstatSync2,openSync as openSync2,writeSync as writeSync2}from"node:fs";import{isAbsolute as isAbsolute2,join as join2,resolve}from"node:path";import{chmodSync,closeSync,constants,existsSync,fchmodSync,fsyncSync,fstatSync,lstatSync,linkSync,mkdirSync,openSync,readSync,renameSync,unlinkSync,writeSync}from"node:fs";var DEFAULT_DIRECTORY_MODE=448;var DEFAULT_MALFORMED_LOCK_STALE_MS=5*6e4;var NO_FOLLOW=typeof constants.O_NOFOLLOW==="number"?constants.O_NOFOLLOW:0;var SafeFileError=class extends Error{code;constructor(code,message,options){super(message,options);this.name="SafeFileError";this.code=code}};function ownerAndMode(stat,expectedMode,label,kind){if(kind==="file"){if(!stat.isFile())throw new SafeFileError("unsafe_type",`${label} must be a regular file.`)}else if(!stat.isDirectory()){throw new SafeFileError("unsafe_type",`${label} must be a real directory.`)}if(process.platform==="win32")return;if(stat.uid!==process.getuid?.())throw new SafeFileError("unsafe_owner",`${label} must be owned by the current user.`);if((stat.mode&511)!==expectedMode)throw new SafeFileError("unsafe_mode",`${label} must have mode ${expectedMode.toString(8)}.`)}function inspectRealDirectory(path,label,mode=DEFAULT_DIRECTORY_MODE){let stat;try{stat=lstatSync(path)}catch(error){throw new SafeFileError("directory_unavailable",`${label} cannot be inspected: ${path}.`,{cause:error})}if(stat.isSymbolicLink())throw new SafeFileError("symlink_refused",`${label} must not be a symbolic link: ${path}.`);ownerAndMode(stat,mode,label,"directory");return stat}function ensureOwnerOnlyDirectory(path,options={label:"Owner-only directory"}){const mode=options.mode??DEFAULT_DIRECTORY_MODE;if(!existsSync(path)){if(options.create===false)throw new SafeFileError("directory_missing",`${options.label} is missing: ${path}.`);try{mkdirSync(path,{recursive:true,mode})}catch(error){throw new SafeFileError("directory_create_failed",`${options.label} could not be created: ${path}.`,{cause:error})}}let stat;try{stat=lstatSync(path)}catch(error){throw new SafeFileError("directory_unavailable",`${options.label} cannot be inspected: ${path}.`,{cause:error})}if(stat.isSymbolicLink())throw new SafeFileError("symlink_refused",`${options.label} must not be a symbolic link: ${path}.`);if(!stat.isDirectory())throw new SafeFileError("unsafe_type",`${options.label} must be a real directory.`);if(process.platform!=="win32"&&stat.uid!==process.getuid?.())throw new SafeFileError("unsafe_owner",`${options.label} must be owned by the current user.`);if(options.repairMode&&process.platform!=="win32"&&(stat.mode&511)!==mode)chmodSync(path,mode);inspectRealDirectory(path,options.label,mode);return path}var DAY_MS=24*60*60*1e3;var ParleApiError=class extends Error{status;code;action;scope;retryAfterMs;retryable;details;requestId;constructor(message,options={}){super(message);this.name="ParleApiError";this.status=options.status;this.code=options.code;this.action=options.action;this.scope=options.scope;this.retryAfterMs=options.retryAfterMs;this.retryable=options.retryable??false;this.details=options.details;this.requestId=options.requestId}};var ADDRESS_HANDLE_MIN_LENGTH=2;var ADDRESS_HANDLE_MAX_LENGTH=24;var NEW_HANDLE_RULE=`${ADDRESS_HANDLE_MIN_LENGTH} to ${ADDRESS_HANDLE_MAX_LENGTH} lowercase letters, digits and single hyphens, with at least one letter, not a reserved word`;var LEVELS={debug:1,trace:2};var DEBUG_EVENTS=["client_start","http_start","http_response","http_error","http_body_error","delivery_start","delivery_stop","stream_connect","stream_open","stream_eof","stream_error","stream_retry","stream_close","room_error","wake_open","wake_hint","fetch_started","fetch_success","row_fetched","handling_complete","ack_started","ack_success","background_error","mcp_client","mcp_call_meta"];var TRACE_EVENTS=["hook_walk_step","hook_probe_error","hook_host_found","hook_host_missing","hook_bridges_none","hook_bridge_unresponsive"];var EVENTS=new Map([...DEBUG_EVENTS.map(event=>[event,"debug"]),...TRACE_EVENTS.map(event=>[event,"trace"])]);var METHODS=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"]);var REASONS=new Set(["stopped","revision_changed","interrupted","recover","drain","handler","ack","walk_end","self_parent","depth"]);var PROCESS_KINDS=new Set(["codex","codex_refused","shell","other","unknown"]);var TOOLS=new Set(["ps","lsof"]);var BACKGROUND_OPERATIONS=["key_rotation","address_reconnect","room_instructions_refresh","host_session_rebind","address_facts_refresh","room_drain","hook_socket_listen","address_rooms_read","features_read","missed_notices_read","room_set_refresh"];var OPERATIONS=new Set(BACKGROUND_OPERATIONS);var TRIGGERS=new Set(["startup","wake_open","wake_hint","test"]);var TRANSPORT_CODES=new Set(["UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_ABORTED","UND_ERR_DESTROYED","UND_ERR_CLOSED","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","ENOTFOUND","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","ECANCELED","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","CERT_HAS_EXPIRED","ERR_TLS_CERT_ALTNAME_INVALID","UNABLE_TO_GET_ISSUER_CERT_LOCALLY"]);var PROCESS_CODES=new Set(["EAGAIN","ENOMEM","EMFILE","ENFILE","EPERM","EACCES","ENOENT","EIO","ETIMEDOUT"]);var SIGNALS=new Set(["SIGTERM","SIGKILL","SIGINT","SIGHUP"]);var ERROR_NAMES=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","ParleApiError","TokenEndpointError"]);var ACTIONS=new Set(["retry","backoff","retry_with_backoff","reauthorize","fix_client","stop","rebootstrap"]);var SYSCALLS=new Set(["read","write","connect","getaddrinfo"]);var MAX_BYTES=1024*1024;var COMPONENTS=new Set(["client","delivery","account","desktop","approval","oauth","hook"]);var wrappedFetches=new WeakMap;var responseDiagnostics=new WeakMap;var MAX_SINKS=64;var sinks=new Map;var CLIENT_LABEL=/^[A-Za-z0-9 ._@/+:-]{1,64}$/;var META_KEY=/^[A-Za-z0-9_.:/-]{1,64}$/;var META_KEYS_MAX=24;function metaFingerprints(meta){if(!meta||typeof meta!=="object"||Array.isArray(meta))return void 0;const out={};const add=(key,value)=>{if(Object.keys(out).length>=META_KEYS_MAX||!META_KEY.test(key))return;const type=value===null?"null":Array.isArray(value)?"array":typeof value;let text;try{text=JSON.stringify(value)??String(value)}catch{text=type}out[key]=`${type}:${createHash("sha256").update("parle-debug-meta\0").update(text.slice(0,8192)).digest("hex").slice(0,16)}`};for(const key of Object.keys(meta)){const value=own(meta,key);if(value&&typeof value==="object"&&!Array.isArray(value)){for(const inner of Object.keys(value))add(`${key}.${inner}`,own(value,inner))}else add(key,value)}return out}var noop=()=>Object.assign(()=>{},{close:()=>{},nextRequest:()=>0,enabled:false});function own(value,key){if(!value||typeof value!=="object")return void 0;return Object.getOwnPropertyDescriptor(value,key)?.value}function nameOf(error){const name=own(error,"name");if(typeof name==="string"&&ERROR_NAMES.has(name))return name;if(error instanceof TypeError)return"TypeError";if(error instanceof RangeError)return"RangeError";if(error instanceof SyntaxError)return"SyntaxError";return"Error"}function debugLevel(env){if(env.PARLE_DEBUG==="1"||env.PARLE_DEBUG==="true")return"debug";if(env.PARLE_DEBUG==="trace")return"trace";return void 0}function debugScope(env,component){if(!COMPONENTS.has(component)||!debugLevel(env))return void 0;const home=parleHome(env);if(!isAbsolute2(home))return void 0;const normalized=resolve(home);return{home:normalized,key:JSON.stringify([component,normalized])}}function createAdapterDebugLog(env,now,component="delivery"){try{const scope=debugScope(env,component);if(!scope)return noop();let sink=sinks.get(scope.key);if(!sink){if(sinks.size>=MAX_SINKS)return noop();sink=createSink(scope.home,component);sinks.set(scope.key,sink)}const shared=sink,logger=shared.nextLogger();const level=LEVELS[debugLevel(env)??"debug"];let closed=false;const log=(event,detail,error)=>{const eventLevel=EVENTS.get(event);if(closed||!shared.enabled||!eventLevel||LEVELS[eventLevel]>level)return;try{shared.write(Date.prototype.toISOString.call(now()),logger,event,detail,error)}catch{closed=true}};return Object.defineProperty(Object.assign(log,{close:()=>{closed=true},nextRequest:()=>closed||!shared.enabled?0:shared.nextRequest()}),"enabled",{get:()=>!closed&&shared.enabled})}catch{return noop()}}function createSink(home,component){const root=home;const stem=`${component}-${process.pid}-${randomUUID()}`;const salt=randomBytes(32);const ref=value=>typeof value==="string"&&value.length>0?createHmac("sha256",salt).update(value.slice(0,8192)).digest("hex").slice(0,24):void 0;let slot=0,bytes=0,failed=false,loggerSequence=0,requestSequence=0;const identities=[];const errorFacts=error=>{const result={name:nameOf(error)};const code=own(error,"code");if(typeof code==="string"&&(TRANSPORT_CODES.has(code)||PROCESS_CODES.has(code)))result.code=code;else if(ref(code))result.codeRef=ref(code);if(Array.isArray(own(error,"output"))){const signal=own(error,"signal"),exitStatus=own(error,"status");if(typeof signal==="string"&&SIGNALS.has(signal))result.signal=signal;if(typeof exitStatus==="number"&&Number.isInteger(exitStatus)&&exitStatus>=0&&exitStatus<=255)result.exitStatus=exitStatus}const action=own(error,"action");if(typeof action==="string"&&ACTIONS.has(action))result.action=action;if(error instanceof ParleApiError){const status=own(error,"status"),retryAfterMs=own(error,"retryAfterMs"),retryable=own(error,"retryable");if(typeof status==="number"&&Number.isInteger(status)&&status>=100&&status<=599)result.status=status;if(typeof retryAfterMs==="number"&&Number.isInteger(retryAfterMs)&&retryAfterMs>=0&&retryAfterMs<=2**31-1)result.retryAfterMs=retryAfterMs;if(typeof retryable==="boolean")result.retryable=retryable}const message=own(error,"message");if(message==="terminated")result.reason="terminated";if(message==="Parle agent stream ended unexpectedly")result.reason="stream_eof";const seen=new Set([error]);let cause=own(error,"cause");const causes=[];for(let depth=0;cause&&typeof cause==="object"&&!seen.has(cause)&&depth<3;depth++){seen.add(cause);const facts={name:nameOf(cause)};const code2=own(cause,"code"),syscall=own(cause,"syscall");if(typeof code2==="string"&&TRANSPORT_CODES.has(code2))facts.code=code2;else if(ref(code2))facts.codeRef=ref(code2);if(typeof syscall==="string"&&SYSCALLS.has(syscall))facts.syscall=syscall;causes.push(facts);cause=own(cause,"cause")}if(causes.length)result.causes=causes;return result};const write=(at,logger,event,detail,error)=>{if(failed||!EVENTS.has(event))return;let fd;try{const safe={};for(const key of["attempt","durationMs","retryMs","request","status","seq","rowCount","processId","depth"]){const value=own(detail,key);if(typeof value!=="number"||!Number.isFinite(value)||value<0)continue;if(key==="status"&&(value!==0&&(!Number.isInteger(value)||value<100||value>599)))continue;if(!["durationMs","retryMs"].includes(key)&&!Number.isSafeInteger(value))continue;safe[key]=value}for(const[key,allowed]of[["trigger",TRIGGERS],["reason",REASONS],["method",METHODS],["kind",PROCESS_KINDS],["tool",TOOLS],["operation",OPERATIONS]]){const value=own(detail,key);if(typeof value==="string"&&allowed.has(value))safe[key]=value}for(const key of["clientName","clientVersion"]){const value=own(detail,key);if(typeof value==="string"&&CLIENT_LABEL.test(value))safe[key]=value}const meta=metaFingerprints(own(detail,"meta"));if(meta)safe.metaKeys=meta;for(const key of["roomId","eventId","path"]){const value=ref(own(detail,key));if(value)safe[key==="path"?"routeRef":key==="roomId"?"roomRef":"eventRef"]=value}const line=JSON.stringify({at,pid:process.pid,component,logger,event,...safe,...error?{error:errorFacts(error)}:{}})+"\n";const buffer=Buffer.from(line);if(buffer.length>MAX_BYTES)return;ensureOwnerOnlyDirectory(root,{label:"Parle state directory"});const directory=ensureOwnerOnlyDirectory(join2(root,"debug"),{label:"Parle debug directory"});const rotate=bytes+buffer.length>MAX_BYTES;if(rotate){slot=1-slot;bytes=0}const path=join2(directory,`${stem}-${slot}.jsonl`);fd=openSync2(path,constants2.O_WRONLY|(identities[slot]?0:constants2.O_CREAT|constants2.O_EXCL)|(constants2.O_NOFOLLOW||0),384);const stat=fstatSync2(fd),link=lstatSync2(path),identity=identities[slot];if(!stat.isFile()||stat.nlink!==1||link.isSymbolicLink()||stat.dev!==link.dev||stat.ino!==link.ino||identity&&(stat.dev!==identity.dev||stat.ino!==identity.ino)||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||(stat.mode&511)!==384))throw new Error("unsafe debug file");identities[slot]={dev:stat.dev,ino:stat.ino};if(rotate&&identity){ftruncateSync(fd,0)}let written=0;while(written<buffer.length){const count=writeSync2(fd,buffer,written,buffer.length-written,bytes+written);if(count<=0)throw new Error("debug write made no progress");written+=count}bytes+=buffer.length}catch{failed=true}finally{if(fd!==void 0){try{closeSync2(fd)}catch{failed=true}}}};return{write,nextLogger:()=>++loggerSequence,nextRequest:()=>++requestSequence,get enabled(){return!failed}}}function createDebugFetch(env,fetchImpl,now,component="client"){const existing=wrappedFetches.get(fetchImpl);let key;try{const scope=debugScope(env,component);if(!scope)return existing?.original||fetchImpl;key=scope.key}catch{return existing?.original||fetchImpl}if(existing?.key===key)return fetchImpl;if(existing)fetchImpl=existing.original;const log=createAdapterDebugLog(env,now,component);if(!log.enabled)return fetchImpl;log("client_start");if(!log.enabled)return fetchImpl;const wrapped=async function(input,init){if(!log.enabled)return fetchImpl.call(this,input,init);const request=log.nextRequest();const startedAt=performance.now();let method,path;try{method=init?.method||(input instanceof Request?input.method:"GET");path=typeof input==="string"?new URL(input).pathname:input instanceof URL?input.pathname:input instanceof Request?new URL(input.url).pathname:void 0}catch{}log("http_start",{request,method,path});try{const response=await fetchImpl.call(this,input,init);try{log("http_response",{request,method,path,status:response.status,durationMs:Math.max(0,performance.now()-startedAt)});if(log.enabled)responseDiagnostics.set(response,{log,detail:{request,method,path:path?.slice(0,8192)}})}catch{}return response}catch(error){log("http_error",{request,method,path,durationMs:Math.max(0,performance.now()-startedAt)},error);throw error}};wrappedFetches.set(wrapped,{original:fetchImpl,key});return wrapped}async function readDebugResponse(response,method){try{return await response[method]()}catch(error){const diagnostics=responseDiagnostics.get(response);diagnostics?.log("http_body_error",diagnostics.detail,error);throw error}}export{BACKGROUND_OPERATIONS,createAdapterDebugLog,createDebugFetch,debugLevel,metaFingerprints,readDebugResponse};
|