omo-ai 5.1.13 → 5.1.14

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.
@@ -291,7 +291,7 @@ You are working on tasks that don't fit specific categories but require moderate
291
291
  </Category_Context>`,UNSPECIFIED_LOW_CATEGORY_CALLER_GUIDANCE=`<Selection_Gate>Use only when no specialist category fits, effort is moderate, and scope stays within a few files/modules. Prefer any matching specialist category.</Selection_Gate>
292
292
  <Caller_Warning>Provide explicit must-do steps, forbidden scope, and concrete success criteria.</Caller_Warning>`,UNSPECIFIED_HIGH_CATEGORY_PROMPT_APPEND=`<Category_Context>
293
293
  You are working on tasks that don't fit specific categories but require substantial effort.
294
- </Category_Context>`,UNSPECIFIED_HIGH_CATEGORY_CALLER_GUIDANCE="<Selection_Gate>Use only when no specialist category fits and substantial effort spans systems/modules with broad impact. Use unspecified-low for contained moderate work.</Selection_Gate>",DEEP_LOW_CATEGORY_CALLER_GUIDANCE="<Selection_Gate>Route here when one subsystem plus its callers holds the mechanism and the evidence, once read, leaves one right answer. Wide but mechanical work belongs here or in a quick batch. When unsure, choose deep-low: a misrouted child returns `ESCALATE: deep-high` after one cheap attempt; re-spawn the same brief as deep-high with its findings.</Selection_Gate>",DEEP_HIGH_CATEGORY_CALLER_GUIDANCE="<Selection_Gate>Route here only when you can name the decision evidence cannot settle: a trade-off with no single right answer, a contract change crossing a package or process boundary, a mechanism with no in-repo pattern to copy, or correctness argued from invariants rather than observed in a test. Wide scope with easy decisions is deep-low or unspecified-high; reasoning as the deliverable is ultrabrain.</Selection_Gate>",GPT_FLAGSHIP_GATE_MODELS=["gpt-6-astra","gpt-5.6-sol"],DEEP_LOW_GATE_MODELS=["gpt-6.1-sol","gpt-6.1-sol-fast","gpt-5.6-sol-fast","gpt-5.6-sol"],DEEP_HIGH_GATE_MODEL="gpt-6-astra",OPENAI_CATEGORIES=[{name:"ultrabrain",config:{model:"chatgpt-subscription/gpt-6-astra",variant:"max"},description:"Use ONLY for genuinely hard, logic-heavy tasks. Give clear goals only, not step-by-step instructions.",promptAppend:`<Category_Context>
294
+ </Category_Context>`,UNSPECIFIED_HIGH_CATEGORY_CALLER_GUIDANCE="<Selection_Gate>Use only when no specialist category fits and substantial effort spans systems/modules with broad impact. Use unspecified-low for contained moderate work.</Selection_Gate>",DEEP_LOW_CATEGORY_CALLER_GUIDANCE="<Selection_Gate>Of the two deep lanes this is the default: the child settles its decisions from what it reads. When unsure, choose deep-low; a misrouted child returns `ESCALATE: deep-high` after one cheap attempt, and you re-spawn the same brief as deep-high with its findings.</Selection_Gate>",DEEP_HIGH_CATEGORY_CALLER_GUIDANCE="<Selection_Gate>Route here only when you can name the decision evidence cannot settle: a trade-off with no single right answer, a contract change crossing a package or process boundary, a mechanism with no in-repo pattern to copy, or correctness argued from invariants rather than observed in a test. Wide scope with easy decisions is deep-low or unspecified-high; reasoning as the deliverable is ultrabrain.</Selection_Gate>",GPT_FLAGSHIP_GATE_MODELS=["gpt-6-astra","gpt-5.6-sol"],DEEP_LOW_GATE_MODELS=["gpt-6.1-sol","gpt-6.1-sol-fast","gpt-5.6-sol-fast","gpt-5.6-sol"],DEEP_HIGH_GATE_MODEL="gpt-6-astra",OPENAI_CATEGORIES=[{name:"ultrabrain",config:{model:"chatgpt-subscription/gpt-6-astra",variant:"max"},description:"Use ONLY for genuinely hard, logic-heavy tasks. Give clear goals only, not step-by-step instructions.",promptAppend:`<Category_Context>
295
295
  You are working on DEEP LOGICAL REASONING / COMPLEX ARCHITECTURE tasks.
296
296
 
297
297
  **CRITICAL - CODE STYLE REQUIREMENTS (NON-NEGOTIABLE)**:
@@ -311,7 +311,7 @@ Response format:
311
311
  - Bottom line (2-3 sentences)
312
312
  - Action plan (numbered steps)
313
313
  - Risks and mitigations (if relevant)
314
- </Category_Context>`,resolvePromptAppend:resolveUltrabrainCategoryPromptAppend,requiresModel:GPT_FLAGSHIP_GATE_MODELS},{name:"deep-low",config:{model:"chatgpt-subscription/gpt-6.1-sol",variant:"medium"},description:"Default deep lane: one goal, one deliverable, decisions the child can settle from what it reads. **3D graphics, computer/browser use, CAPTCHA, multimodal, backend, logic, and algorithm work is routed here.** Multiple goals fan out as parallel calls.",callerGuidance:DEEP_LOW_CATEGORY_CALLER_GUIDANCE,promptAppend:`<Category_Context name="deep-low">
314
+ </Category_Context>`,resolvePromptAppend:resolveUltrabrainCategoryPromptAppend,requiresModel:GPT_FLAGSHIP_GATE_MODELS},{name:"deep-low",config:{model:"chatgpt-subscription/gpt-6.1-sol",variant:"medium"},description:"Default deep lane: one goal, one deliverable, decisions the child can settle from what it reads; preferred over deep-high for 3D graphics, computer/browser use, CAPTCHA, multimodal, backend, logic, and algorithm work. Multiple goals fan out as parallel calls.",callerGuidance:DEEP_LOW_CATEGORY_CALLER_GUIDANCE,promptAppend:`<Category_Context name="deep-low">
315
315
  You are working on a GOAL-ORIENTED AUTONOMOUS task: one goal, one deliverable, decisions the codebase can settle.
316
316
 
317
317
  Before any change, read the files involved and trace their dependencies until you can explain the mechanism you are about to modify. The goal is already defined: do not ask clarifying questions; make reasonable assumptions, record them in the final message, and proceed.
