@cotal-ai/connector-claude-code 0.144.0 → 0.145.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/carried.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type ResumeTranscriptLocator } from "@cotal-ai/core";
1
+ import { type ResumeTranscriptLocator, type McpServerSpec } from "@cotal-ai/core";
2
2
  export declare const claudeResumeTranscript: ResumeTranscriptLocator;
3
3
  /**
4
4
  * Refuse a carried launch this host cannot run, before anything is written: a Claude that ignores
@@ -11,7 +11,7 @@ export declare function carriedForkRecord(home: string): string;
11
11
  * fresh home would otherwise prompt for, trusting the authorized launch directory. Neither file is
12
12
  * written through a symlink: the state takes the private open, and the transcript copy refuses a
13
13
  * name that already exists. */
14
- export declare function placeCarried(home: string, transcript: string, resume: string | undefined, cwd: string): Record<string, string>;
14
+ export declare function placeCarried(home: string, transcript: string, resume: string | undefined, cwd: string, server: McpServerSpec): Record<string, string>;
15
15
  /**
16
16
  * Write a carried seat's fork record once Claude has forked: the digest of the transcript its
17
17
  * `--resume` read, which the manager holds to the carried claim before it records the seat's
@@ -1 +1 @@
1
- {"version":3,"file":"carried.d.ts","sourceRoot":"","sources":["../src/carried.ts"],"names":[],"mappings":"AAUA,OAAO,EAAsB,KAAK,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AAiDlF,eAAO,MAAM,sBAAsB,EAAE,uBAqBpC,CAAC;AAUF;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAWzF;AAED,sGAAsG;AACtG,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED;;;gCAGgC;AAChC,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQ9H;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,EAAE,EAAE,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAY3F"}
1
+ {"version":3,"file":"carried.d.ts","sourceRoot":"","sources":["../src/carried.ts"],"names":[],"mappings":"AAUA,OAAO,EAAsB,KAAK,uBAAuB,EAAE,KAAK,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAiDtG,eAAO,MAAM,sBAAsB,EAAE,uBAqBpC,CAAC;AAUF;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAWzF;AAED,sGAAsG;AACtG,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED;;;gCAGgC;AAChC,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAWrJ;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,EAAE,EAAE,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAY3F"}
Binary file
Binary file
@@ -1 +1 @@
1
- {"version":3,"file":"extension.d.ts","sourceRoot":"","sources":["../src/extension.ts"],"names":[],"mappings":"AAEA,OAAO,EAAgD,KAAK,SAAS,EAAoC,MAAM,gBAAgB,CAAC;AAWhI;;;;;;;;;4FAS4F;AAC5F,eAAO,MAAM,oBAAoB,8/DA4EvB,CAAC;AAiDX;;;;;GAKG;AACH,eAAO,MAAM,eAAe,EAAE,SAiO7B,CAAC"}
1
+ {"version":3,"file":"extension.d.ts","sourceRoot":"","sources":["../src/extension.ts"],"names":[],"mappings":"AAEA,OAAO,EAAgD,KAAK,SAAS,EAAoC,MAAM,gBAAgB,CAAC;AAWhI;;;;;;;;;4FAS4F;AAC5F,eAAO,MAAM,oBAAoB,8/DA4EvB,CAAC;AAqDX;;;;;GAKG;AACH,eAAO,MAAM,eAAe,EAAE,SAqO7B,CAAC"}
package/dist/index.js CHANGED
@@ -66,10 +66,12 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
66
66
  missingProperty: ${missingProperty},
67
67
  depsCount: ${depsCount},
68
68
  deps: ${deps}}`};var def={keyword:"dependencies",type:"object",schemaType:"object",error:exports.error,code(cxt){const[propDeps,schDeps]=splitDependencies(cxt);validatePropertyDeps(cxt,propDeps);validateSchemaDeps(cxt,schDeps)}};function splitDependencies({schema}){const propertyDeps={};const schemaDeps={};for(const key in schema){if(key==="__proto__")continue;const deps=Array.isArray(schema[key])?propertyDeps:schemaDeps;deps[key]=schema[key]}return[propertyDeps,schemaDeps]}function validatePropertyDeps(cxt,propertyDeps=cxt.schema){const{gen,data,it}=cxt;if(Object.keys(propertyDeps).length===0)return;const missing=gen.let("missing");for(const prop in propertyDeps){const deps=propertyDeps[prop];if(deps.length===0)continue;const hasProperty=(0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties);cxt.setParams({property:prop,depsCount:deps.length,deps:deps.join(", ")});if(it.allErrors){gen.if(hasProperty,()=>{for(const depProp of deps){(0,code_1.checkReportMissingProp)(cxt,depProp)}})}else{gen.if((0,codegen_1._)`${hasProperty} && (${(0,code_1.checkMissingProp)(cxt,deps,missing)})`);(0,code_1.reportMissingProp)(cxt,missing);gen.else()}}}exports.validatePropertyDeps=validatePropertyDeps;function validateSchemaDeps(cxt,schemaDeps=cxt.schema){const{gen,data,keyword,it}=cxt;const valid=gen.name("valid");for(const prop in schemaDeps){if((0,util_1.alwaysValidSchema)(it,schemaDeps[prop]))continue;gen.if((0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties),()=>{const schCxt=cxt.subschema({keyword,schemaProp:prop},valid);cxt.mergeValidEvaluated(schCxt,valid)},()=>gen.var(valid,true));cxt.ok(valid)}}exports.validateSchemaDeps=validateSchemaDeps;exports.default=def}});var require_propertyNames=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var error51={message:"property name must be valid",params:({params})=>(0,codegen_1._)`{propertyName: ${params.propertyName}}`};var def={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:error51,code(cxt){const{gen,schema,data,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema))return;const valid=gen.name("valid");gen.forIn("key",data,key=>{cxt.setParams({propertyName:key});cxt.subschema({keyword:"propertyNames",data:key,dataTypes:["string"],propertyName:key,compositeRule:true},valid);gen.if((0,codegen_1.not)(valid),()=>{cxt.error(true);if(!it.allErrors)gen.break()})});cxt.ok(valid)}};exports.default=def}});var require_additionalProperties=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var code_1=require_code2();var codegen_1=require_codegen();var names_1=require_names();var util_1=require_util();var error51={message:"must NOT have additional properties",params:({params})=>(0,codegen_1._)`{additionalProperty: ${params.additionalProperty}}`};var def={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:true,trackErrors:true,error:error51,code(cxt){const{gen,schema,parentSchema,data,errsCount,it}=cxt;if(!errsCount)throw new Error("ajv implementation error");const{allErrors,opts}=it;it.props=true;if(opts.removeAdditional!=="all"&&(0,util_1.alwaysValidSchema)(it,schema))return;const props=(0,code_1.allSchemaProperties)(parentSchema.properties);const patProps=(0,code_1.allSchemaProperties)(parentSchema.patternProperties);checkAdditionalProperties();cxt.ok((0,codegen_1._)`${errsCount} === ${names_1.default.errors}`);function checkAdditionalProperties(){gen.forIn("key",data,key=>{if(!props.length&&!patProps.length)additionalPropertyCode(key);else gen.if(isAdditional(key),()=>additionalPropertyCode(key))})}function isAdditional(key){let definedProp;if(props.length>8){const propsSchema=(0,util_1.schemaRefOrVal)(it,parentSchema.properties,"properties");definedProp=(0,code_1.isOwnProperty)(gen,propsSchema,key)}else if(props.length){definedProp=(0,codegen_1.or)(...props.map(p=>(0,codegen_1._)`${key} === ${p}`))}else{definedProp=codegen_1.nil}if(patProps.length){definedProp=(0,codegen_1.or)(definedProp,...patProps.map(p=>(0,codegen_1._)`${(0,code_1.usePattern)(cxt,p)}.test(${key})`))}return(0,codegen_1.not)(definedProp)}function deleteAdditional(key){gen.code((0,codegen_1._)`delete ${data}[${key}]`)}function additionalPropertyCode(key){if(opts.removeAdditional==="all"||opts.removeAdditional&&schema===false){deleteAdditional(key);return}if(schema===false){cxt.setParams({additionalProperty:key});cxt.error();if(!allErrors)gen.break();return}if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it,schema)){const valid=gen.name("valid");if(opts.removeAdditional==="failing"){applyAdditionalSchema(key,valid,false);gen.if((0,codegen_1.not)(valid),()=>{cxt.reset();deleteAdditional(key)})}else{applyAdditionalSchema(key,valid);if(!allErrors)gen.if((0,codegen_1.not)(valid),()=>gen.break())}}}function applyAdditionalSchema(key,valid,errors){const subschema={keyword:"additionalProperties",dataProp:key,dataPropType:util_1.Type.Str};if(errors===false){Object.assign(subschema,{compositeRule:true,createErrors:false,allErrors:false})}cxt.subschema(subschema,valid)}}};exports.default=def}});var require_properties=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var validate_1=require_validate();var code_1=require_code2();var util_1=require_util();var additionalProperties_1=require_additionalProperties();var def={keyword:"properties",type:"object",schemaType:"object",code(cxt){const{gen,schema,parentSchema,data,it}=cxt;if(it.opts.removeAdditional==="all"&&parentSchema.additionalProperties===void 0){additionalProperties_1.default.code(new validate_1.KeywordCxt(it,additionalProperties_1.default,"additionalProperties"))}const allProps=(0,code_1.allSchemaProperties)(schema);for(const prop of allProps){it.definedProperties.add(prop)}if(it.opts.unevaluated&&allProps.length&&it.props!==true){it.props=util_1.mergeEvaluated.props(gen,(0,util_1.toHash)(allProps),it.props)}const properties=allProps.filter(p=>!(0,util_1.alwaysValidSchema)(it,schema[p]));if(properties.length===0)return;const valid=gen.name("valid");for(const prop of properties){if(hasDefault(prop)){applyPropertySchema(prop)}else{gen.if((0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties));applyPropertySchema(prop);if(!it.allErrors)gen.else().var(valid,true);gen.endIf()}cxt.it.definedProperties.add(prop);cxt.ok(valid)}function hasDefault(prop){return it.opts.useDefaults&&!it.compositeRule&&schema[prop].default!==void 0}function applyPropertySchema(prop){cxt.subschema({keyword:"properties",schemaProp:prop,dataProp:prop},valid)}}};exports.default=def}});var require_patternProperties=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var code_1=require_code2();var codegen_1=require_codegen();var util_1=require_util();var util_2=require_util();var def={keyword:"patternProperties",type:"object",schemaType:"object",code(cxt){const{gen,schema,data,parentSchema,it}=cxt;const{opts}=it;const patterns=(0,code_1.allSchemaProperties)(schema);const alwaysValidPatterns=patterns.filter(p=>(0,util_1.alwaysValidSchema)(it,schema[p]));if(patterns.length===0||alwaysValidPatterns.length===patterns.length&&(!it.opts.unevaluated||it.props===true)){return}const checkProperties=opts.strictSchema&&!opts.allowMatchingProperties&&parentSchema.properties;const valid=gen.name("valid");if(it.props!==true&&!(it.props instanceof codegen_1.Name)){it.props=(0,util_2.evaluatedPropsToName)(gen,it.props)}const{props}=it;validatePatternProperties();function validatePatternProperties(){for(const pat of patterns){if(checkProperties)checkMatchingProperties(pat);if(it.allErrors){validateProperties(pat)}else{gen.var(valid,true);validateProperties(pat);gen.if(valid)}}}function checkMatchingProperties(pat){for(const prop in checkProperties){if(new RegExp(pat).test(prop)){(0,util_1.checkStrictMode)(it,`property ${prop} matches pattern ${pat} (use allowMatchingProperties)`)}}}function validateProperties(pat){gen.forIn("key",data,key=>{gen.if((0,codegen_1._)`${(0,code_1.usePattern)(cxt,pat)}.test(${key})`,()=>{const alwaysValid=alwaysValidPatterns.includes(pat);if(!alwaysValid){cxt.subschema({keyword:"patternProperties",schemaProp:pat,dataProp:key,dataPropType:util_2.Type.Str},valid)}if(it.opts.unevaluated&&props!==true){gen.assign((0,codegen_1._)`${props}[${key}]`,true)}else if(!alwaysValid&&!it.allErrors){gen.if((0,codegen_1.not)(valid),()=>gen.break())}})})}}};exports.default=def}});var require_not=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var util_1=require_util();var def={keyword:"not",schemaType:["object","boolean"],trackErrors:true,code(cxt){const{gen,schema,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema)){cxt.fail();return}const valid=gen.name("valid");cxt.subschema({keyword:"not",compositeRule:true,createErrors:false,allErrors:false},valid);cxt.failResult(valid,()=>cxt.reset(),()=>cxt.error())},error:{message:"must NOT be valid"}};exports.default=def}});var require_anyOf=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var code_1=require_code2();var def={keyword:"anyOf",schemaType:"array",trackErrors:true,code:code_1.validateUnion,error:{message:"must match a schema in anyOf"}};exports.default=def}});var require_oneOf=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var error51={message:"must match exactly one schema in oneOf",params:({params})=>(0,codegen_1._)`{passingSchemas: ${params.passing}}`};var def={keyword:"oneOf",schemaType:"array",trackErrors:true,error:error51,code(cxt){const{gen,schema,parentSchema,it}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");if(it.opts.discriminator&&parentSchema.discriminator)return;const schArr=schema;const valid=gen.let("valid",false);const passing=gen.let("passing",null);const schValid=gen.name("_valid");cxt.setParams({passing});gen.block(validateOneOf);cxt.result(valid,()=>cxt.reset(),()=>cxt.error(true));function validateOneOf(){schArr.forEach((sch,i)=>{let schCxt;if((0,util_1.alwaysValidSchema)(it,sch)){gen.var(schValid,true)}else{schCxt=cxt.subschema({keyword:"oneOf",schemaProp:i,compositeRule:true},schValid)}if(i>0){gen.if((0,codegen_1._)`${schValid} && ${valid}`).assign(valid,false).assign(passing,(0,codegen_1._)`[${passing}, ${i}]`).else()}gen.if(schValid,()=>{gen.assign(valid,true);gen.assign(passing,i);if(schCxt)cxt.mergeEvaluated(schCxt,codegen_1.Name)})})}}};exports.default=def}});var require_allOf=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var util_1=require_util();var def={keyword:"allOf",schemaType:"array",code(cxt){const{gen,schema,it}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");const valid=gen.name("valid");schema.forEach((sch,i)=>{if((0,util_1.alwaysValidSchema)(it,sch))return;const schCxt=cxt.subschema({keyword:"allOf",schemaProp:i},valid);cxt.ok(valid);cxt.mergeEvaluated(schCxt)})}};exports.default=def}});var require_if=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var error51={message:({params})=>(0,codegen_1.str)`must match "${params.ifClause}" schema`,params:({params})=>(0,codegen_1._)`{failingKeyword: ${params.ifClause}}`};var def={keyword:"if",schemaType:["object","boolean"],trackErrors:true,error:error51,code(cxt){const{gen,parentSchema,it}=cxt;if(parentSchema.then===void 0&&parentSchema.else===void 0){(0,util_1.checkStrictMode)(it,'"if" without "then" and "else" is ignored')}const hasThen=hasSchema(it,"then");const hasElse=hasSchema(it,"else");if(!hasThen&&!hasElse)return;const valid=gen.let("valid",true);const schValid=gen.name("_valid");validateIf();cxt.reset();if(hasThen&&hasElse){const ifClause=gen.let("ifClause");cxt.setParams({ifClause});gen.if(schValid,validateClause("then",ifClause),validateClause("else",ifClause))}else if(hasThen){gen.if(schValid,validateClause("then"))}else{gen.if((0,codegen_1.not)(schValid),validateClause("else"))}cxt.pass(valid,()=>cxt.error(true));function validateIf(){const schCxt=cxt.subschema({keyword:"if",compositeRule:true,createErrors:false,allErrors:false},schValid);cxt.mergeEvaluated(schCxt)}function validateClause(keyword,ifClause){return()=>{const schCxt=cxt.subschema({keyword},schValid);gen.assign(valid,schValid);cxt.mergeValidEvaluated(schCxt,valid);if(ifClause)gen.assign(ifClause,(0,codegen_1._)`${keyword}`);else cxt.setParams({ifClause:keyword})}}}};function hasSchema(it,keyword){const schema=it.schema[keyword];return schema!==void 0&&!(0,util_1.alwaysValidSchema)(it,schema)}exports.default=def}});var require_thenElse=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var util_1=require_util();var def={keyword:["then","else"],schemaType:["object","boolean"],code({keyword,parentSchema,it}){if(parentSchema.if===void 0)(0,util_1.checkStrictMode)(it,`"${keyword}" without "if" is ignored`)}};exports.default=def}});var require_applicator=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var additionalItems_1=require_additionalItems();var prefixItems_1=require_prefixItems();var items_1=require_items();var items2020_1=require_items2020();var contains_1=require_contains();var dependencies_1=require_dependencies();var propertyNames_1=require_propertyNames();var additionalProperties_1=require_additionalProperties();var properties_1=require_properties();var patternProperties_1=require_patternProperties();var not_1=require_not();var anyOf_1=require_anyOf();var oneOf_1=require_oneOf();var allOf_1=require_allOf();var if_1=require_if();var thenElse_1=require_thenElse();function getApplicator(draft2020=false){const applicator=[not_1.default,anyOf_1.default,oneOf_1.default,allOf_1.default,if_1.default,thenElse_1.default,propertyNames_1.default,additionalProperties_1.default,dependencies_1.default,properties_1.default,patternProperties_1.default];if(draft2020)applicator.push(prefixItems_1.default,items2020_1.default);else applicator.push(additionalItems_1.default,items_1.default);applicator.push(contains_1.default);return applicator}exports.default=getApplicator}});var require_format=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/format.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var error51={message:({schemaCode})=>(0,codegen_1.str)`must match format "${schemaCode}"`,params:({schemaCode})=>(0,codegen_1._)`{format: ${schemaCode}}`};var def={keyword:"format",type:["number","string"],schemaType:"string",$data:true,error:error51,code(cxt,ruleType){const{gen,data,$data,schema,schemaCode,it}=cxt;const{opts,errSchemaPath,schemaEnv,self}=it;if(!opts.validateFormats)return;if($data)validate$DataFormat();else validateFormat();function validate$DataFormat(){const fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats});const fDef=gen.const("fDef",(0,codegen_1._)`${fmts}[${schemaCode}]`);const fType=gen.let("fType");const format=gen.let("format");gen.if((0,codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`,()=>gen.assign(fType,(0,codegen_1._)`${fDef}.type || "string"`).assign(format,(0,codegen_1._)`${fDef}.validate`),()=>gen.assign(fType,(0,codegen_1._)`"string"`).assign(format,fDef));cxt.fail$data((0,codegen_1.or)(unknownFmt(),invalidFmt()));function unknownFmt(){if(opts.strictSchema===false)return codegen_1.nil;return(0,codegen_1._)`${schemaCode} && !${format}`}function invalidFmt(){const callFormat=schemaEnv.$async?(0,codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`:(0,codegen_1._)`${format}(${data})`;const validData=(0,codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;return(0,codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`}}function validateFormat(){const formatDef=self.formats[schema];if(!formatDef){unknownFormat();return}if(formatDef===true)return;const[fmtType,format,fmtRef]=getFormat(formatDef);if(fmtType===ruleType)cxt.pass(validCondition());function unknownFormat(){if(opts.strictSchema===false){self.logger.warn(unknownMsg());return}throw new Error(unknownMsg());function unknownMsg(){return`unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`}}function getFormat(fmtDef){const code=fmtDef instanceof RegExp?(0,codegen_1.regexpCode)(fmtDef):opts.code.formats?(0,codegen_1._)`${opts.code.formats}${(0,codegen_1.getProperty)(schema)}`:void 0;const fmt=gen.scopeValue("formats",{key:schema,ref:fmtDef,code});if(typeof fmtDef=="object"&&!(fmtDef instanceof RegExp)){return[fmtDef.type||"string",fmtDef.validate,(0,codegen_1._)`${fmt}.validate`]}return["string",fmtDef,fmt]}function validCondition(){if(typeof formatDef=="object"&&!(formatDef instanceof RegExp)&&formatDef.async){if(!schemaEnv.$async)throw new Error("async format in sync schema");return(0,codegen_1._)`await ${fmtRef}(${data})`}return typeof format=="function"?(0,codegen_1._)`${fmtRef}(${data})`:(0,codegen_1._)`${fmtRef}.test(${data})`}}}};exports.default=def}});var require_format2=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var format_1=require_format();var format=[format_1.default];exports.default=format}});var require_metadata=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/metadata.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.contentVocabulary=exports.metadataVocabulary=void 0;exports.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];exports.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]}});var require_draft7=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/draft7.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var core_1=require_core2();var validation_1=require_validation();var applicator_1=require_applicator();var format_1=require_format2();var metadata_1=require_metadata();var draft7Vocabularies=[core_1.default,validation_1.default,(0,applicator_1.default)(),format_1.default,metadata_1.metadataVocabulary,metadata_1.contentVocabulary];exports.default=draft7Vocabularies}});var require_types=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DiscrError=void 0;var DiscrError;(function(DiscrError2){DiscrError2["Tag"]="tag";DiscrError2["Mapping"]="mapping"})(DiscrError||(exports.DiscrError=DiscrError={}))}});var require_discriminator=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var types_1=require_types();var compile_1=require_compile();var ref_error_1=require_ref_error();var util_1=require_util();var error51={message:({params:{discrError,tagName}})=>discrError===types_1.DiscrError.Tag?`tag "${tagName}" must be string`:`value of tag "${tagName}" must be in oneOf`,params:({params:{discrError,tag,tagName}})=>(0,codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`};var def={keyword:"discriminator",type:"object",schemaType:"object",error:error51,code(cxt){const{gen,data,schema,parentSchema,it}=cxt;const{oneOf}=parentSchema;if(!it.opts.discriminator){throw new Error("discriminator: requires discriminator option")}const tagName=schema.propertyName;if(typeof tagName!="string")throw new Error("discriminator: requires propertyName");if(schema.mapping)throw new Error("discriminator: mapping is not supported");if(!oneOf)throw new Error("discriminator: requires oneOf keyword");const valid=gen.let("valid",false);const tag=gen.const("tag",(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(tagName)}`);gen.if((0,codegen_1._)`typeof ${tag} == "string"`,()=>validateMapping(),()=>cxt.error(false,{discrError:types_1.DiscrError.Tag,tag,tagName}));cxt.ok(valid);function validateMapping(){const mapping=getMapping();gen.if(false);for(const tagValue in mapping){gen.elseIf((0,codegen_1._)`${tag} === ${tagValue}`);gen.assign(valid,applyTagSchema(mapping[tagValue]))}gen.else();cxt.error(false,{discrError:types_1.DiscrError.Mapping,tag,tagName});gen.endIf()}function applyTagSchema(schemaProp){const _valid=gen.name("valid");const schCxt=cxt.subschema({keyword:"oneOf",schemaProp},_valid);cxt.mergeEvaluated(schCxt,codegen_1.Name);return _valid}function getMapping(){var _a3;const oneOfMapping={};const topRequired=hasRequired(parentSchema);let tagRequired=true;for(let i=0;i<oneOf.length;i++){let sch=oneOf[i];if((sch===null||sch===void 0?void 0:sch.$ref)&&!(0,util_1.schemaHasRulesButRef)(sch,it.self.RULES)){const ref=sch.$ref;sch=compile_1.resolveRef.call(it.self,it.schemaEnv.root,it.baseId,ref);if(sch instanceof compile_1.SchemaEnv)sch=sch.schema;if(sch===void 0)throw new ref_error_1.default(it.opts.uriResolver,it.baseId,ref)}const propSch=(_a3=sch===null||sch===void 0?void 0:sch.properties)===null||_a3===void 0?void 0:_a3[tagName];if(typeof propSch!="object"){throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`)}tagRequired=tagRequired&&(topRequired||hasRequired(sch));addMappings(propSch,i)}if(!tagRequired)throw new Error(`discriminator: "${tagName}" must be required`);return oneOfMapping;function hasRequired({required:required2}){return Array.isArray(required2)&&required2.includes(tagName)}function addMappings(sch,i){if(sch.const){addMapping(sch.const,i)}else if(sch.enum){for(const tagValue of sch.enum){addMapping(tagValue,i)}}else{throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`)}}function addMapping(tagValue,i){if(typeof tagValue!="string"||tagValue in oneOfMapping){throw new Error(`discriminator: "${tagName}" values must be unique strings`)}oneOfMapping[tagValue]=i}}}};exports.default=def}});var require_json_schema_draft_07=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports,module){module.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:true,readOnly:{type:"boolean",default:false},examples:{type:"array",items:true},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:true},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:true,enum:{type:"array",items:true,minItems:1,uniqueItems:true},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:true}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:true}}});var require_ajv=__commonJS({"../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/ajv.js"(exports,module){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv=void 0;var core_1=require_core();var draft7_1=require_draft7();var discriminator_1=require_discriminator();var draft7MetaSchema=require_json_schema_draft_07();var META_SUPPORT_DATA=["/properties"];var META_SCHEMA_ID="http://json-schema.org/draft-07/schema";var Ajv=class extends core_1.default{_addVocabularies(){super._addVocabularies();draft7_1.default.forEach(v=>this.addVocabulary(v));if(this.opts.discriminator)this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();if(!this.opts.meta)return;const metaSchema=this.opts.$data?this.$dataMetaSchema(draft7MetaSchema,META_SUPPORT_DATA):draft7MetaSchema;this.addMetaSchema(metaSchema,META_SCHEMA_ID,false);this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0)}};exports.Ajv=Ajv;module.exports=exports=Ajv;module.exports.Ajv=Ajv;Object.defineProperty(exports,"__esModule",{value:true});exports.default=Ajv;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:true,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:true,get:function(){return codegen_1._}});Object.defineProperty(exports,"str",{enumerable:true,get:function(){return codegen_1.str}});Object.defineProperty(exports,"stringify",{enumerable:true,get:function(){return codegen_1.stringify}});Object.defineProperty(exports,"nil",{enumerable:true,get:function(){return codegen_1.nil}});Object.defineProperty(exports,"Name",{enumerable:true,get:function(){return codegen_1.Name}});Object.defineProperty(exports,"CodeGen",{enumerable:true,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports,"ValidationError",{enumerable:true,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports,"MissingRefError",{enumerable:true,get:function(){return ref_error_1.default}})}});var require_formats=__commonJS({"../../node_modules/.pnpm/ajv-formats@3.0.1/node_modules/ajv-formats/dist/formats.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.formatNames=exports.fastFormats=exports.fullFormats=void 0;function fmtDef(validate,compare){return{validate,compare}}exports.fullFormats={date:fmtDef(date5,compareDate),time:fmtDef(getTime(true),compareTime),"date-time":fmtDef(getDateTime(true),compareDateTime),"iso-time":fmtDef(getTime(),compareIsoTime),"iso-date-time":fmtDef(getDateTime(),compareIsoDateTime),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte,int32:{type:"number",validate:validateInt32},int64:{type:"number",validate:validateInt64},float:{type:"number",validate:validateNumber},double:{type:"number",validate:validateNumber},password:true,binary:true};exports.fastFormats={...exports.fullFormats,date:fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,compareDate),time:fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareTime),"date-time":fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareDateTime),"iso-time":fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoTime),"iso-date-time":fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoDateTime),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};exports.formatNames=Object.keys(exports.fullFormats);function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}var DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;var DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31];function date5(str2){const matches=DATE.exec(str2);if(!matches)return false;const year=+matches[1];const month=+matches[2];const day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month===2&&isLeapYear(year)?29:DAYS[month])}function compareDate(d1,d2){if(!(d1&&d2))return void 0;if(d1>d2)return 1;if(d1<d2)return-1;return 0}var TIME=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function getTime(strictTimeZone){return function time3(str2){const matches=TIME.exec(str2);if(!matches)return false;const hr=+matches[1];const min=+matches[2];const sec=+matches[3];const tz=matches[4];const tzSign=matches[5]==="-"?-1:1;const tzH=+(matches[6]||0);const tzM=+(matches[7]||0);if(tzH>23||tzM>59||strictTimeZone&&!tz)return false;if(hr<=23&&min<=59&&sec<60)return true;const utcMin=min-tzM*tzSign;const utcHr=hr-tzH*tzSign-(utcMin<0?1:0);return(utcHr===23||utcHr===-1)&&(utcMin===59||utcMin===-1)&&sec<61}}function compareTime(s1,s2){if(!(s1&&s2))return void 0;const t1=new Date("2020-01-01T"+s1).valueOf();const t2=new Date("2020-01-01T"+s2).valueOf();if(!(t1&&t2))return void 0;return t1-t2}function compareIsoTime(t1,t2){if(!(t1&&t2))return void 0;const a1=TIME.exec(t1);const a2=TIME.exec(t2);if(!(a1&&a2))return void 0;t1=a1[1]+a1[2]+a1[3];t2=a2[1]+a2[2]+a2[3];if(t1>t2)return 1;if(t1<t2)return-1;return 0}var DATE_TIME_SEPARATOR=/t|\s/i;function getDateTime(strictTimeZone){const time3=getTime(strictTimeZone);return function date_time(str2){const dateTime=str2.split(DATE_TIME_SEPARATOR);return dateTime.length===2&&date5(dateTime[0])&&time3(dateTime[1])}}function compareDateTime(dt1,dt2){if(!(dt1&&dt2))return void 0;const d1=new Date(dt1).valueOf();const d2=new Date(dt2).valueOf();if(!(d1&&d2))return void 0;return d1-d2}function compareIsoDateTime(dt1,dt2){if(!(dt1&&dt2))return void 0;const[d1,t1]=dt1.split(DATE_TIME_SEPARATOR);const[d2,t2]=dt2.split(DATE_TIME_SEPARATOR);const res=compareDate(d1,d2);if(res===void 0)return void 0;return res||compareTime(t1,t2)}var NOT_URI_FRAGMENT=/\/|:/;var URI=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function uri(str2){return NOT_URI_FRAGMENT.test(str2)&&URI.test(str2)}var BYTE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function byte(str2){BYTE.lastIndex=0;return BYTE.test(str2)}var MIN_INT32=-(2**31);var MAX_INT32=2**31-1;function validateInt32(value){return Number.isInteger(value)&&value<=MAX_INT32&&value>=MIN_INT32}function validateInt64(value){return Number.isInteger(value)}function validateNumber(){return true}var Z_ANCHOR=/[^\\]\\Z/;function regex(str2){if(Z_ANCHOR.test(str2))return false;try{new RegExp(str2);return true}catch(e){return false}}}});var require_limit=__commonJS({"../../node_modules/.pnpm/ajv-formats@3.0.1/node_modules/ajv-formats/dist/limit.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.formatLimitDefinition=void 0;var ajv_1=require_ajv();var codegen_1=require_codegen();var ops=codegen_1.operators;var KWDs={formatMaximum:{okStr:"<=",ok:ops.LTE,fail:ops.GT},formatMinimum:{okStr:">=",ok:ops.GTE,fail:ops.LT},formatExclusiveMaximum:{okStr:"<",ok:ops.LT,fail:ops.GTE},formatExclusiveMinimum:{okStr:">",ok:ops.GT,fail:ops.LTE}};var error51={message:({keyword,schemaCode})=>(0,codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`,params:({keyword,schemaCode})=>(0,codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`};exports.formatLimitDefinition={keyword:Object.keys(KWDs),type:"string",schemaType:"string",$data:true,error:error51,code(cxt){const{gen,data,schemaCode,keyword,it}=cxt;const{opts,self}=it;if(!opts.validateFormats)return;const fCxt=new ajv_1.KeywordCxt(it,self.RULES.all.format.definition,"format");if(fCxt.$data)validate$DataFormat();else validateFormat();function validate$DataFormat(){const fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats});const fmt=gen.const("fmt",(0,codegen_1._)`${fmts}[${fCxt.schemaCode}]`);cxt.fail$data((0,codegen_1.or)((0,codegen_1._)`typeof ${fmt} != "object"`,(0,codegen_1._)`${fmt} instanceof RegExp`,(0,codegen_1._)`typeof ${fmt}.compare != "function"`,compareCode(fmt)))}function validateFormat(){const format=fCxt.schema;const fmtDef=self.formats[format];if(!fmtDef||fmtDef===true)return;if(typeof fmtDef!="object"||fmtDef instanceof RegExp||typeof fmtDef.compare!="function"){throw new Error(`"${keyword}": format "${format}" does not define "compare" function`)}const fmt=gen.scopeValue("formats",{key:format,ref:fmtDef,code:opts.code.formats?(0,codegen_1._)`${opts.code.formats}${(0,codegen_1.getProperty)(format)}`:void 0});cxt.fail$data(compareCode(fmt))}function compareCode(fmt){return(0,codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`}},dependencies:["format"]};var formatLimitPlugin=ajv=>{ajv.addKeyword(exports.formatLimitDefinition);return ajv};exports.default=formatLimitPlugin}});var require_dist=__commonJS({"../../node_modules/.pnpm/ajv-formats@3.0.1/node_modules/ajv-formats/dist/index.js"(exports,module){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var formats_1=require_formats();var limit_1=require_limit();var codegen_1=require_codegen();var fullName=new codegen_1.Name("fullFormats");var fastName=new codegen_1.Name("fastFormats");var formatsPlugin=(ajv,opts={keywords:true})=>{if(Array.isArray(opts)){addFormats(ajv,opts,formats_1.fullFormats,fullName);return ajv}const[formats,exportName]=opts.mode==="fast"?[formats_1.fastFormats,fastName]:[formats_1.fullFormats,fullName];const list=opts.formats||formats_1.formatNames;addFormats(ajv,list,formats,exportName);if(opts.keywords)(0,limit_1.default)(ajv);return ajv};formatsPlugin.get=(name,mode="full")=>{const formats=mode==="fast"?formats_1.fastFormats:formats_1.fullFormats;const f=formats[name];if(!f)throw new Error(`Unknown format "${name}"`);return f};function addFormats(ajv,list,fs,exportName){var _a3;var _b;(_a3=(_b=ajv.opts.code).formats)!==null&&_a3!==void 0?_a3:_b.formats=(0,codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;for(const f of list)ajv.addFormat(f,fs[f])}module.exports=exports=formatsPlugin;Object.defineProperty(exports,"__esModule",{value:true});exports.default=formatsPlugin}});import{spawn,spawnSync as spawnSync2}from"node:child_process";import{createHash as createHash2,randomUUID}from"node:crypto";import{cpSync,existsSync as existsSync3,mkdirSync,readdirSync,readFileSync as readFileSync3,renameSync as renameSync2,rmSync,statSync as statSync2,writeFileSync as writeFileSync2}from"node:fs";import{homedir as homedir3}from"node:os";import{dirname as dirname2,join as join4,relative}from"node:path";import{fileURLToPath}from"node:url";import{acquireLock,globalConfigPath,mcpServerProblem as mcpServerProblem2,registry as registry3,writePrivateRecord}from"@cotal-ai/core";import{DEFAULT_SERVER,DEV_OWNER,LAUNCH_MATERIAL_ENV as LAUNCH_MATERIAL_ENV2,brokerUrlHasUserinfo,discardLaunchMaterial,assertLifecycleToken,assertValidChannel,assertValidKind,channelInAllow,credsClaims,eventChannel,idFromCreds,isConcreteChannel,loadAgentFile,parseJoinLink,resolveReadAcl}from"@cotal-ai/core";import{LAUNCH_MATERIAL_ENV,readLaunchMaterial}from"@cotal-ai/core/launch-material";import{normalizeMentions,RUN_LAUNCH_DEADLINE_MS,subjectMatches,isConcreteChannel as isConcreteChannel2,isChannelFamily,assertValidChannel as assertValidChannel2,channelInAllow as channelInAllow2,eventChannelPrincipal,resolvePeer as resolvePeerInRoster,peerLabel as peerLabel2,CotalEndpoint,acquireLocalConsumer,BASELINE_LIFECYCLE_ENDPOINT as BASELINE_LIFECYCLE_ENDPOINT2,BIND_SPLIT_REISSUES,assertLifecycleToken as assertLifecycleToken2,EpEnvelopeError as EpEnvelopeError2,isPublishPermissionDenied,unansweredRequest,EP_UNANSWERED,controlReplyFrom,controlReplyFromThrown,runAgentBearer,partsToText,assertValidRole,turnNoticeFilter,renderOnceTask}from"@cotal-ai/core";import{LINE_BREAK,peerLabel}from"@cotal-ai/core/peer-label";import{BASELINE_LIFECYCLE_ENDPOINT,EpEnvelopeError,dialerFor,goalFollowRefusal,invokeCommand,isPermissionDenied,issuedUserCaller,managerCallerBinding,registryListingCaller,replyRefusedBeforeEffect,resolveService,standaloneConnectOpts}from"@cotal-ai/core";var LEGACY_RAIL_RECHECK_MS=60*6e4;var MAX_INBOX=200;var MAX_IN_FLIGHT=MAX_INBOX*2;import{tmpdir}from"node:os";import{join}from"node:path";import{createHash,randomBytes}from"node:crypto";var SUN_PATH_MAX_BYTES=process.platform==="darwin"?104:108;function controlEndpoint(space,name,token=randomBytes(32).toString("base64url")){const id=createHash("sha256").update(`${space}\0${name}\0${process.pid}\0${token}`).digest("base64url").slice(0,32);const path=process.platform==="win32"?`\\\\.\\pipe\\cotal-${id}`:join(tmpdir(),`cotal-${id}.sock`);const bytes=Buffer.byteLength(path);if(process.platform!=="win32"&&bytes>SUN_PATH_MAX_BYTES){const tail=`/cotal-${id}.sock`.length;throw new Error(`control socket path is ${bytes} bytes, over the ${SUN_PATH_MAX_BYTES}-byte sun_path limit on ${process.platform}, so it cannot be bound and the kernel would report only EINVAL: ${path}. The socket name is a fixed ${tail} bytes, so the temp root must be at most ${SUN_PATH_MAX_BYTES-tail} bytes \u2014 TMPDIR is ${Buffer.byteLength(tmpdir())} bytes (${tmpdir()}). Point TMPDIR at a shorter directory.`)}return{path,token}}import{eventChannel as eventChannel2,LAUNCH_MATERIAL_ENV as LAUNCH_MATERIAL_ENV3,parsePrincipalKey,principalKey,writeLaunchMaterial}from"@cotal-ai/core";import{dirname}from"node:path";import{EVENT_CHANNEL_PREFIX,eventChannel as eventChannel3,eventChannelPrincipal as eventChannelPrincipal2,isEventChannel}from"@cotal-ai/core";var OS_ENV_ALLOW=["PATH","HOME","USERPROFILE","HOMEDRIVE","HOMEPATH","USER","LOGNAME","SHELL","COMSPEC","PATHEXT","TERM","COLORTERM","COLORFGBG","LANG","LC_ALL","LC_CTYPE","LC_MESSAGES","TZ","TEMP","TMPDIR","TMP","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_STATE_HOME","XDG_CACHE_HOME","APPDATA","LOCALAPPDATA","XDG_RUNTIME_DIR","DO_NOT_TRACK","CI","SystemRoot","windir","SystemDrive","PROCESSOR_ARCHITECTURE","NUMBER_OF_PROCESSORS","ALLUSERSPROFILE","ProgramData","ProgramFiles","ProgramFiles(x86)","CommonProgramFiles","PUBLIC"];var OPERATOR_ENV_KEEP=["COTAL_HOME","COTAL_FEEDBACK_KEY","COTAL_FEEDBACK_EMAIL","COTAL_FEEDBACK_URL","COTAL_DEFAULT_AGENT","COTAL_DEFAULT_PERSONA","COTAL_SKIP_CONNECTOR_SEED","COTAL_SKIP_ASSIST","COTAL_DETACH_KEY","COTAL_COMPLETE_DEBUG","COTAL_DEBUG","COTAL_SERVE_HEADLESS","COTAL_MEMBERSHIP_INTERVAL_MS","COTAL_DELIVERY_BROKER_GONE_MS","COTAL_IDP_TIMEOUT_MS","COTAL_CODEX_BIN","COTAL_OPENCODE_BIN","COTAL_ORCA_BIN","COTAL_TELEMETRY","COTAL_TELEMETRY_DISABLED","COTAL_TELEMETRY_URL"];function launchEnv(opts={}){for(const[source,keys]of[["spawn.env",opts.envAllow],["MCP environment references",opts.mcpKeys]]){for(const k of keys??[]){const name=k.toUpperCase();if(name.startsWith("COTAL_")&&!OPERATOR_ENV_KEEP.some(keep=>keep===name))throw new Error(`${source} cannot list "${k}": the launcher sets COTAL_ names for each seat, and only the machine-wide ones such as COTAL_HOME cross from the spawning process`)}}const env={};const sourceKey=new Map;for(const k of Object.keys(process.env))sourceKey.set(k.toLowerCase(),k);const copy=name=>{const src=sourceKey.get(name.toLowerCase());if(src===void 0)return;const v=process.env[src];if(v!==void 0)env[src]=v};for(const k of OS_ENV_ALLOW)copy(k);for(const k of OPERATOR_ENV_KEEP)copy(k);for(const k of[...opts.providerKeys??[],...opts.mcpKeys??[],...opts.envAllow??[]])copy(k);return env}function aclEnv(opts){const env={};if(opts.subscribe)env.COTAL_SUBSCRIBE=opts.subscribe.join(",");if(opts.allowSubscribe)env.COTAL_ALLOW_SUBSCRIBE=opts.allowSubscribe.join(",");if(opts.allowPublish)env.COTAL_ALLOW_PUBLISH=opts.allowPublish.join(",");if(opts.capabilities?.length)env.COTAL_CAPABILITIES=opts.capabilities.join(",");return env}var UNSAFE_LAUNCH_OPTION_KEYS=new Set(["__proto__","constructor","prototype"]);var LAUNCH_OPTION_KEY=/^[A-Za-z][A-Za-z0-9_-]*$/;function connectorLaunchOptions(connector,launchOptions){if(!launchOptions)return[];for(const k of Object.keys(launchOptions))if(UNSAFE_LAUNCH_OPTION_KEYS.has(k)||!LAUNCH_OPTION_KEY.test(k))throw new Error(`${connector} connector: launch option key ${JSON.stringify(k)} is not a valid flag name`);return Object.entries(launchOptions)}function materialEnv(opts,artifacts){if(opts.userAuth&&opts.creds)throw new Error("launch: creds (static auth) and userAuth (user-mode auth) are mutually exclusive \u2014 one launch carries one identity plane");const material={};if(opts.creds)material.creds=opts.creds;if(opts.servers)material.servers=opts.servers;if(opts.token)material.token=opts.token;if(opts.controlToken)material.controlToken=opts.controlToken;if(opts.eventsRequired)material.eventsRequired=true;if(opts.userAuth)material.userAuth=opts.userAuth;if(Object.keys(material).length===0)return{};const path=writeLaunchMaterial(material);artifacts.push(dirname(path));return{[LAUNCH_MATERIAL_ENV3]:path}}function launchArmsEvents(opts){return opts.events!==false||opts.eventsRequired===true}var ENV_REFERENCE=/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-[^}]*)?\}/g;function mcpServerEnvKeys(servers){const names=new Set;const scan=s=>{if(!s)return;for(const m of s.matchAll(ENV_REFERENCE))names.add(m[1])};for(const spec of Object.values(servers)){scan(spec.command);spec.args?.forEach(scan);if(spec.env)for(const v of Object.values(spec.env))scan(v);scan(spec.url);if(spec.headers)for(const v of Object.values(spec.headers))scan(v)}return[...names]}import{AGUI_FRAME_KIND,AGUI_EVENT_TYPE,isAguiFramePart}from"@cotal-ai/core";import{AGUI_FRAME_KIND as AGUI_FRAME_KIND2,AGUI_EVENT_TYPE as AGUI_EVENT_TYPE2,isAguiFramePart as isAguiFramePart2}from"@cotal-ai/core";var TOOL_RESULT_EVENT="cotal.toolResult";var TRUNCATABLE_FIELDS=[{type:AGUI_EVENT_TYPE2.TOOL_CALL_ARGS,field:"delta"},{type:AGUI_EVENT_TYPE2.TOOL_CALL_RESULT,field:"content"},{type:AGUI_EVENT_TYPE2.TEXT_MESSAGE_CONTENT,field:"delta"}];var EGRESS_FORBIDDEN_TYPES=new Set([AGUI_EVENT_TYPE2.TOOL_CALL_ARGS,AGUI_EVENT_TYPE2.TOOL_CALL_RESULT]);var KNOWN_EVENT_KEYS_BY_TYPE=new Map([[AGUI_EVENT_TYPE2.RUN_STARTED,new Set(["type","timestamp","rawEvent","threadId","runId","parentRunId","input","cotal"])],[AGUI_EVENT_TYPE2.RUN_FINISHED,new Set(["type","timestamp","rawEvent","threadId","runId","result","outcome","cotal"])],[AGUI_EVENT_TYPE2.RUN_ERROR,new Set(["type","timestamp","rawEvent","message","code","cotal"])],[AGUI_EVENT_TYPE2.TEXT_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","name","cotal"])],[AGUI_EVENT_TYPE2.TEXT_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE2.TEXT_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE2.TOOL_CALL_START,new Set(["type","timestamp","rawEvent","toolCallId","toolCallName","parentMessageId","cotal"])],[AGUI_EVENT_TYPE2.TOOL_CALL_ARGS,new Set(["type","timestamp","rawEvent","toolCallId","delta","cotal"])],[AGUI_EVENT_TYPE2.TOOL_CALL_END,new Set(["type","timestamp","rawEvent","toolCallId","cotal"])],[AGUI_EVENT_TYPE2.TOOL_CALL_RESULT,new Set(["type","timestamp","rawEvent","messageId","toolCallId","content","role","cotal"])],[AGUI_EVENT_TYPE2.REASONING_MESSAGE_START,new Set(["type","timestamp","rawEvent","messageId","role","cotal"])],[AGUI_EVENT_TYPE2.REASONING_MESSAGE_CONTENT,new Set(["type","timestamp","rawEvent","messageId","delta","cotal"])],[AGUI_EVENT_TYPE2.REASONING_MESSAGE_END,new Set(["type","timestamp","rawEvent","messageId","cotal"])],[AGUI_EVENT_TYPE2.CUSTOM,new Set(["type","timestamp","rawEvent","name","value","cotal"])]]);var TOOL_RESULT_VALUE_KEYS=new Set(["toolCallId","isError"]);function toolResultValueDefect(value){if(typeof value!=="object"||value===null||Array.isArray(value))return"value";const keys=Object.keys(value);for(const key of keys){if(!TOOL_RESULT_VALUE_KEYS.has(key))return`value.${key}`}if(keys.length!==TOOL_RESULT_VALUE_KEYS.size)return"value";const v=value;if(typeof v.toolCallId!=="string")return"value";if(typeof v.isError!=="boolean")return"value";return void 0}function toolResultValue(value){if(toolResultValueDefect(value)!==void 0)return void 0;const v=value;return{toolCallId:v.toolCallId,isError:v.isError}}import{isAguiFramePart as isAguiFramePart3,isCasLoss,principalKey as principalKey2}from"@cotal-ai/core";var SIZING_ID="S".repeat(64);var SIZING_EXPECTATION=Number.MAX_SAFE_INTEGER;import{assertIdToken}from"@cotal-ai/core";import{ensureDirNoSymlink}from"@cotal-ai/core";import{AGUI_EVENT_TYPE as AGUI_EVENT_TYPE3,AGUI_FRAME_KIND as AGUI_FRAME_KIND3,isAguiFramePart as isAguiFramePart4,registry}from"@cotal-ai/core";var str=v=>typeof v==="string"?v:void 0;var CONT=" \xB7 ";var TEXT_PREFIX="\xBB ";var THINK_PREFIX="(thinking) ";var TOOL_PREFIX="\u2699 ";var RESULT_PREFIX=" \u21B3 ";var BLOCK_START_CHARS=new Set([..."#>|`~=_*+-[<0123456789"," "]);function renderEvents(events){const lines=[];const text=new Map;const reasoning=new Map;const toolName=new Map;const toolArgs=new Map;const emit=(first,cont,body)=>{const[head,...rest]=body.split("\n");lines.push(first+head);for(const l of rest)lines.push(cont+l)};const flush=(map2,id,first,cont,suffix="")=>{const acc=map2.get(id);if(acc!==void 0&&acc.length>0)emit(first,cont,acc+suffix);map2.delete(id)};for(const e of events){const type=typeof e==="object"&&e!==null?str(e.type):void 0;switch(type){case AGUI_EVENT_TYPE3.RUN_STARTED:emit("\u25B8 ",CONT,`run ${str(e.runId)??"?"} started`);break;case AGUI_EVENT_TYPE3.RUN_FINISHED:{const outcome=str(e.outcome?.type);emit("\u25C2 ",CONT,`run ${str(e.runId)??"?"} finished${outcome?` (${outcome})`:""}`);break}case AGUI_EVENT_TYPE3.RUN_ERROR:{const code=str(e.code);emit("\u2717 ",CONT,`run error${code?` [${code}]`:""}: ${str(e.message)??"(no message)"}`);break}case AGUI_EVENT_TYPE3.TEXT_MESSAGE_START:text.set(str(e.messageId)??"","");break;case AGUI_EVENT_TYPE3.TEXT_MESSAGE_CONTENT:{const id=str(e.messageId)??"";text.set(id,(text.get(id)??"")+(str(e.delta)??""));break}case AGUI_EVENT_TYPE3.TEXT_MESSAGE_END:flush(text,str(e.messageId)??"",TEXT_PREFIX,TEXT_PREFIX);break;case AGUI_EVENT_TYPE3.REASONING_MESSAGE_START:reasoning.set(str(e.messageId)??"","");break;case AGUI_EVENT_TYPE3.REASONING_MESSAGE_CONTENT:{const id=str(e.messageId)??"";reasoning.set(id,(reasoning.get(id)??"")+(str(e.delta)??""));break}case AGUI_EVENT_TYPE3.REASONING_MESSAGE_END:flush(reasoning,str(e.messageId)??"",THINK_PREFIX,CONT);break;case AGUI_EVENT_TYPE3.TOOL_CALL_START:{const id=str(e.toolCallId)??"";toolName.set(id,str(e.toolCallName)??"?");toolArgs.set(id,"");break}case AGUI_EVENT_TYPE3.TOOL_CALL_ARGS:{const id=str(e.toolCallId)??"";toolArgs.set(id,(toolArgs.get(id)??"")+(str(e.delta)??""));break}case AGUI_EVENT_TYPE3.TOOL_CALL_END:{const id=str(e.toolCallId)??"";emit(TOOL_PREFIX,CONT,`${toolName.get(id)??"?"}(${toolArgs.get(id)??""})`);toolName.delete(id);toolArgs.delete(id);break}case AGUI_EVENT_TYPE3.TOOL_CALL_RESULT:emit(RESULT_PREFIX,CONT,str(e.content)??"(no content)");break;case AGUI_EVENT_TYPE3.CUSTOM:{const failed=e.name===TOOL_RESULT_EVENT?toolResultValue(e.value)?.isError:void 0;if(failed!==void 0)emit(RESULT_PREFIX,CONT,failed?"failed":"done");else emit("\u2022 ",CONT,`custom ${str(e.name)??"(unnamed)"}`);break}default:emit("\u2022 ",CONT,`unrecognised event ${JSON.stringify(type??null)}`)}}for(const id of[...text.keys()])flush(text,id,TEXT_PREFIX,TEXT_PREFIX," \u2026");for(const id of[...reasoning.keys()])flush(reasoning,id,THINK_PREFIX,CONT," \u2026");for(const id of[...toolName.keys()])emit(TOOL_PREFIX,CONT,`${toolName.get(id)??"?"}(${toolArgs.get(id)??""}) \u2026`);return lines}var aguiFramePartRenderer=Object.freeze({kind:"part-renderer",name:AGUI_FRAME_KIND3,render(part){if(!isAguiFramePart4(part))return`[not an AG-UI frame]`;const events=part.events;if(!Array.isArray(events)||events.length===0)return`[AG-UI frame carrying no events]`;const lines=renderEvents(events);return lines.length>0?lines.join("\n"):`[AG-UI frame with ${events.length} event(s) and nothing to show]`}});function registerAguiFramePartRenderer(){if(registry.has("part-renderer",AGUI_FRAME_KIND3))return;registry.register(aguiFramePartRenderer)}registerAguiFramePartRenderer();var MAX_FRAME_BYTES=1<<20;init_external();init_external();import{isConcreteChannel as isConcreteChannel4,isChannelFamily as isChannelFamily2,assertValidChannel as assertValidChannel3,MAX_CHANNEL_LENGTH,channelInAllow as channelInAllow3,patternInAllow,AmbiguousPeerError,peerLabel as peerLabel4,assertLifecycleToken as assertLifecycleToken3,isPermissionDenied as isPermissionDenied2,renderLifecycleBlocked,EpEnvelopeError as EpEnvelopeError3,EP_UNANSWERED as EP_UNANSWERED2,REGISTRY_PAGE_LIMIT,LANG_PROBLEM_DETAIL_KIND,formatAge,parseDuration,presenceAges,presenceText}from"@cotal-ai/core";import{isConcreteChannel as isConcreteChannel3,parsePrincipalKey as parsePrincipalKey2,peerLabel as peerLabel3}from"@cotal-ai/core";var STOP=new Set("a an and are as at be by do for from has how in is it of on or that the this to use using was what when where which who with you your".split(" "));var NO_TOOL_ARGS=external_exports.strictObject({});var managerInstanceArg=external_exports.string().refine(value=>{try{assertLifecycleToken3(value,"instance");return true}catch{return false}},"instance must be a lifecycle token ([a-z0-9]{26,32})").optional().describe("Optional manager instance id for a multi-manager space. When omitted, a seat a manager launched uses that manager and any other caller lets the mesh select one; on a user-auth mesh with several of your managers live, that selection refuses and lists their ids. A pin that cannot be resolved is refused without falling back to another manager.");var PATTERN_SEND_HELP="A pattern such as team.> is refused. To reach the agents following team.>, post once to one channel it matches, such as team.announce: those connected then get it, and one that is away gets a stored copy if that channel is durable. To reach several channels, post to each by name (cotal_channels lists the existing ones).";init_types();var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");init_types();var import_ajv_formats=__toESM(require_dist(),1);init_types();init_types();var McpZodTypeKind;(function(McpZodTypeKind2){McpZodTypeKind2["Completable"]="McpCompletable"})(McpZodTypeKind||(McpZodTypeKind={}));init_types();import{assertValidName,conversationSelection,SELECTION_MAX_ITEMS}from"@cotal-ai/core";var GATEWAY_TOOLS=new Set(["cotal_orientation","cotal_connection_status","cotal_roster","cotal_docs","cotal_inbox","cotal_send","cotal_dm","cotal_anycast","cotal_status","cotal_channel_info","cotal_channels","cotal_channel_mode","cotal_join","cotal_leave"]);var NATIVE_GATEWAY_TOOLS=new Set([...GATEWAY_TOOLS,"cotal_spawn","cotal_persona","cotal_personas","cotal_despawn","cotal_run","cotal_turn_participate","cotal_yield","cotal_reconnect"]);var SELECTION_SHAPE={channels:external_exports.array(external_exports.strictObject({channel:external_exports.string().min(1),access:external_exports.enum(["read","read-post"])})).max(SELECTION_MAX_ITEMS).optional().describe("Channels this connection may join and read, or read and post to. A pattern such as team.* or team.> covers every matching channel, including ones created later."),role:external_exports.string().min(1).optional().describe("A role to hold, so role requests (cotal_anycast) reach this connection."),capabilities:external_exports.array(external_exports.enum(["spawn","run"])).optional().describe("spawn: start and stop agents through a manager. run: start and manage workflow runs.")};var SEND_CHANNEL=`Channel to send on. Omit it to use this connection's default, the first concrete channel it reads and may post to (cotal_orientation lists both); with none, an omitted channel is refused. ${PATTERN_SEND_HELP} Reply on the channel you received a message on.`;var CONNECTION_ID=external_exports.string().min(1).describe("The connection_id cotal_connect returned in THIS conversation. Never reuse another conversation's.");var GATEWAY_LISTENING="Messages reach you only when you call a tool: to listen, call cotal_wait, which returns as soon as a message arrives. When the person asks you to stay on Cotal or keep listening, call cotal_wait again each time it returns and handle each message as it arrives, until they ask you to stop.";var GATEWAY_CONNECTING="Cotal connects this conversation to the person's Cotal space after they approve its permissions. Call cotal_connect with a short name. If approval is pending, show the person its link and wait for their decision; do not approve for them or poll. Then resume the same request as directed. Only a successful connection returns connection_id, required on every other cotal tool call. Each conversation needs its own connection. Never reuse another conversation's connection_id or approval_id.";var GATEWAY_INSTRUCTIONS=`${GATEWAY_CONNECTING} ${GATEWAY_LISTENING}`;var CLI_RECORD="cli.json";import{spawnSync}from"node:child_process";import{existsSync,readFileSync,renameSync,statSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{join as join2}from"node:path";var DESKTOP_SERVER="cotal";function desktopConfigPath(platform=process.platform,env=process.env,home=homedir()){if(platform==="darwin")return join2(home,"Library","Application Support","Claude","claude_desktop_config.json");if(platform==="win32"&&env.APPDATA)return join2(env.APPDATA,"Claude","claude_desktop_config.json");return void 0}function readConfig(path){if(!existsSync(path))return{};const text=readFileSync(path,"utf8");let parsed;try{parsed=text.trim()?JSON.parse(text):{}}catch{throw new Error(`${path} is not valid JSON, so Cotal left it alone. Fix it, then run \`cotal setup\` again.`)}const servers=parsed?.mcpServers;if(!parsed||typeof parsed!=="object"||Array.isArray(parsed)||servers!==void 0&&(!servers||typeof servers!=="object"||Array.isArray(servers)))throw new Error(`${path} is not a Claude Desktop config (an object whose mcpServers is an object), so Cotal left it alone.`);return parsed}function readDesktopEntry(path){return readConfig(path).mcpServers?.[DESKTOP_SERVER]}function desktopRunning(platform=process.platform){if(platform!=="darwin")return false;const ps=spawnSync("ps",["-A","-o","comm="],{encoding:"utf8",maxBuffer:64*1024*1024,timeout:1e4,killSignal:"SIGKILL"});if(ps.status!==0)throw new Error(`Cotal could not list processes to tell whether Claude Desktop is running: ${ps.error?.message??ps.stderr.trim()}`);return ps.stdout.split("\n").some(line=>line.endsWith("/Claude.app/Contents/MacOS/Claude"))}function writeDesktopEntry(path,entry,running=desktopRunning){const config2=readConfig(path);const before=config2.mcpServers?.[DESKTOP_SERVER];if(JSON.stringify(before)===JSON.stringify(entry))return"current";if(running())return before===void 0?"not added":"not updated";config2.mcpServers={...config2.mcpServers,[DESKTOP_SERVER]:entry};const tmp=`${path}.cotal-${process.pid}`;writeFileSync(tmp,`${JSON.stringify(config2,null,2)}
69
- `,{mode:existsSync(path)?statSync(path).mode&511:384});renameSync(tmp,path);return before===void 0?"added":"updated"}import{existsSync as existsSync2,readFileSync as readFileSync2}from"node:fs";import{homedir as homedir2}from"node:os";import{join as join3}from"node:path";import{mcpServerProblem}from"@cotal-ai/core";function claudeUserMcpServers(){const path=join3(process.env.CLAUDE_CONFIG_DIR?.trim()||homedir2(),".claude.json");if(!existsSync2(path))return{};let config2;try{config2=JSON.parse(readFileSync2(path,"utf8"))}catch(e){throw new Error(`${path}: invalid JSON - ${e.message}`)}return config2?.mcpServers??{}}function claudeUserMcpEnvKeys(){const valid=Object.fromEntries(Object.entries(claudeUserMcpServers()).filter(([name,spec])=>mcpServerProblem(name,spec)===void 0));return mcpServerEnvKeys(valid)}var PACKAGE_ROOT=fileURLToPath(new URL("..",import.meta.url));var COTAL_ASSETS=[".claude-plugin",".mcp.json","hooks","monitors","dist/seat.cjs","dist/mcp.cjs","dist/docs-bundle.bin","dist/docs-index.bin","dist/hook.cjs","dist/monitor.cjs"];function pluginVersion(root,assets,files){const hash2=createHash2("sha256");const add=(path,bytes)=>hash2.update(`${path}\0${bytes.length}\0`).update(bytes);const walk=path=>{if(statSync2(path).isDirectory())for(const entry of readdirSync(path).sort())walk(join4(path,entry));else add(relative(root,path),readFileSync3(path))};for(const asset of[...assets].sort())walk(join4(root,asset));for(const[path,text]of Object.entries(files).sort(([a],[b])=>a.localeCompare(b)))add(path,text);const release=JSON.parse(readFileSync3(join4(PACKAGE_ROOT,"package.json"),"utf8")).version;return`${release}+${hash2.digest("hex").slice(0,12)}`}function materializeCotal(cotal){for(const asset of COTAL_ASSETS)if(!existsSync3(join4(PACKAGE_ROOT,asset)))throw new Error(`plugin asset missing: ${join4(PACKAGE_ROOT,asset)}`);const files=pluginFiles(cotal);const version2=pluginVersion(PACKAGE_ROOT,COTAL_ASSETS,files);materialize("cotal",PACKAGE_ROOT,COTAL_ASSETS,version2,files);return version2}function pluginFiles(cotal){const node=cotal[0];if(!node)throw new Error("the Cotal CLI record has no Node executable");if(process.platform==="win32"&&/[\"%!\r\n]/.test(node))throw new Error("the Node executable path contains characters Claude's Windows command hooks cannot safely run");const quoted=process.platform==="win32"?`"${node}"`:`'${node.replace(/'/g,"'\\''")}'`;const mcp=JSON.parse(readFileSync3(join4(PACKAGE_ROOT,".mcp.json"),"utf8"));mcp.mcpServers.cotal.command=node;const hooks=JSON.parse(readFileSync3(join4(PACKAGE_ROOT,"hooks","hooks.json"),"utf8"));for(const groups of Object.values(hooks.hooks))for(const group of groups)for(const hook of group.hooks){if(hook.command==='node "${CLAUDE_PLUGIN_ROOT}/dist/hook.cjs"')hook.command=quoted+' "${CLAUDE_PLUGIN_ROOT}/dist/hook.cjs"'}return{[`dist/${CLI_RECORD}`]:`${JSON.stringify({argv:cotal})}
69
+ `,{mode:existsSync(path)?statSync(path).mode&511:384});renameSync(tmp,path);return before===void 0?"added":"updated"}import{existsSync as existsSync2,readFileSync as readFileSync2}from"node:fs";import{homedir as homedir2}from"node:os";import{join as join3}from"node:path";import{mcpServerProblem}from"@cotal-ai/core";function claudeUserMcpServers(){const path=join3(process.env.CLAUDE_CONFIG_DIR?.trim()||homedir2(),".claude.json");if(!existsSync2(path))return{};let config2;try{config2=JSON.parse(readFileSync2(path,"utf8"))}catch(e){throw new Error(`${path}: invalid JSON - ${e.message}`)}return config2?.mcpServers??{}}function claudeUserMcpEnvKeys(){const valid=Object.fromEntries(Object.entries(claudeUserMcpServers()).filter(([name,spec])=>mcpServerProblem(name,spec)===void 0));return mcpServerEnvKeys(valid)}function claudeDeclaredServerNames(cwd){const names=new Set(Object.keys(claudeUserMcpServers()));const project=join3(cwd,".mcp.json");if(!existsSync2(project))return names;let config2;try{config2=JSON.parse(readFileSync2(project,"utf8"))}catch(e){throw new Error(`${project}: invalid JSON - ${e.message}`)}for(const name of Object.keys(config2?.mcpServers??{}))names.add(name);return names}function assertChannelServerDeclared(name,cwd){if(claudeDeclaredServerNames(cwd).has(name))return;throw new Error(`claude connector: Claude Code binds the server:${name} wake channel only to a server its own configuration declares, and neither the user config nor ${join3(cwd,".mcp.json")} declares one named ${name}; run \`cotal setup\` or \`cotal update\`, which registers it at user scope`)}var PACKAGE_ROOT=fileURLToPath(new URL("..",import.meta.url));var COTAL_ASSETS=[".claude-plugin",".mcp.json","hooks","monitors","dist/seat.cjs","dist/mcp.cjs","dist/docs-bundle.bin","dist/docs-index.bin","dist/hook.cjs","dist/monitor.cjs"];function pluginVersion(root,assets,files){const hash2=createHash2("sha256");const add=(path,bytes)=>hash2.update(`${path}\0${bytes.length}\0`).update(bytes);const walk=path=>{if(statSync2(path).isDirectory())for(const entry of readdirSync(path).sort())walk(join4(path,entry));else add(relative(root,path),readFileSync3(path))};for(const asset of[...assets].sort())walk(join4(root,asset));for(const[path,text]of Object.entries(files).sort(([a],[b])=>a.localeCompare(b)))add(path,text);const release=JSON.parse(readFileSync3(join4(PACKAGE_ROOT,"package.json"),"utf8")).version;return`${release}+${hash2.digest("hex").slice(0,12)}`}function materializeCotal(cotal){for(const asset of COTAL_ASSETS)if(!existsSync3(join4(PACKAGE_ROOT,asset)))throw new Error(`plugin asset missing: ${join4(PACKAGE_ROOT,asset)}`);const files=pluginFiles(cotal);const version2=pluginVersion(PACKAGE_ROOT,COTAL_ASSETS,files);materialize("cotal",PACKAGE_ROOT,COTAL_ASSETS,version2,files);return version2}function pluginFiles(cotal){const node=cotal[0];if(!node)throw new Error("the Cotal CLI record has no Node executable");if(process.platform==="win32"&&/[\"%!\r\n]/.test(node))throw new Error("the Node executable path contains characters Claude's Windows command hooks cannot safely run");const quoted=process.platform==="win32"?`"${node}"`:`'${node.replace(/'/g,"'\\''")}'`;const mcp=JSON.parse(readFileSync3(join4(PACKAGE_ROOT,".mcp.json"),"utf8"));mcp.mcpServers.cotal.command=node;const hooks=JSON.parse(readFileSync3(join4(PACKAGE_ROOT,"hooks","hooks.json"),"utf8"));for(const groups of Object.values(hooks.hooks))for(const group of groups)for(const hook of group.hooks){if(hook.command==='node "${CLAUDE_PLUGIN_ROOT}/dist/hook.cjs"')hook.command=quoted+' "${CLAUDE_PLUGIN_ROOT}/dist/hook.cjs"'}return{[`dist/${CLI_RECORD}`]:`${JSON.stringify({argv:cotal})}
70
70
  `,".mcp.json":`${JSON.stringify(mcp,null,2)}
71
71
  `,"hooks/hooks.json":`${JSON.stringify(hooks,null,2)}
72
- `}}function desktopEntry(cotal){return{command:cotal[0],args:[join4(marketplaceDir(),"cotal","dist","seat.cjs"),"--desktop"],...process.env.COTAL_HOME?{env:{COTAL_HOME:process.env.COTAL_HOME}}:{}}}function hostedConnector(s){const next=s.hostedConnector?`add ${s.hostedConnector} under Settings > Connectors > Add custom connector`:s.unread?`its hosted connector could not be read (${s.unread})`:`"${s.space}" advertises no hosted connector`;return`chat joins signed-in space "${s.space}" only through a hosted connector: ${next}`}function desktop(cotal,add,signedIn){const path=desktopConfigPath();if(!path||!existsSync3(dirname2(path)))return void 0;if(signedIn)return`Claude Desktop ${hostedConnector(signedIn)}`;if(!add&&readDesktopEntry(path)===void 0)return void 0;const state=writeDesktopEntry(path,desktopEntry(cotal));if(state==="not added"||state==="not updated")return`Claude Desktop ${state}: Claude Desktop is running and writes back the config it read when it started, which would drop the entry. Quit Claude Desktop, then run \`cotal setup\` again from a terminal outside it`;return`Claude Desktop ${state}${state==="current"?"":"; quit and reopen Claude Desktop to load it"}`}var DOCS_URL="https://github.com/Cotal-AI/Cotal/blob/main/docs/connect-claude.mdx";var MARKETPLACE="cotal-mesh";function claudeCommand(){const terminal=spawnSync2("claude",["--version"],{stdio:"ignore",timeout:5e3,killSignal:"SIGKILL"});if(terminal.status===0)return"claude";if(terminal.error?.code!=="ENOENT")throw new Error("The installed Claude Code command could not run. Repair it before running `cotal setup`.");const config2=desktopConfigPath();const app=config2?dirname2(config2):process.platform==="linux"?join4(process.env.XDG_CONFIG_HOME||join4(homedir3(),".config"),"Claude"):void 0;if(!app||!existsSync3(join4(app,"claude-code")))throw new Error("Claude Code is unavailable. Install it or open Desktop's Code tab, then retry setup.");const cache=join4(app,"claude-code");const versions=readdirSync(cache,{withFileTypes:true}).filter(entry=>entry.isDirectory()&&/^\d+\.\d+\.\d+$/.test(entry.name)).sort((a,b)=>b.name.localeCompare(a.name,void 0,{numeric:true}));const executable=process.platform==="win32"?"claude.exe":"claude";for(const version2 of versions){const root=join4(cache,version2.name);for(const entry of readdirSync(root,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){if(!entry.isDirectory())continue;const candidates=process.platform==="darwin"?[join4(root,entry.name,"claude.app","Contents","MacOS","claude"),join4(root,entry.name,executable)]:[join4(root,entry.name,executable)];for(const candidate of candidates){if(!existsSync3(candidate))continue;if(spawnSync2(candidate,["--version"],{stdio:"ignore",timeout:5e3,killSignal:"SIGKILL"}).status!==0)throw new Error("Claude Desktop's bundled Code executable could not run. Update or reinstall Claude Desktop.");return candidate}}}throw new Error("Claude Code is unavailable. Install it or open Desktop's Code tab, then retry setup.")}function claudeAvailable(){try{claudeCommand();return true}catch{return false}}function cotalHome(){if(process.env.COTAL_HOME)return process.env.COTAL_HOME;if(process.platform==="win32"&&process.env.LOCALAPPDATA)return join4(process.env.LOCALAPPDATA,"Cotal");return join4(homedir3(),".cotal")}function marketplaceDir(){return join4(cotalHome(),"claude-plugin")}function withPluginLock(run){const lock=acquireLock(join4(marketplaceDir(),".setup.lock"),{label:"Claude plugin setup"});try{return run()}finally{lock.release()}}function materialize(name,root,assets,version2,files={}){const market=marketplaceDir();mkdirSync(market,{recursive:true});const dest=join4(market,name);const staging=`${dest}.staging.${process.pid}`;const old=`${dest}.old.${process.pid}`;const orphans=readdirSync(market,{withFileTypes:true}).filter(entry=>entry.isDirectory()&&(entry.name.startsWith(`${name}.old.`)||entry.name.startsWith(`${name}.staging.`))).map(entry=>entry.name);if(!existsSync3(dest)){const recoverable=orphans.find(entry=>entry.startsWith(`${name}.old.`));if(recoverable)renameSync2(join4(market,recoverable),dest)}for(const entry of orphans)rmSync(join4(market,entry),{recursive:true,force:true});let movedAside=false;let swapped=false;try{mkdirSync(staging);for(const asset of assets){const destination=join4(staging,asset);mkdirSync(join4(destination,".."),{recursive:true});cpSync(join4(root,asset),destination,{recursive:true,dereference:true})}for(const[path,text]of Object.entries(files))writeFileSync2(join4(staging,path),text);if(version2){const manifestPath=join4(staging,".claude-plugin","plugin.json");const manifest=JSON.parse(readFileSync3(manifestPath,"utf8"));manifest.version=version2;writeFileSync2(manifestPath,JSON.stringify(manifest,null,2)+"\n")}if(existsSync3(dest)){renameSync2(dest,old);movedAside=true}renameSync2(staging,dest);swapped=true;if(movedAside)rmSync(old,{recursive:true,force:true})}catch(error51){if(movedAside&&!swapped&&!existsSync3(dest)&&existsSync3(old))renameSync2(old,dest);throw error51}finally{rmSync(staging,{recursive:true,force:true});if(swapped)rmSync(old,{recursive:true,force:true})}}var CLAUDE_OUTPUT_LIMIT=64*1024*1024;function command(...args){return commandIn(process.cwd(),...args)}function commandIn(cwd,...args){const result=spawnSync2(claudeCommand(),args,{cwd,encoding:"utf8",maxBuffer:CLAUDE_OUTPUT_LIMIT,timeout:12e4,killSignal:"SIGKILL"});if(result.error)return{status:null,output:result.error.message};return{status:result.status,output:`${result.stdout??""}${result.stderr??""}`.trim()}}function marketplaceEntry(market,name){const manifest=JSON.parse(readFileSync3(join4(market,name,".claude-plugin","plugin.json"),"utf8"));const description=typeof manifest.description==="string"?manifest.description:void 0;return{name,source:`./${name}`,...description?{description}:{}}}function marketplaceManifest(market){const plugins=["cotal","cotal-skills"].filter(name=>existsSync3(join4(market,name,".claude-plugin","plugin.json"))).map(name=>marketplaceEntry(market,name));return{name:MARKETPLACE,description:"Cotal for Claude Code",owner:{name:"Cotal"},plugins}}function writeMarketplaceManifest(market){const path=join4(market,".claude-plugin","marketplace.json");mkdirSync(dirname2(path),{recursive:true});writePrivateRecord(path,JSON.stringify(marketplaceManifest(market),null,2)+"\n");return path}function writeMarketplace(){const market=marketplaceDir();writeMarketplaceManifest(market);const add=command("plugin","marketplace","add",market);if(add.status!==0&&!/already (?:exists|added|on disk)/i.test(add.output))throw new Error(`plugin marketplace add failed:
72
+ `}}function desktopEntry(cotal){return{command:cotal[0],args:[join4(marketplaceDir(),"cotal","dist","seat.cjs"),"--desktop"],...process.env.COTAL_HOME?{env:{COTAL_HOME:process.env.COTAL_HOME}}:{}}}function userServerEntry(cotal){const node=cotal[0];if(!node)throw new Error("the Cotal CLI record has no Node executable");const mcp=JSON.parse(readFileSync3(join4(PACKAGE_ROOT,".mcp.json"),"utf8"));return{command:node,args:mcp.mcpServers.cotal.args.map(arg=>arg.replace("${CLAUDE_PLUGIN_ROOT}",join4(marketplaceDir(),"cotal")))}}function userServerState(current,desired){if(current===void 0)return"add";const entry=current;const args=Array.isArray(entry.args)?entry.args:[];const same=entry.command===desired.command&&(entry.type===void 0||entry.type==="stdio")&&args.length===(desired.args??[]).length&&args.every((arg,i)=>arg===desired.args[i]);return same?"current":"replace"}function registerUserServer(cotal){const desired=userServerEntry(cotal);const state=userServerState(claudeUserMcpServers().cotal,desired);if(state==="current")return"user MCP entry cotal current";if(state==="replace"){const removed=command("mcp","remove","--scope","user","cotal");if(removed.status!==0)throw new Error(`mcp remove failed (cotal):
73
+ ${removed.output}`)}const added=command("mcp","add","--scope","user","cotal","--",desired.command,...desired.args);if(added.status!==0)throw new Error(`mcp add failed (cotal):
74
+ ${added.output}`);if(userServerState(claudeUserMcpServers().cotal,desired)!=="current")throw new Error("the user-scope MCP entry cotal was not registered as requested");return`user MCP entry cotal ${state==="replace"?"replaced":"registered"}`}function userServerRow(){let declared;try{declared=claudeUserMcpServers().cotal!==void 0}catch(e){return{label:"Claude wake channel",state:"error",text:e.message}}return declared?{label:"Claude wake channel",state:"ok",text:"user MCP entry cotal registered"}:{label:"Claude wake channel",state:"off",text:"user MCP entry cotal not registered \xB7 run cotal setup"}}function hostedConnector(s){const next=s.hostedConnector?`add ${s.hostedConnector} under Settings > Connectors > Add custom connector`:s.unread?`its hosted connector could not be read (${s.unread})`:`"${s.space}" advertises no hosted connector`;return`chat joins signed-in space "${s.space}" only through a hosted connector: ${next}`}function desktop(cotal,add,signedIn){const path=desktopConfigPath();if(!path||!existsSync3(dirname2(path)))return void 0;if(signedIn)return`Claude Desktop ${hostedConnector(signedIn)}`;if(!add&&readDesktopEntry(path)===void 0)return void 0;const state=writeDesktopEntry(path,desktopEntry(cotal));if(state==="not added"||state==="not updated")return`Claude Desktop ${state}: Claude Desktop is running and writes back the config it read when it started, which would drop the entry. Quit Claude Desktop, then run \`cotal setup\` again from a terminal outside it`;return`Claude Desktop ${state}${state==="current"?"":"; quit and reopen Claude Desktop to load it"}`}var DOCS_URL="https://github.com/Cotal-AI/Cotal/blob/main/docs/connect-claude.mdx";var MARKETPLACE="cotal-mesh";function claudeCommand(){const terminal=spawnSync2("claude",["--version"],{stdio:"ignore",timeout:5e3,killSignal:"SIGKILL"});if(terminal.status===0)return"claude";if(terminal.error?.code!=="ENOENT")throw new Error("The installed Claude Code command could not run. Repair it before running `cotal setup`.");const config2=desktopConfigPath();const app=config2?dirname2(config2):process.platform==="linux"?join4(process.env.XDG_CONFIG_HOME||join4(homedir3(),".config"),"Claude"):void 0;if(!app||!existsSync3(join4(app,"claude-code")))throw new Error("Claude Code is unavailable. Install it or open Desktop's Code tab, then retry setup.");const cache=join4(app,"claude-code");const versions=readdirSync(cache,{withFileTypes:true}).filter(entry=>entry.isDirectory()&&/^\d+\.\d+\.\d+$/.test(entry.name)).sort((a,b)=>b.name.localeCompare(a.name,void 0,{numeric:true}));const executable=process.platform==="win32"?"claude.exe":"claude";for(const version2 of versions){const root=join4(cache,version2.name);for(const entry of readdirSync(root,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){if(!entry.isDirectory())continue;const candidates=process.platform==="darwin"?[join4(root,entry.name,"claude.app","Contents","MacOS","claude"),join4(root,entry.name,executable)]:[join4(root,entry.name,executable)];for(const candidate of candidates){if(!existsSync3(candidate))continue;if(spawnSync2(candidate,["--version"],{stdio:"ignore",timeout:5e3,killSignal:"SIGKILL"}).status!==0)throw new Error("Claude Desktop's bundled Code executable could not run. Update or reinstall Claude Desktop.");return candidate}}}throw new Error("Claude Code is unavailable. Install it or open Desktop's Code tab, then retry setup.")}function claudeAvailable(){try{claudeCommand();return true}catch{return false}}function cotalHome(){if(process.env.COTAL_HOME)return process.env.COTAL_HOME;if(process.platform==="win32"&&process.env.LOCALAPPDATA)return join4(process.env.LOCALAPPDATA,"Cotal");return join4(homedir3(),".cotal")}function marketplaceDir(){return join4(cotalHome(),"claude-plugin")}function withPluginLock(run){const lock=acquireLock(join4(marketplaceDir(),".setup.lock"),{label:"Claude plugin setup"});try{return run()}finally{lock.release()}}function materialize(name,root,assets,version2,files={}){const market=marketplaceDir();mkdirSync(market,{recursive:true});const dest=join4(market,name);const staging=`${dest}.staging.${process.pid}`;const old=`${dest}.old.${process.pid}`;const orphans=readdirSync(market,{withFileTypes:true}).filter(entry=>entry.isDirectory()&&(entry.name.startsWith(`${name}.old.`)||entry.name.startsWith(`${name}.staging.`))).map(entry=>entry.name);if(!existsSync3(dest)){const recoverable=orphans.find(entry=>entry.startsWith(`${name}.old.`));if(recoverable)renameSync2(join4(market,recoverable),dest)}for(const entry of orphans)rmSync(join4(market,entry),{recursive:true,force:true});let movedAside=false;let swapped=false;try{mkdirSync(staging);for(const asset of assets){const destination=join4(staging,asset);mkdirSync(join4(destination,".."),{recursive:true});cpSync(join4(root,asset),destination,{recursive:true,dereference:true})}for(const[path,text]of Object.entries(files))writeFileSync2(join4(staging,path),text);if(version2){const manifestPath=join4(staging,".claude-plugin","plugin.json");const manifest=JSON.parse(readFileSync3(manifestPath,"utf8"));manifest.version=version2;writeFileSync2(manifestPath,JSON.stringify(manifest,null,2)+"\n")}if(existsSync3(dest)){renameSync2(dest,old);movedAside=true}renameSync2(staging,dest);swapped=true;if(movedAside)rmSync(old,{recursive:true,force:true})}catch(error51){if(movedAside&&!swapped&&!existsSync3(dest)&&existsSync3(old))renameSync2(old,dest);throw error51}finally{rmSync(staging,{recursive:true,force:true});if(swapped)rmSync(old,{recursive:true,force:true})}}var CLAUDE_OUTPUT_LIMIT=64*1024*1024;function command(...args){return commandIn(process.cwd(),...args)}function commandIn(cwd,...args){const result=spawnSync2(claudeCommand(),args,{cwd,encoding:"utf8",maxBuffer:CLAUDE_OUTPUT_LIMIT,timeout:12e4,killSignal:"SIGKILL"});if(result.error)return{status:null,output:result.error.message};return{status:result.status,output:`${result.stdout??""}${result.stderr??""}`.trim()}}function marketplaceEntry(market,name){const manifest=JSON.parse(readFileSync3(join4(market,name,".claude-plugin","plugin.json"),"utf8"));const description=typeof manifest.description==="string"?manifest.description:void 0;return{name,source:`./${name}`,...description?{description}:{}}}function marketplaceManifest(market){const plugins=["cotal","cotal-skills"].filter(name=>existsSync3(join4(market,name,".claude-plugin","plugin.json"))).map(name=>marketplaceEntry(market,name));return{name:MARKETPLACE,description:"Cotal for Claude Code",owner:{name:"Cotal"},plugins}}function writeMarketplaceManifest(market){const path=join4(market,".claude-plugin","marketplace.json");mkdirSync(dirname2(path),{recursive:true});writePrivateRecord(path,JSON.stringify(marketplaceManifest(market),null,2)+"\n");return path}function writeMarketplace(){const market=marketplaceDir();writeMarketplaceManifest(market);const add=command("plugin","marketplace","add",market);if(add.status!==0&&!/already (?:exists|added|on disk)/i.test(add.output))throw new Error(`plugin marketplace add failed:
73
75
  ${add.output}`);const update=command("plugin","marketplace","update",MARKETPLACE);if(update.status!==0)throw new Error(`plugin marketplace update failed:
74
76
  ${update.output}`)}function installedForRefresh(){const config2=process.env.CLAUDE_CONFIG_DIR?.trim()||join4(homedir3(),".claude");const cache=process.env.CLAUDE_CODE_PLUGIN_CACHE_DIR?.trim()||join4(config2,"plugins");const path=join4(cache,"installed_plugins.json");if(!existsSync3(path))return[];let records;try{records=JSON.parse(readFileSync3(path,"utf8")).plugins}catch{throw new Error("Claude's plugin records could not be read, so Cotal cannot verify their upgrade")}if(!records||typeof records!=="object"||Array.isArray(records))throw new Error("Claude's plugin records have an unsupported shape, so Cotal cannot verify their upgrade");for(const name of["cotal","cotal-skills"]){const entries=records[`${name}@${MARKETPLACE}`];if(entries!==void 0&&(!Array.isArray(entries)||entries.length>0)){if(!claudeAvailable())throw new Error(`${name}@${MARKETPLACE} is installed, but Claude Code is unavailable. Restore Claude Code or open Desktop's Code tab, then retry the Cotal update.`);return listPlugins()}}return[]}function listPlugins(cwd=process.cwd()){const result=commandIn(cwd,"plugin","list","--json");if(result.status!==0)throw new Error(`plugin list failed:
75
77
  ${result.output}`);let entries;try{entries=JSON.parse(result.output)}catch{throw new Error(`could not parse plugin list:
@@ -78,5 +80,5 @@ ${result.output}`);return entries}function verify(name,scope,expectedVersion){co
78
80
  ${result.output}`);if(/already installed/i.test(result.output)){const update=command("plugin","update",`${name}@${MARKETPLACE}`,"--scope",scope);if(update.status!==0)throw new Error(`plugin update failed (${name}):
79
81
  ${update.output}`)}verify(name,scope,expectedVersion)}function refreshInstalls(name,entries,version2){const warnings=[];for(const entry of entries){const scope=entry.scope;if(scope!=="user"&&scope!=="local"&&scope!=="project")throw new Error(`cannot refresh ${name}@${MARKETPLACE} at ${String(scope)} scope; its administrator must update it`);const cwd=scope==="user"?cotalHome():entry.projectPath;if(typeof cwd!=="string")throw new Error(`${name}@${MARKETPLACE} (${scope} scope) has no project path`);if(!statSync2(cwd,{throwIfNoEntry:false})?.isDirectory())continue;if(resolvedPluginCurrent(entry,version2,name))continue;const where=scope==="user"?"user scope":`${scope} scope, ${cwd}`;const update=commandIn(cwd,"plugin","update",`${name}@${MARKETPLACE}`,"--scope",scope);if(update.status!==0)throw new Error(`plugin update failed (${name}, ${where}):
80
82
  ${update.output}`);const current=listPlugins(cwd).find(candidate=>candidate.id===entry.id&&candidate.scope===scope&&(scope==="user"||candidate.projectPath===entry.projectPath));if(current&&resolvedPluginCurrent(current,version2,name))continue;const stale=`${name}@${MARKETPLACE} (${where}) did not load the updated plugin ${version2}`;if(scope==="user")throw new Error(stale);warnings.push(`warning: ${stale}; to remove it, run \`claude plugin uninstall ${name}@${MARKETPLACE} --scope ${scope}\` in that directory`)}return warnings}function resolvedPluginCurrent(entry,version2,name="cotal"){const sourceRoot=name==="cotal"?PACKAGE_ROOT:join4(marketplaceDir(),name);const assets=name==="cotal"?COTAL_ASSETS:[".claude-plugin","skills"];const root=entry.readFromFolder??entry.installPath;if(typeof root!=="string")return false;try{const manifest=JSON.parse(readFileSync3(join4(root,".claude-plugin","plugin.json"),"utf8"));if(manifest.version!==version2)return false;const record2=name==="cotal"?JSON.parse(readFileSync3(join4(marketplaceDir(),"cotal","dist",CLI_RECORD),"utf8")):void 0;const generated=record2?pluginFiles(record2.argv):{};const same=asset=>{const source=join4(sourceRoot,asset);const target=join4(root,asset);const generatedText=generated[asset.replaceAll("\\","/")];if(generatedText!==void 0)return readFileSync3(target).equals(Buffer.from(generatedText));if(statSync2(source).isDirectory())return readdirSync(source).every(name2=>same(join4(asset,name2)));if(asset===join4(".claude-plugin","plugin.json")){const expected=JSON.parse(readFileSync3(source,"utf8"));return JSON.stringify({...expected,version:version2})===JSON.stringify(manifest)}return readFileSync3(source).equals(readFileSync3(target))};return assets.every(same)&&(name!=="cotal"||readFileSync3(join4(root,"dist",CLI_RECORD)).equals(readFileSync3(join4(marketplaceDir(),"cotal","dist",CLI_RECORD))))}catch{return false}}function retireProjectInstalls(entries=listPlugins()){let removed=0;const failed=[];for(const entry of entries){if(entry.id!==`cotal@${MARKETPLACE}`||entry.scope!=="local"||typeof entry.projectPath!=="string")continue;if(!statSync2(entry.projectPath,{throwIfNoEntry:false})?.isDirectory())continue;const result=commandIn(entry.projectPath,"plugin","uninstall",`cotal@${MARKETPLACE}`,"--scope","local");if(result.status===0)removed+=1;else failed.push(`${entry.projectPath}: ${result.output}`)}if(failed.length)throw new Error(`cotal@${MARKETPLACE} is installed at user scope, but ${failed.length} earlier per-project install${failed.length===1?"":"s"} could not be removed. In each directory, run \`claude plugin uninstall cotal@${MARKETPLACE} --scope local\`:
81
- ${failed.join("\n")}`);return removed}function offForAccount(){const path=join4(process.env.CLAUDE_CONFIG_DIR?.trim()||join4(homedir3(),".claude"),"settings.json");if(!existsSync3(path))return false;const settings=JSON.parse(readFileSync3(path,"utf8"));return settings.enabledPlugins?.[`cotal@${MARKETPLACE}`]===false}function promoteLocalOnly(installs,version2){if(installs.some(entry=>entry.scope!=="local"&&entry.scope!=="project")||offForAccount())return void 0;const on=installs.filter(entry=>{const project=entry.projectPath;if(entry.scope!=="local"||typeof project!=="string"||!statSync2(project,{throwIfNoEntry:false})?.isDirectory())return false;return listPlugins(project).some(own=>own.id===entry.id&&own.scope==="local"&&own.projectPath===project&&own.enabled===true)});if(!on.length)return void 0;install("cotal","user",version2);return retireProjectInstalls(on)}function pluginList(){try{const result=command("plugin","list","--json");if(result.status!==0)return void 0;const parsed=JSON.parse(result.output||"[]");return Array.isArray(parsed)?parsed:void 0}catch{return void 0}}function skillsRow(entries,{version:version2,skillsRemedy}){const row=(state,text)=>({label:"Claude skills",state,text});if(entries===void 0)return row("off","unknown");const match=entries.find(entry=>entry.id===`cotal-skills@${MARKETPLACE}`&&entry.scope==="user");if(!match||match.enabled===false)return row("off",`not installed \xB7 ${skillsRemedy}`);const errors=match.errors??match.error;if(Array.isArray(errors)?errors.length>0:Boolean(errors))return row("error",`load error \xB7 ${skillsRemedy}`);if(resolvedPluginCurrent(match,version2,"cotal-skills"))return row("ok","current");return row("warn",`${typeof match.version==="string"?`v${match.version} \u2260 v${version2} \xB7 `:""}stale \xB7 ${skillsRemedy}`)}function pluginRow(entries,{version:version2}){const row=(state,text)=>({label:"Claude plugin",state,text});if(entries===void 0)return row("off","unknown");const installs=entries.filter(entry=>entry.id===`cotal@${MARKETPLACE}`);if(!installs.length)return row("off","not installed");if(installs.some(entry=>Array.isArray(entry.errors)?entry.errors.length>0:Boolean(entry.errors??entry.error)))return row("error","load error \xB7 run `cotal setup`");let materialized;try{materialized=JSON.parse(readFileSync3(join4(marketplaceDir(),"cotal",".claude-plugin","plugin.json"),"utf8")).version}catch{materialized=void 0}if(typeof materialized!=="string"||!materialized.startsWith(`${version2}+`))return row("warn","stale \xB7 run `cotal setup`");const active=installs.filter(entry=>entry.scope==="user"||typeof entry.projectPath!=="string"||statSync2(entry.projectPath,{throwIfNoEntry:false})?.isDirectory());if(active.some(entry=>!resolvedPluginCurrent(entry,materialized)))return row("warn","stale \xB7 run `cotal setup`");if(installs.some(entry=>entry.scope==="user"))return row("ok","current (user scope)");return row("ok",`current (${installs.length} install${installs.length===1?"":"s"})`)}function desktopRow(signedIn){const path=desktopConfigPath();if(!path||!existsSync3(dirname2(path)))return void 0;const row=(state,text)=>({label:"Claude Desktop",state,text});let entry;try{entry=readDesktopEntry(path)}catch(e){return row("error",e.message)}if(signedIn)return entry===void 0?row("off",hostedConnector(signedIn)):row("warn",`added, but Desktop ${hostedConnector(signedIn)}`);if(entry===void 0)return row("off","not added \xB7 run `cotal setup`");const server=entry.args;const expected=join4(marketplaceDir(),"cotal","dist","seat.cjs");if(!Array.isArray(server)||server[0]!==expected||!existsSync3(expected))return row("warn","stale \xB7 run `cotal setup`");return row("ok","added")}function copyable(name,spec){if(mcpServerProblem2(name,spec)!==void 0)return false;const{env,headers}=spec;return[env,headers].every(values=>values===void 0||Object.values(values).every(v=>v.replace(ENV_REFERENCE,"")===""))}var assistSession;function materializeSkills({skillsDir,version:version2,stateDir}){const manifestRoot=join4(PACKAGE_ROOT,"skills-plugin");if(!existsSync3(join4(manifestRoot,".claude-plugin","plugin.json")))throw new Error("Claude skills plugin manifest is missing");const payload=join4(stateDir,`.claude-skills-payload.${process.pid}`);rmSync(payload,{recursive:true,force:true});try{mkdirSync(stateDir,{recursive:true});mkdirSync(payload);cpSync(join4(manifestRoot,".claude-plugin"),join4(payload,".claude-plugin"),{recursive:true,dereference:true});cpSync(skillsDir,join4(payload,"skills"),{recursive:true,dereference:true});materialize("cotal-skills",payload,[".claude-plugin","skills"],version2)}finally{rmSync(payload,{recursive:true,force:true})}}var claudeSetupProvider={kind:"connector-setup",name:"claude",requires:["claude"],available:claudeAvailable,connector:{name:"claude-plugin",title:"Install the Claude Code plugin",explain:"Installs Cotal messaging for Claude Code, including supported local sessions in Desktop's Code tab. Reopen Claude after setup.",context:[DOCS_URL],run({cotal,signedIn}){return withPluginLock(()=>{const version2=materializeCotal(cotal);install("cotal","user",version2);const app=desktop(cotal,true,signedIn);const removed=retireProjectInstalls();const replaced=removed?`, replacing ${removed} project install${removed===1?"":"s"}`:"";return`cotal@${MARKETPLACE} (user scope${replaced})${app?`; ${app}`:""}`})}},refresh:{name:"claude-plugin-refresh",title:"Refresh the Claude Code plugin",explain:"Rewrites the copy of the Cotal plugin that Claude Code sessions load, and Cotal's entry in Claude Desktop, for this release.",context:[DOCS_URL],run({cotal,skills}){return withPluginLock(()=>{const entries=installedForRefresh();const installs=entries.filter(entry=>entry.id===`cotal@${MARKETPLACE}`);const skillInstalls=entries.filter(entry=>entry.id===`cotal-skills@${MARKETPLACE}`);const path=desktopConfigPath();const app=path!==void 0&&readDesktopEntry(path)!==void 0;if(!installs.length&&!skillInstalls.length&&!app)return"not installed";if(skillInstalls.length&&!skills)throw new Error("current skills are required to refresh the installed Claude skills plugin");const version2=installs.length||app?materializeCotal(cotal):void 0;if(skillInstalls.length)materializeSkills(skills);if(installs.length||skillInstalls.length)writeMarketplace();const parts=[];if(installs.length){const promoted=promoteLocalOnly(installs,version2);const current=promoted===void 0?installs:listPlugins().filter(entry=>entry.id===`cotal@${MARKETPLACE}`);const warnings=refreshInstalls("cotal",current,version2);if(promoted!==void 0)parts.push(`cotal@${MARKETPLACE} (user scope${promoted?`, replacing ${promoted} project install${promoted===1?"":"s"}`:""})`);parts.push(`cotal@${MARKETPLACE} ${version2}; reload plugins or reopen Claude to load it in running sessions`,...warnings)}if(skillInstalls.length){const warnings=refreshInstalls("cotal-skills",skillInstalls,skills.version);parts.push(`cotal-skills@${MARKETPLACE} ${skills.version}`,...warnings)}const desktopText=app?desktop(cotal,false):void 0;if(desktopText)parts.push(desktopText);return parts.join("; ")})}},skills:{name:"claude-skills-plugin",title:"Add Cotal's skills to Claude Code",explain:"Installs Cotal's authored skills as a Claude Code plugin.",context:[DOCS_URL],run(input){return withPluginLock(()=>{materializeSkills(input);install("cotal-skills","user",input.version);return`cotal-skills@${MARKETPLACE} (user scope)`})}},mcpServers:{name:"claude-mcp-servers",title:"Share your MCP servers with spawned sessions",explain:"A spawned Claude Code session gets the cotal tools plus the MCP servers your own sessions load. Each spawn starts its own copy of every shared server, so on a small machine remove the heavy ones from the cotal config or spawn with --share-tools none.",context:[DOCS_URL],run({seed}){const installed=Object.entries(claudeUserMcpServers());const shared=Object.fromEntries(installed.filter(entry=>copyable(...entry)));const left=installed.filter(entry=>!copyable(...entry)).map(([name])=>name);const path=globalConfigPath();if(!seed(shared))return`kept the list ${path} already declares`;const parts=[`${Object.keys(shared).join(", ")||"none"} via ${path}`];if(left.length)parts.push(`not shared: ${left.join(", ")} (setup copies a server only when it is well formed and its env and headers values are all \${VAR} references; add it to ${path} by hand to share it)`);return parts.join("; ")}},assist:{title:"Claude",run(prompt){const sessionArgs=assistSession?["--resume",assistSession]:["--session-id",assistSession=randomUUID()];const child=spawn(claudeCommand(),[prompt,"--permission-mode","auto",...sessionArgs],{stdio:"inherit"});return new Promise((resolve2,reject)=>{child.on("exit",()=>resolve2());child.on("error",reject)})}},status(input){const plugins=pluginList();const app=desktopRow(input.signedIn);return[pluginRow(plugins,input),...app?[app]:[],skillsRow(plugins,input)]}};registry3.register(claudeSetupProvider);import{resolve}from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";import{loadAgentFile as loadAgentFile2,registry as registry4,writeLaunchArtifact}from"@cotal-ai/core";import{createHash as createHash3}from"node:crypto";import{execFileSync}from"node:child_process";import{constants,copyFileSync,lstatSync,mkdirSync as mkdirSync2,readdirSync as readdirSync2,readFileSync as readFileSync4,writeFileSync as writeFileSync3}from"node:fs";import{homedir as homedir4,hostname as hostname3}from"node:os";import{join as join5}from"node:path";import{writePrivateRecord as writePrivateRecord2}from"@cotal-ai/core";var SEAT_PROJECT="seat";var FORK_RECORD="cotal-fork.json";var MIN_VERSION=[2,1,234];var MAX_TITLE=1024;function configDir(env){return env.CLAUDE_CONFIG_DIR||join5(env.HOME||homedir4(),".claude")}function transcripts(env){const projects=join5(configDir(env),"projects");let dirs;try{dirs=readdirSync2(projects,{withFileTypes:true}).filter(d=>d.isDirectory()).map(d=>join5(projects,d.name))}catch(e){if(e.code==="ENOENT")return[];throw e}return dirs.flatMap(dir=>readdirSync2(dir,{withFileTypes:true}).filter(f=>f.isFile()&&f.name.endsWith(".jsonl")).map(f=>join5(dir,f.name)))}function titleOf(path){let title;for(const line of readFileSync4(path,"utf8").split("\n")){try{const entry=JSON.parse(line);if(entry.type==="custom-title"&&typeof entry.customTitle==="string")title=entry.customTitle}catch{}}return title}function sha256(path){return createHash3("sha256").update(readFileSync4(path)).digest("hex")}var claudeResumeTranscript={find(id,env){const all=transcripts(env);const held=all.filter(p=>p.endsWith(`/${id}.jsonl`));if(held.length>0){const digests=new Set(held.map(sha256));if(digests.size>1)throw new Error(`session ${id} is held by ${digests.size} different transcripts on this host (${held.join(", ")}); remove the stale copy`);const title=titleOf(held[0]);if(title!==void 0&&title.length>MAX_TITLE)throw new Error(`session ${id} has a title of ${title.length} characters; a carried session's title is at most ${MAX_TITLE}`);return{path:held[0],...title?{title}:{}}}const named=all.filter(p=>titleOf(p)===id);if(named.length===0)return void 0;const rows=named.map(p=>{const sid=p.slice(p.lastIndexOf("/")+1,-".jsonl".length);return` ${hostname3()} ${sid} sha256:${sha256(p)} ${lstatSync(p).mtime.toISOString()}`});throw new Error(`"${id}" is a session name, not a session id; resume by id:
82
- ${rows.join("\n")}`)}};function versionAtLeast(text){const m=/(\d+)\.(\d+)\.(\d+)/.exec(text);if(!m)return false;const v=[Number(m[1]),Number(m[2]),Number(m[3])];for(let i=0;i<3;i++)if(v[i]!==MIN_VERSION[i])return v[i]>MIN_VERSION[i];return true}function refuseCarriedLaunch(binary,seatEnv){const version2=execFileSync(binary,["--version"],{encoding:"utf8",timeout:1e4});if(!versionAtLeast(version2))throw new Error(`claude connector: a carried resume needs Claude ${MIN_VERSION.join(".")} or later (CLAUDE_CODE_PROJECT_DIR_NAME); this host runs ${version2.trim()}`);const provider=Object.keys(seatEnv).some(k=>k.startsWith("CLAUDE_CODE_USE_")&&seatEnv[k]!==""&&seatEnv[k]!=="0");if(!seatEnv.CLAUDE_CODE_OAUTH_TOKEN&&!seatEnv.ANTHROPIC_AUTH_TOKEN&&!provider)throw new Error("claude connector: a carried resume runs in a seat-private Claude home that holds no login"+(seatEnv.ANTHROPIC_API_KEY?", and ANTHROPIC_API_KEY alone needs an approval that home cannot remember":"")+"; run `claude setup-token` and set CLAUDE_CODE_OAUTH_TOKEN in the manager's environment")}function carriedForkRecord(home){return join5(home,FORK_RECORD)}function placeCarried(home,transcript,resume,cwd){writePrivateRecord2(join5(home,".claude.json"),JSON.stringify({hasCompletedOnboarding:true,projects:{[cwd]:{hasTrustDialogAccepted:true}}}));if(resume!==void 0){const dir=join5(home,"projects",SEAT_PROJECT);mkdirSync2(dir,{recursive:true,mode:448});copyFileSync(transcript,join5(dir,`${resume}.jsonl`),constants.COPYFILE_EXCL)}return{CLAUDE_CONFIG_DIR:home,CLAUDE_CODE_PROJECT_DIR_NAME:SEAT_PROJECT,...resume!==void 0?{COTAL_CLAUDE_CARRIED:resume}:{}}}var CLAUDE_WORKSPACE_TRUST_REPLIES=Object.freeze([Object.freeze({prompt:"\u276F 1. Yes, I trust this folder\n2. No, exit",key:"Enter",optional:true}),Object.freeze({prompt:"\u276F No, exit\nYes, I trust this folder",key:"Down"}),Object.freeze({prompt:"No, exit\n\u276F Yes, I trust this folder",key:"Enter"})]);var CLAUDE_READY_TEXTS=Object.freeze(["(shift+tab to cycle)","? for shortcuts"]);var CLAUDE_STARTUP_BLOCKERS=Object.freeze([Object.freeze({prompt:"Choose the text style that looks best with your terminal",reason:"Claude Code is showing its first-run setup, which Cotal does not answer. Run `claude` once in a terminal as this user, finish setup and log in, then launch again."}),Object.freeze({prompt:"Select login method:",reason:"Claude Code is not logged in for this user and asks for a login method, which Cotal does not answer. Run `claude` once in a terminal and log in, or pass a credential the connector forwards, such as CLAUDE_CODE_OAUTH_TOKEN, then launch again."}),Object.freeze({prompt:"WARNING: Claude Code running in Bypass Permissions mode",reason:"Claude Code asks this user to accept Bypass Permissions mode, which a managed seat uses by default, and Cotal never accepts it for you. Accept it once yourself with `claude --permission-mode bypassPermissions` in a terminal, or launch with permission-mode=default (`--opt permission-mode=default`, or `launchOptions` in a manifest)."})]);import{accessSync,constants as constants2,readFileSync as readFileSync5,realpathSync,statSync as statSync3}from"node:fs";import{delimiter,isAbsolute,join as join6}from"node:path";var HOST_EXE_ENV="COTAL_CLAUDE_EXE";function resolveHostExe(binary,env){if(process.platform!=="linux")return void 0;const candidates=binary.includes("/")?[binary]:(env.PATH??"").split(delimiter).filter(d=>isAbsolute(d)).map(d=>join6(d,binary));for(const c of candidates){try{if(!statSync3(c).isFile())continue;accessSync(c,constants2.X_OK);return realpathSync(c)}catch{}}return void 0}var HOOK_CONTEXT_CHARS=9e3;var MCP_SERVER_NAME="cotal";var CLAUDE_PROVIDER_KEYS=["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_OAUTH_REFRESH_TOKEN","CLAUDE_CODE_OAUTH_SCOPES","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_MANTLE","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH","CLAUDE_CODE_SKIP_MANTLE_AUTH","CLAUDE_CODE_SKIP_AWS_CRED_CACHE","CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS","ANTHROPIC_AWS_API_KEY","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_AWS_WORKSPACE_ID","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_PROFILE","AWS_REGION","AWS_DEFAULT_REGION","AWS_SHARED_CREDENTIALS_FILE","AWS_CONFIG_FILE","AWS_BEARER_TOKEN_BEDROCK","ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL","ANTHROPIC_BEDROCK_REGION_PREFIX","ANTHROPIC_BEDROCK_SERVICE_TIER","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","ANTHROPIC_VERTEX_BASE_URL","ANTHROPIC_VERTEX_PROJECT_ID","GOOGLE_APPLICATION_CREDENTIALS","CLOUD_ML_REGION","GCLOUD_PROJECT","GOOGLE_CLOUD_PROJECT","VERTEX_REGION_CLAUDE_3_5_HAIKU","VERTEX_REGION_CLAUDE_3_5_SONNET","VERTEX_REGION_CLAUDE_3_7_SONNET","VERTEX_REGION_CLAUDE_4_0_OPUS","VERTEX_REGION_CLAUDE_4_0_SONNET","VERTEX_REGION_CLAUDE_4_1_OPUS","VERTEX_REGION_CLAUDE_4_5_OPUS","VERTEX_REGION_CLAUDE_4_5_SONNET","VERTEX_REGION_CLAUDE_4_6_OPUS","VERTEX_REGION_CLAUDE_4_6_SONNET","VERTEX_REGION_CLAUDE_4_7_OPUS","VERTEX_REGION_CLAUDE_4_8_OPUS","VERTEX_REGION_CLAUDE_5_OPUS","VERTEX_REGION_CLAUDE_5_SONNET","VERTEX_REGION_CLAUDE_FABLE_5","VERTEX_REGION_CLAUDE_FABLE_5_1","VERTEX_REGION_CLAUDE_HAIKU_4_5","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_FOUNDRY_AUTH_TOKEN","ANTHROPIC_FOUNDRY_BASE_URL","ANTHROPIC_FOUNDRY_RESOURCE","ANTHROPIC_PROFILE","ANTHROPIC_FEDERATION_RULE_ID","ANTHROPIC_ORGANIZATION_ID","ANTHROPIC_WORKSPACE_ID","ANTHROPIC_IDENTITY_TOKEN","ANTHROPIC_IDENTITY_TOKEN_FILE"];var CHANNEL_REF=`server:${MCP_SERVER_NAME}`;var PLUGIN_ROOT=fileURLToPath2(new URL("..",import.meta.url));var SEAT_ENTRY=resolve(PLUGIN_ROOT,"dist","seat.cjs");var CLAUDE_MCP_KEYS=["ENABLE_CLAUDEAI_MCP_SERVERS","ENABLE_TOOL_SEARCH","MCP_TIMEOUT","MCP_CONNECTION_NONBLOCKING"];function assertServableModel(model){if(!model.includes("/")||model.startsWith("arn:"))return;throw new Error(`claude connector: cannot serve model ${JSON.stringify(model)} - a "provider/model" specifier belongs to another runtime (use the opencode connector for it). Refusing at launch: passing it through starts a session on a DIFFERENT model than the one named, and everything that session produces would carry the wrong attribution.`)}var claudeConnector={kind:"connector",name:"claude",setup:{kind:"connector-setup",name:"claude"},eventChannel:eventChannel3,pluginRoot:PLUGIN_ROOT,requires:["claude"],supportsResume:true,resumeTranscript:claudeResumeTranscript,supportsToolListAnnounce:true,supportsPrompt:true,supportsTurnRelay:true,onceNeedsConfirmed:"its startup did not show channels on (Claude's development-channels prompt and its notice that server:cotal messages reach the session)",turnFrameLimit:HOOK_CONTEXT_CHARS,launchHint:"press Enter at the dev-channels prompt",waitsForOperator:launchOptions=>launchOptions?.resume===""?"Claude's session picker":void 0,buildLaunch(opts){if(opts.continueSession)throw new Error("claude connector does not support exact-session continuation");if(opts.variant)throw new Error("claude connector: model variants are not supported");const shared=opts.mcpServers??{};const exclusive=opts.mcpServersExclusive===true||opts.carried!==void 0;const nativeEnvKeys=exclusive?[]:claudeUserMcpEnvKeys();const control=controlEndpoint(opts.space,opts.name);const env={...launchEnv({providerKeys:CLAUDE_PROVIDER_KEYS,mcpKeys:[...mcpServerEnvKeys(shared),...nativeEnvKeys,...CLAUDE_MCP_KEYS],envAllow:opts.envAllow}),...aclEnv(opts),COTAL_SPACE:opts.space,COTAL_NAME:opts.name,COTAL_CHANNEL:"1",COTAL_CONTROL_SOCKET:control.path};if(launchArmsEvents(opts)){env.COTAL_EVENTS="1";if(!opts.workspaceRoot)throw new Error("claude connector: events were requested but the launch carries no workspaceRoot, so the event write-ahead log has nowhere to live that a later start would look. Refusing rather than defaulting to the working directory.");env.COTAL_WORKSPACE_ROOT=opts.workspaceRoot}const named=opts.resolvedBinaries?.claude??"claude";const hostExe=opts.once?resolveHostExe(named,env):void 0;if(hostExe!==void 0)env[HOST_EXE_ENV]=hostExe;const binary=hostExe??named;if(opts.carried)refuseCarriedLaunch(binary,env);if(opts.role)env.COTAL_ROLE=opts.role;if(opts.id)env.COTAL_ID=opts.id;if(opts.lifecycleUid)env.COTAL_LIFECYCLE_UID=opts.lifecycleUid;if(opts.backfillFloor!==void 0)env.COTAL_BACKFILL_FLOOR=String(opts.backfillFloor);if(opts.acceptedToken)env.COTAL_ACCEPTED_TOKEN=opts.acceptedToken;const prompt=opts.prompt===void 0?void 0:opts.prompt.trim();if(prompt==="")throw new Error("claude connector: an initial prompt was given but it is empty, there is no first turn to submit");const args=prompt?[prompt,"--dangerously-load-development-channels",CHANNEL_REF,"--plugin-dir",PLUGIN_ROOT]:["--dangerously-load-development-channels",CHANNEL_REF,"--plugin-dir",PLUGIN_ROOT];args.push("--allowedTools","WebFetch(domain:github.com),WebFetch(domain:raw.githubusercontent.com)");const mcpServers={...shared,[MCP_SERVER_NAME]:{command:"node",args:["--optimize-for-size","--max-semi-space-size=1",SEAT_ENTRY]}};const agentFile=opts.configPath?resolve(opts.configPath):void 0;const def=agentFile?loadAgentFile2(agentFile):void 0;if(opts.model)assertServableModel(opts.model);const passthrough=connectorLaunchOptions("claude",opts.launchOptions).map(([k,v])=>[k,String(v)]);const artifacts=[];Object.assign(env,materialEnv({creds:opts.creds,servers:opts.servers,controlToken:control.token,eventsRequired:opts.eventsRequired,userAuth:opts.userAuth},artifacts));let mcpConfig;if(Object.keys(shared).length===0){mcpConfig=JSON.stringify({mcpServers})}else{mcpConfig=writeLaunchArtifact(artifacts,"cotal-mcp-","mcp.json",JSON.stringify({mcpServers},null,2))}if(exclusive)args.push("--strict-mcp-config");args.push("--mcp-config",mcpConfig);if(agentFile)env.COTAL_AGENT_FILE=agentFile;if(def?.persona){args.push("--append-system-prompt-file",writeLaunchArtifact(artifacts,"cotal-claude-persona-","persona.md",def.persona))}if(opts.model){args.push("--model",opts.model);env.COTAL_MODEL=opts.model}if(opts.resume)args.push("--resume",opts.resume,"--fork-session");if(opts.carried)Object.assign(env,placeCarried(opts.carried.home,opts.carried.transcript,opts.resume,opts.carried.cwd));if(opts.cwd&&!passthrough.some(([k])=>k==="permission-mode"||k==="dangerously-skip-permissions"))args.push("--permission-mode","bypassPermissions");for(const[k,val]of passthrough){if(val==="")args.push(`--${k}`);else args.push(`--${k}`,val)}return{command:binary,args,env,confirm:"WARNING: Loading development channels",...opts.once?{confirmNotice:`messages from ${CHANNEL_REF} inject directly in this session`}:{},confirmReady:CLAUDE_READY_TEXTS,confirmBlockers:CLAUDE_STARTUP_BLOCKERS,...opts.cwd?{confirmBefore:CLAUDE_WORKSPACE_TRUST_REPLIES}:{},control,...opts.carried?{resumeRecordPath:carriedForkRecord(opts.carried.home)}:{},...artifacts.length>0?{artifacts}:{}}}};registry4.register(claudeConnector);export{CLAUDE_PROVIDER_KEYS,claudeConnector,claudeSetupProvider,marketplaceManifest,materialize,writeMarketplaceManifest};
83
+ ${failed.join("\n")}`);return removed}function offForAccount(){const path=join4(process.env.CLAUDE_CONFIG_DIR?.trim()||join4(homedir3(),".claude"),"settings.json");if(!existsSync3(path))return false;const settings=JSON.parse(readFileSync3(path,"utf8"));return settings.enabledPlugins?.[`cotal@${MARKETPLACE}`]===false}function promoteLocalOnly(installs,version2){if(installs.some(entry=>entry.scope!=="local"&&entry.scope!=="project")||offForAccount())return void 0;const on=installs.filter(entry=>{const project=entry.projectPath;if(entry.scope!=="local"||typeof project!=="string"||!statSync2(project,{throwIfNoEntry:false})?.isDirectory())return false;return listPlugins(project).some(own=>own.id===entry.id&&own.scope==="local"&&own.projectPath===project&&own.enabled===true)});if(!on.length)return void 0;install("cotal","user",version2);return retireProjectInstalls(on)}function pluginList(){try{const result=command("plugin","list","--json");if(result.status!==0)return void 0;const parsed=JSON.parse(result.output||"[]");return Array.isArray(parsed)?parsed:void 0}catch{return void 0}}function skillsRow(entries,{version:version2,skillsRemedy}){const row=(state,text)=>({label:"Claude skills",state,text});if(entries===void 0)return row("off","unknown");const match=entries.find(entry=>entry.id===`cotal-skills@${MARKETPLACE}`&&entry.scope==="user");if(!match||match.enabled===false)return row("off",`not installed \xB7 ${skillsRemedy}`);const errors=match.errors??match.error;if(Array.isArray(errors)?errors.length>0:Boolean(errors))return row("error",`load error \xB7 ${skillsRemedy}`);if(resolvedPluginCurrent(match,version2,"cotal-skills"))return row("ok","current");return row("warn",`${typeof match.version==="string"?`v${match.version} \u2260 v${version2} \xB7 `:""}stale \xB7 ${skillsRemedy}`)}function pluginRow(entries,{version:version2}){const row=(state,text)=>({label:"Claude plugin",state,text});if(entries===void 0)return row("off","unknown");const installs=entries.filter(entry=>entry.id===`cotal@${MARKETPLACE}`);if(!installs.length)return row("off","not installed");if(installs.some(entry=>Array.isArray(entry.errors)?entry.errors.length>0:Boolean(entry.errors??entry.error)))return row("error","load error \xB7 run `cotal setup`");let materialized;try{materialized=JSON.parse(readFileSync3(join4(marketplaceDir(),"cotal",".claude-plugin","plugin.json"),"utf8")).version}catch{materialized=void 0}if(typeof materialized!=="string"||!materialized.startsWith(`${version2}+`))return row("warn","stale \xB7 run `cotal setup`");const active=installs.filter(entry=>entry.scope==="user"||typeof entry.projectPath!=="string"||statSync2(entry.projectPath,{throwIfNoEntry:false})?.isDirectory());if(active.some(entry=>!resolvedPluginCurrent(entry,materialized)))return row("warn","stale \xB7 run `cotal setup`");if(installs.some(entry=>entry.scope==="user"))return row("ok","current (user scope)");return row("ok",`current (${installs.length} install${installs.length===1?"":"s"})`)}function desktopRow(signedIn){const path=desktopConfigPath();if(!path||!existsSync3(dirname2(path)))return void 0;const row=(state,text)=>({label:"Claude Desktop",state,text});let entry;try{entry=readDesktopEntry(path)}catch(e){return row("error",e.message)}if(signedIn)return entry===void 0?row("off",hostedConnector(signedIn)):row("warn",`added, but Desktop ${hostedConnector(signedIn)}`);if(entry===void 0)return row("off","not added \xB7 run `cotal setup`");const server=entry.args;const expected=join4(marketplaceDir(),"cotal","dist","seat.cjs");if(!Array.isArray(server)||server[0]!==expected||!existsSync3(expected))return row("warn","stale \xB7 run `cotal setup`");return row("ok","added")}function copyable(name,spec){if(mcpServerProblem2(name,spec)!==void 0)return false;const{env,headers}=spec;return[env,headers].every(values=>values===void 0||Object.values(values).every(v=>v.replace(ENV_REFERENCE,"")===""))}var assistSession;function materializeSkills({skillsDir,version:version2,stateDir}){const manifestRoot=join4(PACKAGE_ROOT,"skills-plugin");if(!existsSync3(join4(manifestRoot,".claude-plugin","plugin.json")))throw new Error("Claude skills plugin manifest is missing");const payload=join4(stateDir,`.claude-skills-payload.${process.pid}`);rmSync(payload,{recursive:true,force:true});try{mkdirSync(stateDir,{recursive:true});mkdirSync(payload);cpSync(join4(manifestRoot,".claude-plugin"),join4(payload,".claude-plugin"),{recursive:true,dereference:true});cpSync(skillsDir,join4(payload,"skills"),{recursive:true,dereference:true});materialize("cotal-skills",payload,[".claude-plugin","skills"],version2)}finally{rmSync(payload,{recursive:true,force:true})}}var claudeSetupProvider={kind:"connector-setup",name:"claude",requires:["claude"],available:claudeAvailable,connector:{name:"claude-plugin",title:"Install the Claude Code plugin",explain:"Installs Cotal messaging for Claude Code, including supported local sessions in Desktop's Code tab. Reopen Claude after setup.",context:[DOCS_URL],run({cotal,signedIn}){return withPluginLock(()=>{const version2=materializeCotal(cotal);install("cotal","user",version2);const entry=registerUserServer(cotal);const app=desktop(cotal,true,signedIn);const removed=retireProjectInstalls();const replaced=removed?`, replacing ${removed} project install${removed===1?"":"s"}`:"";return`cotal@${MARKETPLACE} (user scope${replaced}); ${entry}${app?`; ${app}`:""}`})}},refresh:{name:"claude-plugin-refresh",title:"Refresh the Claude Code plugin",explain:"Rewrites the copy of the Cotal plugin that Claude Code sessions load, and Cotal's entry in Claude Desktop, for this release.",context:[DOCS_URL],run({cotal,skills}){return withPluginLock(()=>{const entries=installedForRefresh();const installs=entries.filter(entry=>entry.id===`cotal@${MARKETPLACE}`);const skillInstalls=entries.filter(entry=>entry.id===`cotal-skills@${MARKETPLACE}`);const path=desktopConfigPath();const app=path!==void 0&&readDesktopEntry(path)!==void 0;if(!installs.length&&!skillInstalls.length&&!app)return"not installed";if(skillInstalls.length&&!skills)throw new Error("current skills are required to refresh the installed Claude skills plugin");const version2=installs.length||app?materializeCotal(cotal):void 0;if(skillInstalls.length)materializeSkills(skills);if(installs.length||skillInstalls.length)writeMarketplace();const parts=[];if(installs.length){const promoted=promoteLocalOnly(installs,version2);const current=promoted===void 0?installs:listPlugins().filter(entry=>entry.id===`cotal@${MARKETPLACE}`);const warnings=refreshInstalls("cotal",current,version2);if(promoted!==void 0)parts.push(`cotal@${MARKETPLACE} (user scope${promoted?`, replacing ${promoted} project install${promoted===1?"":"s"}`:""})`);parts.push(`cotal@${MARKETPLACE} ${version2}; reload plugins or reopen Claude to load it in running sessions`,...warnings);parts.push(registerUserServer(cotal))}if(skillInstalls.length){const warnings=refreshInstalls("cotal-skills",skillInstalls,skills.version);parts.push(`cotal-skills@${MARKETPLACE} ${skills.version}`,...warnings)}const desktopText=app?desktop(cotal,false):void 0;if(desktopText)parts.push(desktopText);return parts.join("; ")})}},skills:{name:"claude-skills-plugin",title:"Add Cotal's skills to Claude Code",explain:"Installs Cotal's authored skills as a Claude Code plugin.",context:[DOCS_URL],run(input){return withPluginLock(()=>{materializeSkills(input);install("cotal-skills","user",input.version);return`cotal-skills@${MARKETPLACE} (user scope)`})}},mcpServers:{name:"claude-mcp-servers",title:"Share your MCP servers with spawned sessions",explain:"A spawned Claude Code session gets the cotal tools plus the MCP servers your own sessions load. Each spawn starts its own copy of every shared server, so on a small machine remove the heavy ones from the cotal config or spawn with --share-tools none.",context:[DOCS_URL],run({seed}){const installed=Object.entries(claudeUserMcpServers());const shared=Object.fromEntries(installed.filter(entry=>copyable(...entry)));const left=installed.filter(entry=>!copyable(...entry)).map(([name])=>name);const path=globalConfigPath();if(!seed(shared))return`kept the list ${path} already declares`;const parts=[`${Object.keys(shared).join(", ")||"none"} via ${path}`];if(left.length)parts.push(`not shared: ${left.join(", ")} (setup copies a server only when it is well formed and its env and headers values are all \${VAR} references; add it to ${path} by hand to share it)`);return parts.join("; ")}},assist:{title:"Claude",run(prompt){const sessionArgs=assistSession?["--resume",assistSession]:["--session-id",assistSession=randomUUID()];const child=spawn(claudeCommand(),[prompt,"--permission-mode","auto",...sessionArgs],{stdio:"inherit"});return new Promise((resolve2,reject)=>{child.on("exit",()=>resolve2());child.on("error",reject)})}},status(input){const plugins=pluginList();const app=desktopRow(input.signedIn);return[pluginRow(plugins,input),userServerRow(),...app?[app]:[],skillsRow(plugins,input)]}};registry3.register(claudeSetupProvider);import{resolve}from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";import{loadAgentFile as loadAgentFile2,registry as registry4,writeLaunchArtifact}from"@cotal-ai/core";import{createHash as createHash3}from"node:crypto";import{execFileSync}from"node:child_process";import{constants,copyFileSync,lstatSync,mkdirSync as mkdirSync2,readdirSync as readdirSync2,readFileSync as readFileSync4,writeFileSync as writeFileSync3}from"node:fs";import{homedir as homedir4,hostname as hostname3}from"node:os";import{join as join5}from"node:path";import{writePrivateRecord as writePrivateRecord2}from"@cotal-ai/core";var SEAT_PROJECT="seat";var FORK_RECORD="cotal-fork.json";var MIN_VERSION=[2,1,234];var MAX_TITLE=1024;function configDir(env){return env.CLAUDE_CONFIG_DIR||join5(env.HOME||homedir4(),".claude")}function transcripts(env){const projects=join5(configDir(env),"projects");let dirs;try{dirs=readdirSync2(projects,{withFileTypes:true}).filter(d=>d.isDirectory()).map(d=>join5(projects,d.name))}catch(e){if(e.code==="ENOENT")return[];throw e}return dirs.flatMap(dir=>readdirSync2(dir,{withFileTypes:true}).filter(f=>f.isFile()&&f.name.endsWith(".jsonl")).map(f=>join5(dir,f.name)))}function titleOf(path){let title;for(const line of readFileSync4(path,"utf8").split("\n")){try{const entry=JSON.parse(line);if(entry.type==="custom-title"&&typeof entry.customTitle==="string")title=entry.customTitle}catch{}}return title}function sha256(path){return createHash3("sha256").update(readFileSync4(path)).digest("hex")}var claudeResumeTranscript={find(id,env){const all=transcripts(env);const held=all.filter(p=>p.endsWith(`/${id}.jsonl`));if(held.length>0){const digests=new Set(held.map(sha256));if(digests.size>1)throw new Error(`session ${id} is held by ${digests.size} different transcripts on this host (${held.join(", ")}); remove the stale copy`);const title=titleOf(held[0]);if(title!==void 0&&title.length>MAX_TITLE)throw new Error(`session ${id} has a title of ${title.length} characters; a carried session's title is at most ${MAX_TITLE}`);return{path:held[0],...title?{title}:{}}}const named=all.filter(p=>titleOf(p)===id);if(named.length===0)return void 0;const rows=named.map(p=>{const sid=p.slice(p.lastIndexOf("/")+1,-".jsonl".length);return` ${hostname3()} ${sid} sha256:${sha256(p)} ${lstatSync(p).mtime.toISOString()}`});throw new Error(`"${id}" is a session name, not a session id; resume by id:
84
+ ${rows.join("\n")}`)}};function versionAtLeast(text){const m=/(\d+)\.(\d+)\.(\d+)/.exec(text);if(!m)return false;const v=[Number(m[1]),Number(m[2]),Number(m[3])];for(let i=0;i<3;i++)if(v[i]!==MIN_VERSION[i])return v[i]>MIN_VERSION[i];return true}function refuseCarriedLaunch(binary,seatEnv){const version2=execFileSync(binary,["--version"],{encoding:"utf8",timeout:1e4});if(!versionAtLeast(version2))throw new Error(`claude connector: a carried resume needs Claude ${MIN_VERSION.join(".")} or later (CLAUDE_CODE_PROJECT_DIR_NAME); this host runs ${version2.trim()}`);const provider=Object.keys(seatEnv).some(k=>k.startsWith("CLAUDE_CODE_USE_")&&seatEnv[k]!==""&&seatEnv[k]!=="0");if(!seatEnv.CLAUDE_CODE_OAUTH_TOKEN&&!seatEnv.ANTHROPIC_AUTH_TOKEN&&!provider)throw new Error("claude connector: a carried resume runs in a seat-private Claude home that holds no login"+(seatEnv.ANTHROPIC_API_KEY?", and ANTHROPIC_API_KEY alone needs an approval that home cannot remember":"")+"; run `claude setup-token` and set CLAUDE_CODE_OAUTH_TOKEN in the manager's environment")}function carriedForkRecord(home){return join5(home,FORK_RECORD)}function placeCarried(home,transcript,resume,cwd,server){writePrivateRecord2(join5(home,".claude.json"),JSON.stringify({hasCompletedOnboarding:true,projects:{[cwd]:{hasTrustDialogAccepted:true}},mcpServers:{cotal:server}}));if(resume!==void 0){const dir=join5(home,"projects",SEAT_PROJECT);mkdirSync2(dir,{recursive:true,mode:448});copyFileSync(transcript,join5(dir,`${resume}.jsonl`),constants.COPYFILE_EXCL)}return{CLAUDE_CONFIG_DIR:home,CLAUDE_CODE_PROJECT_DIR_NAME:SEAT_PROJECT,...resume!==void 0?{COTAL_CLAUDE_CARRIED:resume}:{}}}var CLAUDE_WORKSPACE_TRUST_REPLIES=Object.freeze([Object.freeze({prompt:"\u276F 1. Yes, I trust this folder\n2. No, exit",key:"Enter",optional:true}),Object.freeze({prompt:"\u276F No, exit\nYes, I trust this folder",key:"Down"}),Object.freeze({prompt:"No, exit\n\u276F Yes, I trust this folder",key:"Enter"})]);var CLAUDE_READY_TEXTS=Object.freeze(["(shift+tab to cycle)","? for shortcuts"]);var CLAUDE_STARTUP_BLOCKERS=Object.freeze([Object.freeze({prompt:"Choose the text style that looks best with your terminal",reason:"Claude Code is showing its first-run setup, which Cotal does not answer. Run `claude` once in a terminal as this user, finish setup and log in, then launch again."}),Object.freeze({prompt:"Select login method:",reason:"Claude Code is not logged in for this user and asks for a login method, which Cotal does not answer. Run `claude` once in a terminal and log in, or pass a credential the connector forwards, such as CLAUDE_CODE_OAUTH_TOKEN, then launch again."}),Object.freeze({prompt:"WARNING: Claude Code running in Bypass Permissions mode",reason:"Claude Code asks this user to accept Bypass Permissions mode, which a managed seat uses by default, and Cotal never accepts it for you. Accept it once yourself with `claude --permission-mode bypassPermissions` in a terminal, or launch with permission-mode=default (`--opt permission-mode=default`, or `launchOptions` in a manifest)."})]);import{accessSync,constants as constants2,readFileSync as readFileSync5,realpathSync,statSync as statSync3}from"node:fs";import{delimiter,isAbsolute,join as join6}from"node:path";var HOST_EXE_ENV="COTAL_CLAUDE_EXE";function resolveHostExe(binary,env){if(process.platform!=="linux")return void 0;const candidates=binary.includes("/")?[binary]:(env.PATH??"").split(delimiter).filter(d=>isAbsolute(d)).map(d=>join6(d,binary));for(const c of candidates){try{if(!statSync3(c).isFile())continue;accessSync(c,constants2.X_OK);return realpathSync(c)}catch{}}return void 0}var HOOK_CONTEXT_CHARS=9e3;var MCP_SERVER_NAME="cotal";var CLAUDE_PROVIDER_KEYS=["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_OAUTH_REFRESH_TOKEN","CLAUDE_CODE_OAUTH_SCOPES","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_MANTLE","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH","CLAUDE_CODE_SKIP_MANTLE_AUTH","CLAUDE_CODE_SKIP_AWS_CRED_CACHE","CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS","ANTHROPIC_AWS_API_KEY","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_AWS_WORKSPACE_ID","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_PROFILE","AWS_REGION","AWS_DEFAULT_REGION","AWS_SHARED_CREDENTIALS_FILE","AWS_CONFIG_FILE","AWS_BEARER_TOKEN_BEDROCK","ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL","ANTHROPIC_BEDROCK_REGION_PREFIX","ANTHROPIC_BEDROCK_SERVICE_TIER","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","ANTHROPIC_VERTEX_BASE_URL","ANTHROPIC_VERTEX_PROJECT_ID","GOOGLE_APPLICATION_CREDENTIALS","CLOUD_ML_REGION","GCLOUD_PROJECT","GOOGLE_CLOUD_PROJECT","VERTEX_REGION_CLAUDE_3_5_HAIKU","VERTEX_REGION_CLAUDE_3_5_SONNET","VERTEX_REGION_CLAUDE_3_7_SONNET","VERTEX_REGION_CLAUDE_4_0_OPUS","VERTEX_REGION_CLAUDE_4_0_SONNET","VERTEX_REGION_CLAUDE_4_1_OPUS","VERTEX_REGION_CLAUDE_4_5_OPUS","VERTEX_REGION_CLAUDE_4_5_SONNET","VERTEX_REGION_CLAUDE_4_6_OPUS","VERTEX_REGION_CLAUDE_4_6_SONNET","VERTEX_REGION_CLAUDE_4_7_OPUS","VERTEX_REGION_CLAUDE_4_8_OPUS","VERTEX_REGION_CLAUDE_5_OPUS","VERTEX_REGION_CLAUDE_5_SONNET","VERTEX_REGION_CLAUDE_FABLE_5","VERTEX_REGION_CLAUDE_FABLE_5_1","VERTEX_REGION_CLAUDE_HAIKU_4_5","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_FOUNDRY_AUTH_TOKEN","ANTHROPIC_FOUNDRY_BASE_URL","ANTHROPIC_FOUNDRY_RESOURCE","ANTHROPIC_PROFILE","ANTHROPIC_FEDERATION_RULE_ID","ANTHROPIC_ORGANIZATION_ID","ANTHROPIC_WORKSPACE_ID","ANTHROPIC_IDENTITY_TOKEN","ANTHROPIC_IDENTITY_TOKEN_FILE"];var CHANNEL_REF=`server:${MCP_SERVER_NAME}`;var PLUGIN_ROOT=fileURLToPath2(new URL("..",import.meta.url));var SEAT_ENTRY=resolve(PLUGIN_ROOT,"dist","seat.cjs");var CLAUDE_MCP_KEYS=["ENABLE_CLAUDEAI_MCP_SERVERS","ENABLE_TOOL_SEARCH","MCP_TIMEOUT","MCP_CONNECTION_NONBLOCKING"];function assertServableModel(model){if(!model.includes("/")||model.startsWith("arn:"))return;throw new Error(`claude connector: cannot serve model ${JSON.stringify(model)} - a "provider/model" specifier belongs to another runtime (use the opencode connector for it). Refusing at launch: passing it through starts a session on a DIFFERENT model than the one named, and everything that session produces would carry the wrong attribution.`)}var claudeConnector={kind:"connector",name:"claude",setup:{kind:"connector-setup",name:"claude"},eventChannel:eventChannel3,pluginRoot:PLUGIN_ROOT,requires:["claude"],supportsResume:true,resumeTranscript:claudeResumeTranscript,supportsToolListAnnounce:true,supportsPrompt:true,supportsTurnRelay:true,onceNeedsConfirmed:"its startup did not show channels on (Claude's development-channels prompt and its notice that server:cotal messages reach the session)",turnFrameLimit:HOOK_CONTEXT_CHARS,launchHint:"press Enter at the dev-channels prompt",waitsForOperator:launchOptions=>launchOptions?.resume===""?"Claude's session picker":void 0,buildLaunch(opts){if(opts.continueSession)throw new Error("claude connector does not support exact-session continuation");if(opts.variant)throw new Error("claude connector: model variants are not supported");const shared=opts.mcpServers??{};const exclusive=opts.mcpServersExclusive===true||opts.carried!==void 0;const nativeEnvKeys=exclusive?[]:claudeUserMcpEnvKeys();const control=controlEndpoint(opts.space,opts.name);const env={...launchEnv({providerKeys:CLAUDE_PROVIDER_KEYS,mcpKeys:[...mcpServerEnvKeys(shared),...nativeEnvKeys,...CLAUDE_MCP_KEYS],envAllow:opts.envAllow}),...aclEnv(opts),COTAL_SPACE:opts.space,COTAL_NAME:opts.name,COTAL_CHANNEL:"1",COTAL_CONTROL_SOCKET:control.path};if(launchArmsEvents(opts)){env.COTAL_EVENTS="1";if(!opts.workspaceRoot)throw new Error("claude connector: events were requested but the launch carries no workspaceRoot, so the event write-ahead log has nowhere to live that a later start would look. Refusing rather than defaulting to the working directory.");env.COTAL_WORKSPACE_ROOT=opts.workspaceRoot}const named=opts.resolvedBinaries?.claude??"claude";const hostExe=opts.once?resolveHostExe(named,env):void 0;if(hostExe!==void 0)env[HOST_EXE_ENV]=hostExe;const binary=hostExe??named;if(opts.carried)refuseCarriedLaunch(binary,env);if(opts.role)env.COTAL_ROLE=opts.role;if(opts.id)env.COTAL_ID=opts.id;if(opts.lifecycleUid)env.COTAL_LIFECYCLE_UID=opts.lifecycleUid;if(opts.backfillFloor!==void 0)env.COTAL_BACKFILL_FLOOR=String(opts.backfillFloor);if(opts.acceptedToken)env.COTAL_ACCEPTED_TOKEN=opts.acceptedToken;const prompt=opts.prompt===void 0?void 0:opts.prompt.trim();if(prompt==="")throw new Error("claude connector: an initial prompt was given but it is empty, there is no first turn to submit");if(opts.cwd!==void 0&&!opts.carried)assertChannelServerDeclared(MCP_SERVER_NAME,opts.cwd);const args=prompt?[prompt,"--dangerously-load-development-channels",CHANNEL_REF,"--plugin-dir",PLUGIN_ROOT]:["--dangerously-load-development-channels",CHANNEL_REF,"--plugin-dir",PLUGIN_ROOT];args.push("--allowedTools","WebFetch(domain:github.com),WebFetch(domain:raw.githubusercontent.com)");const mcpServers={...shared,[MCP_SERVER_NAME]:{command:"node",args:["--optimize-for-size","--max-semi-space-size=1",SEAT_ENTRY]}};const agentFile=opts.configPath?resolve(opts.configPath):void 0;const def=agentFile?loadAgentFile2(agentFile):void 0;if(opts.model)assertServableModel(opts.model);const passthrough=connectorLaunchOptions("claude",opts.launchOptions).map(([k,v])=>[k,String(v)]);const artifacts=[];Object.assign(env,materialEnv({creds:opts.creds,servers:opts.servers,controlToken:control.token,eventsRequired:opts.eventsRequired,userAuth:opts.userAuth},artifacts));let mcpConfig;if(Object.keys(shared).length===0){mcpConfig=JSON.stringify({mcpServers})}else{mcpConfig=writeLaunchArtifact(artifacts,"cotal-mcp-","mcp.json",JSON.stringify({mcpServers},null,2))}if(exclusive)args.push("--strict-mcp-config");args.push("--mcp-config",mcpConfig);if(agentFile)env.COTAL_AGENT_FILE=agentFile;if(def?.persona){args.push("--append-system-prompt-file",writeLaunchArtifact(artifacts,"cotal-claude-persona-","persona.md",def.persona))}if(opts.model){args.push("--model",opts.model);env.COTAL_MODEL=opts.model}if(opts.resume)args.push("--resume",opts.resume,"--fork-session");if(opts.carried)Object.assign(env,placeCarried(opts.carried.home,opts.carried.transcript,opts.resume,opts.carried.cwd,mcpServers[MCP_SERVER_NAME]));if(opts.cwd&&!passthrough.some(([k])=>k==="permission-mode"||k==="dangerously-skip-permissions"))args.push("--permission-mode","bypassPermissions");for(const[k,val]of passthrough){if(val==="")args.push(`--${k}`);else args.push(`--${k}`,val)}return{command:binary,args,env,confirm:"WARNING: Loading development channels",...opts.once?{confirmNotice:`messages from ${CHANNEL_REF} inject directly in this session`}:{},confirmReady:CLAUDE_READY_TEXTS,confirmBlockers:CLAUDE_STARTUP_BLOCKERS,...opts.cwd?{confirmBefore:CLAUDE_WORKSPACE_TRUST_REPLIES}:{},control,...opts.carried?{resumeRecordPath:carriedForkRecord(opts.carried.home)}:{},...artifacts.length>0?{artifacts}:{}}}};registry4.register(claudeConnector);export{CLAUDE_PROVIDER_KEYS,claudeConnector,claudeSetupProvider,marketplaceManifest,materialize,userServerState,writeMarketplaceManifest};