@@ -333,6 +333,6 @@ Prefer the fix that removes the cause over the patch that hides the symptom. Rep
333
333
  `;var UnderScore="_";var DollarSign="$";var LineComment="//",OpenComment="/*",CloseComment="*/";function DiscardMultilineComment(input){let index=input.indexOf(CloseComment);return IsEqual(index,-1)?"":input.slice(index+2)}function DiscardLineComment(input){let index=input.indexOf(NewLine);return IsEqual(index,-1)?"":input.slice(index)}function TrimStartUntilNewline(input){return input.replace(/^[ \t\r\f\v]+/,"")}function TrimWhitespace(input){let trimmed=TrimStartUntilNewline(input);return trimmed.startsWith(OpenComment)?TrimWhitespace(DiscardMultilineComment(trimmed.slice(2))):trimmed.startsWith(LineComment)?TrimWhitespace(DiscardLineComment(trimmed.slice(2))):trimmed}function Trim(input){let trimmed=input.trimStart();return trimmed.startsWith(OpenComment)?Trim(DiscardMultilineComment(trimmed.slice(2))):trimmed.startsWith(LineComment)?Trim(DiscardLineComment(trimmed.slice(2))):trimmed}var AllowedDigits=[...Digit,UnderScore];function TakeConst(const_,input){return Take([const_],input)}function Const(const_,input){return IsEqual(const_,"")?["",input]:const_.startsWith(NewLine)?TakeConst(const_,TrimWhitespace(input)):const_.startsWith(WhiteSpace)?TakeConst(const_,input):TakeConst(const_,Trim(input))}var Initial=[...Alpha,UnderScore,DollarSign];var Remaining=[...Initial,...Digit];var AllowedDigits2=[...Digit,UnderScore];function TakeOne(input){return IsEqual(input,"")?[]:[input.slice(0,1),input.slice(1)]}function IsInputMatchSentinal(end,input){return ShiftLeft(end,(left,right)=>input.startsWith(left)?!0:IsInputMatchSentinal(right,input),()=>!1)}function Until(end,input,result=""){return Match3(TakeOne(input),(One,Rest)=>IsInputMatchSentinal(end,input)?[result,input]:Until(end,Rest,`${result}${One}`),()=>[])}function Until_1(end,input){return Match3(Until(end,input),(Until,UntilRest)=>IsEqual(Until,"")?[]:[Until,UntilRest],()=>[])}var If=(result,left,right=()=>[])=>result.length===2?left(result):right();var PatternBigInt=(input)=>If(Const("-?(?:0|[1-9][0-9]*)n",input),([_0,input])=>[PatternBigIntMapping(_0),input]),PatternString=(input)=>If(Const(".*",input),([_0,input])=>[PatternStringMapping(_0),input]),PatternNumber=(input)=>If(Const("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",input),([_0,input])=>[PatternNumberMapping(_0),input]),PatternInteger=(input)=>If(Const("-?(?:0|[1-9][0-9]*)",input),([_0,input])=>[PatternIntegerMapping(_0),input]),PatternNever=(input)=>If(Const("(?!)",input),([_0,input])=>[PatternNeverMapping(_0),input]),PatternText=(input)=>If(Until_1(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],input),([_0,input])=>[PatternTextMapping(_0),input]),PatternBase=(input)=>If(If(PatternBigInt(input),([_0,input])=>[_0,input],()=>If(PatternString(input),([_0,input])=>[_0,input],()=>If(PatternNumber(input),([_0,input])=>[_0,input],()=>If(PatternInteger(input),([_0,input])=>[_0,input],()=>If(PatternNever(input),([_0,input])=>[_0,input],()=>If(PatternGroup(input),([_0,input])=>[_0,input],()=>If(PatternText(input),([_0,input])=>[_0,input],()=>[]))))))),([_0,input])=>[PatternBaseMapping(_0),input]),PatternGroup=(input)=>If(If(Const("(",input),([_0,input])=>If(PatternBody(input),([_1,input])=>If(Const(")",input),([_2,input])=>[[_0,_1,_2],input]))),([_0,input])=>[PatternGroupMapping(_0),input]),PatternUnion=(input)=>If(If(If(PatternTerm(input),([_0,input])=>If(Const("|",input),([_1,input])=>If(PatternUnion(input),([_2,input])=>[[_0,_1,_2],input]))),([_0,input])=>[_0,input],()=>If(If(PatternTerm(input),([_0,input])=>[[_0],input]),([_0,input])=>[_0,input],()=>If([[],input],([_0,input])=>[_0,input],()=>[]))),([_0,input])=>[PatternUnionMapping(_0),input]),PatternTerm=(input)=>If(If(PatternBase(input),([_0,input])=>If(PatternBody(input),([_1,input])=>[[_0,_1],input])),([_0,input])=>[PatternTermMapping(_0),input]),PatternBody=(input)=>If(If(PatternUnion(input),([_0,input])=>[_0,input],()=>If(PatternTerm(input),([_0,input])=>[_0,input],()=>[])),([_0,input])=>[PatternBodyMapping(_0),input]),Pattern=(input)=>If(If(Const("^",input),([_0,input])=>If(PatternBody(input),([_1,input])=>If(Const("$",input),([_2,input])=>[[_0,_1,_2],input]))),([_0,input])=>[PatternMapping(_0),input]);function JoinString(input){return input.join("|")}function UnwrapTemplateLiteralPattern(pattern){return pattern.slice(1,pattern.length-1)}function EncodeLiteral(value,right,pattern){return EncodeTypes(right,`${pattern}${value}`)}function EncodeBigInt(right,pattern){return EncodeTypes(right,`${pattern}${BigIntPattern}`)}function EncodeInteger(right,pattern){return EncodeTypes(right,`${pattern}${IntegerPattern}`)}function EncodeNumber(right,pattern){return EncodeTypes(right,`${pattern}${NumberPattern}`)}function EncodeBoolean(right,pattern){return EncodeType(Union([Literal("false"),Literal("true")]),right,pattern)}function EncodeString(right,pattern){return EncodeTypes(right,`${pattern}${StringPattern}`)}function EncodeTemplateLiteral(templatePattern,right,pattern){return EncodeTypes(right,`${pattern}${UnwrapTemplateLiteralPattern(templatePattern)}`)}function EncodeTemplateLiteralDeferred(types,right,pattern){let templateLiteral=TemplateLiteralAction(types,{});return EncodeType(templateLiteral,right,pattern)}function EncodeEnum(values,right,pattern){let evaluated=EvaluateEnum(values);return EncodeType(evaluated,right,pattern)}function EncodeUnion(types,right,pattern,result=[]){return ShiftLeft(types,(head,tail)=>EncodeUnion(tail,right,pattern,[...result,EncodeType(head,[],"")]),()=>EncodeTypes(right,`${pattern}(${JoinString(result)})`))}function EncodeType(type,right,pattern){return IsEnum2(type)?EncodeEnum(type.enum,right,pattern):IsInteger2(type)?EncodeInteger(right,pattern):IsLiteral(type)?EncodeLiteral(type.const,right,pattern):IsBigInt2(type)?EncodeBigInt(right,pattern):IsBoolean3(type)?EncodeBoolean(right,pattern):IsNumber3(type)?EncodeNumber(right,pattern):IsString3(type)?EncodeString(right,pattern):IsTemplateLiteral(type)?EncodeTemplateLiteral(type.pattern,right,pattern):IsTemplateLiteralDeferred(type)?EncodeTemplateLiteralDeferred(type.parameters[0],right,pattern):IsUnion(type)?EncodeUnion(type.anyOf,right,pattern):NeverPattern}function EncodeTypes(types,pattern){return ShiftLeft(types,(left,right)=>EncodeType(left,right,pattern),()=>pattern)}function EncodePattern(types){return`^${EncodeTypes(types,"")}$`}function TemplateLiteralEncode(types){let pattern=EncodePattern(types);return TemplateLiteralCreate(pattern)}function TemplateLiteralAction(types,options){return CanInstantiate(types)?Update(TemplateLiteralEncode(types),{},options):TemplateLiteralDeferred(types,options)}function TemplateLiteralInstantiate(context,state,types,options){let instantiatedTypes=InstantiateTypes(context,state,types);return TemplateLiteralAction(instantiatedTypes,options)}function TemplateLiteralDeferred(types,options={}){return Deferred("TemplateLiteral",[types],options)}function IsTemplateLiteralDeferred(value){return IsSchema2(value)&&HasPropertyKey(value,"action")&&IsEqual(value.action,"TemplateLiteral")}function IsTemplateLiteral(value){return IsKind(value,"TemplateLiteral")}function ExtendsUnion(inferred){return Create({["~kind"]:"ExtendsUnion"},{inferred})}function IsExtendsUnion(value){return IsObject(value)&&HasPropertyKey(value,"~kind")&&HasPropertyKey(value,"inferred")&&IsEqual(value["~kind"],"ExtendsUnion")&&IsObject(value.inferred)}function ExtendsTrue(inferred){return Create({["~kind"]:"ExtendsTrue"},{inferred})}function IsExtendsTrue(value){return IsObject(value)&&HasPropertyKey(value,"~kind")&&HasPropertyKey(value,"inferred")&&IsEqual(value["~kind"],"ExtendsTrue")&&IsObject(value.inferred)}function ExtendsFalse(){return Create({["~kind"]:"ExtendsFalse"},{})}function IsExtendsFalse(value){return IsObject(value)&&HasPropertyKey(value,"~kind")&&IsEqual(value["~kind"],"ExtendsFalse")}function IsExtendsTrueLike(value){return IsExtendsUnion(value)||IsExtendsTrue(value)}function Match4(result,true_,false_){return IsExtendsTrueLike(result)?true_(result.inferred):false_()}function ExtendsRightInfer(inferred,name,left,right){return Match4(ExtendsLeft(inferred,left,right),(checkInferred)=>ExtendsTrue(Assign(Assign(inferred,checkInferred),{[name]:left})),()=>ExtendsFalse())}function ExtendsRightAny(inferred,_left){return ExtendsTrue(inferred)}function ExtendsRightDependent(inferred,left,if_,then_,else_){return Match4(ExtendsLeft(inferred,left,if_),(inferred)=>Match4(ExtendsLeft(inferred,left,then_),(inferred)=>ExtendsTrue(inferred),()=>ExtendsFalse()),()=>Match4(ExtendsLeft(inferred,left,else_),(inferred)=>ExtendsTrue(inferred),()=>ExtendsFalse()))}function ExtendsRightEnum(inferred,left,right){let evaluated=EvaluateEnum(right);return ExtendsLeft(inferred,left,evaluated)}function ExtendsRightIntersect(inferred,left,right){return ShiftLeft(right,(head,tail)=>Match4(ExtendsLeft(inferred,left,head),(inferred)=>ExtendsRightIntersect(inferred,left,tail),()=>ExtendsFalse()),()=>ExtendsTrue(inferred))}function ExtendsRightTemplateLiteral(inferred,left,right){let evaluated=EvaluateTemplateLiteral(right);return ExtendsLeft(inferred,left,evaluated)}function ExtendsRightUnion(inferred,left,right){return ShiftLeft(right,(head,tail)=>Match4(ExtendsLeft(inferred,left,head),(inferred)=>ExtendsTrue(inferred),()=>ExtendsRightUnion(inferred,left,tail)),()=>ExtendsFalse())}function ExtendsRight(inferred,left,right){return IsAny(right)?ExtendsRightAny(inferred,left):IsDependent(right)?ExtendsRightDependent(inferred,left,right.if,right.then,right.else):IsEnum2(right)?ExtendsRightEnum(inferred,left,right.enum):IsInfer(right)?ExtendsRightInfer(inferred,right.name,left,right.extends):IsIntersect(right)?ExtendsRightIntersect(inferred,left,right.allOf):IsTemplateLiteral(right)?ExtendsRightTemplateLiteral(inferred,left,right.pattern):IsUnion(right)?ExtendsRightUnion(inferred,left,right.anyOf):IsUnknown(right)?ExtendsTrue(inferred):ExtendsFalse()}function ExtendsAny(inferred,left,right){return IsInfer(right)?ExtendsRight(inferred,left,right):IsAny(right)?ExtendsTrue(inferred):IsUnknown(right)?ExtendsTrue(inferred):ExtendsUnion(inferred)}function ExtendsImmutable(left,right){let isImmutableLeft=IsImmutable(left),isImmutableRight=IsImmutable(right);return isImmutableLeft&&isImmutableRight?!0:!isImmutableLeft&&isImmutableRight?!0:isImmutableLeft&&!isImmutableRight?!1:!0}function ExtendsArray(inferred,arrayLeft,left,right){return IsArray2(right)?ExtendsImmutable(arrayLeft,right)?ExtendsLeft(inferred,left,right.items):ExtendsFalse():ExtendsRight(inferred,arrayLeft,right)}function ExtendsBigInt(inferred,left,right){return IsBigInt2(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsBoolean(inferred,left,right){return IsBoolean3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ParameterCompare(inferred,left,leftRest,right,rightRest){let checkLeft=IsInfer(right)?left:right,checkRight=IsInfer(right)?right:left,isLeftOptional=IsOptional(left),isRightOptional=IsOptional(right);return!isLeftOptional&&isRightOptional?ExtendsFalse():Match4(ExtendsLeft(inferred,checkLeft,checkRight),(inferred)=>ExtendsParameters(inferred,leftRest,rightRest),()=>ExtendsFalse())}function ParameterRight(inferred,left,leftRest,rightRest){return ShiftLeft(rightRest,(head,tail)=>ParameterCompare(inferred,left,leftRest,head,tail),()=>IsOptional(left)?ExtendsTrue(inferred):ExtendsFalse())}function ParametersLeft(inferred,left,rightRest){return ShiftLeft(left,(head,tail)=>ParameterRight(inferred,head,tail,rightRest),()=>ExtendsTrue(inferred))}function ExtendsParameters(inferred,left,right){return ParametersLeft(inferred,left,right)}function ExtendsReturnType(inferred,left,right){return IsVoid(right)?ExtendsTrue(inferred):ExtendsLeft(inferred,left,right)}function ExtendsConstructor(inferred,parameters,returnType,right){return IsAny(right)?ExtendsTrue(inferred):IsUnknown(right)?ExtendsTrue(inferred):IsConstructor2(right)?Match4(ExtendsParameters(inferred,parameters,right.parameters),(inferred)=>ExtendsReturnType(inferred,returnType,right.instanceType),()=>ExtendsFalse()):ExtendsFalse()}function ExtendsDependent(inferred,if_,then_,else_,right){return Match4(ExtendsLeft(inferred,if_,right),()=>ExtendsLeft(inferred,then_,right),()=>ExtendsLeft(inferred,else_,right))}function ExtendsEnum(inferred,left,right){let evaluated=EvaluateEnum(left);return ExtendsLeft(inferred,evaluated,right)}function ExtendsFunction(inferred,parameters,returnType,right){return IsAny(right)?ExtendsTrue(inferred):IsUnknown(right)?ExtendsTrue(inferred):IsFunction2(right)?Match4(ExtendsParameters(inferred,parameters,right.parameters),(inferred)=>ExtendsReturnType(inferred,returnType,right.returnType),()=>ExtendsFalse()):ExtendsFalse()}function ExtendsInteger(inferred,left,right){return IsInteger2(right)?ExtendsTrue(inferred):IsNumber3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsIntersect(inferred,left,right){let evaluated=EvaluateIntersect(left);return ExtendsLeft(inferred,evaluated,right)}function ExtendsLiteralValue(inferred,left,right){return left===right?ExtendsTrue(inferred):ExtendsFalse()}function ExtendsLiteralBigInt(inferred,left,right){return IsLiteral(right)?ExtendsLiteralValue(inferred,left,right.const):IsBigInt2(right)?ExtendsTrue(inferred):ExtendsRight(inferred,Literal(left),right)}function ExtendsLiteralBoolean(inferred,left,right){return IsLiteral(right)?ExtendsLiteralValue(inferred,left,right.const):IsBoolean3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,Literal(left),right)}function ExtendsLiteralNumber(inferred,left,right){return IsLiteral(right)?ExtendsLiteralValue(inferred,left,right.const):IsNumber3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,Literal(left),right)}function ExtendsLiteralString(inferred,left,right){return IsLiteral(right)?ExtendsLiteralValue(inferred,left,right.const):IsString3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,Literal(left),right)}function ExtendsLiteral(inferred,left,right){return IsBigInt(left.const)?ExtendsLiteralBigInt(inferred,left.const,right):IsBoolean(left.const)?ExtendsLiteralBoolean(inferred,left.const,right):IsNumber(left.const)?ExtendsLiteralNumber(inferred,left.const,right):IsString(left.const)?ExtendsLiteralString(inferred,left.const,right):Unreachable()}function ExtendsNever(inferred,left,right){return IsInfer(right)?ExtendsRight(inferred,left,right):ExtendsTrue(inferred)}function ExtendsNull(inferred,left,right){return IsNull2(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsNumber(inferred,left,right){return IsNumber3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsPropertyOptional(inferred,left,right){return IsOptional(left)?IsOptional(right)?ExtendsTrue(inferred):ExtendsFalse():ExtendsTrue(inferred)}function ExtendsProperty(inferred,left,right){return IsInfer(right)&&IsNever(right.extends)?ExtendsFalse():Match4(ExtendsLeft(inferred,left,right),(inferred)=>ExtendsPropertyOptional(inferred,left,right),()=>ExtendsFalse())}function ExtractInferredProperties(keys,properties){return keys.reduce((result,key)=>(key in properties)?IsExtendsTrueLike(properties[key])?{...result,...properties[key].inferred}:Unreachable():Unreachable(),{})}function ExtendsPropertiesComparer(inferred,left,right){let properties={};for(let rightKey of Keys(right))properties[rightKey]=rightKey in left?ExtendsProperty({},left[rightKey],right[rightKey]):IsOptional(right[rightKey])?IsInfer(right[rightKey])?ExtendsTrue(Assign(inferred,{[right[rightKey].name]:right[rightKey].extends})):ExtendsTrue(inferred):ExtendsFalse();let checked=Values(properties).every((result)=>IsExtendsTrueLike(result)),extracted=checked?ExtractInferredProperties(Keys(properties),properties):{};return checked?ExtendsTrue(extracted):ExtendsFalse()}function ExtendsProperties(inferred,left,right){let compared=ExtendsPropertiesComparer(inferred,left,right);return IsExtendsTrueLike(compared)?ExtendsTrue(Assign(inferred,compared.inferred)):ExtendsFalse()}function ExtendsObjectToObject(inferred,left,right){return ExtendsProperties(inferred,left,right)}function RecordMergeInferred(left,right){return Keys(right).reduce((result,key)=>({...result,[key]:HasPropertyKey(left,key)?IsUnion(result[key])?Union([...result[key].anyOf,right[key]]):Union([left[key],right[key]]):right[key]}),left)}function ExtendsRecordComparer(properties,keys,type,result){return ShiftLeft(keys,(left,right)=>Match4(ExtendsLeft({},properties[left],type),(inferred)=>ExtendsRecordComparer(properties,right,type,RecordMergeInferred(result,inferred)),()=>ExtendsFalse()),()=>ExtendsTrue(result))}function ExtendsObjectToRecord(inferred,properties,_pattern,value){let keys=Keys(properties);return ExtendsRecordComparer(properties,keys,value,inferred)}function ExtendsObject(inferred,left,right){return IsRecord(right)?ExtendsObjectToRecord(inferred,left,RecordPattern(right),RecordValue(right)):IsObject2(right)?ExtendsObjectToObject(inferred,left,right.properties):ExtendsRight(inferred,_Object_(left),right)}function FromObject3(inferred,properties){return IsEqual(Keys(properties).length,0)?ExtendsTrue(inferred):ExtendsFalse()}function FromRecord(inferred,_leftKey,leftValue,_rightKey,rightValue){return ExtendsLeft(inferred,leftValue,rightValue)}function ExtendsRecord(inferred,leftPattern,leftValue,right){return IsRecord(right)?FromRecord(inferred,RecordPatternToType(leftPattern),leftValue,RecordPatternToType(RecordPattern(right)),RecordValue(right)):IsObject2(right)?FromObject3(inferred,right.properties):IsAny(right)?ExtendsTrue(inferred):IsUnknown(right)?ExtendsTrue(inferred):ExtendsFalse()}function ExtendsString(inferred,left,right){return IsString3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsSymbol(inferred,left,right){return IsSymbol2(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsTemplateLiteral(inferred,left,right){let evaluated=EvaluateTemplateLiteral(left);return ExtendsLeft(inferred,evaluated,right)}function Inferrable(name,type){return Create({"~kind":"Inferrable"},{name,type},{})}function IsInferable(value){return IsObject(value)&&HasPropertyKey(value,"~kind")&&HasPropertyKey(value,"name")&&HasPropertyKey(value,"type")&&IsEqual(value["~kind"],"Inferrable")&&IsString(value.name)&&IsObject(value.type)}function TryRestInferable(type){return IsRest(type)?IsInfer(type.items)?IsArray2(type.items.extends)?Inferrable(type.items.name,type.items.extends.items):IsUnknown(type.items.extends)?Inferrable(type.items.name,type.items.extends):void 0:Unreachable():void 0}function TryInferable(type){return IsInfer(type)?Inferrable(type.name,type.extends):void 0}function TryInferResults(rest,right){let result=[];for(let head of rest){if(!IsExtendsTrueLike(ExtendsLeft({},head,right)))return;result.push(head)}return result}function InferTupleResult(inferred,name,left,right){let results=TryInferResults(left,right);return IsArray(results)?ExtendsTrue(Assign(inferred,{[name]:Tuple(results)})):ExtendsFalse()}function InferUnionResult(inferred,name,left,right){let results=TryInferResults(left,right);return IsArray(results)?ExtendsTrue(Assign(inferred,{[name]:Union(results)})):ExtendsFalse()}function Reverse(types){return[...types].reverse()}function ApplyReverse(types,reversed){return reversed?Reverse(types):types}function Reversed(types){let first=types.length>0?types[0]:void 0,inferrable=IsSchema2(first)?TryRestInferable(first):void 0;return IsSchema2(inferrable)}function ElementsCompare(inferred,reversed,left,leftRest,right,rightRest){return Match4(ExtendsLeft(inferred,left,right),(checkInferred)=>Elements(checkInferred,reversed,leftRest,rightRest),()=>ExtendsFalse())}function ElementsLeft(inferred,reversed,leftRest,right,rightRest){let inferable=TryRestInferable(right);return IsInferable(inferable)?InferTupleResult(inferred,inferable.name,ApplyReverse(leftRest,reversed),inferable.type):ShiftLeft(leftRest,(head,tail)=>ElementsCompare(inferred,reversed,head,tail,right,rightRest),()=>ExtendsFalse())}function ElementsRight(inferred,reversed,leftRest,rightRest){return ShiftLeft(rightRest,(head,tail)=>ElementsLeft(inferred,reversed,leftRest,head,tail),()=>IsEqual(leftRest.length,0)?ExtendsTrue(inferred):ExtendsFalse())}function Elements(inferred,reversed,leftRest,rightRest){return ElementsRight(inferred,reversed,leftRest,rightRest)}function ExtendsTupleToTuple(inferred,left,right){let instantiatedRight=InstantiateElements(inferred,State([],[]),right),reversed=Reversed(instantiatedRight);return Elements(inferred,reversed,ApplyReverse(left,reversed),ApplyReverse(instantiatedRight,reversed))}function ExtendsTupleToArrayReduce(inferred,left,right){for(let head of left){let result=ExtendsLeft(inferred,head,right);if(!IsExtendsTrueLike(result))return result;inferred=result.inferred}return ExtendsTrue(inferred)}function ExtendsTupleToArray(inferred,left,right){let inferrable=TryInferable(right);return IsInferable(inferrable)?InferUnionResult(inferred,inferrable.name,left,inferrable.type):ExtendsTupleToArrayReduce(inferred,left,right)}function ExtendsTuple(inferred,left,right){let instantiatedLeft=InstantiateElements(inferred,State([],[]),left);return IsTuple(right)?ExtendsTupleToTuple(inferred,instantiatedLeft,right.items):IsArray2(right)?ExtendsTupleToArray(inferred,instantiatedLeft,right.items):ExtendsRight(inferred,Tuple(instantiatedLeft),right)}function ExtendsUndefined(inferred,left,right){return IsVoid(right)?ExtendsTrue(inferred):IsUndefined2(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsUnionSome(inferred,type,unionTypes){return ShiftLeft(unionTypes,(head,tail)=>Match4(ExtendsLeft(inferred,type,head),(inferred)=>ExtendsTrue(inferred),()=>ExtendsUnionSome(inferred,type,tail)),()=>ExtendsFalse())}function ExtendsUnionLeft(inferred,left,right){return ShiftLeft(left,(head,tail)=>Match4(ExtendsUnionSome(inferred,head,right),(inferred)=>ExtendsUnionLeft(inferred,tail,right),()=>ExtendsFalse()),()=>ExtendsTrue(inferred))}function ExtendsUnion2(inferred,left,right){let inferrable=TryInferable(right);return IsInferable(inferrable)?InferUnionResult(inferred,inferrable.name,left,inferrable.type):IsUnion(right)?ExtendsUnionLeft(inferred,left,right.anyOf):ExtendsUnionLeft(inferred,left,[right])}function ExtendsUnknown(inferred,left,right){return IsInfer(right)?ExtendsRight(inferred,left,right):IsAny(right)?ExtendsTrue(inferred):IsUnknown(right)?ExtendsTrue(inferred):ExtendsFalse()}function ExtendsVoid(inferred,left,right){return IsVoid(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsLeft(inferred,left,right){return IsAny(left)?ExtendsAny(inferred,left,right):IsArray2(left)?ExtendsArray(inferred,left,left.items,right):IsBigInt2(left)?ExtendsBigInt(inferred,left,right):IsBoolean3(left)?ExtendsBoolean(inferred,left,right):IsConstructor2(left)?ExtendsConstructor(inferred,left.parameters,left.instanceType,right):IsDependent(left)?ExtendsDependent(inferred,left.if,left.then,left.else,right):IsEnum2(left)?ExtendsEnum(inferred,left.enum,right):IsFunction2(left)?ExtendsFunction(inferred,left.parameters,left.returnType,right):IsInteger2(left)?ExtendsInteger(inferred,left,right):IsIntersect(left)?ExtendsIntersect(inferred,left.allOf,right):IsLiteral(left)?ExtendsLiteral(inferred,left,right):IsNever(left)?ExtendsNever(inferred,left,right):IsNull2(left)?ExtendsNull(inferred,left,right):IsNumber3(left)?ExtendsNumber(inferred,left,right):IsObject2(left)?ExtendsObject(inferred,left.properties,right):IsRecord(left)?ExtendsRecord(inferred,RecordPattern(left),RecordValue(left),right):IsString3(left)?ExtendsString(inferred,left,right):IsSymbol2(left)?ExtendsSymbol(inferred,left,right):IsTemplateLiteral(left)?ExtendsTemplateLiteral(inferred,left.pattern,right):IsTuple(left)?ExtendsTuple(inferred,left.items,right):IsUndefined2(left)?ExtendsUndefined(inferred,left,right):IsUnion(left)?ExtendsUnion2(inferred,left.anyOf,right):IsUnknown(left)?ExtendsUnknown(inferred,left,right):IsVoid(left)?ExtendsVoid(inferred,left,right):ExtendsFalse()}function InterfaceOperation(heritage,properties){return EvaluateIntersect([...heritage,_Object_(properties)])}function InterfaceAction(heritage,properties,options){return CanInstantiate(heritage)?Update(InterfaceOperation(heritage,properties),{},options):InterfaceDeferred(heritage,properties,options)}function InterfaceInstantiate(context,state,heritage,properties,options){let instantiatedHeritage=InstantiateTypes(context,state,heritage),instantiatedProperties=InstantiateProperties(context,state,properties);return InterfaceAction(instantiatedHeritage,instantiatedProperties,options)}function InterfaceDeferred(heritage,properties,options={}){return Deferred("Interface",[heritage,properties],options)}function IsInterfaceDeferred(value){return IsSchema2(value)&&HasPropertyKey(value,"action")&&IsEqual(value.action,"Interface")}function FromRef(stack,context,ref){return stack.includes(ref)?!0:FromType3([...stack,ref],context,context[ref])}function FromProperties(stack,context,properties){let types=PropertyValues(properties);return FromTypes2(stack,context,types)}function FromTypes2(stack,context,types){return ShiftLeft(types,(left,right)=>FromType3(stack,context,left)?!0:FromTypes2(stack,context,right),()=>!1)}function FromType3(stack,context,type){return IsRef2(type)?FromRef(stack,context,type.$ref):IsArray2(type)?FromType3(stack,context,type.items):IsConstructor2(type)?FromTypes2(stack,context,[...type.parameters,type.instanceType]):IsFunction2(type)?FromTypes2(stack,context,[...type.parameters,type.returnType]):IsInterfaceDeferred(type)?FromProperties(stack,context,type.parameters[1]):IsIntersect(type)?FromTypes2(stack,context,type.allOf):IsObject2(type)?FromProperties(stack,context,type.properties):IsUnion(type)?FromTypes2(stack,context,type.anyOf):IsTuple(type)?FromTypes2(stack,context,type.items):IsRecord(type)?FromType3(stack,context,RecordValue(type)):!1}function CyclicCheck(stack,context,type){return FromType3(stack,context,type)}function ResolveCandidateKeys(context,keys){return keys.reduce((result,left)=>CyclicCheck([left],context,context[left])?[...result,left]:result,[])}function CyclicCandidates(context){let keys=PropertyKeys(context);return ResolveCandidateKeys(context,keys)}function FromRef2(context,ref,result){return result.includes(ref)?result:(ref in context)?FromType4(context,context[ref],[...result,ref]):Unreachable()}function FromProperties2(context,properties,result){let types=PropertyValues(properties);return FromTypes3(context,types,result)}function FromTypes3(context,types,result){return types.reduce((result,left)=>FromType4(context,left,result),result)}function FromType4(context,type,result){return IsRef2(type)?FromRef2(context,type.$ref,result):IsArray2(type)?FromType4(context,type.items,result):IsConstructor2(type)?FromTypes3(context,[...type.parameters,type.instanceType],result):IsFunction2(type)?FromTypes3(context,[...type.parameters,type.returnType],result):IsInterfaceDeferred(type)?FromProperties2(context,type.parameters[1],result):IsIntersect(type)?FromTypes3(context,type.allOf,result):IsObject2(type)?FromProperties2(context,type.properties,result):IsUnion(type)?FromTypes3(context,type.anyOf,result):IsTuple(type)?FromTypes3(context,type.items,result):IsRecord(type)?FromType4(context,RecordValue(type),result):result}function CyclicDependencies(context,key,type){return FromType4(context,type,[key])}function FromRef3(_ref){return Any()}function FromProperties3(properties){return Keys(properties).reduce((result,key)=>({...result,[key]:FromType5(properties[key])}),{})}function FromTypes4(types){return types.reduce((result,left)=>[...result,FromType5(left)],[])}function FromType5(type){return IsRef2(type)?FromRef3(type.$ref):IsArray2(type)?_Array_(FromType5(type.items),ArrayOptions(type)):IsConstructor2(type)?Constructor(FromTypes4(type.parameters),FromType5(type.instanceType)):IsFunction2(type)?_Function_(FromTypes4(type.parameters),FromType5(type.returnType)):IsIntersect(type)?Intersect(FromTypes4(type.allOf)):IsObject2(type)?_Object_(FromProperties3(type.properties)):IsRecord(type)?Record(RecordKey(type),FromType5(RecordValue(type))):IsUnion(type)?Union(FromTypes4(type.anyOf)):IsTuple(type)?Tuple(FromTypes4(type.items)):type}function CyclicAnyFromParameters(defs,ref){return ref in defs?FromType5(defs[ref]):Unknown()}function CyclicExtends(type){return CyclicAnyFromParameters(type.$defs,type.$ref)}function CyclicInterface(context,heritage,properties){let instantiatedHeritage=InstantiateTypes(context,State([],[]),heritage),instantiatedProperties=InstantiateProperties({},State([],[]),properties);return EvaluateIntersect([...instantiatedHeritage,_Object_(instantiatedProperties)])}function CyclicDefinitions(context,dependencies){return Keys(context).filter((key)=>dependencies.includes(key)).reduce((result,key)=>{let type=context[key],instantiatedType=IsInterfaceDeferred(type)?CyclicInterface(context,type.parameters[0],type.parameters[1]):type;return{...result,[key]:instantiatedType}},{})}function InstantiateCyclic(context,ref,type){let dependencies=CyclicDependencies(context,ref,type),definitions=CyclicDefinitions(context,dependencies);return Cyclic(definitions,ref)}function Resolve(defs,ref){return ref in defs?IsRef2(defs[ref])?Resolve(defs,defs[ref].$ref):defs[ref]:Never()}function CyclicTarget(defs,ref){return Resolve(defs,ref)}function Canonical(type){return IsCyclic(type)?CyclicExtends(type):IsUnsafe(type)?Unknown():type}function Extends(inferred,left,right){let canonicalLeft=Canonical(left),canonicalRight=Canonical(right);return ExtendsLeft(inferred,canonicalLeft,canonicalRight)}var CompareResultEqual=0,CompareResultDisjoint=1,CompareResultLeftInside=2,CompareResultRightInside=3;function Compare(left,right){let extendsCheck=[Extends({},left,right),Extends({},right,left)];return IsExtendsTrueLike(extendsCheck[0])&&IsExtendsTrueLike(extendsCheck[1])?CompareResultEqual:IsExtendsTrueLike(extendsCheck[0])&&IsExtendsFalse(extendsCheck[1])?CompareResultLeftInside:IsExtendsFalse(extendsCheck[0])&&IsExtendsTrueLike(extendsCheck[1])?CompareResultRightInside:CompareResultDisjoint}function BroadenFilter(type,types,result=[],all=types){return ShiftLeft(types,(left,right)=>{let compare=Compare(type,left);return IsEqual(compare,CompareResultLeftInside)||IsEqual(compare,CompareResultEqual)?all:IsEqual(compare,CompareResultDisjoint)?BroadenFilter(type,right,[...result,left],all):BroadenFilter(type,right,result,all)},()=>[...result,type])}function BroadenType(type,types,result){let evaluated=EvaluateType(type);return IsAny(evaluated)?[evaluated]:IsUnknown(evaluated)?[evaluated]:IsNever(evaluated)?BroadenTypes(types,result):IsObject2(evaluated)?BroadenTypes(types,[...result,evaluated]):BroadenTypes(types,BroadenFilter(evaluated,result))}function BroadenTypes(types,result=[]){return ShiftLeft(types,(left,right)=>BroadenType(left,right,result),()=>result)}function Broaden(types){let broadened=BroadenTypes(types);return Flatten(broadened)}function EvaluateAction(type,options){return Update(EvaluateType(type),{},options)}function EvaluateInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return EvaluateAction(instantiatedType,options)}function CollectDistributionNames(expression,result=[]){return IsDeferred(expression)&&IsEqual(expression.action,"Conditional")?IsRef2(expression.parameters[0])?CollectDistributionNames(expression.parameters[2],CollectDistributionNames(expression.parameters[3],[...result,expression.parameters[0].$ref])):CollectDistributionNames(expression.parameters[2],CollectDistributionNames(expression.parameters[3],result)):IsDeferred(expression)&&IsEqual(expression.action,"Mapped")?IsDeferred(expression.parameters[1])&&IsEqual(expression.parameters[1].action,"KeyOf")&&IsRef2(expression.parameters[1].parameters[0])?[...result,expression.parameters[1].parameters[0].$ref]:result:result}function BuildDistributionArray(parameters,names){return parameters.reduce((result,left)=>[...result,names.includes(left.name)],[])}function ZipDistributionArray(arguments_,distributionArray,result=[]){return ShiftLeft(arguments_,(argumentLeft,argumentRight)=>ShiftLeft(distributionArray,(booleanLeft,booleanRight)=>ZipDistributionArray(argumentRight,booleanRight,[...result,[booleanLeft,argumentLeft]]),()=>result),()=>result)}function CanonicalArgument(type){return IsTemplateLiteral(type)?EvaluateTemplateLiteral(type.pattern):IsEnum2(type)?EvaluateEnum(type.enum):type}function Expand(type){let canonicalArgument=CanonicalArgument(type);return IsUnion(canonicalArgument)?[...canonicalArgument.anyOf]:[canonicalArgument]}function Append(current,type){return current.reduce((result,left)=>[...result,[...left,type]],[])}function Cross(current,variants){return variants.reduce((result,left)=>[...result,...Append(current,left)],[])}function Distribute2(zipped){return zipped.reduce((result,left)=>IsEqual(left[0],!0)?Cross(result,Expand(left[1])):Cross(result,[left[1]]),[[]])}function DistributeArguments(parameters,arguments_,expression){let distributionNames=CollectDistributionNames(expression),distributionArray=BuildDistributionArray(parameters,distributionNames),zippedArguments=ZipDistributionArray(arguments_,distributionArray);return IsDeferred(expression)&&IsEqual(expression.action,"Conditional")?Distribute2(zippedArguments):IsDeferred(expression)&&IsEqual(expression.action,"Mapped")?Distribute2(zippedArguments):[arguments_]}function FromNotResolvable(){return["(not-resolvable)",Never()]}function FromNotGeneric(){return["(not-generic)",Never()]}function FromGeneric(name,parameters,expression){return[name,Generic(parameters,expression)]}function FromRef4(context,ref,arguments_){return ref in context?FromType6(context,ref,context[ref],arguments_):FromNotResolvable()}function FromType6(context,name,target,arguments_){return IsGeneric(target)?FromGeneric(name,target.parameters,target.expression):IsRef2(target)?FromRef4(context,target.$ref,arguments_):FromNotGeneric()}function ResolveTarget(context,target,arguments_){return FromType6(context,"(anonymous)",target,arguments_)}function AssertArgumentExtends(name,type,extends_){if(IsInfer(type)||IsCall(type)||IsExtendsTrueLike(Extends({},type,extends_)))return;let cause={parameter:name,expect:extends_,actual:type};throw Error(`Argument for parameter ${name} does not satisfy constraint`,{cause})}function BindArgument(context,state,name,extends_,type){let instantiatedArgument=InstantiateType(context,state,type);return AssertArgumentExtends(name,instantiatedArgument,extends_),Assign(context,{[name]:instantiatedArgument})}function BindArguments(context,state,parameterLeft,parameterRight,arguments_){let instantiatedExtends=InstantiateType(context,state,parameterLeft.extends),instantiatedEquals=InstantiateType(context,state,parameterLeft.equals);return ShiftLeft(arguments_,(left,right)=>BindParameters(BindArgument(context,state,parameterLeft.name,instantiatedExtends,left),state,parameterRight,right),()=>BindParameters(BindArgument(context,state,parameterLeft.name,instantiatedExtends,instantiatedEquals),state,parameterRight,[]))}function BindParameters(context,state,parameters,arguments_){return ShiftLeft(parameters,(left,right)=>BindArguments(context,state,left,right,arguments_),()=>context)}function ResolveArgumentsContext(context,state,parameters,arguments_){return BindParameters(context,state,parameters,arguments_)}var instantiationDepth=0,instantiationCount=0;function InstantiationAssert(){if(IsLessThan(instantiationCount,Get().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function InstantiationIncrement(){InstantiationAssert(),instantiationCount++,instantiationDepth++}function InstantiationDecrement(){if(instantiationDepth--,IsEqual(instantiationDepth,0))instantiationCount=0}function Peek(state){return IsGreaterThan(state.callstack.length,0)?state.callstack[state.callstack.length-1]:""}function IsTailCall(state,name){return IsEqual(Peek(state),name)}function CallDispatch(context,state,target,parameters,expression,arguments_){InstantiationIncrement();try{let argumentsContext=ResolveArgumentsContext(context,state,parameters,arguments_),returnType=InstantiateType(argumentsContext,State([...state.callstack,target.$ref],state.visited),expression);return InstantiateType(argumentsContext,State([],[]),returnType)}finally{InstantiationDecrement()}}function CallDistributed(context,state,target,parameters,expression,distributedArguments){return distributedArguments.reduce((result,arguments_)=>{let returnType=CallDispatch(context,state,target,parameters,expression,arguments_);return[...result,returnType]},[])}function CallImmediate(context,state,target,parameters,expression,arguments_){let distributedArguments=DistributeArguments(parameters,arguments_,expression),returnTypes=CallDistributed(context,state,target,parameters,expression,distributedArguments);return IsEqual(returnTypes.length,1)?returnTypes[0]:EvaluateUnion(returnTypes)}function CallInstantiate(context,state,target,arguments_){let instantiatedArguments=InstantiateTypes(context,state,arguments_),resolved=ResolveTarget(context,target,arguments_),name=resolved[0],type=resolved[1];return IsGeneric(type)?IsTailCall(state,name)?CallConstruct(Ref2(name),instantiatedArguments):CallImmediate(context,state,Ref2(name),type.parameters,type.expression,instantiatedArguments):CallConstruct(target,instantiatedArguments)}function CallConstruct(target,arguments_){return Create({["~kind"]:"Call"},{type:"call",target,arguments:arguments_},{})}function IsCall(value){return IsKind(value,"Call")}function RemoveImmutableOperation(type){return Discard(type,["~immutable"])}function RemoveImmutableAction(type,options){return Update(RemoveImmutableOperation(type),{},options)}function RemoveImmutableInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return RemoveImmutableAction(instantiatedType,options)}function ApplyMapping(mapping,value){return mapping(value)}function FromLiteral3(mapping,value){return IsString(value)?Literal(ApplyMapping(mapping,value)):Literal(value)}function FromTemplateLiteral(mapping,pattern){let evaluated=EvaluateTemplateLiteral(pattern);return FromType7(mapping,evaluated)}function FromUnion2(mapping,types){let result=types.map((type)=>FromType7(mapping,type));return Union(result)}function FromType7(mapping,type){return IsLiteral(type)?FromLiteral3(mapping,type.const):IsTemplateLiteral(type)?FromTemplateLiteral(mapping,type.pattern):IsUnion(type)?FromUnion2(mapping,type.anyOf):type}function CapitalizeDeferred(type,options={}){return Deferred("Capitalize",[type],options)}function LowercaseDeferred(type,options={}){return Deferred("Lowercase",[type],options)}function UncapitalizeDeferred(type,options={}){return Deferred("Uncapitalize",[type],options)}function UppercaseDeferred(type,options={}){return Deferred("Uppercase",[type],options)}var CapitalizeMapping=(input)=>input[0].toUpperCase()+input.slice(1),LowercaseMapping=(input)=>input.toLowerCase(),UncapitalizeMapping=(input)=>input[0].toLowerCase()+input.slice(1),UppercaseMapping=(input)=>input.toUpperCase();function CapitalizeAction(type,options){return CanInstantiate([type])?Update(FromType7(CapitalizeMapping,type),{},options):CapitalizeDeferred(type,options)}function LowercaseAction(type,options){return CanInstantiate([type])?Update(FromType7(LowercaseMapping,type),{},options):LowercaseDeferred(type,options)}function UncapitalizeAction(type,options){return CanInstantiate([type])?Update(FromType7(UncapitalizeMapping,type),{},options):UncapitalizeDeferred(type,options)}function UppercaseAction(type,options){return CanInstantiate([type])?Update(FromType7(UppercaseMapping,type),{},options):UppercaseDeferred(type,options)}function CapitalizeInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return CapitalizeAction(instantiatedType,options)}function LowercaseInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return LowercaseAction(instantiatedType,options)}function UncapitalizeInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return UncapitalizeAction(instantiatedType,options)}function UppercaseInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return UppercaseAction(instantiatedType,options)}function ConditionalDeferred(left,right,true_,false_,options={}){return Deferred("Conditional",[left,right,true_,false_],options)}function ConditionalOperation(context,state,left,right,true_,false_){let extendsResult=Extends(context,left,right);return IsExtendsUnion(extendsResult)?Union([InstantiateType(extendsResult.inferred,state,true_),InstantiateType(context,state,false_)]):IsExtendsTrue(extendsResult)?InstantiateType(extendsResult.inferred,state,true_):InstantiateType(context,state,false_)}function ConditionalAction(context,state,left,right,true_,false_,options){return CanInstantiate([left,right])?Update(ConditionalOperation(context,state,left,right,true_,false_),{},options):ConditionalDeferred(left,right,true_,false_,options)}function ConditionalInstantiate(context,state,left,right,true_,false_,options){let instantiatedLeft=InstantiateType(context,state,left),instantiatedRight=InstantiateType(context,state,right);return ConditionalAction(context,state,instantiatedLeft,instantiatedRight,true_,false_,options)}function ConstructorParametersDeferred(type,options={}){return Deferred("ConstructorParameters",[type],options)}function ConstructorParametersOperation(type){let parameters=IsConstructor2(type)?type.parameters:[],instantiatedParameters=InstantiateElements({},State([],[]),parameters);return Tuple(instantiatedParameters)}function ConstructorParametersAction(type,options){return CanInstantiate([type])?Update(ConstructorParametersOperation(type),{},options):ConstructorParametersDeferred(type,options)}function ConstructorParametersInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return ConstructorParametersAction(instantiatedType,options)}function ExcludeDeferred(left,right,options={}){return Deferred("Exclude",[left,right],options)}function ExcludeAction(left,right,options){return CanInstantiate([left,right])?Update(ExcludeOperation(left,right),{},options):ExcludeDeferred(left,right,options)}function ExcludeInstantiate(context,state,left,right,options){let instantiatedLeft=InstantiateType(context,state,left),instantiatedRight=InstantiateType(context,state,right);return ExcludeAction(instantiatedLeft,instantiatedRight,options)}function ExtractDeferred(left,right,options={}){return Deferred("Extract",[left,right],options)}function ExtractType(left,right){let check=Extends({},left,right);return IsExtendsTrueLike(check)?[left]:[]}function ExtractUnion(left,right,result=[]){return ShiftLeft(left,(head,tail)=>ExtractUnion(tail,right,[...result,...ExtractType(head,right)]),()=>result)}function ExtractOperation(left,right){let evaluated=EvaluateType(left),canonical=IsUnion(evaluated)?evaluated.anyOf:[evaluated],remaining=ExtractUnion(canonical,right);return EvaluateUnion(remaining)}function ExtractAction(left,right,options){return CanInstantiate([left,right])?Update(ExtractOperation(left,right),{},options):ExtractDeferred(left,right,options)}function ExtractInstantiate(context,state,left,right,options){let instantiatedLeft=InstantiateType(context,state,left),instantiatedRight=InstantiateType(context,state,right);return ExtractAction(instantiatedLeft,instantiatedRight,options)}function IndexDeferred(type,indexer,options={}){return Deferred("Index",[type,indexer],options)}function FromCyclic(defs,ref){let target=CyclicTarget(defs,ref);return FromType8(target)}function FromDependent(if_,then_,else_){let evaluated=EvaluateDependent(if_,then_,else_);return FromType8(evaluated)}function CollapseIntersectProperties(left,right){let leftKeys=Keys(left).filter((key)=>!HasPropertyKey(right,key)),rightKeys=Keys(right).filter((key)=>!HasPropertyKey(left,key)),sharedKeys=Keys(left).filter((key)=>HasPropertyKey(right,key)),leftProperties=leftKeys.reduce((result,key)=>({...result,[key]:left[key]}),{}),rightProperties=rightKeys.reduce((result,key)=>({...result,[key]:right[key]}),{}),sharedProperties=sharedKeys.reduce((result,key)=>({...result,[key]:EvaluateIntersect([left[key],right[key]])}),{}),unique=Assign(leftProperties,rightProperties);return Assign(unique,sharedProperties)}function FromIntersect(types){return types.reduce((result,left)=>CollapseIntersectProperties(result,FromType8(left)),{})}function FromObject4(properties){return properties}function FromTuple(types){let object=TupleToObject(Tuple(types));return FromType8(object)}function CollapseUnionProperties(left,right){return Keys(left).filter((key)=>(key in right)).reduce((result,key)=>({...result,[key]:EvaluateUnion([left[key],right[key]])}),{})}function ReduceVariants(types,result){return ShiftLeft(types,(left,right)=>ReduceVariants(right,CollapseUnionProperties(result,FromType8(left))),()=>result)}function FromUnion3(types){return ShiftLeft(types,(left,right)=>ReduceVariants(right,FromType8(left)),()=>Unreachable())}function FromType8(type){return IsCyclic(type)?FromCyclic(type.$defs,type.$ref):IsDependent(type)?FromDependent(type.if,type.then,type.else):IsIntersect(type)?FromIntersect(type.allOf):IsUnion(type)?FromUnion3(type.anyOf):IsTuple(type)?FromTuple(type.items):IsObject2(type)?FromObject4(type.properties):{}}function CollapseToObject(type){let properties=FromType8(type);return _Object_(properties)}var integerKeyPattern=new RegExp("^(?:0|[1-9][0-9]*)$");function ConvertToIntegerKey(value){let normal=`${value}`;return integerKeyPattern.test(normal)?parseInt(normal):value}function NormalizeLiteral(value){return Literal(ConvertToIntegerKey(value))}function NormalizeIndexerTypes(types){return types.map((type)=>NormalizeIndexer(type))}function NormalizeIndexer(type){return IsIntersect(type)?Intersect(NormalizeIndexerTypes(type.allOf)):IsUnion(type)?Union(NormalizeIndexerTypes(type.anyOf)):IsLiteral(type)?NormalizeLiteral(type.const):type}function FromArray3(type,indexer){let normalizedIndexer=NormalizeIndexer(indexer),check=Extends({},normalizedIndexer,Number2());return IsExtendsTrueLike(check)?type:IsLiteral(indexer)&&IsEqual(indexer.const,"length")?Number2():Never()}function FromCyclic2(defs,ref){let target=CyclicTarget(defs,ref);return FromType9(target)}function FromDependent2(if_,then_,else_){let evaluated=EvaluateDependent(if_,then_,else_);return FromType9(evaluated)}function FromEnum(values){let evaluated=EvaluateEnum(values);return FromType9(evaluated)}function FromIntersect2(types){let evaluated=EvaluateIntersect(types);return FromType9(evaluated)}function FromLiteral4(value){return[`${value}`]}function FromTemplateLiteral2(pattern){let evaluated=EvaluateTemplateLiteral(pattern);return FromType9(evaluated)}function FromUnion4(types){return types.reduce((result,left)=>[...result,...FromType9(left)],[])}function FromType9(type){return IsCyclic(type)?FromCyclic2(type.$defs,type.$ref):IsDependent(type)?FromDependent2(type.if,type.then,type.else):IsEnum2(type)?FromEnum(type.enum):IsIntersect(type)?FromIntersect2(type.allOf):IsLiteral(type)?FromLiteral4(type.const):IsTemplateLiteral(type)?FromTemplateLiteral2(type.pattern):IsUnion(type)?FromUnion4(type.anyOf):[]}function ToIndexableKeys(type){return FromType9(type)}function FromTypes5(properties,types){return types.map((type)=>FromType10(properties,type))}function FromType10(properties,type){return IsArray2(type)?_Array_(FromType10(properties,type.items)):IsConstructor2(type)?Constructor(FromTypes5(properties,type.parameters),FromType10(properties,type.instanceType)):IsFunction2(type)?_Function_(FromTypes5(properties,type.parameters),FromType10(properties,type.returnType)):IsTuple(type)?Tuple(FromTypes5(properties,type.items)):IsUnion(type)?Union(FromTypes5(properties,type.anyOf)):IsIntersect(type)?Intersect(FromTypes5(properties,type.allOf)):IsThis(type)?_Object_(properties):type}function ExpandThis(properties,type){return FromType10(properties,type)}function IndexProperty(properties,key){let selectedType=key in properties?properties[key]:Never();return ExpandThis(properties,selectedType)}function IndexProperties(properties,keys){return keys.reduce((result,left)=>[...result,IndexProperty(properties,left)],[])}function FromIndexer(properties,indexer){let keys=ToIndexableKeys(indexer),variants=IndexProperties(properties,keys);return EvaluateUnion(variants)}var NumericKeyPattern=new RegExp(IntegerKey);function NumericKeys(keys){return keys.filter((key)=>NumericKeyPattern.test(key))}function FromIndexerNumber(properties){let keys=PropertyKeys(properties),numericKeys=NumericKeys(keys),variants=IndexProperties(properties,numericKeys);return EvaluateUnion(variants)}function FromObject5(properties,indexer){return IsNumber3(indexer)?FromIndexerNumber(properties):FromIndexer(properties,indexer)}function ConvertLiteral(value){return Literal(ConvertToIntegerKey(value))}function ArrayIndexerTypes(types){return types.map((type)=>FormatArrayIndexer(type))}function FormatArrayIndexer(type){return IsIntersect(type)?Intersect(ArrayIndexerTypes(type.allOf)):IsUnion(type)?Union(ArrayIndexerTypes(type.anyOf)):IsLiteral(type)?ConvertLiteral(type.const):type}function IndexElementsWithIndexer(types,indexer){return types.reduceRight((result,right,index)=>{let check=Extends({},Literal(index),indexer);return IsExtendsTrueLike(check)?[right,...result]:result},[])}function FromTupleWithIndexer(types,indexer){let formattedArrayIndexer=FormatArrayIndexer(indexer),elements=IndexElementsWithIndexer(types,formattedArrayIndexer);return EvaluateUnionFast(elements)}function FromTupleWithoutIndexer(types){return EvaluateUnionFast(types)}function FromTuple2(types,indexer){return IsLiteral(indexer)&&IsEqual(indexer.const,"length")?Literal(types.length):IsNumber3(indexer)||IsInteger2(indexer)?FromTupleWithoutIndexer(types):FromTupleWithIndexer(types,indexer)}function FromType11(type,indexer){return IsArray2(type)?FromArray3(type.items,indexer):IsObject2(type)?FromObject5(type.properties,indexer):IsTuple(type)?FromTuple2(type.items,indexer):Never()}function NormalizeType(type){return IsCyclic(type)||IsDependent(type)||IsIntersect(type)||IsUnion(type)?CollapseToObject(type):type}function IndexAction(type,indexer,options){return CanInstantiate([type,indexer])?Update(FromType11(NormalizeType(type),indexer),{},options):IndexDeferred(type,indexer,options)}function IndexInstantiate(context,state,type,indexer,options){let instantiatedType=InstantiateType(context,state,type),instantiatedIndexer=InstantiateType(context,state,indexer);return IndexAction(instantiatedType,instantiatedIndexer,options)}function InstanceTypeDeferred(type,options={}){return Deferred("InstanceType",[type],options)}function InstanceTypeOperation(type){return IsConstructor2(type)?type.instanceType:Never()}function InstanceTypeAction(type,options){return CanInstantiate([type])?Update(InstanceTypeOperation(type),{},options):InstanceTypeDeferred(type,options)}function InstanceTypeInstantiate(context,state,type,options={}){let instantiatedType=InstantiateType(context,state,type);return InstanceTypeAction(instantiatedType,options)}function KeyOfDeferred(type,options={}){return Deferred("KeyOf",[type],options)}function FromAny(){return Union([Number2(),String2(),Symbol2()])}function FromArray4(_type){return Number2()}function FromPropertyKeys(keys){return keys.reduce((result,left)=>IsLiteralValue(left)?[...result,Literal(ConvertToIntegerKey(left))]:Unreachable(),[])}function FromObject6(properties){let propertyKeys=Keys(properties),variants=FromPropertyKeys(propertyKeys);return EvaluateUnionFast(variants)}function FromRecord2(type){return RecordKey(type)}function FromTuple3(types){let result=types.map((_,index)=>Literal(index));return EvaluateUnionFast(result)}function FromType12(type){return IsAny(type)?FromAny():IsArray2(type)?FromArray4(type.items):IsObject2(type)?FromObject6(type.properties):IsRecord(type)?FromRecord2(type):IsTuple(type)?FromTuple3(type.items):Never()}function NormalizeType2(type){return IsCyclic(type)||IsDependent(type)||IsIntersect(type)||IsUnion(type)?CollapseToObject(type):type}function KeyOfAction(type,options){return CanInstantiate([type])?Update(FromType12(NormalizeType2(type)),{},options):KeyOfDeferred(type,options)}function KeyOfInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return KeyOfAction(instantiatedType,options)}function MappedDeferred(identifier,type,as,property,options={}){return Deferred("Mapped",[identifier,type,as,property],options)}function FromTemplateLiteral3(pattern){let evaluated=EvaluateTemplateLiteral(pattern);return FromType13(evaluated)}function FromUnion5(types){return types.reduce((result,left)=>[...result,...FromType13(left)],[])}function FromEnum2(values){let evaluated=EvaluateEnum(values);return FromType13(evaluated)}function FromLiteral5(value){return IsNumber(value)?[Literal(`${value}`)]:[Literal(value)]}function FromType13(type){return IsEnum2(type)?FromEnum2(type.enum):IsLiteral(type)?FromLiteral5(type.const):IsTemplateLiteral(type)?FromTemplateLiteral3(type.pattern):IsUnion(type)?FromUnion5(type.anyOf):[type]}function MappedVariants(type){return FromType13(type)}function CanonicalAs(instantiatedAs){return IsTemplateLiteral(instantiatedAs)?EvaluateTemplateLiteral(instantiatedAs.pattern):instantiatedAs}function MappedVariant(context,state,identifier,variant,as,property){let variantContext=Assign(context,{[identifier.name]:variant}),instantiatedAs=InstantiateType(variantContext,state,as),canonicalAs=CanonicalAs(instantiatedAs),instantiatedProperty=InstantiateType(variantContext,state,property);return IsLiteralNumber(canonicalAs)||IsLiteralString(canonicalAs)?{[canonicalAs.const]:instantiatedProperty}:{}}function MappedProperties(context,state,identifier,variants,as,property){return variants.reduce((result,left)=>[...result,MappedVariant(context,state,identifier,left,as,property)],[])}function MappedObjects(properties){return properties.reduce((result,left)=>[...result,_Object_(left)],[])}function MappedOperation(context,state,identifier,type,as,property){let variants=MappedVariants(type),mappedProperties=MappedProperties(context,state,identifier,variants,as,property),mappedObjects=MappedObjects(mappedProperties);return EvaluateIntersect(mappedObjects)}function MappedAction(context,state,identifier,type,as,property,options){return CanInstantiate([type])?Update(MappedOperation(context,state,identifier,type,as,property),{},options):MappedDeferred(identifier,type,as,property,options)}function MappedInstantiate(context,state,identifier,type,as,property,options){let instantiatedType=InstantiateType(context,state,type);return MappedAction(context,state,identifier,instantiatedType,as,property,options)}function InstantiateCyclics(context,declarations,cyclicKeys){let declarationContext=Assign(context,declarations);return Keys(declarations).filter((key)=>cyclicKeys.includes(key)).reduce((result,key)=>({...result,[key]:InstantiateCyclic(declarationContext,key,declarations[key])}),{})}function InstantiateNonCyclics(context,declarations,cyclicKeys){let declarationContext=Assign(context,declarations);return Keys(declarations).filter((key)=>!cyclicKeys.includes(key)).reduce((result,key)=>({...result,[key]:InstantiateType(declarationContext,State([],[]),declarations[key])}),{})}function InstantiateModule(context,declarations,options){let cyclicCandidates=CyclicCandidates(declarations),instantiatedCyclics=InstantiateCyclics(context,declarations,cyclicCandidates),instantiatedNonCyclics=InstantiateNonCyclics(context,declarations,cyclicCandidates),instantiatedModule={...instantiatedCyclics,...instantiatedNonCyclics};return Update(instantiatedModule,{},options)}function ModuleInstantiate(context,_state,declarations,options){return InstantiateModule(context,declarations,options)}function NonNullableDeferred(type,options={}){return Deferred("NonNullable",[type],options)}function NonNullableOperation(type){let excluded=Union([Null(),Undefined()]);return ExcludeAction(type,excluded,{})}function NonNullableAction(type,options){return CanInstantiate([type])?Update(NonNullableOperation(type),{},options):NonNullableDeferred(type,options)}function NonNullableInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return NonNullableAction(instantiatedType,options)}function OmitDeferred(type,indexer,options={}){return Deferred("Omit",[type,indexer],options)}function ToIndexable(type){let collapsed=CollapseToObject(type);return IsObject2(collapsed)?collapsed.properties:Unreachable()}function FromKeys(properties,keys){return Keys(properties).reduce((result,key)=>keys.includes(key)?result:{...result,[key]:properties[key]},{})}function FromType14(type,indexer){let indexable=ToIndexable(type),indexableKeys=ToIndexableKeys(indexer),omitted=FromKeys(indexable,indexableKeys);return _Object_(omitted)}function OmitAction(type,indexer,options){return CanInstantiate([type,indexer])?Update(FromType14(type,indexer),{},options):OmitDeferred(type,indexer,options)}function OmitInstantiate(context,state,type,indexer,options){let instantiatedType=InstantiateType(context,state,type),instantiatedIndexer=InstantiateType(context,state,indexer);return OmitAction(instantiatedType,instantiatedIndexer,options)}function ParametersDeferred(type,options={}){return Deferred("Parameters",[type],options)}function ParametersOperation(type){let parameters=IsFunction2(type)?type.parameters:[],instantiatedParameters=InstantiateElements({},State([],[]),parameters);return Tuple(instantiatedParameters)}function ParametersAction(type,options){return CanInstantiate([type])?Update(ParametersOperation(type),{},options):ParametersDeferred(type,options)}function ParametersInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return ParametersAction(instantiatedType,options)}function PartialDeferred(type,options={}){return Deferred("Partial",[type],options)}function FromCyclic3(defs,ref){let target=CyclicTarget(defs,ref),partial=FromType15(target);return Cyclic(Assign(defs,{[ref]:partial}),ref)}function FromDependent3(if_,then_,else_){let evaluated=EvaluateDependent(if_,then_,else_);return FromType15(evaluated)}function FromIntersect3(types){let evaluated=EvaluateIntersect(types);return FromType15(evaluated)}function FromUnion6(types){let result=types.map((type)=>FromType15(type));return Union(result)}function FromObject7(properties){let mapped=Keys(properties).reduce((result,left)=>({...result,[left]:AddOptional(properties[left])}),{});return _Object_(mapped)}function FromType15(type){return IsCyclic(type)?FromCyclic3(type.$defs,type.$ref):IsDependent(type)?FromDependent3(type.if,type.then,type.else):IsIntersect(type)?FromIntersect3(type.allOf):IsUnion(type)?FromUnion6(type.anyOf):IsObject2(type)?FromObject7(type.properties):_Object_({})}function PartialAction(type,options){return CanInstantiate([type])?Update(FromType15(type),{},options):PartialDeferred(type,options)}function PartialInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return PartialAction(instantiatedType,options)}function PickDeferred(type,indexer,options={}){return Deferred("Pick",[type,indexer],options)}function FromKeys2(properties,keys){return Keys(properties).reduce((result,key)=>keys.includes(key)?Assign(result,{[key]:properties[key]}):result,{})}function FromType16(type,indexer){let indexable=ToIndexable(type),keys=ToIndexableKeys(indexer),applied=FromKeys2(indexable,keys);return _Object_(applied)}function PickAction(type,indexer,options){return CanInstantiate([type,indexer])?Update(FromType16(type,indexer),{},options):PickDeferred(type,indexer,options)}function PickInstantiate(context,state,type,indexer,options){let instantiatedType=InstantiateType(context,state,type),instantiatedIndexer=InstantiateType(context,state,indexer);return PickAction(instantiatedType,instantiatedIndexer,options)}function ReadonlyObjectDeferred(type,options={}){return Deferred("ReadonlyObject",[type],options)}function FromArray5(type){return AddImmutable(_Array_(type))}function FromCyclic4(defs,ref){let target=CyclicTarget(defs,ref),partial=FromType17(target);return Cyclic(Assign(defs,{[ref]:partial}),ref)}function FromDependent4(if_,then_,else_){let evaluated=EvaluateDependent(if_,then_,else_);return FromType17(evaluated)}function FromIntersect4(types){let evaluated=EvaluateIntersect(types);return FromType17(evaluated)}function FromObject8(properties){let mapped=Keys(properties).reduce((result,left)=>({...result,[left]:AddReadonly(properties[left])}),{});return _Object_(mapped)}function FromTuple4(types){return AddImmutable(Tuple(types))}function FromUnion7(types){let result=types.map((type)=>FromType17(type));return Union(result)}function FromType17(type){return IsArray2(type)?FromArray5(type.items):IsCyclic(type)?FromCyclic4(type.$defs,type.$ref):IsDependent(type)?FromDependent4(type.if,type.then,type.else):IsIntersect(type)?FromIntersect4(type.allOf):IsObject2(type)?FromObject8(type.properties):IsTuple(type)?FromTuple4(type.items):IsUnion(type)?FromUnion7(type.anyOf):type}function ReadonlyObjectAction(type,options){return CanInstantiate([type])?Update(FromType17(type),{},options):ReadonlyObjectDeferred(type)}function ReadonlyObjectInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return ReadonlyObjectAction(instantiatedType,options)}function RefInstantiate(context,state,type,ref){return state.visited.includes(ref)?type:(ref in context)?InstantiateType(context,State(state.callstack,[...state.visited,ref]),context[ref]):type}function FromCyclic5(defs,ref){let target=CyclicTarget(defs,ref),partial=FromType18(target);return Cyclic(Assign(defs,{[ref]:partial}),ref)}function FromDependent5(if_,then_,else_){let evaluated=EvaluateDependent(if_,then_,else_);return FromType18(evaluated)}function FromIntersect5(types){let evaluated=EvaluateIntersect(types);return FromType18(evaluated)}function FromUnion8(types){let result=types.map((type)=>FromType18(type));return Union(result)}function FromObject9(properties){let mapped=Keys(properties).reduce((result,left)=>({...result,[left]:RemoveOptional(properties[left])}),{});return _Object_(mapped)}function FromType18(type){return IsCyclic(type)?FromCyclic5(type.$defs,type.$ref):IsDependent(type)?FromDependent5(type.if,type.then,type.else):IsIntersect(type)?FromIntersect5(type.allOf):IsUnion(type)?FromUnion8(type.anyOf):IsObject2(type)?FromObject9(type.properties):_Object_({})}function RequiredDeferred(type,options={}){return Deferred("Required",[type],options)}function RequiredAction(type,options){return CanInstantiate([type])?Update(FromType18(type),{},options):RequiredDeferred(type,options)}function RequiredInstantiate(context,state,type,options){let instaniatedType=InstantiateType(context,state,type);return RequiredAction(instaniatedType,options)}function ReturnTypeDeferred(type,options={}){return Deferred("ReturnType",[type],options)}function ReturnTypeOperation(type){return IsFunction2(type)?type.returnType:Never()}function ReturnTypeAction(type,options){return CanInstantiate([type])?Update(ReturnTypeOperation(type),{},options):ReturnTypeDeferred(type,options)}function ReturnTypeInstantiate(context,state,type,options={}){let instantiatedType=InstantiateType(context,state,type);return ReturnTypeAction(instantiatedType,options)}function WithDeferred(type,options){return Deferred("With",[type,options],{})}function With(type,options){return WithAction(type,options)}function WithAction(type,options){return CanInstantiate([type])?Update(type,{},options):WithDeferred(type,options)}function WithInstantiate(context,state,type,options){let instaniatedType=InstantiateType(context,state,type);return WithAction(instaniatedType,options)}function SpreadElement(type){return IsRest(type)?IsTuple(type.items)?RestSpread(type.items.items):IsInfer(type.items)?[type]:IsRef2(type.items)?[type]:[Never()]:[type]}function RestSpread(types){return types.reduce((result,left)=>[...result,...SpreadElement(left)],[])}function State(callstack,visited){return{callstack,visited}}function CanInstantiate(types){return ShiftLeft(types,(left,right)=>IsRef2(left)?!1:CanInstantiate(right),()=>!0)}function InstantiateProperties(context,state,properties){return Keys(properties).reduce((result,key)=>({...result,[key]:InstantiateType(context,state,properties[key])}),{})}function InstantiateElements(context,state,types){let elements=InstantiateTypes(context,state,types);return RestSpread(elements)}function InstantiateTypes(context,state,types){return types.map((type)=>InstantiateType(context,state,type))}function WithModifiers(type,instantiatedType){let withOptional=IsOptional(type)?AddOptionalAction(instantiatedType,{}):instantiatedType,withReadonly=IsReadonly(type)?AddReadonlyAction(withOptional,{}):withOptional;return IsImmutable(type)?AddImmutableAction(withReadonly,{}):withReadonly}function InstantiateDeferred(context,state,action,parameters,options){return IsEqual(action,"AddImmutable")?AddImmutableInstantiate(context,state,parameters[0],options):IsEqual(action,"RemoveImmutable")?RemoveImmutableInstantiate(context,state,parameters[0],options):IsEqual(action,"AddReadonly")?AddReadonlyInstantiate(context,state,parameters[0],options):IsEqual(action,"RemoveReadonly")?RemoveReadonlyInstantiate(context,state,parameters[0],options):IsEqual(action,"AddOptional")?AddOptionalInstantiate(context,state,parameters[0],options):IsEqual(action,"RemoveOptional")?RemoveOptionalInstantiate(context,state,parameters[0],options):IsEqual(action,"Capitalize")?CapitalizeInstantiate(context,state,parameters[0],options):IsEqual(action,"Conditional")?ConditionalInstantiate(context,state,parameters[0],parameters[1],parameters[2],parameters[3],options):IsEqual(action,"ConstructorParameters")?ConstructorParametersInstantiate(context,state,parameters[0],options):IsEqual(action,"Evaluate")?EvaluateInstantiate(context,state,parameters[0],options):IsEqual(action,"Exclude")?ExcludeInstantiate(context,state,parameters[0],parameters[1],options):IsEqual(action,"Extract")?ExtractInstantiate(context,state,parameters[0],parameters[1],options):IsEqual(action,"Index")?IndexInstantiate(context,state,parameters[0],parameters[1],options):IsEqual(action,"InstanceType")?InstanceTypeInstantiate(context,state,parameters[0],options):IsEqual(action,"Interface")?InterfaceInstantiate(context,state,parameters[0],parameters[1],options):IsEqual(action,"KeyOf")?KeyOfInstantiate(context,state,parameters[0],options):IsEqual(action,"Lowercase")?LowercaseInstantiate(context,state,parameters[0],options):IsEqual(action,"Mapped")?MappedInstantiate(context,state,parameters[0],parameters[1],parameters[2],parameters[3],options):IsEqual(action,"Module")?ModuleInstantiate(context,state,parameters[0],options):IsEqual(action,"NonNullable")?NonNullableInstantiate(context,state,parameters[0],options):IsEqual(action,"Pick")?PickInstantiate(context,state,parameters[0],parameters[1],options):IsEqual(action,"Parameters")?ParametersInstantiate(context,state,parameters[0],options):IsEqual(action,"Partial")?PartialInstantiate(context,state,parameters[0],options):IsEqual(action,"Omit")?OmitInstantiate(context,state,parameters[0],parameters[1],options):IsEqual(action,"ReadonlyObject")?ReadonlyObjectInstantiate(context,state,parameters[0],options):IsEqual(action,"Record")?RecordInstantiate(context,state,parameters[0],parameters[1],options):IsEqual(action,"Required")?RequiredInstantiate(context,state,parameters[0],options):IsEqual(action,"ReturnType")?ReturnTypeInstantiate(context,state,parameters[0],options):IsEqual(action,"TemplateLiteral")?TemplateLiteralInstantiate(context,state,parameters[0],options):IsEqual(action,"Uncapitalize")?UncapitalizeInstantiate(context,state,parameters[0],options):IsEqual(action,"Uppercase")?UppercaseInstantiate(context,state,parameters[0],options):IsEqual(action,"With")?WithInstantiate(context,state,parameters[0],parameters[1]):Deferred(action,parameters,options)}function InstantiateImmediate(context,state,type){let instantiatedType=IsRef2(type)?RefInstantiate(context,state,type,type.$ref):IsArray2(type)?_Array_(InstantiateType(context,state,type.items),ArrayOptions(type)):IsCall(type)?CallInstantiate(context,state,type.target,type.arguments):IsConstructor2(type)?Constructor(InstantiateTypes(context,state,type.parameters),InstantiateType(context,state,type.instanceType),ConstructorOptions(type)):IsFunction2(type)?_Function_(InstantiateTypes(context,state,type.parameters),InstantiateType(context,state,type.returnType),FunctionOptions(type)):IsDependent(type)?Dependent(InstantiateType(context,state,type.if),InstantiateType(context,state,type.then),InstantiateType(context,state,type.else),DependentOptions(type)):IsIntersect(type)?Intersect(InstantiateTypes(context,state,type.allOf),IntersectOptions(type)):IsObject2(type)?_Object_(InstantiateProperties(context,state,type.properties),ObjectOptions(type)):IsRecord(type)?RecordFromPattern(RecordPattern(type),InstantiateType(context,state,RecordValue(type))):IsRest(type)?Rest(InstantiateType(context,state,type.items)):IsTuple(type)?Tuple(InstantiateElements(context,state,type.items),TupleOptions(type)):IsUnion(type)?Union(InstantiateTypes(context,state,type.anyOf),UnionOptions(type)):type;return WithModifiers(type,instantiatedType)}function InstantiateType(context,state,type){return IsDeferred(type)?InstantiateDeferred(context,state,type.action,type.parameters,type.options):InstantiateImmediate(context,state,type)}function Instantiate(context,type){return InstantiateType(context,State([],[]),type)}function AddImmutableOperation(type){return Update(type,{"~immutable":!0},{})}function AddImmutableAction(type,options){return Update(AddImmutableOperation(type),{},options)}function AddImmutableInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return AddImmutableAction(instantiatedType,options)}function AddImmutable(type,options={}){return AddImmutableAction(type,options)}function Evaluate(type,options={}){return EvaluateAction(type,options)}function Comparer(left,right){let compareResult=Compare(left,right);return IsEqual(compareResult,CompareResultRightInside)?1:IsEqual(compareResult,CompareResultDisjoint)?1:0}function Insert(type,types,result=[]){return ShiftLeft(types,(left,right)=>IsEqual(Comparer(type,left),1)?Insert(type,right,[...result,left]):[...result,type,...types],()=>[...result,type])}function Sort(types,result=[]){return ShiftLeft(types,(left,right)=>Sort(right,Insert(left,result)),()=>result)}function Priority(types){return Sort(types)}function FromArray6(context,type,value){if(!IsArray(value))return value;return value.map((value)=>FromType19(context,type.items,value))}function FromCyclic6(context,type,value){return FromType19({...context,...type.$defs},Ref2(type.$ref),value)}function EvaluateIntersection(context,type){let additionalProperties=HasPropertyKey(type,"unevaluatedProperties")?{additionalProperties:type.unevaluatedProperties}:{},instantiated=Instantiate(context,type),evaluated=Evaluate(instantiated);return IsObject2(evaluated)?With(evaluated,additionalProperties):evaluated}function FromIntersect6(context,type,value){let evaluated=EvaluateIntersection(context,type);return FromType19(context,evaluated,value)}function GetAdditionalProperties(type){return HasPropertyKey(type,"additionalProperties")?type.additionalProperties:void 0}function FromObject10(context,type,value){if(!IsObject(value)||IsArray(value))return value;let additionalProperties=GetAdditionalProperties(type);for(let key of Keys(value)){if(HasPropertyKey(type.properties,key)){value[key]=FromType19(context,type.properties[key],value[key]);continue}if(IsBoolean(additionalProperties)&&IsEqual(additionalProperties,!0)||IsSchema2(additionalProperties)&&Check2(context,additionalProperties,value[key])){value[key]=FromType19(context,additionalProperties,value[key]);continue}delete value[key]}return value}function FromRecord3(context,type,value){if(!IsObject(value))return value;let additionalProperties=GetAdditionalProperties(type),[recordPattern,recordValue]=[new RegExp(RecordPattern(type)),RecordValue(type)];for(let key of Keys(value)){if(recordPattern.test(key)){value[key]=FromType19(context,recordValue,value[key]);continue}if(IsBoolean(additionalProperties)&&IsEqual(additionalProperties,!0)||IsSchema2(additionalProperties)&&Check2(context,additionalProperties,value[key])){value[key]=FromType19(context,additionalProperties,value[key]);continue}delete value[key]}return value}function FromRef5(context,type,value){return HasPropertyKey(context,type.$ref)?FromType19(context,context[type.$ref],value):value}function FromTuple5(context,schema,value){if(!IsArray(value))return value;let length=Math.min(value.length,schema.items.length);for(let index=0;index<length;index++)value[index]=FromType19(context,schema.items[index],value[index]);return IsGreaterThan(value.length,length)?value.slice(0,length):value}function Clone2(value){return Clone(value)}function FromUnion9(context,type,value){for(let schema of type.anyOf){let clean=FromType19(context,schema,Clone2(value));if(Check2(context,schema,clean))return clean}return value}function FromType19(context,type,value){return IsArray2(type)?FromArray6(context,type,value):IsCyclic(type)?FromCyclic6(context,type,value):IsIntersect(type)?FromIntersect6(context,type,value):IsObject2(type)?FromObject10(context,type,value):IsRecord(type)?FromRecord3(context,type,value):IsRef2(type)?FromRef5(context,type,value):IsTuple(type)?FromTuple5(context,type,value):IsUnion(type)?FromUnion9(context,type,value):value}function Modifiers(type,next){for(let key of Keys(type)){if(HasPropertyKey(next,key))continue;next[key]=type[key]}return next}function FromProperties4(properties){let result={};for(let key of Keys(properties))result[key]=FromType20(properties[key]);return result}function FromPriorityTypes(types){return FromTypes6(Priority(types))}function FromTypes6(types){return types.map((type)=>FromType20(type))}function FromType20(type){let next=IsArray2(type)?_Array_(FromType20(type.items),ArrayOptions(type)):IsIntersect(type)?Intersect(FromTypes6(type.allOf)):IsUnion(type)?Union(FromPriorityTypes(type.anyOf)):IsObject2(type)?_Object_(FromProperties4(type.properties)):IsRecord(type)?Record(RecordKey(type),FromType20(RecordValue(type))):IsTuple(type)?Tuple(FromTypes6(type.items)):type;return Modifiers(type,next)}function UnionPrioritySort(type){return FromType20(type)}function Clean(...args){let[context,type,value]=Match(args,{3:(context,type,value)=>[context,type,value],2:(type,value)=>[{},type,value]}),sorted=Get().unionPrioritySort?UnionPrioritySort(type):type;return FromType19(context,sorted,value)}function IsOk(value){return IsObject(value)&&HasPropertyKey(value,"value")}function Ok(value){return{value}}function Fail(){return}function TryArray(value){return IsArray(value)?Ok(value):Ok([value])}function FromBoolean2(value){return IsEqual(value,!0)?Ok(BigInt(1)):Ok(BigInt(0))}var bigintPattern=/^-?(0|[1-9]\d*)n$/,decimalPattern=/^-?(0|[1-9]\d*)\.\d+$/,integerPattern=/^-?(0|[1-9]\d*)$/;function IsStringBigIntLike(value){return bigintPattern.test(value)}function IsStringDecimalLike(value){return decimalPattern.test(value)}function IsStringIntegerLike(value){return integerPattern.test(value)}function FromString2(value){let lowercase=value.toLowerCase();return IsStringBigIntLike(value)?Ok(BigInt(value.slice(0,value.length-1))):IsStringDecimalLike(value)?Ok(BigInt(value.split(".")[0])):IsStringIntegerLike(value)?Ok(BigInt(value)):IsEqual(lowercase,"false")?Ok(BigInt(0)):IsEqual(lowercase,"true")?Ok(BigInt(1)):Fail()}function TryBigInt(value){return IsBigInt(value)?Ok(value):IsBoolean(value)?FromBoolean2(value):IsNumber(value)?Ok(BigInt(Math.trunc(value))):IsNull(value)?Ok(BigInt(0)):IsString(value)?FromString2(value):IsUndefined(value)?Ok(BigInt(0)):Fail()}function FromBigInt2(value){return IsEqual(value,BigInt(0))?Ok(!1):IsEqual(value,BigInt(1))?Ok(!0):Fail()}function FromNumber2(value){return IsEqual(value,0)?Ok(!1):IsEqual(value,1)?Ok(!0):Fail()}function FromString3(value){return IsEqual(value.toLowerCase(),"false")?Ok(!1):IsEqual(value.toLowerCase(),"true")?Ok(!0):IsEqual(value,"0")?Ok(!1):IsEqual(value,"1")?Ok(!0):Fail()}function TryBoolean(value){return IsBigInt(value)?FromBigInt2(value):IsBoolean(value)?Ok(value):IsNumber(value)?FromNumber2(value):IsNull(value)?Ok(!1):IsString(value)?FromString3(value):IsUndefined(value)?Ok(!1):Fail()}function FromBigInt3(value){return IsEqual(value,BigInt(0))?Ok(null):Fail()}function FromBoolean3(value){return IsEqual(value,!1)?Ok(null):Fail()}function FromNumber3(value){return IsEqual(value,0)?Ok(null):Fail()}function FromString4(value){let lowercase=value.toLowerCase();return IsEqual(lowercase,"undefined")||IsEqual(lowercase,"null")||IsEqual(value,"")||IsEqual(value,"0")?Ok(null):Fail()}function TryNull(value){return IsBigInt(value)?FromBigInt3(value):IsBoolean(value)?FromBoolean3(value):IsNumber(value)?FromNumber3(value):IsNull(value)?Ok(null):IsString(value)?FromString4(value):IsUndefined(value)?Ok(null):Fail()}var maxBigInt=BigInt(Number.MAX_SAFE_INTEGER),minBigInt=BigInt(Number.MIN_SAFE_INTEGER);function FromBigInt4(value){return value<=maxBigInt&&value>=minBigInt?Ok(Number(value)):Fail()}function FromBoolean4(value){return Ok(value?1:0)}function FromString5(value){let coerced=+value;if(IsNumber(coerced))return Ok(coerced);let lowercase=value.toLowerCase();if(IsEqual(lowercase,"false"))return Ok(0);if(IsEqual(lowercase,"true"))return Ok(1);let result=TryBigInt(value);if(IsOk(result))return result.value<=maxBigInt&&result.value>=minBigInt?Ok(Number(result.value)):Fail();return Fail()}function TryNumber(value){return IsBigInt(value)?FromBigInt4(value):IsBoolean(value)?FromBoolean4(value):IsNumber(value)?Ok(value):IsNull(value)?Ok(0):IsString(value)?FromString5(value):IsUndefined(value)?Ok(0):Fail()}function TryString(value){return IsBigInt(value)?Ok(value.toString()):IsBoolean(value)?Ok(value.toString()):IsNumber(value)?Ok(value.toString()):IsNull(value)?Ok("null"):IsString(value)?Ok(value):IsUndefined(value)?Ok(""):Fail()}function FromBigInt5(value){return IsEqual(value,BigInt(0))?Ok(void 0):Fail()}function FromBoolean5(value){return IsEqual(value,!1)?Ok(void 0):Fail()}function FromNumber4(value){return IsEqual(value,0)?Ok(void 0):Fail()}function FromString6(value){let lowercase=value.toLowerCase();return IsEqual(lowercase,"undefined")||IsEqual(lowercase,"null")||IsEqual(value,"")||IsEqual(value,"0")?Ok(void 0):Fail()}function TryUndefined(value){return IsBigInt(value)?FromBigInt5(value):IsBoolean(value)?FromBoolean5(value):IsNumber(value)?FromNumber4(value):IsNull(value)?Ok(void 0):IsString(value)?FromString6(value):IsUndefined(value)?Ok(value):Fail()}function FromArray7(context,type,value){return TryArray(value).value.map((value)=>FromType21(context,type.items,value))}function FromBigInt6(_context,_type,value){let result=TryBigInt(value);return IsOk(result)?result.value:value}function FromBoolean6(_context,_type,value){let result=TryBoolean(value);return IsOk(result)?result.value:value}function FromCyclic7(context,type,value){return FromType21({...context,...type.$defs},Ref2(type.$ref),value)}function FromEnum3(context,type,value){return FromType21(context,Evaluate(type),value)}function FromInteger(_context,_type,value){let result=TryNumber(value);return IsOk(result)?Math.trunc(result.value):value}function FromIntersect7(context,type,value){let instantiated=Instantiate(context,type),evaluated=Evaluate(instantiated);return FromType21(context,evaluated,value)}function FromLiteralBigInt(_context,type,value){let result=TryBigInt(value);return IsOk(result)&&IsEqual(type.const,result.value)?result.value:value}function FromLiteralBoolean(_context,type,value){let result=TryBoolean(value);return IsOk(result)&&IsEqual(type.const,result.value)?result.value:value}function FromLiteralNumber(_context,type,value){let result=TryNumber(value);return IsOk(result)&&IsEqual(type.const,result.value)?result.value:value}function FromLiteralString(_context,type,value){let result=TryString(value);return IsOk(result)&&IsEqual(type.const,result.value)?result.value:value}function FromLiteral6(context,type,value){if(IsEqual(type.const,value))return value;return IsLiteralBigInt(type)?FromLiteralBigInt(context,type,value):IsLiteralBoolean(type)?FromLiteralBoolean(context,type,value):IsLiteralNumber(type)?FromLiteralNumber(context,type,value):IsLiteralString(type)?FromLiteralString(context,type,value):Unreachable()}function FromNull2(_context,_type,value){let result=TryNull(value);return IsOk(result)?result.value:value}function FromNumber5(_context,_type,value){let result=TryNumber(value);return IsOk(result)?result.value:value}function FromAdditionalProperties(context,entries,additionalProperties,value){let keys=Keys(value);for(let[regexp,_]of entries)for(let key of keys)if(!regexp.test(key))value[key]=FromType21(context,additionalProperties,value[key]);return value}function IsOptionalUndefined(property,key,value){return IsOptional(property)&&IsUndefined(value[key])}function FromProperties5(context,type,value){let entries=EntriesRegExp(type.properties),keys=Keys(value);for(let[regexp,property]of entries)for(let key of keys){if(!regexp.test(key)||IsOptionalUndefined(property,key,value))continue;value[key]=FromType21(context,property,value[key])}return HasPropertyKey(type,"additionalProperties")&&IsObject(type.additionalProperties)?FromAdditionalProperties(context,entries,type.additionalProperties,value):value}function FromObject11(context,type,value){return IsObjectNotArray(value)?FromProperties5(context,type,value):value}function FromPatternProperties(context,type,value){let entries=EntriesRegExp(type.patternProperties),keys=Keys(value);for(let[regexp,schema]of entries)for(let key of keys)if(regexp.test(key))value[key]=FromType21(context,schema,value[key]);return HasPropertyKey(type,"additionalProperties")&&IsObject(type.additionalProperties)?FromAdditionalProperties(context,entries,type.additionalProperties,value):value}function FromRecord4(context,type,value){return IsObjectNotArray(value)?FromPatternProperties(context,type,value):value}function FromRef6(context,type,value){return HasPropertyKey(context,type.$ref)?FromType21(context,context[type.$ref],value):value}function FromString7(_context,_type,value){let result=TryString(value);return IsOk(result)?result.value:value}function FromTemplateLiteral4(context,type,value){return FromType21(context,Evaluate(type),value)}function FromTuple6(context,type,value){if(!IsArray(value))return value;for(let index=0;index<Math.min(type.items.length,value.length);index++)value[index]=FromType21(context,type.items[index],value[index]);return value}function FromUndefined2(_context,_type,value){let result=TryUndefined(value);return IsOk(result)?result.value:value}function FromUnion10(context,type,value){if(type.anyOf.some((type)=>Check2(context,type,value)))return value;let selected=type.anyOf.map((type)=>FromType21(context,type,Clone2(value))).find((value)=>Check2(context,type,value));return IsUndefined(selected)?value:selected}function FromVoid(_context,_type,value){let result=TryUndefined(value);return IsOk(result)?void 0:value}function FromType21(context,type,value){return IsArray2(type)?FromArray7(context,type,value):IsBigInt2(type)?FromBigInt6(context,type,value):IsBoolean3(type)?FromBoolean6(context,type,value):IsCyclic(type)?FromCyclic7(context,type,value):IsEnum2(type)?FromEnum3(context,type,value):IsInteger2(type)?FromInteger(context,type,value):IsIntersect(type)?FromIntersect7(context,type,value):IsLiteral(type)?FromLiteral6(context,type,value):IsNull2(type)?FromNull2(context,type,value):IsNumber3(type)?FromNumber5(context,type,value):IsObject2(type)?FromObject11(context,type,value):IsRecord(type)?FromRecord4(context,type,value):IsRef2(type)?FromRef6(context,type,value):IsString3(type)?FromString7(context,type,value):IsTemplateLiteral(type)?FromTemplateLiteral4(context,type,value):IsTuple(type)?FromTuple6(context,type,value):IsUndefined2(type)?FromUndefined2(context,type,value):IsUnion(type)?FromUnion10(context,type,value):IsVoid(type)?FromVoid(context,type,value):value}function Convert(...args){let[context,type,value]=Match(args,{3:(context,type,value)=>[context,type,value],2:(type,value)=>[{},type,value]});return FromType21(context,type,value)}function FromArray8(context,type,value){if(!IsArray(value))return value;for(let i=0;i<value.length;i++)value[i]=FromType22(context,type.items,value[i]);return value}function FromCyclic8(context,type,value){return FromType22({...context,...type.$defs},Ref2(type.$ref),value)}function FromDefault(type,value){if(!IsUndefined(value))return value;return IsFunction(type.default)?type.default():Clone2(type.default)}function FromIntersect8(context,type,value){let instantiated=Instantiate(context,type),evaluated=Evaluate(instantiated);return FromType22(context,evaluated,value)}function FromObject12(context,type,value){if(!IsObject(value))return value;let knownPropertyKeys=Keys(type.properties);for(let key of knownPropertyKeys){let propertyValue=FromType22(context,type.properties[key],value[key]);if(IsUndefined(propertyValue)&&(IsOptional(type.properties[key])||!HasPropertyKey(type.properties[key],"default")))continue;value[key]=propertyValue}if(!IsAdditionalProperties(type)||IsBoolean(type.additionalProperties))return value;for(let key of Keys(value)){if(knownPropertyKeys.includes(key))continue;value[key]=FromType22(context,type.additionalProperties,value[key])}return value}function FromRecord5(context,type,value){if(!IsObject(value))return value;let[recordKey,recordValue]=[new RegExp(RecordPattern(type)),RecordValue(type)];for(let key of Keys(value)){if(!(recordKey.test(key)&&IsDefault(recordValue)))continue;value[key]=FromType22(context,recordValue,value[key])}if(!IsAdditionalProperties(type))return value;for(let key of Keys(value)){if(recordKey.test(key))continue;value[key]=FromType22(context,type.additionalProperties,value[key])}return value}function FromRef7(context,type,value){return HasPropertyKey(context,type.$ref)?FromType22(context,context[type.$ref],value):value}function FromTuple7(context,schema,value){if(!IsArray(value))return value;let[items,max]=[schema.items,Math.max(schema.items.length,value.length)];for(let i=0;i<max;i++)if(i<items.length)value[i]=FromType22(context,items[i],value[i]);return value}function FromUnion11(context,schema,value){for(let inner of schema.anyOf){let result=FromType22(context,inner,Clone2(value));if(Check2(context,inner,result))return result}return value}function FromType22(context,type,value){let defaulted=IsDefault(type)?FromDefault(type,value):value;return IsArray2(type)?FromArray8(context,type,defaulted):IsCyclic(type)?FromCyclic8(context,type,defaulted):IsIntersect(type)?FromIntersect8(context,type,defaulted):IsObject2(type)?FromObject12(context,type,defaulted):IsRecord(type)?FromRecord5(context,type,defaulted):IsRef2(type)?FromRef7(context,type,defaulted):IsTuple(type)?FromTuple7(context,type,defaulted):IsUnion(type)?FromUnion11(context,type,defaulted):defaulted}function Default(...args){let[context,type,value]=Match(args,{3:(context,type,value)=>[context,type,value],2:(type,value)=>[{},type,value]});return FromType22(context,type,value)}function Pipeline(pipeline){return(...args)=>{let[context,type,value]=Match(args,{3:(context,type,value)=>[context,type,value],2:(type,value)=>[{},type,value]});return pipeline.reduce((result,func)=>func(context,type,result),value)}}function Decode2(_context,type,value){return type["~codec"].decode(value)}function Encode2(_context,type,value){return type["~codec"].encode(value)}function Callback(direction,context,type,value){if(!IsCodec(type))return value;return IsEqual(direction,"Decode")?Decode2(context,type,value):Encode2(context,type,value)}function Decode3(direction,context,type,value){if(!IsArray(value))return value;for(let i=0;i<value.length;i++)value[i]=FromType23(direction,context,type.items,value[i]);return Callback(direction,context,type,value)}function Encode3(direction,context,type,value){let exterior=Callback(direction,context,type,value);if(!IsArray(exterior))return exterior;for(let i=0;i<exterior.length;i++)exterior[i]=FromType23(direction,context,type.items,exterior[i]);return exterior}function FromArray9(direction,context,type,value){return IsEqual(direction,"Decode")?Decode3(direction,context,type,value):Encode3(direction,context,type,value)}function FromCyclic9(direction,context,type,value){return value=FromType23(direction,{...context,...type.$defs},Ref2(type.$ref),value),Callback(direction,context,type,value)}function MergeInteriors(interiors){return interiors.reduce((results,interior)=>({...results,...interior}),{})}function NonMatchingInterior(value,interiors){for(let interior of interiors)if(!IsDeepEqual(value,interior))return interior;return value}function Decode4(direction,context,type,value){if(IsEqual(type.allOf.length,0))return Callback(direction,context,type,value);let interiors=type.allOf.map((schema)=>FromType23(direction,context,schema,Clean(schema,Clone2(value)))),exterior=interiors.every((result)=>IsObject(result))?MergeInteriors(interiors):NonMatchingInterior(value,interiors);return Callback(direction,context,type,exterior)}function Encode4(direction,context,type,value){if(IsEqual(type.allOf.length,0))return Callback(direction,context,type,value);let exterior=Callback(direction,context,type,value),interiors=type.allOf.map((schema)=>FromType23(direction,context,schema,Clean(schema,Clone2(exterior))));if(interiors.every((result)=>IsObject(result)))return MergeInteriors(interiors);return NonMatchingInterior(exterior,interiors)}function FromIntersect9(direction,context,type,value){return IsEqual(direction,"Decode")?Decode4(direction,context,type,value):Encode4(direction,context,type,value)}function Decode5(direction,context,type,value){if(!IsObjectNotArray(value))return value;for(let key of Keys(type.properties)){if(!HasPropertyKey(value,key)||IsOptionalUndefined(type.properties[key],key,value))continue;value[key]=FromType23(direction,context,type.properties[key],value[key])}return Callback(direction,context,type,value)}function Encode5(direction,context,type,value){let exterior=Callback(direction,context,type,value);if(!IsObjectNotArray(exterior))return exterior;for(let key of Keys(type.properties)){if(!HasPropertyKey(exterior,key)||IsOptionalUndefined(type.properties[key],key,exterior))continue;exterior[key]=FromType23(direction,context,type.properties[key],exterior[key])}return exterior}function FromObject13(direction,context,type,value){return IsEqual(direction,"Decode")?Decode5(direction,context,type,value):Encode5(direction,context,type,value)}function Decode6(direction,context,type,value){if(!IsObjectNotArray(value))return value;let regexp=new RegExp(RecordPattern(type));for(let key of Keys(value)){if(!regexp.test(key))continue;value[key]=FromType23(direction,context,RecordValue(type),value[key])}return Callback(direction,context,type,value)}function Encode6(direction,context,type,value){let exterior=Callback(direction,context,type,value);if(!IsObjectNotArray(exterior))return exterior;let regexp=new RegExp(RecordPattern(type));for(let key of Keys(exterior)){if(!regexp.test(key))continue;exterior[key]=FromType23(direction,context,RecordValue(type),exterior[key])}return exterior}function FromRecord6(direction,context,type,value){return IsEqual(direction,"Decode")?Decode6(direction,context,type,value):Encode6(direction,context,type,value)}function ResolveRef(direction,context,type,value){return HasPropertyKey(context,type.$ref)?FromType23(direction,context,context[type.$ref],value):value}function FromRef8(direction,context,type,value){return IsEqual(direction,"Decode")?Callback(direction,context,type,ResolveRef(direction,context,type,value)):ResolveRef(direction,context,type,Callback(direction,context,type,value))}function Decode7(direction,context,type,value){if(!IsArray(value))return value;for(let i=0;i<Math.min(type.items.length,value.length);i++)value[i]=FromType23(direction,context,type.items[i],value[i]);return Callback(direction,context,type,value)}function Encode7(direction,context,type,value){let exterior=Callback(direction,context,type,value);if(!IsArray(exterior))return value;for(let i=0;i<Math.min(type.items.length,exterior.length);i++)exterior[i]=FromType23(direction,context,type.items[i],exterior[i]);return exterior}function FromTuple8(direction,context,type,value){return IsEqual(direction,"Decode")?Decode7(direction,context,type,value):Encode7(direction,context,type,value)}function Decode8(direction,context,type,value){for(let schema of type.anyOf){if(!Check2(context,schema,value))continue;let variant=FromType23(direction,context,schema,value);return Callback(direction,context,type,variant)}return value}function Encode8(direction,context,type,value){let exterior=Callback(direction,context,type,value);for(let schema of type.anyOf){let variant=FromType23(direction,context,schema,Clone2(exterior));if(!Check2(context,schema,variant))continue;return variant}return exterior}function FromUnion12(direction,context,type,value){return IsEqual(direction,"Decode")?Decode8(direction,context,type,value):Encode8(direction,context,type,value)}function FromType23(direction,context,type,value){return IsArray2(type)?FromArray9(direction,context,type,value):IsCyclic(type)?FromCyclic9(direction,context,type,value):IsIntersect(type)?FromIntersect9(direction,context,type,value):IsObject2(type)?FromObject13(direction,context,type,value):IsRecord(type)?FromRecord6(direction,context,type,value):IsRef2(type)?FromRef8(direction,context,type,value):IsTuple(type)?FromTuple8(direction,context,type,value):IsUnion(type)?FromUnion12(direction,context,type,value):Callback(direction,context,type,value)}class DecodeError extends AssertError{constructor(value,errors){super("Decode",value,errors)}}function Assert(context,type,value){if(!Check2(context,type,value))throw new DecodeError(value,Errors2(context,type,value));return value}function DecodeUnsafe(context,type,value){let sorted=Get().unionPrioritySort?UnionPrioritySort(type):type;return FromType23("Decode",context,sorted,value)}var Decoder=Pipeline([(_context,_type,value)=>Clone2(value),(context,type,value)=>Default(context,type,value),(context,type,value)=>Convert(context,type,value),(context,type,value)=>Clean(context,type,value),(context,type,value)=>Assert(context,type,value),(context,type,value)=>DecodeUnsafe(context,type,value)]);class EncodeError extends AssertError{constructor(value,errors){super("Encode",value,errors)}}function Assert2(context,type,value){if(!Check2(context,type,value))throw new EncodeError(value,Errors2(context,type,value));return value}function EncodeUnsafe(context,type,value){let sorted=Get().unionPrioritySort?UnionPrioritySort(type):type;return FromType23("Encode",context,sorted,value)}var Encoder=Pipeline([(_context,_type,value)=>Clone2(value),(context,type,value)=>EncodeUnsafe(context,type,value),(context,type,value)=>Default(context,type,value),(context,type,value)=>Convert(context,type,value),(context,type,value)=>Clean(context,type,value),(context,type,value)=>Assert2(context,type,value)]);class ParseError extends AssertError{constructor(value,errors){super("Parse",value,errors)}}function Assert3(context,type,value){EnableParseErrors();let errors=Errors2(context,type,value);if(DisableParseErrors(),!Check2(context,type,value))throw new ParseError(value,errors);return value}var Parser=Pipeline([(_context,_type,value)=>Clone2(value),(context,type,value)=>Default(context,type,value),(context,type,value)=>Convert(context,type,value),(context,type,value)=>Clean(context,type,value),(context,type,value)=>Assert3(context,type,value)]);var Insert2=_Object_({type:Literal("insert"),path:String2(),value:Unknown()}),Update2=Object({type:Literal("update"),path:String2(),value:Unknown()}),Delete=_Object_({type:Literal("delete"),path:String2()}),Edit=Union([Insert2,Update2,Delete]);function actionBranches(branches){return new Map(branches.map((branch)=>[String(Reflect.get(branch.properties.action??{},"const")),branch]))}var Button=Union([Literal("left"),Literal("right"),Literal("middle")]),shared2={timeout:Optional(Number2({exclusiveMinimum:0,description:"Maximum time in seconds for this action."})),include_screenshot:Optional(Boolean2({description:"Capture a screenshot after the action."}))},point={x:Number2(),y:Number2()},strict={additionalProperties:!1},SingleActionBranches=[_Object_({action:Literal("screenshot"),...shared2},strict),_Object_({action:Literal("click"),...point,button:Optional(Button),...shared2},strict),_Object_({action:Literal("double_click"),...point,button:Optional(Button),...shared2},strict),_Object_({action:Literal("move"),...point,button:Optional(Button),...shared2},strict),_Object_({action:Literal("drag"),...point,to_x:Number2(),to_y:Number2(),button:Optional(Button),...shared2},strict),_Object_({action:Literal("scroll"),...point,scroll_x:Number2(),scroll_y:Number2(),...shared2},strict),_Object_({action:Literal("type"),text:String2(),...shared2},strict),_Object_({action:Literal("keypress"),keys:_Array_(String2(),{minItems:1}),...shared2},strict),_Object_({action:Literal("wait"),ms:Integer({minimum:0}),...shared2},strict)],SingleAction=Union([...SingleActionBranches]),BatchShape=_Object_({action:Literal("batch"),actions:_Array_(SingleAction,{minItems:1}),...shared2},strict),ComputerActionsShape=Union([SingleAction,BatchShape]),ACTION_NAMES=["screenshot","click","double_click","move","drag","scroll","type","keypress","wait"],flatActionFields={x:Optional(Number2({description:"click, double_click, move, drag (start), scroll (required): x pixel"})),y:Optional(Number2({description:"click, double_click, move, drag (start), scroll (required): y pixel"})),button:Optional(Enum(["left","right","middle"],{type:"string",description:"click, double_click, move, drag: mouse button (default left)"})),to_x:Optional(Number2({description:"drag (required): end x pixel"})),to_y:Optional(Number2({description:"drag (required): end y pixel"})),scroll_x:Optional(Number2({description:"scroll (required): horizontal scroll distance in pixels on every OS (one wheel notch is about 40 px); positive scrolls right"})),scroll_y:Optional(Number2({description:"scroll (required): vertical scroll distance in pixels on every OS (one wheel notch is about 40 px); positive moves the view toward the end of the content (down)"})),text:Optional(String2({description:"type (required): text to type"})),keys:Optional(_Array_(String2(),{minItems:1,description:"keypress (required): keys pressed together"})),ms:Optional(Integer({minimum:0,description:"wait (required): milliseconds"})),...shared2},ComputerActionsParams=_Object_({action:Enum([...ACTION_NAMES,"batch"],{type:"string",description:"The action to perform, or batch to run `actions` in order"}),actions:Optional(_Array_(_Object_({action:Enum([...ACTION_NAMES],{type:"string",description:"The action to perform"}),...flatActionFields},strict),{minItems:1,description:"batch (required): actions to execute in order"})),...flatActionFields},strict),SINGLE_BRANCHES=actionBranches(SingleActionBranches),TOP_BRANCHES=actionBranches([...SingleActionBranches,BatchShape]);var METHOD_NAMES=new Set(ENGINE_METHODS),ERROR_CODE_NAMES=new Set(ERROR_CODES);var DESCRIPTION=["Drive the user's real desktop with OpenAI computer-use actions (experimental): screenshot, click, double_click, move, drag, scroll, type, keypress, wait, or a batch of them.","x,y are pixels of the latest screenshot. A batch stops at the first failed action; an in-batch screenshot becomes the frame for the actions after it.","Pass only the fields the chosen action takes (each field's description names its actions); anything else is refused with COMPUTER_INVALID_ARGUMENTS before any input.","Errors carry COMPUTER_* codes with a recovery hint. COMPUTER_SUSPENDED or COMPUTER_SUPERVISOR_NOT_LIVE means the user stopped you: stop and wait."].join(`
334
334
  `);var DEFAULT_TIMEOUT_SECONDS=60,MAX_TIMEOUT_SECONDS=600,CallStep=_Object_({method:String2({description:"desktop helper name, e.g. screenshot, window, click, clipboard.read"}),args:Optional(_Array_(Unknown(),{description:"positional helper arguments"}))},{additionalProperties:!1}),RunTimeout=Number2({minimum:1,maximum:MAX_TIMEOUT_SECONDS,description:`run: budget in seconds (default ${DEFAULT_TIMEOUT_SECONDS})`}),ComputerActionBranches=[_Object_({action:Literal("call"),chain:_Array_(CallStep,{description:"one desktop helper call, optionally followed by one call on the window/element it returns"})},{additionalProperties:!1}),_Object_({action:Literal("run"),code:String2({description:"JavaScript async function body; `desktop`, `wait`, `assert`, `tool` in scope; `return` sets the value"}),read_only:Optional(Boolean2({description:"true = inspection only: screenshots and AX reads, input/mutation blocked"})),timeout:Optional(RunTimeout)},{additionalProperties:!1}),_Object_({action:Literal("capabilities")},{additionalProperties:!1}),_Object_({action:Literal("close")},{additionalProperties:!1})],ComputerActionShape=Union([...ComputerActionBranches]),ComputerParams=_Object_({action:Enum(["call","run","capabilities","close"],{type:"string",description:"call: one desktop helper chain; run: a JavaScript body; capabilities: host report; close: end the session"}),chain:Optional(_Array_(CallStep,{description:"call (required): one desktop helper call, optionally followed by one call on the window/element it returns"})),code:Optional(String2({description:"run (required): JavaScript async function body; `desktop`, `wait`, `assert`, `tool` in scope; `return` sets the value"})),read_only:Optional(Boolean2({description:"run: true = inspection only: screenshots and AX reads, input/mutation blocked"})),timeout:Optional(RunTimeout)},{additionalProperties:!1});import{readFileSync as readFileSync5}from"node:fs";import{dirname as dirname3,join as join5}from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";var ASSET_FIELDS=["COMPUTER_PRELUDE_JAVASCRIPT","COMPUTER_PRELUDE_PYTHON","COMPUTER_DECLARATIONS","COMPUTER_DOCUMENTATION","COMPUTER_SAFETY"],ASSETS_JSON_PATH=join5(dirname3(fileURLToPath2(import.meta.url)),"assets.generated.json"),cached2;function preludeAssets(){if(cached2===void 0){let parsed=JSON.parse(readFileSync5(ASSETS_JSON_PATH,"utf8"));cached2=validateAssets(parsed)}return cached2}function validateAssets(value){let record=value&&typeof value==="object"?value:void 0,missing=ASSET_FIELDS.filter((field)=>typeof record?.[field]!=="string");if(missing.length>0)throw Error(`senpi-desktop-prelude asset JSON is malformed at ${ASSETS_JSON_PATH}: missing ${missing.join(", ")}`);return value}var METHOD_ALLOWLIST=["actions","attributes","ax","bounds","capabilities","children","click","clipboard.read","clipboard.write","displays","doubleClick","drag","elementAt","find","focus","focusedElement","focusedWindow","move","parent","perform","press","raise","ref","screenshot","scroll","setValue","type","value","window","windows"],computerPreludeAssets={get javascript(){return preludeAssets().COMPUTER_PRELUDE_JAVASCRIPT},get python(){return preludeAssets().COMPUTER_PRELUDE_PYTHON},get declarations(){return preludeAssets().COMPUTER_DECLARATIONS},get documentation(){return preludeAssets().COMPUTER_DOCUMENTATION},get safety(){return preludeAssets().COMPUTER_SAFETY},exports:["computer"],methodAllowlist:METHOD_ALLOWLIST};var DESCRIPTION2=["Drive the user's real desktop (experimental): windows, screenshots, native mouse and keyboard input, the OS accessibility (AX) tree, and the clipboard. Not a browser.",'- `{action:"call", chain}` runs one desktop helper, optionally followed by one call on the window/element it returns, e.g. `[{method:"window",args:[{app:"Code"}]},{method:"screenshot"}]`.','- `{action:"run", code, read_only?, timeout?}` runs a JavaScript async function body with `desktop`, `wait`, `assert`, and `tool` in scope; `read_only: true` blocks input.','- `{action:"capabilities"}` reports backend, permissions, `stopPath`, and `focusGuard`; availability is unknown until `computer.capabilities()` returns in this session, so make no availability claim before it and repeat the host and reason on `native-unavailable`. `{action:"close"}` ends the desktop session.',"Pass only the fields of the chosen action; any other field is refused with COMPUTER_INVALID_ARGUMENTS.","In eval cells prefer the `computer` global, which wraps these actions. Pointer x,y are pixels of the latest screenshot of the same target."].join(`
335
335
  `),SAFETY_GUIDELINES=computerPreludeAssets.safety.split(`
336
- `).filter((line)=>line.startsWith("- ")).map((line)=>line.slice(2));var BRANCHES=actionBranches(ComputerActionBranches);var SUPPORTED_PLATFORMS=new Set(["darwin","linux","win32"]);function isSupportedHost(platform=process.platform){return SUPPORTED_PLATFORMS.has(platform)}function defaultStopHotkey(platform=process.platform){return platform==="darwin"?"ctrl+alt+cmd+escape":"ctrl+alt+shift+escape"}var ComputerSettingsSchema=_Object_({enabled:Optional(Boolean2({description:"Register the computer tool (experimental; default: host supported)"})),display:Optional(String2({description:"`all` composites every display; otherwise a display id"})),maxWidth:Optional(Integer({minimum:1,default:3840})),maxHeight:Optional(Integer({minimum:1,default:2400})),screenshotMaxBytes:Optional(Integer({minimum:1,default:5000000})),stopHotkey:Optional(String2({minLength:1,description:"Stop chord, e.g. ctrl+alt+shift+escape"})),allowHostRelayOnlyStop:Optional(Boolean2({default:!1})),macosCanary:Optional(Union([Literal("session"),Literal("off")],{default:"session"})),auditLog:Optional(_Object_({enabled:Optional(Boolean2({default:!0}))},{additionalProperties:!1})),screenshotGc:Optional(_Object_({enabled:Optional(Boolean2({default:!0})),staleMs:Optional(Integer({minimum:0,default:43200000})),scanIntervalMs:Optional(Integer({minimum:0,default:1800000}))},{additionalProperties:!1})),enginePath:Optional(String2({minLength:1,description:"Override the located engine binary"})),cuaAdapter:Optional(Boolean2({default:!1,description:"Also register computer_actions (OpenAI computer-use actions)"}))},{additionalProperties:!1});class ComputerSettingsError extends Error{issues;constructor(issues){super(`invalid computer settings: ${issues.join("; ")}`);this.name="ComputerSettingsError",this.issues=issues}}function resolveComputerSettings(raw,platform=process.platform){let value=raw??{};if(!Check2(ComputerSettingsSchema,value)){let issues=Errors2(ComputerSettingsSchema,value).map((error)=>`${error.instancePath||"computer"}: ${error.message}`);throw new ComputerSettingsError(issues)}return{enabled:value.enabled??isSupportedHost(platform),display:value.display??"all",maxWidth:value.maxWidth??3840,maxHeight:value.maxHeight??2400,screenshotMaxBytes:value.screenshotMaxBytes??5000000,stopHotkey:value.stopHotkey??defaultStopHotkey(platform),allowHostRelayOnlyStop:value.allowHostRelayOnlyStop??!1,macosCanary:value.macosCanary??"session",auditLog:{enabled:value.auditLog?.enabled??!0},screenshotGc:{enabled:value.screenshotGc?.enabled??!0,staleMs:value.screenshotGc?.staleMs??43200000,scanIntervalMs:value.screenshotGc?.scanIntervalMs??1800000},enginePath:value.enginePath,cuaAdapter:value.cuaAdapter??!1}}function toComputerSettingsInput(block){if(block===void 0)return;let input={enabled:block.enabled,display:block.display,maxWidth:block.max_width,maxHeight:block.max_height,screenshotMaxBytes:block.screenshot_max_bytes,stopHotkey:block.stop_hotkey,allowHostRelayOnlyStop:block.allow_host_relay_only_stop,macosCanary:block.macos_canary,auditLog:block.audit_log===void 0?void 0:{enabled:block.audit_log.enabled},screenshotGc:block.screenshot_gc===void 0?void 0:{enabled:block.screenshot_gc.enabled,staleMs:block.screenshot_gc.stale_ms,scanIntervalMs:block.screenshot_gc.scan_interval_ms},enginePath:block.engine_path,cuaAdapter:block.cua_adapter};return JSON.parse(JSON.stringify(input))}function resolveOmoComputerSettings(block,platform){return resolveComputerSettings(toComputerSettingsInput(block),platform)}import{accessSync as accessSync3,constants as constants3,existsSync as existsSync5}from"node:fs";import{homedir as homedir2}from"node:os";import{join as join6}from"node:path";function explicitPathDiagnostic(enginePath,host,platform,isQuarantined=(path)=>isQuarantinedFile(path,platform)){let base={host,attemptedPaths:[enginePath]};if(!existsSync5(enginePath))return{...base,code:"native-unavailable",message:`No senpi-desktop-engine binary is available for ${host}.`,cause:`${enginePath}: missing`};if(isQuarantined(enginePath))return{...base,code:"quarantined",message:`The senpi-desktop-engine binary for ${host} is quarantined by macOS Gatekeeper: ${enginePath}.`,cause:`${enginePath}: blocked because com.apple.quarantine is present (macOS Gatekeeper)`};if(platform==="win32")return/\.exe$/i.test(enginePath)?void 0:notExecutable(base,host,`${enginePath}: not executable (expected a .exe file)`);try{accessSync3(enginePath,constants3.X_OK);return}catch(error){if(!(error instanceof Error&&("code"in error)))throw error;return notExecutable(base,host,`${enginePath}: not executable (chmod +x)`)}}function notExecutable(base,host,cause){return{...base,code:"native-unavailable",message:`No senpi-desktop-engine binary is available for ${host}.`,cause}}function resolveInstalledEngine(enginePath,env,version,locatorOptions={}){let platform=locatorOptions.platform??process.platform,host=getDesktopEngineHost(platform,locatorOptions.arch,locatorOptions.libc);if(enginePath!==void 0){let diagnostic=explicitPathDiagnostic(enginePath,host,platform,locatorOptions.isQuarantined);return diagnostic===void 0?{path:enginePath,source:"explicit"}:{diagnostic}}let options={...locatorOptions,runtimeDir:locatorOptions.runtimeDir??env.OMO_PACKAGE_DIR??""},located=locateDesktopEngine(options);if(located.path!==null){let candidates=getDesktopEngineCandidatePaths(options),sources=options.runtimeDir?["runtime-dir","sidecar","package-prebuild","dev-build"]:["sidecar","package-prebuild","dev-build"];return{path:located.path,source:sources[candidates.indexOf(located.path)]}}if(located.diagnostic.code==="quarantined")return{diagnostic:located.diagnostic};if(version!==void 0){let cached=findCachedDesktopEngine({host,version,cacheDir:join6(env.HOME??homedir2(),".omo","cache","senpi-desktop-engine")});if(cached.path!==null)return{path:cached.path,source:"cache"}}return desktopEngineReleaseAssetName(host)===null?{diagnostic:located.diagnostic}:{notInstalled:located.diagnostic}}import{spawn}from"node:child_process";import{createInterface}from"node:readline";var COMPUTER_USE_DOCTOR_TIMEOUT_MS=5000,STDERR_TAIL_CHARS=4096,HelloSchema=object({protocolVersion:string2(),engineVersion:string2(),buildSha:string2(),abi:string2()}),CapabilitiesSchema=object({backend:string2(),displayServer:string2().nullable().optional(),capture:boolean2(),input:boolean2(),ax:boolean2(),backgroundWindowInput:boolean2(),deliveryModes:array(string2()),capturePermission:string2(),inputPermission:string2(),axPermission:string2(),displayCount:number2().int().nonnegative(),focusGuard:boolean2(),stopPath:string2(),stopReason:string2().nullable().optional(),integrityLevel:string2().nullable().optional(),screenLocked:boolean2()}),RpcResponseSchema=object({id:union([literal(1),literal(2)]),result:unknown().optional(),error:unknown().optional()});function validateProbe(hello,capabilities,enginePath){let parsedHello=HelloSchema.safeParse(hello);if(!parsedHello.success)return{ok:!1,code:"handshake-failed",message:`malformed engine.hello result at ${enginePath}`};if(parsedHello.data.abi!==ENGINE_ABI||parsedHello.data.protocolVersion!==PROTOCOL_VERSION)return{ok:!1,code:"abi-mismatch",message:`desktop engine ABI mismatch at ${enginePath}: expected abi ${ENGINE_ABI} protocol ${PROTOCOL_VERSION}, engine reported abi ${parsedHello.data.abi} protocol ${parsedHello.data.protocolVersion}`};let parsedCapabilities=CapabilitiesSchema.safeParse(capabilities);if(!parsedCapabilities.success)return{ok:!1,code:"handshake-failed",message:`malformed capabilities result at ${enginePath}`};return{ok:!0,value:{hello:parsedHello.data,capabilities:parsedCapabilities.data}}}var launchEngineBinary=(enginePath,args,env)=>spawn(enginePath,[...args],{stdio:"pipe",windowsHide:!0,detached:!0,env});function probeComputerUseEngine(enginePath,env,timeoutMs,launch=launchEngineBinary){let child=launch(enginePath,["--stdio"],{...process.env,...env});return new Promise((resolveProbe)=>{let replies=new Map,stderrTail="",settled,settle=(result)=>{if(settled!==void 0)return;settled=result,child.stdin.end()},timer=setTimeout(()=>{let result=settled??{ok:!1,code:"timeout",message:`desktop engine probe timed out after ${timeoutMs} ms at ${enginePath}`};if(settle(result),resolveProbe(result),lines.close(),child.stdin.destroy(),child.stdout.destroy(),child.stderr.destroy(),child.unref(),child.pid===void 0)return;if(process.platform==="win32"){let killer=spawn("taskkill",["/pid",String(child.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});killer.once("error",()=>child.kill("SIGKILL")),killer.unref()}else try{process.kill(-child.pid,"SIGKILL")}catch(error){if(!(error instanceof Error)||!("code"in error)||error.code!=="ESRCH")throw error}},timeoutMs);child.stderr.setEncoding("utf8"),child.stderr.on("data",(chunk)=>{stderrTail=(stderrTail+chunk).slice(-STDERR_TAIL_CHARS)}),child.stdin.on("error",(error)=>{settle({ok:!1,code:"handshake-failed",message:`desktop engine stdin failed at ${enginePath}: ${error.message}`})}),child.on("error",(error)=>{settle({ok:!1,code:"handshake-failed",message:`desktop engine spawn failed at ${enginePath}: ${error.message}`})});let lines=createInterface({input:child.stdout}).on("line",(line)=>{let value;try{value=JSON.parse(line)}catch(error){if(!(error instanceof SyntaxError))throw error;settle({ok:!1,code:"handshake-failed",message:`desktop engine emitted non-JSON output at ${enginePath}`});return}let parsed=RpcResponseSchema.safeParse(value);if(!parsed.success)return;if(parsed.data.error!==void 0){settle({ok:!1,code:"handshake-failed",message:`desktop engine request ${parsed.data.id} failed at ${enginePath}: ${JSON.stringify(parsed.data.error)}`});return}if(replies.set(parsed.data.id,parsed.data.result),replies.has(1)&&replies.has(2))settle(validateProbe(replies.get(1),replies.get(2),enginePath))});child.on("close",(code,signal)=>{clearTimeout(timer),resolveProbe(settled??{ok:!1,code:"handshake-failed",message:`desktop engine exited before the probe completed at ${enginePath} (code ${code??"null"}, signal ${signal??"null"}); stderr: ${stderrTail.trim()||"<empty>"}`})}),child.stdin.write(`${JSON.stringify({jsonrpc:"2.0",id:1,method:"engine.hello",params:{}})}
336
+ `).filter((line)=>line.startsWith("- ")).map((line)=>line.slice(2));var BRANCHES=actionBranches(ComputerActionBranches);var SUPPORTED_PLATFORMS=new Set(["darwin","linux","win32"]);function isSupportedHost(platform=process.platform){return SUPPORTED_PLATFORMS.has(platform)}function defaultStopHotkey(platform=process.platform){return platform==="darwin"?"ctrl+alt+cmd+escape":"ctrl+alt+shift+escape"}var ComputerSettingsSchema=_Object_({enabled:Optional(Boolean2({description:"Register the computer tool (experimental; default: host supported)"})),display:Optional(String2({description:"`all` composites every display; otherwise a display id"})),maxWidth:Optional(Integer({minimum:1,default:3840})),maxHeight:Optional(Integer({minimum:1,default:2400})),screenshotMaxBytes:Optional(Integer({minimum:1,default:5000000})),stopHotkey:Optional(String2({minLength:1,description:"Stop chord, e.g. ctrl+alt+shift+escape"})),allowHostRelayOnlyStop:Optional(Boolean2({default:!1})),macosCanary:Optional(Union([Literal("session"),Literal("off")],{default:"session"})),auditLog:Optional(_Object_({enabled:Optional(Boolean2({default:!0}))},{additionalProperties:!1})),screenshotGc:Optional(_Object_({enabled:Optional(Boolean2({default:!0})),staleMs:Optional(Integer({minimum:0,default:43200000})),scanIntervalMs:Optional(Integer({minimum:0,default:1800000}))},{additionalProperties:!1})),enginePath:Optional(String2({minLength:1,description:"Override the located engine binary"})),cuaAdapter:Optional(Boolean2({default:!1,description:"Also register computer_actions (OpenAI computer-use actions)"}))},{additionalProperties:!1});class ComputerSettingsError extends Error{issues;constructor(issues){super(`invalid computer settings: ${issues.join("; ")}`);this.name="ComputerSettingsError",this.issues=issues}}function resolveComputerSettings(raw,platform=process.platform){let value=raw??{};if(!Check2(ComputerSettingsSchema,value)){let issues=Errors2(ComputerSettingsSchema,value).map((error)=>`${error.instancePath||"computer"}: ${error.message}`);throw new ComputerSettingsError(issues)}return{enabled:value.enabled??isSupportedHost(platform),display:value.display??"all",maxWidth:value.maxWidth??3840,maxHeight:value.maxHeight??2400,screenshotMaxBytes:value.screenshotMaxBytes??5000000,stopHotkey:value.stopHotkey??defaultStopHotkey(platform),allowHostRelayOnlyStop:value.allowHostRelayOnlyStop??!1,macosCanary:value.macosCanary??"session",auditLog:{enabled:value.auditLog?.enabled??!0},screenshotGc:{enabled:value.screenshotGc?.enabled??!0,staleMs:value.screenshotGc?.staleMs??43200000,scanIntervalMs:value.screenshotGc?.scanIntervalMs??1800000},enginePath:value.enginePath,cuaAdapter:value.cuaAdapter??!1}}function toComputerSettingsInput(block){if(block===void 0)return;let input={enabled:block.enabled,display:block.display,maxWidth:block.max_width,maxHeight:block.max_height,screenshotMaxBytes:block.screenshot_max_bytes,stopHotkey:block.stop_hotkey,allowHostRelayOnlyStop:block.allow_host_relay_only_stop,macosCanary:block.macos_canary,auditLog:block.audit_log===void 0?void 0:{enabled:block.audit_log.enabled},screenshotGc:block.screenshot_gc===void 0?void 0:{enabled:block.screenshot_gc.enabled,staleMs:block.screenshot_gc.stale_ms,scanIntervalMs:block.screenshot_gc.scan_interval_ms},enginePath:block.engine_path,cuaAdapter:block.cua_adapter};return JSON.parse(JSON.stringify(input))}function resolveOmoComputerSettings(block,platform){return resolveComputerSettings(toComputerSettingsInput(block),platform)}import{accessSync as accessSync3,constants as constants3,existsSync as existsSync5}from"node:fs";import{homedir as homedir2}from"node:os";import{join as join6}from"node:path";function explicitPathDiagnostic(enginePath,host,platform,isQuarantined=(path)=>isQuarantinedFile(path,platform)){let base={host,attemptedPaths:[enginePath]};if(!existsSync5(enginePath))return{...base,code:"native-unavailable",message:`No senpi-desktop-engine binary is available for ${host}.`,cause:`${enginePath}: missing`};if(isQuarantined(enginePath))return{...base,code:"quarantined",message:`The senpi-desktop-engine binary for ${host} is quarantined by macOS Gatekeeper: ${enginePath}.`,cause:`${enginePath}: blocked because com.apple.quarantine is present (macOS Gatekeeper)`};if(platform==="win32")return/\.exe$/i.test(enginePath)?void 0:notExecutable(base,host,`${enginePath}: not executable (expected a .exe file)`);try{accessSync3(enginePath,constants3.X_OK);return}catch(error){if(!(error instanceof Error&&("code"in error)))throw error;return notExecutable(base,host,`${enginePath}: not executable (chmod +x)`)}}function notExecutable(base,host,cause){return{...base,code:"native-unavailable",message:`No senpi-desktop-engine binary is available for ${host}.`,cause}}function resolveInstalledEngine(enginePath,env,version,locatorOptions={}){let platform=locatorOptions.platform??process.platform,host=getDesktopEngineHost(platform,locatorOptions.arch,locatorOptions.libc);if(enginePath!==void 0){let diagnostic=explicitPathDiagnostic(enginePath,host,platform,locatorOptions.isQuarantined);return diagnostic===void 0?{path:enginePath,source:"explicit"}:{diagnostic}}let options={...locatorOptions,runtimeDir:locatorOptions.runtimeDir??env.OMO_PACKAGE_DIR??""},located=locateDesktopEngine(options);if(located.path!==null){let candidates=getDesktopEngineCandidatePaths(options),sources=options.runtimeDir?["runtime-dir","sidecar","package-prebuild","dev-build"]:["sidecar","package-prebuild","dev-build"];return{path:located.path,source:sources[candidates.indexOf(located.path)]}}if(located.diagnostic.code==="quarantined")return{diagnostic:located.diagnostic};if(version!==void 0){let cached=findCachedDesktopEngine({host,version,cacheDir:join6(env.HOME??homedir2(),".omo","cache","senpi-desktop-engine")});if(cached.path!==null)return{path:cached.path,source:"cache"}}return desktopEngineReleaseAssetName(host)===null?{diagnostic:located.diagnostic}:{notInstalled:located.diagnostic}}import{spawn}from"node:child_process";import{createInterface}from"node:readline";var COMPUTER_USE_DOCTOR_TIMEOUT_MS=5000,STDERR_TAIL_CHARS=4096,HelloSchema=object({protocolVersion:string2(),engineVersion:string2(),buildSha:string2(),abi:string2()}),CapabilitiesSchema=object({backend:string2(),displayServer:string2().nullable().optional(),capture:boolean2(),input:boolean2(),ax:boolean2(),backgroundWindowInput:boolean2(),deliveryModes:array(string2()),capturePermission:string2(),inputPermission:string2(),axPermission:string2(),displayCount:number2().int().nonnegative(),focusGuard:boolean2(),stopPath:string2(),stopReason:string2().nullable().optional(),integrityLevel:string2().nullable().optional(),screenLocked:boolean2()}),RpcResponseSchema=object({id:union([literal(1),literal(2)]),result:unknown().optional(),error:unknown().optional()});function validateProbe(hello,capabilities,enginePath){let parsedHello=HelloSchema.safeParse(hello);if(!parsedHello.success)return{ok:!1,code:"handshake-failed",message:`malformed engine.hello result at ${enginePath}`};if(parsedHello.data.abi!==ENGINE_ABI||parsedHello.data.protocolVersion!==PROTOCOL_VERSION)return{ok:!1,code:"abi-mismatch",message:`desktop engine ABI mismatch at ${enginePath}: expected abi ${ENGINE_ABI} protocol ${PROTOCOL_VERSION}, engine reported abi ${parsedHello.data.abi} protocol ${parsedHello.data.protocolVersion}`};let parsedCapabilities=CapabilitiesSchema.safeParse(capabilities);if(!parsedCapabilities.success)return{ok:!1,code:"handshake-failed",message:`malformed capabilities result at ${enginePath}`};return{ok:!0,value:{hello:parsedHello.data,capabilities:parsedCapabilities.data}}}var launchEngineBinary=(enginePath,args,env)=>spawn(enginePath,[...args],{stdio:"pipe",windowsHide:!0,detached:!0,env});function probeComputerUseEngine(enginePath,env,timeoutMs,launch=launchEngineBinary){let child=launch(enginePath,["--stdio"],{...process.env,...env});return new Promise((resolveProbe)=>{let replies=new Map,stderrTail="",settled,settle=(result)=>{if(settled!==void 0)return;settled=result,child.stdin.end()},timer=setTimeout(()=>{let result=settled??{ok:!1,code:"timeout",message:`desktop engine probe timed out after ${timeoutMs} ms at ${enginePath}`};if(settle(result),resolveProbe(result),lines.close(),child.stdin.destroy(),child.stdout.destroy(),child.stderr.destroy(),child.unref(),child.pid===void 0)return;if(process.platform==="win32"){let killer=spawn("taskkill",["/pid",String(child.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});killer.once("error",()=>child.kill("SIGKILL")),killer.unref()}else try{process.kill(-child.pid,"SIGKILL")}catch(error){if(!(error instanceof Error)||!("code"in error)||error.code!=="ESRCH"&&error.code!=="EPERM")throw error}},timeoutMs);child.stderr.setEncoding("utf8"),child.stderr.on("data",(chunk)=>{stderrTail=(stderrTail+chunk).slice(-STDERR_TAIL_CHARS)}),child.stdin.on("error",(error)=>{settle({ok:!1,code:"handshake-failed",message:`desktop engine stdin failed at ${enginePath}: ${error.message}`})}),child.on("error",(error)=>{settle({ok:!1,code:"handshake-failed",message:`desktop engine spawn failed at ${enginePath}: ${error.message}`})});let lines=createInterface({input:child.stdout}).on("line",(line)=>{let value;try{value=JSON.parse(line)}catch(error){if(!(error instanceof SyntaxError))throw error;settle({ok:!1,code:"handshake-failed",message:`desktop engine emitted non-JSON output at ${enginePath}`});return}let parsed=RpcResponseSchema.safeParse(value);if(!parsed.success)return;if(parsed.data.error!==void 0){settle({ok:!1,code:"handshake-failed",message:`desktop engine request ${parsed.data.id} failed at ${enginePath}: ${JSON.stringify(parsed.data.error)}`});return}if(replies.set(parsed.data.id,parsed.data.result),replies.has(1)&&replies.has(2))settle(validateProbe(replies.get(1),replies.get(2),enginePath))});child.on("close",(code,signal)=>{clearTimeout(timer),resolveProbe(settled??{ok:!1,code:"handshake-failed",message:`desktop engine exited before the probe completed at ${enginePath} (code ${code??"null"}, signal ${signal??"null"}); stderr: ${stderrTail.trim()||"<empty>"}`})}),child.stdin.write(`${JSON.stringify({jsonrpc:"2.0",id:1,method:"engine.hello",params:{}})}
337
337
  `),child.stdin.write(`${JSON.stringify({jsonrpc:"2.0",id:2,method:"capabilities",params:{}})}
338
338
  `)})}function unavailable(base,diagnostic){return{...base,kind:"unavailable",diagnostic}}async function computerUseDoctorReport(input){let platform=input.platform??process.platform,arch=input.arch??process.arch,host=getDesktopEngineHost(platform,arch),supported=isSupportedHost(platform),{config}=loadOmoConfig({cwd:input.cwd,env:input.env,harness:"native"}),settings=resolveOmoComputerSettings(config.computer,platform),base={enabled:settings.enabled,supported,host};if(!supported)return{...base,kind:"skipped",reason:"unsupported"};if(!settings.enabled)return{...base,kind:"skipped",reason:"disabled"};let locatorOptions={platform,arch,runtimeDir:input.env.OMO_PACKAGE_DIR??"",execDir:dirname4(process.execPath),packageDir:resolve3(input.packageRoot,"..","senpi-desktop-engine"),repoRoot:resolve3(input.packageRoot,"..","..")},resolved=resolveInstalledEngine(settings.enginePath,input.env,input.version,locatorOptions);if("notInstalled"in resolved)return{...base,kind:"not-installed",attemptedPaths:resolved.notInstalled.attemptedPaths};if("diagnostic"in resolved)return unavailable(base,resolved.diagnostic);let probe=(path)=>({probe:probeComputerUseEngine(path,input.env,input.timeoutMs??COMPUTER_USE_DOCTOR_TIMEOUT_MS,input.launchEngine)}),home=input.env.HOME??homedir3(),launched=settings.enginePath!==void 0&&"path"in resolved?{path:resolved.path,value:probe(resolved.path)}:await launchDesktopEngine({version:input.version,host,allowDownload:!1,cacheDir:join7(home,".omo","cache","senpi-desktop-engine"),installDir:join7(home,".omo","engines","senpi-desktop-engine"),locatorOptions},probe);if(launched.path===null)return unavailable(base,launched.diagnostic);let probed=await launched.value.probe,location={enginePath:resolved.path,engineSource:resolved.source,...launched.path===resolved.path?{}:{launchedEnginePath:launched.path}};if(!probed.ok)return{...base,...location,kind:"failed",code:probed.code,message:probed.message};return{...base,kind:"ready",...location,hello:probed.value.hello,capabilities:probed.value.capabilities}}function configDoctorLines(input){let{diagnostics}=loadOmoConfig({cwd:input.cwd,env:input.env,harness:"senpi"});return omoConfigDiagnosticLines(diagnostics,{homeDir:resolveHomeDir(input.env)}).map((line)=>`WARN ${line}`)}function categoryCoverage(input){let{config}=loadOmoConfig({cwd:input.cwd,env:input.env,harness:"senpi"}),pinned=Object.fromEntries((input.pinnedCategories??[]).map((name)=>[name,{}])),models=input.models.map((model)=>({provider:model.provider,id:model.id}));return resolveCategoryCoverage({...config,categories:{...pinned,...config.categories}},{getAvailable:()=>models,find:(provider,modelId)=>models.find((model)=>model.provider===provider&&model.id===modelId)})}export{categoryCoverage,computerUseDoctorReport,configDoctorLines};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "version": "0.1.0",
4
- "inputDigest": "sha256:d901d2ef5ab4fdfb6c493f3e33ffb045ecaf8f5b7e02965abdefbfbce21dfe05",
4
+ "inputDigest": "sha256:0e953f1135354ea2a3cf8acfb957a1362fe6f0c58985c520d2af3d5d0d04741b",
5
5
  "outputs": [
6
6
  {
7
7
  "path": "cli.d.ts",