@pickled-dev/cli 0.25.1 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +141 -140
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,212 +1,213 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
`)}displayWidth($){return
|
|
3
|
+
var YJ=Object.create;var{getPrototypeOf:GJ,defineProperty:J3,getOwnPropertyNames:zJ}=Object;var JJ=Object.prototype.hasOwnProperty;function QJ($){return this[$]}var WJ,VJ,Q3=($,Z,X)=>{var Y=$!=null&&typeof $==="object";if(Y){var G=Z?WJ??=new WeakMap:VJ??=new WeakMap,z=G.get($);if(z)return z}X=$!=null?YJ(GJ($)):{};let J=Z||!$||!$.__esModule?J3(X,"default",{value:$,enumerable:!0}):X;for(let Q of zJ($))if(!JJ.call(J,Q))J3(J,Q,{get:QJ.bind($,Q),enumerable:!0});if(Y)G.set($,J);return J};var C=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var n0=import.meta.require;var A2=C((HJ)=>{class H9 extends Error{constructor($,Z,X){super(X);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=Z,this.exitCode=$,this.nestedError=void 0}}class W3 extends H9{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}HJ.CommanderError=H9;HJ.InvalidArgumentError=W3});var r6=C((TJ)=>{var{InvalidArgumentError:BJ}=A2();class V3{constructor($,Z){switch(this.description=Z||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue($,Z){if(Z===this.defaultValue||!Array.isArray(Z))return[$];return Z.push($),Z}default($,Z){return this.defaultValue=$,this.defaultValueDescription=Z,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(Z,X)=>{if(!this.argChoices.includes(Z))throw new BJ(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(Z,X);return Z},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function qJ($){let Z=$.name()+($.variadic===!0?"...":"");return $.required?"<"+Z+">":"["+Z+"]"}TJ.Argument=V3;TJ.humanReadableArgName=qJ});var K9=C((wJ)=>{var{humanReadableArgName:MJ}=r6();class H3{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext($){this.helpWidth=this.helpWidth??$.helpWidth??80}visibleCommands($){let Z=$.commands.filter((Y)=>!Y._hidden),X=$._getHelpCommand();if(X&&!X._hidden)Z.push(X);if(this.sortSubcommands)Z.sort((Y,G)=>{return Y.name().localeCompare(G.name())});return Z}compareOptions($,Z){let X=(Y)=>{return Y.short?Y.short.replace(/^-/,""):Y.long.replace(/^--/,"")};return X($).localeCompare(X(Z))}visibleOptions($){let Z=$.options.filter((Y)=>!Y.hidden),X=$._getHelpOption();if(X&&!X.hidden){let Y=X.short&&$._findOption(X.short),G=X.long&&$._findOption(X.long);if(!Y&&!G)Z.push(X);else if(X.long&&!G)Z.push($.createOption(X.long,X.description));else if(X.short&&!Y)Z.push($.createOption(X.short,X.description))}if(this.sortOptions)Z.sort(this.compareOptions);return Z}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let Z=[];for(let X=$.parent;X;X=X.parent){let Y=X.options.filter((G)=>!G.hidden);Z.push(...Y)}if(this.sortOptions)Z.sort(this.compareOptions);return Z}visibleArguments($){if($._argsDescription)$.registeredArguments.forEach((Z)=>{Z.description=Z.description||$._argsDescription[Z.name()]||""});if($.registeredArguments.find((Z)=>Z.description))return $.registeredArguments;return[]}subcommandTerm($){let Z=$.registeredArguments.map((X)=>MJ(X)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(Z?" "+Z:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,Z){return Z.visibleCommands($).reduce((X,Y)=>{return Math.max(X,this.displayWidth(Z.styleSubcommandTerm(Z.subcommandTerm(Y))))},0)}longestOptionTermLength($,Z){return Z.visibleOptions($).reduce((X,Y)=>{return Math.max(X,this.displayWidth(Z.styleOptionTerm(Z.optionTerm(Y))))},0)}longestGlobalOptionTermLength($,Z){return Z.visibleGlobalOptions($).reduce((X,Y)=>{return Math.max(X,this.displayWidth(Z.styleOptionTerm(Z.optionTerm(Y))))},0)}longestArgumentTermLength($,Z){return Z.visibleArguments($).reduce((X,Y)=>{return Math.max(X,this.displayWidth(Z.styleArgumentTerm(Z.argumentTerm(Y))))},0)}commandUsage($){let Z=$._name;if($._aliases[0])Z=Z+"|"+$._aliases[0];let X="";for(let Y=$.parent;Y;Y=Y.parent)X=Y.name()+" "+X;return X+Z+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let Z=[];if($.argChoices)Z.push(`choices: ${$.argChoices.map((X)=>JSON.stringify(X)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")Z.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)Z.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)Z.push(`env: ${$.envVar}`);if(Z.length>0){let X=`(${Z.join(", ")})`;if($.description)return`${$.description} ${X}`;return X}return $.description}argumentDescription($){let Z=[];if($.argChoices)Z.push(`choices: ${$.argChoices.map((X)=>JSON.stringify(X)).join(", ")}`);if($.defaultValue!==void 0)Z.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(Z.length>0){let X=`(${Z.join(", ")})`;if($.description)return`${$.description} ${X}`;return X}return $.description}formatItemList($,Z,X){if(Z.length===0)return[];return[X.styleTitle($),...Z,""]}groupItems($,Z,X){let Y=new Map;return $.forEach((G)=>{let z=X(G);if(!Y.has(z))Y.set(z,[])}),Z.forEach((G)=>{let z=X(G);if(!Y.has(z))Y.set(z,[]);Y.get(z).push(G)}),Y}formatHelp($,Z){let X=Z.padWidth($,Z),Y=Z.helpWidth??80;function G(K,H){return Z.formatItem(K,X,H,Z)}let z=[`${Z.styleTitle("Usage:")} ${Z.styleUsage(Z.commandUsage($))}`,""],J=Z.commandDescription($);if(J.length>0)z=z.concat([Z.boxWrap(Z.styleCommandDescription(J),Y),""]);let Q=Z.visibleArguments($).map((K)=>{return G(Z.styleArgumentTerm(Z.argumentTerm(K)),Z.styleArgumentDescription(Z.argumentDescription(K)))});if(z=z.concat(this.formatItemList("Arguments:",Q,Z)),this.groupItems($.options,Z.visibleOptions($),(K)=>K.helpGroupHeading??"Options:").forEach((K,H)=>{let U=K.map((B)=>{return G(Z.styleOptionTerm(Z.optionTerm(B)),Z.styleOptionDescription(Z.optionDescription(B)))});z=z.concat(this.formatItemList(H,U,Z))}),Z.showGlobalOptions){let K=Z.visibleGlobalOptions($).map((H)=>{return G(Z.styleOptionTerm(Z.optionTerm(H)),Z.styleOptionDescription(Z.optionDescription(H)))});z=z.concat(this.formatItemList("Global Options:",K,Z))}return this.groupItems($.commands,Z.visibleCommands($),(K)=>K.helpGroup()||"Commands:").forEach((K,H)=>{let U=K.map((B)=>{return G(Z.styleSubcommandTerm(Z.subcommandTerm(B)),Z.styleSubcommandDescription(Z.subcommandDescription(B)))});z=z.concat(this.formatItemList(H,U,Z))}),z.join(`
|
|
4
|
+
`)}displayWidth($){return K3($).length}styleTitle($){return $}styleUsage($){return $.split(" ").map((Z)=>{if(Z==="[options]")return this.styleOptionText(Z);if(Z==="[command]")return this.styleSubcommandText(Z);if(Z[0]==="["||Z[0]==="<")return this.styleArgumentText(Z);return this.styleCommandText(Z)}).join(" ")}styleCommandDescription($){return this.styleDescriptionText($)}styleOptionDescription($){return this.styleDescriptionText($)}styleSubcommandDescription($){return this.styleDescriptionText($)}styleArgumentDescription($){return this.styleDescriptionText($)}styleDescriptionText($){return $}styleOptionTerm($){return this.styleOptionText($)}styleSubcommandTerm($){return $.split(" ").map((Z)=>{if(Z==="[options]")return this.styleOptionText(Z);if(Z[0]==="["||Z[0]==="<")return this.styleArgumentText(Z);return this.styleSubcommandText(Z)}).join(" ")}styleArgumentTerm($){return this.styleArgumentText($)}styleOptionText($){return $}styleArgumentText($){return $}styleSubcommandText($){return $}styleCommandText($){return $}padWidth($,Z){return Math.max(Z.longestOptionTermLength($,Z),Z.longestGlobalOptionTermLength($,Z),Z.longestSubcommandTermLength($,Z),Z.longestArgumentTermLength($,Z))}preformatted($){return/\n[^\S\r\n]/.test($)}formatItem($,Z,X,Y){let z=" ".repeat(2);if(!X)return z+$;let J=$.padEnd(Z+$.length-Y.displayWidth($)),Q=2,V=(this.helpWidth??80)-Z-Q-2,K;if(V<this.minWidthToWrap||Y.preformatted(X))K=X;else K=Y.boxWrap(X,V).replace(/\n/g,`
|
|
5
5
|
`+" ".repeat(Z+Q));return z+J+" ".repeat(Q)+K.replace(/\n/g,`
|
|
6
6
|
${z}`)}boxWrap($,Z){if(Z<this.minWidthToWrap)return $;let X=$.split(/\r\n|\n/),Y=/[\s]*[^\s]+/g,G=[];return X.forEach((z)=>{let J=z.match(Y);if(J===null){G.push("");return}let Q=[J.shift()],W=this.displayWidth(Q[0]);J.forEach((V)=>{let K=this.displayWidth(V);if(W+K<=Z){Q.push(V),W+=K;return}G.push(Q.join(""));let H=V.trimStart();Q=[H],W=this.displayWidth(H)}),G.push(Q.join(""))}),G.join(`
|
|
7
|
-
`)}}function
|
|
7
|
+
`)}}function K3($){let Z=/\x1b\[\d*(;\d*)*m/g;return $.replace(Z,"")}wJ.Help=H3;wJ.stripColor=K3});var U9=C((DJ)=>{var{InvalidArgumentError:_J}=A2();class B3{constructor($,Z){this.flags=$,this.description=Z||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let X=PJ($);if(this.short=X.shortFlag,this.long=X.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default($,Z){return this.defaultValue=$,this.defaultValueDescription=Z,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){let Z=$;if(typeof $==="string")Z={[$]:!0};return this.implied=Object.assign(this.implied||{},Z),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_collectValue($,Z){if(Z===this.defaultValue||!Array.isArray(Z))return[$];return Z.push($),Z}choices($){return this.argChoices=$.slice(),this.parseArg=(Z,X)=>{if(!this.argChoices.includes(Z))throw new _J(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(Z,X);return Z},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return U3(this.name().replace(/^no-/,""));return U3(this.name())}helpGroup($){return this.helpGroupHeading=$,this}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class q3{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((Z)=>{if(Z.negate)this.negativeOptions.set(Z.attributeName(),Z);else this.positiveOptions.set(Z.attributeName(),Z)}),this.negativeOptions.forEach((Z,X)=>{if(this.positiveOptions.has(X))this.dualOptions.add(X)})}valueFromOption($,Z){let X=Z.attributeName();if(!this.dualOptions.has(X))return!0;let Y=this.negativeOptions.get(X).presetArg,G=Y!==void 0?Y:!1;return Z.negate===(G===$)}}function U3($){return $.split("-").reduce((Z,X)=>{return Z+X[0].toUpperCase()+X.slice(1)})}function PJ($){let Z,X,Y=/^-[^-]$/,G=/^--[^-]/,z=$.split(/[ |,]+/).concat("guard");if(Y.test(z[0]))Z=z.shift();if(G.test(z[0]))X=z.shift();if(!Z&&Y.test(z[0]))Z=z.shift();if(!Z&&G.test(z[0]))Z=X,X=z.shift();if(z[0].startsWith("-")){let J=z[0],Q=`option creation failed due to '${J}' in option flags '${$}'`;if(/^-[^-][^-]/.test(J))throw Error(`${Q}
|
|
8
8
|
- a short flag is a single dash and a single character
|
|
9
9
|
- either use a single dash and a single character (for a short flag)
|
|
10
10
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(Y.test(J))throw Error(`${Q}
|
|
11
11
|
- too many short flags`);if(G.test(J))throw Error(`${Q}
|
|
12
12
|
- too many long flags`);throw Error(`${Q}
|
|
13
|
-
- unrecognised flag format`)}if(Z===void 0&&X===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:Z,longFlag:X}}
|
|
13
|
+
- unrecognised flag format`)}if(Z===void 0&&X===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:Z,longFlag:X}}DJ.Option=B3;DJ.DualOptions=q3});var T3=C((CJ)=>{function AJ($,Z){if(Math.abs($.length-Z.length)>3)return Math.max($.length,Z.length);let X=[];for(let Y=0;Y<=$.length;Y++)X[Y]=[Y];for(let Y=0;Y<=Z.length;Y++)X[0][Y]=Y;for(let Y=1;Y<=Z.length;Y++)for(let G=1;G<=$.length;G++){let z=1;if($[G-1]===Z[Y-1])z=0;else z=1;if(X[G][Y]=Math.min(X[G-1][Y]+1,X[G][Y-1]+1,X[G-1][Y-1]+z),G>1&&Y>1&&$[G-1]===Z[Y-2]&&$[G-2]===Z[Y-1])X[G][Y]=Math.min(X[G][Y],X[G-2][Y-2]+1)}return X[$.length][Z.length]}function SJ($,Z){if(!Z||Z.length===0)return"";Z=Array.from(new Set(Z));let X=$.startsWith("--");if(X)$=$.slice(2),Z=Z.map((J)=>J.slice(2));let Y=[],G=3,z=0.4;if(Z.forEach((J)=>{if(J.length<=1)return;let Q=AJ($,J),W=Math.max($.length,J.length);if((W-Q)/W>z){if(Q<G)G=Q,Y=[J];else if(Q===G)Y.push(J)}}),Y.sort((J,Q)=>J.localeCompare(Q)),X)Y=Y.map((J)=>`--${J}`);if(Y.length>1)return`
|
|
14
14
|
(Did you mean one of ${Y.join(", ")}?)`;if(Y.length===1)return`
|
|
15
|
-
(Did you mean ${Y[0]}?)`;return""}
|
|
16
|
-
- specify the name in Command constructor or using .name()`);if(Z=Z||{},Z.isDefault)this._defaultCommandName=$._name;if(Z.noHelp||Z.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,Z){return new
|
|
17
|
-
Expecting one of '${X.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(Z);else this._lifeCycleHooks[$]=[Z];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(Z)=>{if(Z.code!=="commander.executeSubCommandAsync")throw Z};return this}_exit($,Z,X){if(this._exitCallback)this._exitCallback(new
|
|
18
|
-
- already used by option '${Z.flags}'`)}this._initOptionGroup($),this.options.push($)}_registerCommand($){let Z=(Y)=>{return[Y.name()].concat(Y.aliases())},X=Z($).find((Y)=>this._findCommand(Y));if(X){let Y=Z(this._findCommand(X)).join("|"),G=Z($).join("|");throw Error(`cannot add command '${G}' as already have command '${Y}'`)}this._initCommandGroup($),this.commands.push($)}addOption($){this._registerOption($);let Z=$.name(),X=$.attributeName();if($.negate){let G=$.long.replace(/^--no-/,"--");if(!this._findOption(G))this.setOptionValueWithSource(X,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(X,$.defaultValue,"default");let Y=(G,z,J)=>{if(G==null&&$.presetArg!==void 0)G=$.presetArg;let Q=this.getOptionValue(X);if(G!==null&&$.parseArg)G=this._callParseArg($,G,Q,z);else if(G!==null&&$.variadic)G=$._collectValue(G,Q);if(G==null)if($.negate)G=!1;else if($.isBoolean()||$.optional)G=!0;else G="";this.setOptionValueWithSource(X,G,J)};if(this.on("option:"+Z,(G)=>{let z=`error: option '${$.flags}' argument '${G}' is invalid.`;Y(G,z,"cli")}),$.envVar)this.on("optionEnv:"+Z,(G)=>{let z=`error: option '${$.flags}' value '${G}' from env '${$.envVar}' is invalid.`;Y(G,z,"env")});return this}_optionEx($,Z,X,Y,G){if(typeof Z==="object"&&Z instanceof
|
|
19
|
-
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable($,Z,X){if(
|
|
15
|
+
(Did you mean ${Y[0]}?)`;return""}CJ.suggestSimilar=SJ});var w3=C((vJ)=>{var jJ=n0("events").EventEmitter,B9=n0("child_process"),r0=n0("path"),s6=n0("fs"),l=n0("process"),{Argument:xJ,humanReadableArgName:kJ}=r6(),{CommanderError:q9}=A2(),{Help:bJ,stripColor:fJ}=K9(),{Option:F3,DualOptions:yJ}=U9(),{suggestSimilar:L3}=T3();class F9 extends jJ{constructor($){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=$||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(Z)=>l.stdout.write(Z),writeErr:(Z)=>l.stderr.write(Z),outputError:(Z,X)=>X(Z),getOutHelpWidth:()=>l.stdout.isTTY?l.stdout.columns:void 0,getErrHelpWidth:()=>l.stderr.isTTY?l.stderr.columns:void 0,getOutHasColors:()=>T9()??(l.stdout.isTTY&&l.stdout.hasColors?.()),getErrHasColors:()=>T9()??(l.stderr.isTTY&&l.stderr.hasColors?.()),stripColor:(Z)=>fJ(Z)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings($){return this._outputConfiguration=$._outputConfiguration,this._helpOption=$._helpOption,this._helpCommand=$._helpCommand,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}_getCommandAndAncestors(){let $=[];for(let Z=this;Z;Z=Z.parent)$.push(Z);return $}command($,Z,X){let Y=Z,G=X;if(typeof Y==="object"&&Y!==null)G=Y,Y=null;G=G||{};let[,z,J]=$.match(/([^ ]+) *(.*)/),Q=this.createCommand(z);if(Y)Q.description(Y),Q._executableHandler=!0;if(G.isDefault)this._defaultCommandName=Q._name;if(Q._hidden=!!(G.noHelp||G.hidden),Q._executableFile=G.executableFile||null,J)Q.arguments(J);if(this._registerCommand(Q),Q.parent=this,Q.copyInheritedSettings(this),Y)return this;return Q}createCommand($){return new F9($)}createHelp(){return Object.assign(new bJ,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...$},this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,Z){if(!$._name)throw Error(`Command passed to .addCommand() must have a name
|
|
16
|
+
- specify the name in Command constructor or using .name()`);if(Z=Z||{},Z.isDefault)this._defaultCommandName=$._name;if(Z.noHelp||Z.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,Z){return new xJ($,Z)}argument($,Z,X,Y){let G=this.createArgument($,Z);if(typeof X==="function")G.default(Y).argParser(X);else G.default(X);return this.addArgument(G),this}arguments($){return $.trim().split(/ +/).forEach((Z)=>{this.argument(Z)}),this}addArgument($){let Z=this.registeredArguments.slice(-1)[0];if(Z?.variadic)throw Error(`only the last argument can be variadic '${Z.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${$.name()}'`);return this.registeredArguments.push($),this}helpCommand($,Z){if(typeof $==="boolean"){if(this._addImplicitHelpCommand=$,$&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let X=$??"help [command]",[,Y,G]=X.match(/([^ ]+) *(.*)/),z=Z??"display help for command",J=this.createCommand(Y);if(J.helpOption(!1),G)J.arguments(G);if(z)J.description(z);if(this._addImplicitHelpCommand=!0,this._helpCommand=J,$||Z)this._initCommandGroup(J);return this}addHelpCommand($,Z){if(typeof $!=="object")return this.helpCommand($,Z),this;return this._addImplicitHelpCommand=!0,this._helpCommand=$,this._initCommandGroup($),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook($,Z){let X=["preSubcommand","preAction","postAction"];if(!X.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'.
|
|
17
|
+
Expecting one of '${X.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(Z);else this._lifeCycleHooks[$]=[Z];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(Z)=>{if(Z.code!=="commander.executeSubCommandAsync")throw Z};return this}_exit($,Z,X){if(this._exitCallback)this._exitCallback(new q9($,Z,X));l.exit($)}action($){let Z=(X)=>{let Y=this.registeredArguments.length,G=X.slice(0,Y);if(this._storeOptionsAsProperties)G[Y]=this;else G[Y]=this.opts();return G.push(this),$.apply(this,G)};return this._actionHandler=Z,this}createOption($,Z){return new F3($,Z)}_callParseArg($,Z,X,Y){try{return $.parseArg(Z,X)}catch(G){if(G.code==="commander.invalidArgument"){let z=`${Y} ${G.message}`;this.error(z,{exitCode:G.exitCode,code:G.code})}throw G}}_registerOption($){let Z=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(Z){let X=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${X}'
|
|
18
|
+
- already used by option '${Z.flags}'`)}this._initOptionGroup($),this.options.push($)}_registerCommand($){let Z=(Y)=>{return[Y.name()].concat(Y.aliases())},X=Z($).find((Y)=>this._findCommand(Y));if(X){let Y=Z(this._findCommand(X)).join("|"),G=Z($).join("|");throw Error(`cannot add command '${G}' as already have command '${Y}'`)}this._initCommandGroup($),this.commands.push($)}addOption($){this._registerOption($);let Z=$.name(),X=$.attributeName();if($.negate){let G=$.long.replace(/^--no-/,"--");if(!this._findOption(G))this.setOptionValueWithSource(X,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(X,$.defaultValue,"default");let Y=(G,z,J)=>{if(G==null&&$.presetArg!==void 0)G=$.presetArg;let Q=this.getOptionValue(X);if(G!==null&&$.parseArg)G=this._callParseArg($,G,Q,z);else if(G!==null&&$.variadic)G=$._collectValue(G,Q);if(G==null)if($.negate)G=!1;else if($.isBoolean()||$.optional)G=!0;else G="";this.setOptionValueWithSource(X,G,J)};if(this.on("option:"+Z,(G)=>{let z=`error: option '${$.flags}' argument '${G}' is invalid.`;Y(G,z,"cli")}),$.envVar)this.on("optionEnv:"+Z,(G)=>{let z=`error: option '${$.flags}' value '${G}' from env '${$.envVar}' is invalid.`;Y(G,z,"env")});return this}_optionEx($,Z,X,Y,G){if(typeof Z==="object"&&Z instanceof F3)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let z=this.createOption(Z,X);if(z.makeOptionMandatory(!!$.mandatory),typeof Y==="function")z.default(G).argParser(Y);else if(Y instanceof RegExp){let J=Y;Y=(Q,W)=>{let V=J.exec(Q);return V?V[0]:W},z.default(G).argParser(Y)}else z.default(Y);return this.addOption(z)}option($,Z,X,Y){return this._optionEx({},$,Z,X,Y)}requiredOption($,Z,X,Y){return this._optionEx({mandatory:!0},$,Z,X,Y)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){return this._passThroughOptions=!!$,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties($=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!$,this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,Z){return this.setOptionValueWithSource($,Z,void 0)}setOptionValueWithSource($,Z,X){if(this._storeOptionsAsProperties)this[$]=Z;else this._optionValues[$]=Z;return this._optionValueSources[$]=X,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let Z;return this._getCommandAndAncestors().forEach((X)=>{if(X.getOptionValueSource($)!==void 0)Z=X.getOptionValueSource($)}),Z}_prepareUserArgs($,Z){if($!==void 0&&!Array.isArray($))throw Error("first parameter to parse must be array or undefined");if(Z=Z||{},$===void 0&&Z.from===void 0){if(l.versions?.electron)Z.from="electron";let Y=l.execArgv??[];if(Y.includes("-e")||Y.includes("--eval")||Y.includes("-p")||Y.includes("--print"))Z.from="eval"}if($===void 0)$=l.argv;this.rawArgs=$.slice();let X;switch(Z.from){case void 0:case"node":this._scriptPath=$[1],X=$.slice(2);break;case"electron":if(l.defaultApp)this._scriptPath=$[1],X=$.slice(2);else X=$.slice(1);break;case"user":X=$.slice(0);break;case"eval":X=$.slice(1);break;default:throw Error(`unexpected parse option { from: '${Z.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",X}parse($,Z){this._prepareForParse();let X=this._prepareUserArgs($,Z);return this._parseCommand([],X),this}async parseAsync($,Z){this._prepareForParse();let X=this._prepareUserArgs($,Z);return await this._parseCommand([],X),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
19
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable($,Z,X){if(s6.existsSync($))return;let Y=Z?`searched for local subcommand relative to directory '${Z}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",G=`'${$}' does not exist
|
|
20
20
|
- if '${X}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
21
21
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
22
|
-
- ${Y}`;throw Error(G)}_executeSubCommand($,Z){Z=Z.slice();let X=!1,Y=[".js",".ts",".tsx",".mjs",".cjs"];function G(V,K){let H=
|
|
22
|
+
- ${Y}`;throw Error(G)}_executeSubCommand($,Z){Z=Z.slice();let X=!1,Y=[".js",".ts",".tsx",".mjs",".cjs"];function G(V,K){let H=r0.resolve(V,K);if(s6.existsSync(H))return H;if(Y.includes(r0.extname(K)))return;let U=Y.find((B)=>s6.existsSync(`${H}${B}`));if(U)return`${H}${U}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let z=$._executableFile||`${this._name}-${$._name}`,J=this._executableDir||"";if(this._scriptPath){let V;try{V=s6.realpathSync(this._scriptPath)}catch{V=this._scriptPath}J=r0.resolve(r0.dirname(V),J)}if(J){let V=G(J,z);if(!V&&!$._executableFile&&this._scriptPath){let K=r0.basename(this._scriptPath,r0.extname(this._scriptPath));if(K!==this._name)V=G(J,`${K}-${$._name}`)}z=V||z}X=Y.includes(r0.extname(z));let Q;if(l.platform!=="win32")if(X)Z.unshift(z),Z=M3(l.execArgv).concat(Z),Q=B9.spawn(l.argv[0],Z,{stdio:"inherit"});else Q=B9.spawn(z,Z,{stdio:"inherit"});else this._checkForMissingExecutable(z,J,$._name),Z.unshift(z),Z=M3(l.execArgv).concat(Z),Q=B9.spawn(l.execPath,Z,{stdio:"inherit"});if(!Q.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((K)=>{l.on(K,()=>{if(Q.killed===!1&&Q.exitCode===null)Q.kill(K)})});let W=this._exitCallback;Q.on("close",(V)=>{if(V=V??1,!W)l.exit(V);else W(new q9(V,"commander.executeSubCommandAsync","(close)"))}),Q.on("error",(V)=>{if(V.code==="ENOENT")this._checkForMissingExecutable(z,J,$._name);else if(V.code==="EACCES")throw Error(`'${z}' not executable`);if(!W)l.exit(1);else{let K=new q9(1,"commander.executeSubCommandAsync","(error)");K.nestedError=V,W(K)}}),this.runningCommand=Q}_dispatchSubcommand($,Z,X){let Y=this._findCommand($);if(!Y)this.help({error:!0});Y._prepareForParse();let G;return G=this._chainOrCallSubCommandHook(G,Y,"preSubcommand"),G=this._chainOrCall(G,()=>{if(Y._executableHandler)this._executeSubCommand(Y,Z.concat(X));else return Y._parseCommand(Z,X)}),G}_dispatchHelpCommand($){if(!$)this.help();let Z=this._findCommand($);if(Z&&!Z._executableHandler)Z.help();return this._dispatchSubcommand($,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach(($,Z)=>{if($.required&&this.args[Z]==null)this.missingArgument($.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let $=(X,Y,G)=>{let z=Y;if(Y!==null&&X.parseArg){let J=`error: command-argument value '${Y}' is invalid for argument '${X.name()}'.`;z=this._callParseArg(X,Y,G,J)}return z};this._checkNumberOfArguments();let Z=[];this.registeredArguments.forEach((X,Y)=>{let G=X.defaultValue;if(X.variadic){if(Y<this.args.length){if(G=this.args.slice(Y),X.parseArg)G=G.reduce((z,J)=>{return $(X,J,z)},X.defaultValue)}else if(G===void 0)G=[]}else if(Y<this.args.length){if(G=this.args[Y],X.parseArg)G=$(X,G,X.defaultValue)}Z[Y]=G}),this.processedArgs=Z}_chainOrCall($,Z){if($?.then&&typeof $.then==="function")return $.then(()=>Z());return Z()}_chainOrCallHooks($,Z){let X=$,Y=[];if(this._getCommandAndAncestors().reverse().filter((G)=>G._lifeCycleHooks[Z]!==void 0).forEach((G)=>{G._lifeCycleHooks[Z].forEach((z)=>{Y.push({hookedCommand:G,callback:z})})}),Z==="postAction")Y.reverse();return Y.forEach((G)=>{X=this._chainOrCall(X,()=>{return G.callback(G.hookedCommand,this)})}),X}_chainOrCallSubCommandHook($,Z,X){let Y=$;if(this._lifeCycleHooks[X]!==void 0)this._lifeCycleHooks[X].forEach((G)=>{Y=this._chainOrCall(Y,()=>{return G(this,Z)})});return Y}_parseCommand($,Z){let X=this.parseOptions(Z);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(X.operands),Z=X.unknown,this.args=$.concat(Z),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),Z);if(this._getHelpCommand()&&$[0]===this._getHelpCommand().name())return this._dispatchHelpCommand($[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(Z),this._dispatchSubcommand(this._defaultCommandName,$,Z);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(X.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Y=()=>{if(X.unknown.length>0)this.unknownOption(X.unknown[0])},G=`command:${this.name()}`;if(this._actionHandler){Y(),this._processArguments();let z;if(z=this._chainOrCallHooks(z,"preAction"),z=this._chainOrCall(z,()=>this._actionHandler(this.processedArgs)),this.parent)z=this._chainOrCall(z,()=>{this.parent.emit(G,$,Z)});return z=this._chainOrCallHooks(z,"postAction"),z}if(this.parent?.listenerCount(G))Y(),this._processArguments(),this.parent.emit(G,$,Z);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,Z);if(this.listenerCount("command:*"))this.emit("command:*",$,Z);else if(this.commands.length)this.unknownCommand();else Y(),this._processArguments()}else if(this.commands.length)Y(),this.help({error:!0});else Y(),this._processArguments()}_findCommand($){if(!$)return;return this.commands.find((Z)=>Z._name===$||Z._aliases.includes($))}_findOption($){return this.options.find((Z)=>Z.is($))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(($)=>{$.options.forEach((Z)=>{if(Z.mandatory&&$.getOptionValue(Z.attributeName())===void 0)$.missingMandatoryOptionValue(Z)})})}_checkForConflictingLocalOptions(){let $=this.options.filter((X)=>{let Y=X.attributeName();if(this.getOptionValue(Y)===void 0)return!1;return this.getOptionValueSource(Y)!=="default"});$.filter((X)=>X.conflictsWith.length>0).forEach((X)=>{let Y=$.find((G)=>X.conflictsWith.includes(G.attributeName()));if(Y)this._conflictingOption(X,Y)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let Z=[],X=[],Y=Z;function G(V){return V.length>1&&V[0]==="-"}let z=(V)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(V))return!1;return!this._getCommandAndAncestors().some((K)=>K.options.map((H)=>H.short).some((H)=>/^-\d$/.test(H)))},J=null,Q=null,W=0;while(W<$.length||Q){let V=Q??$[W++];if(Q=null,V==="--"){if(Y===X)Y.push(V);Y.push(...$.slice(W));break}if(J&&(!G(V)||z(V))){this.emit(`option:${J.name()}`,V);continue}if(J=null,G(V)){let K=this._findOption(V);if(K){if(K.required){let H=$[W++];if(H===void 0)this.optionMissingArgument(K);this.emit(`option:${K.name()}`,H)}else if(K.optional){let H=null;if(W<$.length&&(!G($[W])||z($[W])))H=$[W++];this.emit(`option:${K.name()}`,H)}else this.emit(`option:${K.name()}`);J=K.variadic?K:null;continue}}if(V.length>2&&V[0]==="-"&&V[1]!=="-"){let K=this._findOption(`-${V[1]}`);if(K){if(K.required||K.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${K.name()}`,V.slice(2));else this.emit(`option:${K.name()}`),Q=`-${V.slice(2)}`;continue}}if(/^--[^=]+=/.test(V)){let K=V.indexOf("="),H=this._findOption(V.slice(0,K));if(H&&(H.required||H.optional)){this.emit(`option:${H.name()}`,V.slice(K+1));continue}}if(Y===Z&&G(V)&&!(this.commands.length===0&&z(V)))Y=X;if((this._enablePositionalOptions||this._passThroughOptions)&&Z.length===0&&X.length===0){if(this._findCommand(V)){Z.push(V),X.push(...$.slice(W));break}else if(this._getHelpCommand()&&V===this._getHelpCommand().name()){Z.push(V,...$.slice(W));break}else if(this._defaultCommandName){X.push(V,...$.slice(W));break}}if(this._passThroughOptions){Y.push(V,...$.slice(W));break}Y.push(V)}return{operands:Z,unknown:X}}opts(){if(this._storeOptionsAsProperties){let $={},Z=this.options.length;for(let X=0;X<Z;X++){let Y=this.options[X].attributeName();$[Y]=Y===this._versionOptionName?this._version:this[Y]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,Z)=>Object.assign($,Z.opts()),{})}error($,Z){if(this._outputConfiguration.outputError(`${$}
|
|
23
23
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
24
24
|
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
25
|
-
`),this.outputHelp({error:!0});let X=Z||{},Y=X.exitCode||1,G=X.code||"commander.error";this._exit(Y,G,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in l.env){let Z=$.attributeName();if(this.getOptionValue(Z)===void 0||["default","config","env"].includes(this.getOptionValueSource(Z)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,l.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new
|
|
26
|
-
`),this._exit(0,"commander.version",$)}),this}description($,Z){if($===void 0&&Z===void 0)return this._description;if(this._description=$,Z)this._argsDescription=Z;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let Z=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)Z=this.commands[this.commands.length-1];if($===Z._name)throw Error("Command alias can't be the same as its name");let X=this.parent?._findCommand($);if(X){let Y=[X.name()].concat(X.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${Y}'`)}return Z._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((Z)=>this.alias(Z)),this}usage($){if($===void 0){if(this._usage)return this._usage;let Z=this.registeredArguments.map((X)=>{return
|
|
25
|
+
`),this.outputHelp({error:!0});let X=Z||{},Y=X.exitCode||1,G=X.code||"commander.error";this._exit(Y,G,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in l.env){let Z=$.attributeName();if(this.getOptionValue(Z)===void 0||["default","config","env"].includes(this.getOptionValueSource(Z)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,l.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new yJ(this.options),Z=(X)=>{return this.getOptionValue(X)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(X))};this.options.filter((X)=>X.implied!==void 0&&Z(X.attributeName())&&$.valueFromOption(this.getOptionValue(X.attributeName()),X)).forEach((X)=>{Object.keys(X.implied).filter((Y)=>!Z(Y)).forEach((Y)=>{this.setOptionValueWithSource(Y,X.implied[Y],"implied")})})}missingArgument($){let Z=`error: missing required argument '${$}'`;this.error(Z,{code:"commander.missingArgument"})}optionMissingArgument($){let Z=`error: option '${$.flags}' argument missing`;this.error(Z,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let Z=`error: required option '${$.flags}' not specified`;this.error(Z,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,Z){let X=(z)=>{let J=z.attributeName(),Q=this.getOptionValue(J),W=this.options.find((K)=>K.negate&&J===K.attributeName()),V=this.options.find((K)=>!K.negate&&J===K.attributeName());if(W&&(W.presetArg===void 0&&Q===!1||W.presetArg!==void 0&&Q===W.presetArg))return W;return V||z},Y=(z)=>{let J=X(z),Q=J.attributeName();if(this.getOptionValueSource(Q)==="env")return`environment variable '${J.envVar}'`;return`option '${J.flags}'`},G=`error: ${Y($)} cannot be used with ${Y(Z)}`;this.error(G,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let Z="";if($.startsWith("--")&&this._showSuggestionAfterError){let Y=[],G=this;do{let z=G.createHelp().visibleOptions(G).filter((J)=>J.long).map((J)=>J.long);Y=Y.concat(z),G=G.parent}while(G&&!G._enablePositionalOptions);Z=L3($,Y)}let X=`error: unknown option '${$}'${Z}`;this.error(X,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let Z=this.registeredArguments.length,X=Z===1?"":"s",G=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${Z} argument${X} but got ${$.length}.`;this.error(G,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],Z="";if(this._showSuggestionAfterError){let Y=[];this.createHelp().visibleCommands(this).forEach((G)=>{if(Y.push(G.name()),G.alias())Y.push(G.alias())}),Z=L3($,Y)}let X=`error: unknown command '${$}'${Z}`;this.error(X,{code:"commander.unknownCommand"})}version($,Z,X){if($===void 0)return this._version;this._version=$,Z=Z||"-V, --version",X=X||"output the version number";let Y=this.createOption(Z,X);return this._versionOptionName=Y.attributeName(),this._registerOption(Y),this.on("option:"+Y.name(),()=>{this._outputConfiguration.writeOut(`${$}
|
|
26
|
+
`),this._exit(0,"commander.version",$)}),this}description($,Z){if($===void 0&&Z===void 0)return this._description;if(this._description=$,Z)this._argsDescription=Z;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let Z=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)Z=this.commands[this.commands.length-1];if($===Z._name)throw Error("Command alias can't be the same as its name");let X=this.parent?._findCommand($);if(X){let Y=[X.name()].concat(X.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${Y}'`)}return Z._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((Z)=>this.alias(Z)),this}usage($){if($===void 0){if(this._usage)return this._usage;let Z=this.registeredArguments.map((X)=>{return kJ(X)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?Z:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}helpGroup($){if($===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=$,this}commandsGroup($){if($===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=$,this}optionsGroup($){if($===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=$,this}_initOptionGroup($){if(this._defaultOptionGroup&&!$.helpGroupHeading)$.helpGroup(this._defaultOptionGroup)}_initCommandGroup($){if(this._defaultCommandGroup&&!$.helpGroup())$.helpGroup(this._defaultCommandGroup)}nameFromFilename($){return this._name=r0.basename($,r0.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let Z=this.createHelp(),X=this._getOutputContext($);Z.prepareContext({error:X.error,helpWidth:X.helpWidth,outputHasColors:X.hasColors});let Y=Z.formatHelp(this,Z);if(X.hasColors)return Y;return this._outputConfiguration.stripColor(Y)}_getOutputContext($){$=$||{};let Z=!!$.error,X,Y,G;if(Z)X=(J)=>this._outputConfiguration.writeErr(J),Y=this._outputConfiguration.getErrHasColors(),G=this._outputConfiguration.getErrHelpWidth();else X=(J)=>this._outputConfiguration.writeOut(J),Y=this._outputConfiguration.getOutHasColors(),G=this._outputConfiguration.getOutHelpWidth();return{error:Z,write:(J)=>{if(!Y)J=this._outputConfiguration.stripColor(J);return X(J)},hasColors:Y,helpWidth:G}}outputHelp($){let Z;if(typeof $==="function")Z=$,$=void 0;let X=this._getOutputContext($),Y={error:X.error,write:X.write,command:this};this._getCommandAndAncestors().reverse().forEach((z)=>z.emit("beforeAllHelp",Y)),this.emit("beforeHelp",Y);let G=this.helpInformation({error:X.error});if(Z){if(G=Z(G),typeof G!=="string"&&!Buffer.isBuffer(G))throw Error("outputHelp callback must return a string or a Buffer")}if(X.write(G),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",Y),this._getCommandAndAncestors().forEach((z)=>z.emit("afterAllHelp",Y))}helpOption($,Z){if(typeof $==="boolean"){if($){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption($??"-h, --help",Z??"display help for command"),$||Z)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption($){return this._helpOption=$,this._initOptionGroup($),this}help($){this.outputHelp($);let Z=Number(l.exitCode??0);if(Z===0&&$&&typeof $!=="function"&&$.error)Z=1;this._exit(Z,"commander.help","(outputHelp)")}addHelpText($,Z){let X=["beforeAll","before","after","afterAll"];if(!X.includes($))throw Error(`Unexpected value for position to addHelpText.
|
|
27
27
|
Expecting one of '${X.join("', '")}'`);let Y=`${$}Help`;return this.on(Y,(G)=>{let z;if(typeof Z==="function")z=Z({error:G.error,command:G.command});else z=Z;if(z)G.write(`${z}
|
|
28
|
-
`)}),this}_outputHelpIfRequested($){let Z=this._getHelpOption();if(Z&&$.find((Y)=>Z.is(Y)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function
|
|
29
|
-
`)}}
|
|
30
|
-
`)?
|
|
28
|
+
`)}),this}_outputHelpIfRequested($){let Z=this._getHelpOption();if(Z&&$.find((Y)=>Z.is(Y)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function M3($){return $.map((Z)=>{if(!Z.startsWith("--inspect"))return Z;let X,Y="127.0.0.1",G="9229",z;if((z=Z.match(/^(--inspect(-brk)?)$/))!==null)X=z[1];else if((z=Z.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(X=z[1],/^\d+$/.test(z[3]))G=z[3];else Y=z[3];else if((z=Z.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)X=z[1],Y=z[3],G=z[4];if(X&&G!=="0")return`${X}=${Y}:${parseInt(G)+1}`;return Z})}function T9(){if(l.env.NO_COLOR||l.env.FORCE_COLOR==="0"||l.env.FORCE_COLOR==="false")return!1;if(l.env.FORCE_COLOR||l.env.CLICOLOR_FORCE!==void 0)return!0;return}vJ.Command=F9;vJ.useColor=T9});var P3=C((dJ)=>{var{Argument:O3}=r6(),{Command:L9}=w3(),{CommanderError:uJ,InvalidArgumentError:N3}=A2(),{Help:mJ}=K9(),{Option:_3}=U9();dJ.program=new L9;dJ.createCommand=($)=>new L9($);dJ.createOption=($,Z)=>new _3($,Z);dJ.createArgument=($,Z)=>new O3($,Z);dJ.Command=L9;dJ.Option=_3;dJ.Argument=O3;dJ.Help=mJ;dJ.CommanderError=uJ;dJ.InvalidArgumentError=N3;dJ.InvalidOptionArgumentError=N3});var m=C((WQ)=>{var N9=Symbol.for("yaml.alias"),R3=Symbol.for("yaml.document"),o6=Symbol.for("yaml.map"),A3=Symbol.for("yaml.pair"),_9=Symbol.for("yaml.scalar"),t6=Symbol.for("yaml.seq"),s0=Symbol.for("yaml.node.type"),ZQ=($)=>!!$&&typeof $==="object"&&$[s0]===N9,XQ=($)=>!!$&&typeof $==="object"&&$[s0]===R3,YQ=($)=>!!$&&typeof $==="object"&&$[s0]===o6,GQ=($)=>!!$&&typeof $==="object"&&$[s0]===A3,S3=($)=>!!$&&typeof $==="object"&&$[s0]===_9,zQ=($)=>!!$&&typeof $==="object"&&$[s0]===t6;function C3($){if($&&typeof $==="object")switch($[s0]){case o6:case t6:return!0}return!1}function JQ($){if($&&typeof $==="object")switch($[s0]){case N9:case o6:case _9:case t6:return!0}return!1}var QQ=($)=>(S3($)||C3($))&&!!$.anchor;WQ.ALIAS=N9;WQ.DOC=R3;WQ.MAP=o6;WQ.NODE_TYPE=s0;WQ.PAIR=A3;WQ.SCALAR=_9;WQ.SEQ=t6;WQ.hasAnchor=QQ;WQ.isAlias=ZQ;WQ.isCollection=C3;WQ.isDocument=XQ;WQ.isMap=YQ;WQ.isNode=JQ;WQ.isPair=GQ;WQ.isScalar=S3;WQ.isSeq=zQ});var S2=C((EQ)=>{var e=m(),w0=Symbol("break visit"),I3=Symbol("skip children"),g0=Symbol("remove node");function e6($,Z){let X=j3(Z);if(e.isDocument($)){if(L1(null,$.contents,X,Object.freeze([$]))===g0)$.contents=null}else L1(null,$,X,Object.freeze([]))}e6.BREAK=w0;e6.SKIP=I3;e6.REMOVE=g0;function L1($,Z,X,Y){let G=x3($,Z,X,Y);if(e.isNode(G)||e.isPair(G))return k3($,Y,G),L1($,G,X,Y);if(typeof G!=="symbol"){if(e.isCollection(Z)){Y=Object.freeze(Y.concat(Z));for(let z=0;z<Z.items.length;++z){let J=L1(z,Z.items[z],X,Y);if(typeof J==="number")z=J-1;else if(J===w0)return w0;else if(J===g0)Z.items.splice(z,1),z-=1}}else if(e.isPair(Z)){Y=Object.freeze(Y.concat(Z));let z=L1("key",Z.key,X,Y);if(z===w0)return w0;else if(z===g0)Z.key=null;let J=L1("value",Z.value,X,Y);if(J===w0)return w0;else if(J===g0)Z.value=null}}return G}async function $Z($,Z){let X=j3(Z);if(e.isDocument($)){if(await M1(null,$.contents,X,Object.freeze([$]))===g0)$.contents=null}else await M1(null,$,X,Object.freeze([]))}$Z.BREAK=w0;$Z.SKIP=I3;$Z.REMOVE=g0;async function M1($,Z,X,Y){let G=await x3($,Z,X,Y);if(e.isNode(G)||e.isPair(G))return k3($,Y,G),M1($,G,X,Y);if(typeof G!=="symbol"){if(e.isCollection(Z)){Y=Object.freeze(Y.concat(Z));for(let z=0;z<Z.items.length;++z){let J=await M1(z,Z.items[z],X,Y);if(typeof J==="number")z=J-1;else if(J===w0)return w0;else if(J===g0)Z.items.splice(z,1),z-=1}}else if(e.isPair(Z)){Y=Object.freeze(Y.concat(Z));let z=await M1("key",Z.key,X,Y);if(z===w0)return w0;else if(z===g0)Z.key=null;let J=await M1("value",Z.value,X,Y);if(J===w0)return w0;else if(J===g0)Z.value=null}}return G}function j3($){if(typeof $==="object"&&($.Collection||$.Node||$.Value))return Object.assign({Alias:$.Node,Map:$.Node,Scalar:$.Node,Seq:$.Node},$.Value&&{Map:$.Value,Scalar:$.Value,Seq:$.Value},$.Collection&&{Map:$.Collection,Seq:$.Collection},$);return $}function x3($,Z,X,Y){if(typeof X==="function")return X($,Z,Y);if(e.isMap(Z))return X.Map?.($,Z,Y);if(e.isSeq(Z))return X.Seq?.($,Z,Y);if(e.isPair(Z))return X.Pair?.($,Z,Y);if(e.isScalar(Z))return X.Scalar?.($,Z,Y);if(e.isAlias(Z))return X.Alias?.($,Z,Y);return}function k3($,Z,X){let Y=Z[Z.length-1];if(e.isCollection(Y))Y.items[$]=X;else if(e.isPair(Y))if($==="key")Y.key=X;else Y.value=X;else if(e.isDocument(Y))Y.contents=X;else{let G=e.isAlias(Y)?"alias":"scalar";throw Error(`Cannot replace node with ${G} parent`)}}EQ.visit=e6;EQ.visitAsync=$Z});var P9=C((jQ)=>{var b3=m(),SQ=S2(),CQ={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},IQ=($)=>$.replace(/[!,[\]{}]/g,(Z)=>CQ[Z]);class A0{constructor($,Z){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},A0.defaultYaml,$),this.tags=Object.assign({},A0.defaultTags,Z)}clone(){let $=new A0(this.yaml,this.tags);return $.docStart=this.docStart,$}atDocument(){let $=new A0(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:A0.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},A0.defaultTags);break}return $}add($,Z){if(this.atNextDocument)this.yaml={explicit:A0.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},A0.defaultTags),this.atNextDocument=!1;let X=$.trim().split(/[ \t]+/),Y=X.shift();switch(Y){case"%TAG":{if(X.length!==2){if(Z(0,"%TAG directive should contain exactly two parts"),X.length<2)return!1}let[G,z]=X;return this.tags[G]=z,!0}case"%YAML":{if(this.yaml.explicit=!0,X.length!==1)return Z(0,"%YAML directive should contain exactly one part"),!1;let[G]=X;if(G==="1.1"||G==="1.2")return this.yaml.version=G,!0;else{let z=/^\d+\.\d+$/.test(G);return Z(6,`Unsupported YAML version ${G}`,z),!1}}default:return Z(0,`Unknown directive ${Y}`,!0),!1}}tagName($,Z){if($==="!")return"!";if($[0]!=="!")return Z(`Not a valid tag: ${$}`),null;if($[1]==="<"){let z=$.slice(2,-1);if(z==="!"||z==="!!")return Z(`Verbatim tags aren't resolved, so ${$} is invalid.`),null;if($[$.length-1]!==">")Z("Verbatim tags must end with a >");return z}let[,X,Y]=$.match(/^(.*!)([^!]*)$/s);if(!Y)Z(`The ${$} tag has no suffix`);let G=this.tags[X];if(G)try{return G+decodeURIComponent(Y)}catch(z){return Z(String(z)),null}if(X==="!")return $;return Z(`Could not resolve tag: ${$}`),null}tagString($){for(let[Z,X]of Object.entries(this.tags))if($.startsWith(X))return Z+IQ($.substring(X.length));return $[0]==="!"?$:`!<${$}>`}toString($){let Z=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],X=Object.entries(this.tags),Y;if($&&X.length>0&&b3.isNode($.contents)){let G={};SQ.visit($.contents,(z,J)=>{if(b3.isNode(J)&&J.tag)G[J.tag]=!0}),Y=Object.keys(G)}else Y=[];for(let[G,z]of X){if(G==="!!"&&z==="tag:yaml.org,2002:")continue;if(!$||Y.some((J)=>J.startsWith(z)))Z.push(`%TAG ${G} ${z}`)}return Z.join(`
|
|
29
|
+
`)}}A0.defaultYaml={explicit:!1,version:"1.2"};A0.defaultTags={"!!":"tag:yaml.org,2002:"};jQ.Directives=A0});var ZZ=C((yQ)=>{var f3=m(),kQ=S2();function bQ($){if(/[\x00-\x19\s,[\]{}]/.test($)){let X=`Anchor must not contain whitespace or control characters: ${JSON.stringify($)}`;throw Error(X)}return!0}function y3($){let Z=new Set;return kQ.visit($,{Value(X,Y){if(Y.anchor)Z.add(Y.anchor)}}),Z}function v3($,Z){for(let X=1;;++X){let Y=`${$}${X}`;if(!Z.has(Y))return Y}}function fQ($,Z){let X=[],Y=new Map,G=null;return{onAnchor:(z)=>{X.push(z),G??(G=y3($));let J=v3(Z,G);return G.add(J),J},setAnchors:()=>{for(let z of X){let J=Y.get(z);if(typeof J==="object"&&J.anchor&&(f3.isScalar(J.node)||f3.isCollection(J.node)))J.node.anchor=J.anchor;else{let Q=Error("Failed to resolve repeated object (this should not happen)");throw Q.source=z,Q}}},sourceObjects:Y}}yQ.anchorIsValid=bQ;yQ.anchorNames=y3;yQ.createNodeAnchors=fQ;yQ.findNewAnchor=v3});var D9=C((mQ)=>{function C2($,Z,X,Y){if(Y&&typeof Y==="object")if(Array.isArray(Y))for(let G=0,z=Y.length;G<z;++G){let J=Y[G],Q=C2($,Y,String(G),J);if(Q===void 0)delete Y[G];else if(Q!==J)Y[G]=Q}else if(Y instanceof Map)for(let G of Array.from(Y.keys())){let z=Y.get(G),J=C2($,Y,G,z);if(J===void 0)Y.delete(G);else if(J!==z)Y.set(G,J)}else if(Y instanceof Set)for(let G of Array.from(Y)){let z=C2($,Y,G,G);if(z===void 0)Y.delete(G);else if(z!==G)Y.delete(G),Y.add(z)}else for(let[G,z]of Object.entries(Y)){let J=C2($,Y,G,z);if(J===void 0)delete Y[G];else if(J!==z)Y[G]=J}return $.call(Z,X,Y)}mQ.applyReviver=C2});var H$=C((lQ)=>{var cQ=m();function g3($,Z,X){if(Array.isArray($))return $.map((Y,G)=>g3(Y,String(G),X));if($&&typeof $.toJSON==="function"){if(!X||!cQ.hasAnchor($))return $.toJSON(Z,X);let Y={aliasCount:0,count:1,res:void 0};X.anchors.set($,Y),X.onCreate=(z)=>{Y.res=z,delete X.onCreate};let G=$.toJSON(Z,X);if(X.onCreate)X.onCreate(G);return G}if(typeof $==="bigint"&&!X?.keep)return Number($);return $}lQ.toJS=g3});var XZ=C((nQ)=>{var iQ=D9(),h3=m(),aQ=H$();class u3{constructor($){Object.defineProperty(this,h3.NODE_TYPE,{value:$})}clone(){let $=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)$.range=this.range.slice();return $}toJS($,{mapAsMap:Z,maxAliasCount:X,onAnchor:Y,reviver:G}={}){if(!h3.isDocument($))throw TypeError("A document argument is required");let z={anchors:new Map,doc:$,keep:!0,mapAsMap:Z===!0,mapKeyWarned:!1,maxAliasCount:typeof X==="number"?X:100},J=aQ.toJS(this,"",z);if(typeof Y==="function")for(let{count:Q,res:W}of z.anchors.values())Y(W,Q);return typeof G==="function"?iQ.applyReviver(G,{"":J},"",J):J}}nQ.NodeBase=u3});var I2=C(($W)=>{var sQ=ZZ(),oQ=S2(),w1=m(),tQ=XZ(),eQ=H$();class m3 extends tQ.NodeBase{constructor($){super(w1.ALIAS);this.source=$,Object.defineProperty(this,"tag",{set(){throw Error("Alias nodes cannot have tags")}})}resolve($,Z){let X;if(Z?.aliasResolveCache)X=Z.aliasResolveCache;else if(X=[],oQ.visit($,{Node:(G,z)=>{if(w1.isAlias(z)||w1.hasAnchor(z))X.push(z)}}),Z)Z.aliasResolveCache=X;let Y=void 0;for(let G of X){if(G===this)break;if(G.anchor===this.source)Y=G}return Y}toJSON($,Z){if(!Z)return{source:this.source};let{anchors:X,doc:Y,maxAliasCount:G}=Z,z=this.resolve(Y,Z);if(!z){let Q=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(Q)}let J=X.get(z);if(!J)eQ.toJS(z,null,Z),J=X.get(z);if(J?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(G>=0){if(J.count+=1,J.aliasCount===0)J.aliasCount=YZ(Y,z,X);if(J.count*J.aliasCount>G)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return J.res}toString($,Z,X){let Y=`*${this.source}`;if($){if(sQ.anchorIsValid(this.source),$.options.verifyAliasOrder&&!$.anchors.has(this.source)){let G=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(G)}if($.implicitKey)return`${Y} `}return Y}}function YZ($,Z,X){if(w1.isAlias(Z)){let Y=Z.resolve($),G=X&&Y&&X.get(Y);return G?G.count*G.aliasCount:0}else if(w1.isCollection(Z)){let Y=0;for(let G of Z.items){let z=YZ($,G,X);if(z>Y)Y=z}return Y}else if(w1.isPair(Z)){let Y=YZ($,Z.key,X),G=YZ($,Z.value,X);return Math.max(Y,G)}return 1}$W.Alias=m3});var t=C((JW)=>{var XW=m(),YW=XZ(),GW=H$(),zW=($)=>!$||typeof $!=="function"&&typeof $!=="object";class v$ extends YW.NodeBase{constructor($){super(XW.SCALAR);this.value=$}toJSON($,Z){return Z?.keep?this.value:GW.toJS(this.value,$,Z)}toString(){return String(this.value)}}v$.BLOCK_FOLDED="BLOCK_FOLDED";v$.BLOCK_LITERAL="BLOCK_LITERAL";v$.PLAIN="PLAIN";v$.QUOTE_DOUBLE="QUOTE_DOUBLE";v$.QUOTE_SINGLE="QUOTE_SINGLE";JW.Scalar=v$;JW.isScalarValue=zW});var j2=C((BW)=>{var VW=I2(),g$=m(),d3=t(),HW="tag:yaml.org,2002:";function KW($,Z,X){if(Z){let Y=X.filter((z)=>z.tag===Z),G=Y.find((z)=>!z.format)??Y[0];if(!G)throw Error(`Tag ${Z} not found`);return G}return X.find((Y)=>Y.identify?.($)&&!Y.format)}function UW($,Z,X){if(g$.isDocument($))$=$.contents;if(g$.isNode($))return $;if(g$.isPair($)){let H=X.schema[g$.MAP].createNode?.(X.schema,null,X);return H.items.push($),H}if($ instanceof String||$ instanceof Number||$ instanceof Boolean||typeof BigInt<"u"&&$ instanceof BigInt)$=$.valueOf();let{aliasDuplicateObjects:Y,onAnchor:G,onTagObj:z,schema:J,sourceObjects:Q}=X,W=void 0;if(Y&&$&&typeof $==="object")if(W=Q.get($),W)return W.anchor??(W.anchor=G($)),new VW.Alias(W.anchor);else W={anchor:null,node:null},Q.set($,W);if(Z?.startsWith("!!"))Z=HW+Z.slice(2);let V=KW($,Z,J.tags);if(!V){if($&&typeof $.toJSON==="function")$=$.toJSON();if(!$||typeof $!=="object"){let H=new d3.Scalar($);if(W)W.node=H;return H}V=$ instanceof Map?J[g$.MAP]:(Symbol.iterator in Object($))?J[g$.SEQ]:J[g$.MAP]}if(z)z(V),delete X.onTagObj;let K=V?.createNode?V.createNode(X.schema,$,X):typeof V?.nodeClass?.from==="function"?V.nodeClass.from(X.schema,$,X):new d3.Scalar($);if(Z)K.tag=Z;else if(!V.default)K.tag=V.tag;if(W)W.node=K;return K}BW.createNode=UW});var GZ=C((LW)=>{var TW=j2(),h0=m(),FW=XZ();function E9($,Z,X){let Y=X;for(let G=Z.length-1;G>=0;--G){let z=Z[G];if(typeof z==="number"&&Number.isInteger(z)&&z>=0){let J=[];J[z]=Y,Y=J}else Y=new Map([[z,Y]])}return TW.createNode(Y,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:$,sourceObjects:new Map})}var c3=($)=>$==null||typeof $==="object"&&!!$[Symbol.iterator]().next().done;class l3 extends FW.NodeBase{constructor($,Z){super($);Object.defineProperty(this,"schema",{value:Z,configurable:!0,enumerable:!1,writable:!0})}clone($){let Z=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if($)Z.schema=$;if(Z.items=Z.items.map((X)=>h0.isNode(X)||h0.isPair(X)?X.clone($):X),this.range)Z.range=this.range.slice();return Z}addIn($,Z){if(c3($))this.add(Z);else{let[X,...Y]=$,G=this.get(X,!0);if(h0.isCollection(G))G.addIn(Y,Z);else if(G===void 0&&this.schema)this.set(X,E9(this.schema,Y,Z));else throw Error(`Expected YAML collection at ${X}. Remaining path: ${Y}`)}}deleteIn($){let[Z,...X]=$;if(X.length===0)return this.delete(Z);let Y=this.get(Z,!0);if(h0.isCollection(Y))return Y.deleteIn(X);else throw Error(`Expected YAML collection at ${Z}. Remaining path: ${X}`)}getIn($,Z){let[X,...Y]=$,G=this.get(X,!0);if(Y.length===0)return!Z&&h0.isScalar(G)?G.value:G;else return h0.isCollection(G)?G.getIn(Y,Z):void 0}hasAllNullValues($){return this.items.every((Z)=>{if(!h0.isPair(Z))return!1;let X=Z.value;return X==null||$&&h0.isScalar(X)&&X.value==null&&!X.commentBefore&&!X.comment&&!X.tag})}hasIn($){let[Z,...X]=$;if(X.length===0)return this.has(Z);let Y=this.get(Z,!0);return h0.isCollection(Y)?Y.hasIn(X):!1}setIn($,Z){let[X,...Y]=$;if(Y.length===0)this.set(X,Z);else{let G=this.get(X,!0);if(h0.isCollection(G))G.setIn(Y,Z);else if(G===void 0&&this.schema)this.set(X,E9(this.schema,Y,Z));else throw Error(`Expected YAML collection at ${X}. Remaining path: ${Y}`)}}}LW.Collection=l3;LW.collectionFromPath=E9;LW.isEmptyPath=c3});var x2=C((PW)=>{var NW=($)=>$.replace(/^(?!$)(?: $)?/gm,"#");function R9($,Z){if(/^\n+$/.test($))return $.substring(1);return Z?$.replace(/^(?! *$)/gm,Z):$}var _W=($,Z,X)=>$.endsWith(`
|
|
30
|
+
`)?R9(X,Z):X.includes(`
|
|
31
31
|
`)?`
|
|
32
|
-
`+
|
|
33
|
-
`){if(X==="block")
|
|
34
|
-
`&&
|
|
35
|
-
`&&P!=="\t")
|
|
32
|
+
`+R9(X,Z):($.endsWith(" ")?"":" ")+X;PW.indentComment=R9;PW.lineComment=_W;PW.stringifyComment=NW});var i3=C((SW)=>{function AW($,Z,X="flow",{indentAtStart:Y,lineWidth:G=80,minContentWidth:z=20,onFold:J,onOverflow:Q}={}){if(!G||G<0)return $;if(G<z)z=0;let W=Math.max(1+z,1+G-Z.length);if($.length<=W)return $;let V=[],K={},H=G-Z.length;if(typeof Y==="number")if(Y>G-Math.max(2,z))V.push(0);else H=G-Y;let U=void 0,B=void 0,T=!1,F=-1,M=-1,O=-1;if(X==="block"){if(F=p3($,F,Z.length),F!==-1)H=F+W}for(let _;_=$[F+=1];){if(X==="quoted"&&_==="\\"){switch(M=F,$[F+1]){case"x":F+=3;break;case"u":F+=5;break;case"U":F+=9;break;default:F+=1}O=F}if(_===`
|
|
33
|
+
`){if(X==="block")F=p3($,F,Z.length);H=F+Z.length+W,U=void 0}else{if(_===" "&&B&&B!==" "&&B!==`
|
|
34
|
+
`&&B!=="\t"){let P=$[F+1];if(P&&P!==" "&&P!==`
|
|
35
|
+
`&&P!=="\t")U=F}if(F>=H)if(U)V.push(U),H=U+W,U=void 0;else if(X==="quoted"){while(B===" "||B==="\t")B=_,_=$[F+=1],T=!0;let P=F>O+1?F-2:M-1;if(K[P])return $;V.push(P),K[P]=!0,H=P+W,U=void 0}else T=!0}B=_}if(T&&Q)Q();if(V.length===0)return $;if(J)J();let N=$.slice(0,V[0]);for(let _=0;_<V.length;++_){let P=V[_],R=V[_+1]||$.length;if(P===0)N=`
|
|
36
36
|
${Z}${$.slice(0,R)}`;else{if(X==="quoted"&&K[P])N+=`${$[P]}\\`;N+=`
|
|
37
|
-
${Z}${$.slice(P+1,R)}`}}return N}function
|
|
38
|
-
`);Y=Z,G=Z+1,z=$[G]}return Y}
|
|
39
|
-
`){if(z-J>Y)return!0;if(J=z+1,G-J<=Y)return!1}return!0}function
|
|
37
|
+
${Z}${$.slice(P+1,R)}`}}return N}function p3($,Z,X){let Y=Z,G=Z+1,z=$[G];while(z===" "||z==="\t")if(Z<G+X)z=$[++Z];else{do z=$[++Z];while(z&&z!==`
|
|
38
|
+
`);Y=Z,G=Z+1,z=$[G]}return Y}SW.FOLD_BLOCK="block";SW.FOLD_FLOW="flow";SW.FOLD_QUOTED="quoted";SW.foldFlowLines=AW});var b2=C((yW)=>{var k0=t(),K$=i3(),JZ=($,Z)=>({indentAtStart:Z?$.indent.length:$.indentAtStart,lineWidth:$.options.lineWidth,minContentWidth:$.options.minContentWidth}),QZ=($)=>/^(%|---|\.\.\.)/m.test($);function kW($,Z,X){if(!Z||Z<0)return!1;let Y=Z-X,G=$.length;if(G<=Y)return!1;for(let z=0,J=0;z<G;++z)if($[z]===`
|
|
39
|
+
`){if(z-J>Y)return!0;if(J=z+1,G-J<=Y)return!1}return!0}function k2($,Z){let X=JSON.stringify($);if(Z.options.doubleQuotedAsJSON)return X;let{implicitKey:Y}=Z,G=Z.options.doubleQuotedMinMultiLineLength,z=Z.indent||(QZ($)?" ":""),J="",Q=0;for(let W=0,V=X[W];V;V=X[++W]){if(V===" "&&X[W+1]==="\\"&&X[W+2]==="n")J+=X.slice(Q,W)+"\\ ",W+=1,Q=W,V="\\";if(V==="\\")switch(X[W+1]){case"u":{J+=X.slice(Q,W);let K=X.substr(W+2,4);switch(K){case"0000":J+="\\0";break;case"0007":J+="\\a";break;case"000b":J+="\\v";break;case"001b":J+="\\e";break;case"0085":J+="\\N";break;case"00a0":J+="\\_";break;case"2028":J+="\\L";break;case"2029":J+="\\P";break;default:if(K.substr(0,2)==="00")J+="\\x"+K.substr(2);else J+=X.substr(W,6)}W+=5,Q=W+1}break;case"n":if(Y||X[W+2]==='"'||X.length<G)W+=1;else{J+=X.slice(Q,W)+`
|
|
40
40
|
|
|
41
41
|
`;while(X[W+2]==="\\"&&X[W+3]==="n"&&X[W+4]!=='"')J+=`
|
|
42
|
-
`,W+=2;if(J+=z,X[W+2]===" ")J+="\\";W+=1,Q=W+1}break;default:W+=1}}return J=Q?J+X.slice(Q):X,Y?J:
|
|
43
|
-
`)||/[ \t]\n|\n[ \t]/.test($))return
|
|
44
|
-
${X}`)+"'";return Z.implicitKey?Y:
|
|
42
|
+
`,W+=2;if(J+=z,X[W+2]===" ")J+="\\";W+=1,Q=W+1}break;default:W+=1}}return J=Q?J+X.slice(Q):X,Y?J:K$.foldFlowLines(J,z,K$.FOLD_QUOTED,JZ(Z,!1))}function A9($,Z){if(Z.options.singleQuote===!1||Z.implicitKey&&$.includes(`
|
|
43
|
+
`)||/[ \t]\n|\n[ \t]/.test($))return k2($,Z);let X=Z.indent||(QZ($)?" ":""),Y="'"+$.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
44
|
+
${X}`)+"'";return Z.implicitKey?Y:K$.foldFlowLines(Y,X,K$.FOLD_FLOW,JZ(Z,!1))}function O1($,Z){let{singleQuote:X}=Z.options,Y;if(X===!1)Y=k2;else{let G=$.includes('"'),z=$.includes("'");if(G&&!z)Y=A9;else if(z&&!G)Y=k2;else Y=X?A9:k2}return Y($,Z)}var S9;try{S9=new RegExp(`(^|(?<!
|
|
45
45
|
))
|
|
46
46
|
+(?!
|
|
47
|
-
|$)`,"g")}catch{
|
|
47
|
+
|$)`,"g")}catch{S9=/\n+(?!\n|$)/g}function zZ({comment:$,type:Z,value:X},Y,G,z){let{blockQuote:J,commentString:Q,lineWidth:W}=Y.options;if(!J||/\n[\t ]+$/.test(X))return O1(X,Y);let V=Y.indent||(Y.forceBlockIndent||QZ(X)?" ":""),K=J==="literal"?!0:J==="folded"||Z===k0.Scalar.BLOCK_FOLDED?!1:Z===k0.Scalar.BLOCK_LITERAL?!0:!kW(X,W,V.length);if(!X)return K?`|
|
|
48
48
|
`:`>
|
|
49
|
-
`;let H,
|
|
50
|
-
`&&R!=="\t"&&R!==" ")break}let
|
|
51
|
-
`);if(
|
|
52
|
-
`)
|
|
53
|
-
`)O=
|
|
54
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${V}`),A=!1,S=
|
|
49
|
+
`;let H,U;for(U=X.length;U>0;--U){let R=X[U-1];if(R!==`
|
|
50
|
+
`&&R!=="\t"&&R!==" ")break}let B=X.substring(U),T=B.indexOf(`
|
|
51
|
+
`);if(T===-1)H="-";else if(X===B||T!==B.length-1){if(H="+",z)z()}else H="";if(B){if(X=X.slice(0,-B.length),B[B.length-1]===`
|
|
52
|
+
`)B=B.slice(0,-1);B=B.replace(S9,`$&${V}`)}let F=!1,M,O=-1;for(M=0;M<X.length;++M){let R=X[M];if(R===" ")F=!0;else if(R===`
|
|
53
|
+
`)O=M;else break}let N=X.substring(0,O<M?O+1:M);if(N)X=X.substring(N.length),N=N.replace(/\n+/g,`$&${V}`);let P=(F?V?"2":"1":"")+H;if($){if(P+=" "+Q($.replace(/ ?[\r\n]+/g," ")),G)G()}if(!K){let R=X.replace(/\n+/g,`
|
|
54
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${V}`),A=!1,S=JZ(Y,!0);if(J!=="folded"&&Z!==k0.Scalar.BLOCK_FOLDED)S.onOverflow=()=>{A=!0};let D=K$.foldFlowLines(`${N}${R}${B}`,V,K$.FOLD_BLOCK,S);if(!A)return`>${P}
|
|
55
55
|
${V}${D}`}return X=X.replace(/\n+/g,`$&${V}`),`|${P}
|
|
56
|
-
${V}${N}${X}${
|
|
57
|
-
`)||K&&/[[\]{},]/.test(z))return
|
|
58
|
-
`)?
|
|
59
|
-
`))return
|
|
60
|
-
${W}`);if(J){let
|
|
61
|
-
${Z.indent}${Q}`}
|
|
62
|
-
${Q}:`}else if(
|
|
56
|
+
${V}${N}${X}${B}`}function bW($,Z,X,Y){let{type:G,value:z}=$,{actualString:J,implicitKey:Q,indent:W,indentStep:V,inFlow:K}=Z;if(Q&&z.includes(`
|
|
57
|
+
`)||K&&/[[\]{},]/.test(z))return O1(z,Z);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(z))return Q||K||!z.includes(`
|
|
58
|
+
`)?O1(z,Z):zZ($,Z,X,Y);if(!Q&&!K&&G!==k0.Scalar.PLAIN&&z.includes(`
|
|
59
|
+
`))return zZ($,Z,X,Y);if(QZ(z)){if(W==="")return Z.forceBlockIndent=!0,zZ($,Z,X,Y);else if(Q&&W===V)return O1(z,Z)}let H=z.replace(/\n+/g,`$&
|
|
60
|
+
${W}`);if(J){let U=(F)=>F.default&&F.tag!=="tag:yaml.org,2002:str"&&F.test?.test(H),{compat:B,tags:T}=Z.doc.schema;if(T.some(U)||B?.some(U))return O1(z,Z)}return Q?H:K$.foldFlowLines(H,W,K$.FOLD_FLOW,JZ(Z,!1))}function fW($,Z,X,Y){let{implicitKey:G,inFlow:z}=Z,J=typeof $.value==="string"?$:Object.assign({},$,{value:String($.value)}),{type:Q}=$;if(Q!==k0.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(J.value))Q=k0.Scalar.QUOTE_DOUBLE}let W=(K)=>{switch(K){case k0.Scalar.BLOCK_FOLDED:case k0.Scalar.BLOCK_LITERAL:return G||z?O1(J.value,Z):zZ(J,Z,X,Y);case k0.Scalar.QUOTE_DOUBLE:return k2(J.value,Z);case k0.Scalar.QUOTE_SINGLE:return A9(J.value,Z);case k0.Scalar.PLAIN:return bW(J,Z,X,Y);default:return null}},V=W(Q);if(V===null){let{defaultKeyType:K,defaultStringType:H}=Z.options,U=G&&K||H;if(V=W(U),V===null)throw Error(`Unsupported default string type ${U}`)}return V}yW.stringifyString=fW});var f2=C((pW)=>{var gW=ZZ(),U$=m(),hW=x2(),uW=b2();function mW($,Z){let X=Object.assign({blockQuote:!0,commentString:hW.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},$.schema.toStringOptions,Z),Y;switch(X.collectionStyle){case"block":Y=!1;break;case"flow":Y=!0;break;default:Y=null}return{anchors:new Set,doc:$,flowCollectionPadding:X.flowCollectionPadding?" ":"",indent:"",indentStep:typeof X.indent==="number"?" ".repeat(X.indent):" ",inFlow:Y,options:X}}function dW($,Z){if(Z.tag){let G=$.filter((z)=>z.tag===Z.tag);if(G.length>0)return G.find((z)=>z.format===Z.format)??G[0]}let X=void 0,Y;if(U$.isScalar(Z)){Y=Z.value;let G=$.filter((z)=>z.identify?.(Y));if(G.length>1){let z=G.filter((J)=>J.test);if(z.length>0)G=z}X=G.find((z)=>z.format===Z.format)??G.find((z)=>!z.format)}else Y=Z,X=$.find((G)=>G.nodeClass&&Y instanceof G.nodeClass);if(!X){let G=Y?.constructor?.name??(Y===null?"null":typeof Y);throw Error(`Tag not resolved for ${G} value`)}return X}function cW($,Z,{anchors:X,doc:Y}){if(!Y.directives)return"";let G=[],z=(U$.isScalar($)||U$.isCollection($))&&$.anchor;if(z&&gW.anchorIsValid(z))X.add(z),G.push(`&${z}`);let J=$.tag??(Z.default?null:Z.tag);if(J)G.push(Y.directives.tagString(J));return G.join(" ")}function lW($,Z,X,Y){if(U$.isPair($))return $.toString(Z,X,Y);if(U$.isAlias($)){if(Z.doc.directives)return $.toString(Z);if(Z.resolvedAliases?.has($))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(Z.resolvedAliases)Z.resolvedAliases.add($);else Z.resolvedAliases=new Set([$]);$=$.resolve(Z.doc)}}let G=void 0,z=U$.isNode($)?$:Z.doc.createNode($,{onTagObj:(W)=>G=W});G??(G=dW(Z.doc.schema.tags,z));let J=cW(z,G,Z);if(J.length>0)Z.indentAtStart=(Z.indentAtStart??0)+J.length+1;let Q=typeof G.stringify==="function"?G.stringify(z,Z,X,Y):U$.isScalar(z)?uW.stringifyString(z,Z,X,Y):z.toString(Z,X,Y);if(!J)return Q;return U$.isScalar(z)||Q[0]==="{"||Q[0]==="["?`${J} ${Q}`:`${J}
|
|
61
|
+
${Z.indent}${Q}`}pW.createStringifyContext=mW;pW.stringify=lW});var r3=C((rW)=>{var o0=m(),a3=t(),n3=f2(),y2=x2();function nW({key:$,value:Z},X,Y,G){let{allNullValues:z,doc:J,indent:Q,indentStep:W,options:{commentString:V,indentSeq:K,simpleKeys:H}}=X,U=o0.isNode($)&&$.comment||null;if(H){if(U)throw Error("With simple keys, key nodes cannot have comments");if(o0.isCollection($)||!o0.isNode($)&&typeof $==="object")throw Error("With simple keys, collection cannot be used as a key value")}let B=!H&&(!$||U&&Z==null&&!X.inFlow||o0.isCollection($)||(o0.isScalar($)?$.type===a3.Scalar.BLOCK_FOLDED||$.type===a3.Scalar.BLOCK_LITERAL:typeof $==="object"));X=Object.assign({},X,{allNullValues:!1,implicitKey:!B&&(H||!z),indent:Q+W});let T=!1,F=!1,M=n3.stringify($,X,()=>T=!0,()=>F=!0);if(!B&&!X.inFlow&&M.length>1024){if(H)throw Error("With simple keys, single line scalar must not span more than 1024 characters");B=!0}if(X.inFlow){if(z||Z==null){if(T&&Y)Y();return M===""?"?":B?`? ${M}`:M}}else if(z&&!H||Z==null&&B){if(M=`? ${M}`,U&&!T)M+=y2.lineComment(M,X.indent,V(U));else if(F&&G)G();return M}if(T)U=null;if(B){if(U)M+=y2.lineComment(M,X.indent,V(U));M=`? ${M}
|
|
62
|
+
${Q}:`}else if(M=`${M}:`,U)M+=y2.lineComment(M,X.indent,V(U));let O,N,_;if(o0.isNode(Z))O=!!Z.spaceBefore,N=Z.commentBefore,_=Z.comment;else if(O=!1,N=null,_=null,Z&&typeof Z==="object")Z=J.createNode(Z);if(X.implicitKey=!1,!B&&!U&&o0.isScalar(Z))X.indentAtStart=M.length+1;if(F=!1,!K&&W.length>=2&&!X.inFlow&&!B&&o0.isSeq(Z)&&!Z.flow&&!Z.tag&&!Z.anchor)X.indent=X.indent.substring(2);let P=!1,R=n3.stringify(Z,X,()=>P=!0,()=>F=!0),A=" ";if(U||O||N){if(A=O?`
|
|
63
63
|
`:"",N){let S=V(N);A+=`
|
|
64
|
-
${
|
|
64
|
+
${y2.indentComment(S,X.indent)}`}if(R===""&&!X.inFlow){if(A===`
|
|
65
65
|
`&&_)A=`
|
|
66
66
|
|
|
67
67
|
`}else A+=`
|
|
68
|
-
${X.indent}`}else if(!
|
|
68
|
+
${X.indent}`}else if(!B&&o0.isCollection(Z)){let S=R[0],D=R.indexOf(`
|
|
69
69
|
`),k=D!==-1,b=X.inFlow??Z.flow??Z.items.length===0;if(k||!b){let i=!1;if(k&&(S==="&"||S==="!")){let c=R.indexOf(" ");if(S==="&"&&c!==-1&&c<D&&R[c+1]==="!")c=R.indexOf(" ",c+1);if(c===-1||D<c)i=!0}if(!i)A=`
|
|
70
70
|
${X.indent}`}}else if(R===""||R[0]===`
|
|
71
|
-
`)A="";if(
|
|
72
|
-
${W}${
|
|
73
|
-
`}}if($){if(
|
|
74
|
-
`+
|
|
75
|
-
`)))V=!0;H.push(O),K=H.length}let{start:
|
|
76
|
-
${z}${G}${
|
|
77
|
-
`;return`${
|
|
78
|
-
${G}${
|
|
79
|
-
`:" ")}return
|
|
71
|
+
`)A="";if(M+=A+R,X.inFlow){if(P&&Y)Y()}else if(_&&!P)M+=y2.lineComment(M,X.indent,V(_));else if(F&&G)G();return M}rW.stringifyPair=nW});var C9=C((eW)=>{var s3=n0("process");function oW($,...Z){if($==="debug")console.log(...Z)}function tW($,Z){if($==="debug"||$==="warn")if(typeof s3.emitWarning==="function")s3.emitWarning(Z);else console.warn(Z)}eW.debug=oW;eW.warn=tW});var HZ=C((YV)=>{var v2=m(),o3=t(),WZ="<<",VZ={identify:($)=>$===WZ||typeof $==="symbol"&&$.description===WZ,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new o3.Scalar(Symbol(WZ)),{addToJSMap:t3}),stringify:()=>WZ},XV=($,Z)=>(VZ.identify(Z)||v2.isScalar(Z)&&(!Z.type||Z.type===o3.Scalar.PLAIN)&&VZ.identify(Z.value))&&$?.doc.schema.tags.some((X)=>X.tag===VZ.tag&&X.default);function t3($,Z,X){if(X=$&&v2.isAlias(X)?X.resolve($.doc):X,v2.isSeq(X))for(let Y of X.items)I9($,Z,Y);else if(Array.isArray(X))for(let Y of X)I9($,Z,Y);else I9($,Z,X)}function I9($,Z,X){let Y=$&&v2.isAlias(X)?X.resolve($.doc):X;if(!v2.isMap(Y))throw Error("Merge sources must be maps or map aliases");let G=Y.toJSON(null,$,Map);for(let[z,J]of G)if(Z instanceof Map){if(!Z.has(z))Z.set(z,J)}else if(Z instanceof Set)Z.add(z);else if(!Object.prototype.hasOwnProperty.call(Z,z))Object.defineProperty(Z,z,{value:J,writable:!0,enumerable:!0,configurable:!0});return Z}YV.addMergeToJSMap=t3;YV.isMergeKey=XV;YV.merge=VZ});var x9=C((KV)=>{var QV=C9(),e3=HZ(),WV=f2(),$7=m(),j9=H$();function VV($,Z,{key:X,value:Y}){if($7.isNode(X)&&X.addToJSMap)X.addToJSMap($,Z,Y);else if(e3.isMergeKey($,X))e3.addMergeToJSMap($,Z,Y);else{let G=j9.toJS(X,"",$);if(Z instanceof Map)Z.set(G,j9.toJS(Y,G,$));else if(Z instanceof Set)Z.add(G);else{let z=HV(X,G,$),J=j9.toJS(Y,z,$);if(z in Z)Object.defineProperty(Z,z,{value:J,writable:!0,enumerable:!0,configurable:!0});else Z[z]=J}}return Z}function HV($,Z,X){if(Z===null)return"";if(typeof Z!=="object")return String(Z);if($7.isNode($)&&X?.doc){let Y=WV.createStringifyContext(X.doc,{});Y.anchors=new Set;for(let z of X.anchors.keys())Y.anchors.add(z.anchor);Y.inFlow=!0,Y.inStringifyKey=!0;let G=$.toString(Y);if(!X.mapKeyWarned){let z=JSON.stringify(G);if(z.length>40)z=z.substring(0,36)+'..."';QV.warn(X.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${z}. Set mapAsMap: true to use object keys.`),X.mapKeyWarned=!0}return G}return JSON.stringify(Z)}KV.addPairToJSMap=VV});var B$=C((FV)=>{var Z7=j2(),BV=r3(),qV=x9(),KZ=m();function TV($,Z,X){let Y=Z7.createNode($,void 0,X),G=Z7.createNode(Z,void 0,X);return new UZ(Y,G)}class UZ{constructor($,Z=null){Object.defineProperty(this,KZ.NODE_TYPE,{value:KZ.PAIR}),this.key=$,this.value=Z}clone($){let{key:Z,value:X}=this;if(KZ.isNode(Z))Z=Z.clone($);if(KZ.isNode(X))X=X.clone($);return new UZ(Z,X)}toJSON($,Z){let X=Z?.mapAsMap?new Map:{};return qV.addPairToJSMap(Z,X,this)}toString($,Z,X){return $?.doc?BV.stringifyPair(this,$,Z,X):JSON.stringify(this)}}FV.Pair=UZ;FV.createPair=TV});var k9=C((_V)=>{var h$=m(),X7=f2(),BZ=x2();function wV($,Z,X){return(Z.inFlow??$.flow?NV:OV)($,Z,X)}function OV({comment:$,items:Z},X,{blockItemPrefix:Y,flowChars:G,itemIndent:z,onChompKeep:J,onComment:Q}){let{indent:W,options:{commentString:V}}=X,K=Object.assign({},X,{indent:z,type:null}),H=!1,U=[];for(let T=0;T<Z.length;++T){let F=Z[T],M=null;if(h$.isNode(F)){if(!H&&F.spaceBefore)U.push("");if(qZ(X,U,F.commentBefore,H),F.comment)M=F.comment}else if(h$.isPair(F)){let N=h$.isNode(F.key)?F.key:null;if(N){if(!H&&N.spaceBefore)U.push("");qZ(X,U,N.commentBefore,H)}}H=!1;let O=X7.stringify(F,K,()=>M=null,()=>H=!0);if(M)O+=BZ.lineComment(O,z,V(M));if(H&&M)H=!1;U.push(Y+O)}let B;if(U.length===0)B=G.start+G.end;else{B=U[0];for(let T=1;T<U.length;++T){let F=U[T];B+=F?`
|
|
72
|
+
${W}${F}`:`
|
|
73
|
+
`}}if($){if(B+=`
|
|
74
|
+
`+BZ.indentComment(V($),W),Q)Q()}else if(H&&J)J();return B}function NV({items:$},Z,{flowChars:X,itemIndent:Y}){let{indent:G,indentStep:z,flowCollectionPadding:J,options:{commentString:Q}}=Z;Y+=z;let W=Object.assign({},Z,{indent:Y,inFlow:!0,type:null}),V=!1,K=0,H=[];for(let T=0;T<$.length;++T){let F=$[T],M=null;if(h$.isNode(F)){if(F.spaceBefore)H.push("");if(qZ(Z,H,F.commentBefore,!1),F.comment)M=F.comment}else if(h$.isPair(F)){let N=h$.isNode(F.key)?F.key:null;if(N){if(N.spaceBefore)H.push("");if(qZ(Z,H,N.commentBefore,!1),N.comment)V=!0}let _=h$.isNode(F.value)?F.value:null;if(_){if(_.comment)M=_.comment;if(_.commentBefore)V=!0}else if(F.value==null&&N?.comment)M=N.comment}if(M)V=!0;let O=X7.stringify(F,W,()=>M=null);if(T<$.length-1)O+=",";if(M)O+=BZ.lineComment(O,Y,Q(M));if(!V&&(H.length>K||O.includes(`
|
|
75
|
+
`)))V=!0;H.push(O),K=H.length}let{start:U,end:B}=X;if(H.length===0)return U+B;else{if(!V){let T=H.reduce((F,M)=>F+M.length+2,2);V=Z.options.lineWidth>0&&T>Z.options.lineWidth}if(V){let T=U;for(let F of H)T+=F?`
|
|
76
|
+
${z}${G}${F}`:`
|
|
77
|
+
`;return`${T}
|
|
78
|
+
${G}${B}`}else return`${U}${J}${H.join(" ")}${J}${B}`}}function qZ({indent:$,options:{commentString:Z}},X,Y,G){if(Y&&G)Y=Y.replace(/^\n+/,"");if(Y){let z=BZ.indentComment(Z(Y),$);X.push(z.trimStart())}}_V.stringifyCollection=wV});var T$=C((SV)=>{var DV=k9(),EV=x9(),RV=GZ(),q$=m(),TZ=B$(),AV=t();function g2($,Z){let X=q$.isScalar(Z)?Z.value:Z;for(let Y of $)if(q$.isPair(Y)){if(Y.key===Z||Y.key===X)return Y;if(q$.isScalar(Y.key)&&Y.key.value===X)return Y}return}class Y7 extends RV.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor($){super(q$.MAP,$);this.items=[]}static from($,Z,X){let{keepUndefined:Y,replacer:G}=X,z=new this($),J=(Q,W)=>{if(typeof G==="function")W=G.call(Z,Q,W);else if(Array.isArray(G)&&!G.includes(Q))return;if(W!==void 0||Y)z.items.push(TZ.createPair(Q,W,X))};if(Z instanceof Map)for(let[Q,W]of Z)J(Q,W);else if(Z&&typeof Z==="object")for(let Q of Object.keys(Z))J(Q,Z[Q]);if(typeof $.sortMapEntries==="function")z.items.sort($.sortMapEntries);return z}add($,Z){let X;if(q$.isPair($))X=$;else if(!$||typeof $!=="object"||!("key"in $))X=new TZ.Pair($,$?.value);else X=new TZ.Pair($.key,$.value);let Y=g2(this.items,X.key),G=this.schema?.sortMapEntries;if(Y){if(!Z)throw Error(`Key ${X.key} already set`);if(q$.isScalar(Y.value)&&AV.isScalarValue(X.value))Y.value.value=X.value;else Y.value=X.value}else if(G){let z=this.items.findIndex((J)=>G(X,J)<0);if(z===-1)this.items.push(X);else this.items.splice(z,0,X)}else this.items.push(X)}delete($){let Z=g2(this.items,$);if(!Z)return!1;return this.items.splice(this.items.indexOf(Z),1).length>0}get($,Z){let Y=g2(this.items,$)?.value;return(!Z&&q$.isScalar(Y)?Y.value:Y)??void 0}has($){return!!g2(this.items,$)}set($,Z){this.add(new TZ.Pair($,Z),!0)}toJSON($,Z,X){let Y=X?new X:Z?.mapAsMap?new Map:{};if(Z?.onCreate)Z.onCreate(Y);for(let G of this.items)EV.addPairToJSMap(Z,Y,G);return Y}toString($,Z,X){if(!$)return JSON.stringify(this);for(let Y of this.items)if(!q$.isPair(Y))throw Error(`Map items must all be pairs; found ${JSON.stringify(Y)} instead`);if(!$.allNullValues&&this.hasAllNullValues(!1))$=Object.assign({},$,{allNullValues:!0});return DV.stringifyCollection(this,$,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:$.indent||"",onChompKeep:X,onComment:Z})}}SV.YAMLMap=Y7;SV.findPair=g2});var N1=C((kV)=>{var jV=m(),G7=T$(),xV={collection:"map",default:!0,nodeClass:G7.YAMLMap,tag:"tag:yaml.org,2002:map",resolve($,Z){if(!jV.isMap($))Z("Expected a mapping for this tag");return $},createNode:($,Z,X)=>G7.YAMLMap.from($,Z,X)};kV.map=xV});var F$=C((uV)=>{var fV=j2(),yV=k9(),vV=GZ(),LZ=m(),gV=t(),hV=H$();class z7 extends vV.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor($){super(LZ.SEQ,$);this.items=[]}add($){this.items.push($)}delete($){let Z=FZ($);if(typeof Z!=="number")return!1;return this.items.splice(Z,1).length>0}get($,Z){let X=FZ($);if(typeof X!=="number")return;let Y=this.items[X];return!Z&&LZ.isScalar(Y)?Y.value:Y}has($){let Z=FZ($);return typeof Z==="number"&&Z<this.items.length}set($,Z){let X=FZ($);if(typeof X!=="number")throw Error(`Expected a valid index, not ${$}.`);let Y=this.items[X];if(LZ.isScalar(Y)&&gV.isScalarValue(Z))Y.value=Z;else this.items[X]=Z}toJSON($,Z){let X=[];if(Z?.onCreate)Z.onCreate(X);let Y=0;for(let G of this.items)X.push(hV.toJS(G,String(Y++),Z));return X}toString($,Z,X){if(!$)return JSON.stringify(this);return yV.stringifyCollection(this,$,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:($.indent||"")+" ",onChompKeep:X,onComment:Z})}static from($,Z,X){let{replacer:Y}=X,G=new this($);if(Z&&Symbol.iterator in Object(Z)){let z=0;for(let J of Z){if(typeof Y==="function"){let Q=Z instanceof Set?J:String(z++);J=Y.call(Z,Q,J)}G.items.push(fV.createNode(J,void 0,X))}}return G}}function FZ($){let Z=LZ.isScalar($)?$.value:$;if(Z&&typeof Z==="string")Z=Number(Z);return typeof Z==="number"&&Number.isInteger(Z)&&Z>=0?Z:null}uV.YAMLSeq=z7});var _1=C((lV)=>{var dV=m(),J7=F$(),cV={collection:"seq",default:!0,nodeClass:J7.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve($,Z){if(!dV.isSeq($))Z("Expected a sequence for this tag");return $},createNode:($,Z,X)=>J7.YAMLSeq.from($,Z,X)};lV.seq=cV});var h2=C((nV)=>{var iV=b2(),aV={identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify($,Z,X,Y){return Z=Object.assign({actualString:!0},Z),iV.stringifyString($,Z,X,Y)}};nV.string=aV});var MZ=C((sV)=>{var Q7=t(),W7={identify:($)=>$==null,createNode:()=>new Q7.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Q7.Scalar(null),stringify:({source:$},Z)=>typeof $==="string"&&W7.test.test($)?$:Z.options.nullStr};sV.nullTag=W7});var b9=C((eV)=>{var tV=t(),V7={identify:($)=>typeof $==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:($)=>new tV.Scalar($[0]==="t"||$[0]==="T"),stringify({source:$,value:Z},X){if($&&V7.test.test($)){let Y=$[0]==="t"||$[0]==="T";if(Z===Y)return $}return Z?X.options.trueStr:X.options.falseStr}};eV.boolTag=V7});var P1=C((XH)=>{function ZH({format:$,minFractionDigits:Z,tag:X,value:Y}){if(typeof Y==="bigint")return String(Y);let G=typeof Y==="number"?Y:Number(Y);if(!isFinite(G))return isNaN(G)?".nan":G<0?"-.inf":".inf";let z=Object.is(Y,-0)?"-0":JSON.stringify(Y);if(!$&&Z&&(!X||X==="tag:yaml.org,2002:float")&&/^\d/.test(z)){let J=z.indexOf(".");if(J<0)J=z.length,z+=".";let Q=Z-(z.length-J-1);while(Q-- >0)z+="0"}return z}XH.stringifyNumber=ZH});var y9=C((WH)=>{var GH=t(),f9=P1(),zH={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:($)=>$.slice(-3).toLowerCase()==="nan"?NaN:$[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:f9.stringifyNumber},JH={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:($)=>parseFloat($),stringify($){let Z=Number($.value);return isFinite(Z)?Z.toExponential():f9.stringifyNumber($)}},QH={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve($){let Z=new GH.Scalar(parseFloat($)),X=$.indexOf(".");if(X!==-1&&$[$.length-1]==="0")Z.minFractionDigits=$.length-X-1;return Z},stringify:f9.stringifyNumber};WH.float=QH;WH.floatExp=JH;WH.floatNaN=zH});var g9=C((TH)=>{var H7=P1(),wZ=($)=>typeof $==="bigint"||Number.isInteger($),v9=($,Z,X,{intAsBigInt:Y})=>Y?BigInt($):parseInt($.substring(Z),X);function K7($,Z,X){let{value:Y}=$;if(wZ(Y)&&Y>=0)return X+Y.toString(Z);return H7.stringifyNumber($)}var UH={identify:($)=>wZ($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:($,Z,X)=>v9($,2,8,X),stringify:($)=>K7($,8,"0o")},BH={identify:wZ,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:($,Z,X)=>v9($,0,10,X),stringify:H7.stringifyNumber},qH={identify:($)=>wZ($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:($,Z,X)=>v9($,2,16,X),stringify:($)=>K7($,16,"0x")};TH.int=BH;TH.intHex=qH;TH.intOct=UH});var U7=C((EH)=>{var wH=N1(),OH=MZ(),NH=_1(),_H=h2(),PH=b9(),h9=y9(),u9=g9(),DH=[wH.map,NH.seq,_H.string,OH.nullTag,PH.boolTag,u9.intOct,u9.int,u9.intHex,h9.floatNaN,h9.floatExp,h9.float];EH.schema=DH});var q7=C((kH)=>{var AH=t(),SH=N1(),CH=_1();function B7($){return typeof $==="bigint"||Number.isInteger($)}var OZ=({value:$})=>JSON.stringify($),IH=[{identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify:OZ},{identify:($)=>$==null,createNode:()=>new AH.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:OZ},{identify:($)=>typeof $==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:($)=>$==="true",stringify:OZ},{identify:B7,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:($,Z,{intAsBigInt:X})=>X?BigInt($):parseInt($,10),stringify:({value:$})=>B7($)?$.toString():JSON.stringify($)},{identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:($)=>parseFloat($),stringify:OZ}],jH={default:!0,tag:"",test:/^/,resolve($,Z){return Z(`Unresolved plain scalar ${JSON.stringify($)}`),$}},xH=[SH.map,CH.seq].concat(IH,jH);kH.schema=xH});var d9=C((vH)=>{var u2=n0("buffer"),m9=t(),fH=b2(),yH={identify:($)=>$ instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve($,Z){if(typeof u2.Buffer==="function")return u2.Buffer.from($,"base64");else if(typeof atob==="function"){let X=atob($.replace(/[\n\r]/g,"")),Y=new Uint8Array(X.length);for(let G=0;G<X.length;++G)Y[G]=X.charCodeAt(G);return Y}else return Z("This environment does not support reading binary tags; either Buffer or atob is required"),$},stringify({comment:$,type:Z,value:X},Y,G,z){if(!X)return"";let J=X,Q;if(typeof u2.Buffer==="function")Q=J instanceof u2.Buffer?J.toString("base64"):u2.Buffer.from(J.buffer).toString("base64");else if(typeof btoa==="function"){let W="";for(let V=0;V<J.length;++V)W+=String.fromCharCode(J[V]);Q=btoa(W)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(Z??(Z=m9.Scalar.BLOCK_LITERAL),Z!==m9.Scalar.QUOTE_DOUBLE){let W=Math.max(Y.options.lineWidth-Y.indent.length,Y.options.minContentWidth),V=Math.ceil(Q.length/W),K=Array(V);for(let H=0,U=0;H<V;++H,U+=W)K[H]=Q.substr(U,W);Q=K.join(Z===m9.Scalar.BLOCK_LITERAL?`
|
|
79
|
+
`:" ")}return fH.stringifyString({comment:$,type:Z,value:Q},Y,G,z)}};vH.binary=yH});var _Z=C((dH)=>{var NZ=m(),c9=B$(),hH=t(),uH=F$();function T7($,Z){if(NZ.isSeq($))for(let X=0;X<$.items.length;++X){let Y=$.items[X];if(NZ.isPair(Y))continue;else if(NZ.isMap(Y)){if(Y.items.length>1)Z("Each pair must have its own sequence indicator");let G=Y.items[0]||new c9.Pair(new hH.Scalar(null));if(Y.commentBefore)G.key.commentBefore=G.key.commentBefore?`${Y.commentBefore}
|
|
80
80
|
${G.key.commentBefore}`:Y.commentBefore;if(Y.comment){let z=G.value??G.key;z.comment=z.comment?`${Y.comment}
|
|
81
|
-
${z.comment}`:Y.comment}Y=G}$.items[X]=_6.isPair(Y)?Y:new cX.Pair(Y)}else Z("Expected a sequence for this tag");return $}function T7($,Z,X){let{replacer:Y}=X,G=new gH.YAMLSeq($);G.tag="tag:yaml.org,2002:pairs";let z=0;if(Z&&Symbol.iterator in Object(Z))for(let J of Z){if(typeof Y==="function")J=Y.call(Z,String(z++),J);let Q,W;if(Array.isArray(J))if(J.length===2)Q=J[0],W=J[1];else throw TypeError(`Expected [key, value] tuple: ${J}`);else if(J&&J instanceof Object){let V=Object.keys(J);if(V.length===1)Q=V[0],W=J[Q];else throw TypeError(`Expected tuple with one key, not ${V.length} keys`)}else Q=J;G.items.push(cX.createPair(Q,W,X))}return G}var hH={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:q7,createNode:T7};uH.createPairs=T7;uH.pairs=hH;uH.resolvePairs=q7});var pX=C((iH)=>{var F7=m(),lX=K$(),l2=F$(),lH=L$(),L7=P6();class l$ extends lH.YAMLSeq{constructor(){super();this.add=l2.YAMLMap.prototype.add.bind(this),this.delete=l2.YAMLMap.prototype.delete.bind(this),this.get=l2.YAMLMap.prototype.get.bind(this),this.has=l2.YAMLMap.prototype.has.bind(this),this.set=l2.YAMLMap.prototype.set.bind(this),this.tag=l$.tag}toJSON($,Z){if(!Z)return super.toJSON($);let X=new Map;if(Z?.onCreate)Z.onCreate(X);for(let Y of this.items){let G,z;if(F7.isPair(Y))G=lX.toJS(Y.key,"",Z),z=lX.toJS(Y.value,G,Z);else G=lX.toJS(Y,"",Z);if(X.has(G))throw Error("Ordered maps must not include duplicate keys");X.set(G,z)}return X}static from($,Z,X){let Y=L7.createPairs($,Z,X),G=new this;return G.items=Y.items,G}}l$.tag="tag:yaml.org,2002:omap";var pH={collection:"seq",identify:($)=>$ instanceof Map,nodeClass:l$,default:!1,tag:"tag:yaml.org,2002:omap",resolve($,Z){let X=L7.resolvePairs($,Z),Y=[];for(let{key:G}of X.items)if(F7.isScalar(G))if(Y.includes(G.value))Z(`Ordered maps must not include duplicate keys: ${G.value}`);else Y.push(G.value);return Object.assign(new l$,X)},createNode:($,Z,X)=>l$.from($,Z,X)};iH.YAMLOMap=l$;iH.omap=pH});var _7=C((rH)=>{var w7=o();function M7({value:$,source:Z},X){if(Z&&($?O7:N7).test.test(Z))return Z;return $?X.options.trueStr:X.options.falseStr}var O7={identify:($)=>$===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new w7.Scalar(!0),stringify:M7},N7={identify:($)=>$===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new w7.Scalar(!1),stringify:M7};rH.falseTag=N7;rH.trueTag=O7});var P7=C((XK)=>{var tH=o(),iX=R1(),eH={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:($)=>$.slice(-3).toLowerCase()==="nan"?NaN:$[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:iX.stringifyNumber},$K={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:($)=>parseFloat($.replace(/_/g,"")),stringify($){let Z=Number($.value);return isFinite(Z)?Z.toExponential():iX.stringifyNumber($)}},ZK={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve($){let Z=new tH.Scalar(parseFloat($.replace(/_/g,""))),X=$.indexOf(".");if(X!==-1){let Y=$.substring(X+1).replace(/_/g,"");if(Y[Y.length-1]==="0")Z.minFractionDigits=Y.length}return Z},stringify:iX.stringifyNumber};XK.float=ZK;XK.floatExp=$K;XK.floatNaN=eH});var E7=C((HK)=>{var D7=R1(),p2=($)=>typeof $==="bigint"||Number.isInteger($);function D6($,Z,X,{intAsBigInt:Y}){let G=$[0];if(G==="-"||G==="+")Z+=1;if($=$.substring(Z).replace(/_/g,""),Y){switch(X){case 2:$=`0b${$}`;break;case 8:$=`0o${$}`;break;case 16:$=`0x${$}`;break}let J=BigInt($);return G==="-"?BigInt(-1)*J:J}let z=parseInt($,X);return G==="-"?-1*z:z}function aX($,Z,X){let{value:Y}=$;if(p2(Y)){let G=Y.toString(Z);return Y<0?"-"+X+G.substr(1):X+G}return D7.stringifyNumber($)}var JK={identify:p2,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:($,Z,X)=>D6($,2,2,X),stringify:($)=>aX($,2,"0b")},QK={identify:p2,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:($,Z,X)=>D6($,1,8,X),stringify:($)=>aX($,8,"0")},WK={identify:p2,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:($,Z,X)=>D6($,0,10,X),stringify:D7.stringifyNumber},VK={identify:p2,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:($,Z,X)=>D6($,2,16,X),stringify:($)=>aX($,16,"0x")};HK.int=WK;HK.intBin=JK;HK.intHex=VK;HK.intOct=QK});var nX=C((FK)=>{var A6=m(),E6=q$(),R6=F$();class p$ extends R6.YAMLMap{constructor($){super($);this.tag=p$.tag}add($){let Z;if(A6.isPair($))Z=$;else if($&&typeof $==="object"&&"key"in $&&"value"in $&&$.value===null)Z=new E6.Pair($.key,null);else Z=new E6.Pair($,null);if(!R6.findPair(this.items,Z.key))this.items.push(Z)}get($,Z){let X=R6.findPair(this.items,$);return!Z&&A6.isPair(X)?A6.isScalar(X.key)?X.key.value:X.key:X}set($,Z){if(typeof Z!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof Z}`);let X=R6.findPair(this.items,$);if(X&&!Z)this.items.splice(this.items.indexOf(X),1);else if(!X&&Z)this.items.push(new E6.Pair($))}toJSON($,Z){return super.toJSON($,Z,Set)}toString($,Z,X){if(!$)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},$,{allNullValues:!0}),Z,X);else throw Error("Set items must all have null values")}static from($,Z,X){let{replacer:Y}=X,G=new this($);if(Z&&Symbol.iterator in Object(Z))for(let z of Z){if(typeof Y==="function")z=Y.call(Z,z,z);G.items.push(E6.createPair(z,null,X))}return G}}p$.tag="tag:yaml.org,2002:set";var TK={collection:"map",identify:($)=>$ instanceof Set,nodeClass:p$,default:!1,tag:"tag:yaml.org,2002:set",createNode:($,Z,X)=>p$.from($,Z,X),resolve($,Z){if(A6.isMap($))if($.hasAllNullValues(!0))return Object.assign(new p$,$);else Z("Set items must all have null values");else Z("Expected a mapping for this tag");return $}};FK.YAMLSet=p$;FK.set=TK});var sX=C((_K)=>{var MK=R1();function rX($,Z){let X=$[0],Y=X==="-"||X==="+"?$.substring(1):$,G=(J)=>Z?BigInt(J):Number(J),z=Y.replace(/_/g,"").split(":").reduce((J,Q)=>J*G(60)+G(Q),G(0));return X==="-"?G(-1)*z:z}function R7($){let{value:Z}=$,X=(J)=>J;if(typeof Z==="bigint")X=(J)=>BigInt(J);else if(isNaN(Z)||!isFinite(Z))return MK.stringifyNumber($);let Y="";if(Z<0)Y="-",Z*=X(-1);let G=X(60),z=[Z%G];if(Z<60)z.unshift(0);else if(Z=(Z-z[0])/G,z.unshift(Z%G),Z>=60)Z=(Z-z[0])/G,z.unshift(Z);return Y+z.map((J)=>String(J).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var OK={identify:($)=>typeof $==="bigint"||Number.isInteger($),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:($,Z,{intAsBigInt:X})=>rX($,X),stringify:R7},NK={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:($)=>rX($,!1),stringify:R7},A7={identify:($)=>$ instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve($){let Z=$.match(A7.test);if(!Z)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,X,Y,G,z,J,Q]=Z.map(Number),W=Z[7]?Number((Z[7]+"00").substr(1,3)):0,V=Date.UTC(X,Y-1,G,z||0,J||0,Q||0,W),K=Z[8];if(K&&K!=="Z"){let H=rX(K,!1);if(Math.abs(H)<30)H*=60;V-=60000*H}return new Date(V)},stringify:({value:$})=>$?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};_K.floatTime=NK;_K.intTime=OK;_K.timestamp=A7});var C7=C((yK)=>{var RK=D1(),AK=M6(),SK=E1(),CK=d2(),IK=dX(),S7=_7(),oX=P7(),S6=E7(),jK=K6(),xK=pX(),kK=P6(),bK=nX(),tX=sX(),fK=[RK.map,SK.seq,CK.string,AK.nullTag,S7.trueTag,S7.falseTag,S6.intBin,S6.intOct,S6.int,S6.intHex,oX.floatNaN,oX.floatExp,oX.float,IK.binary,jK.merge,xK.omap,kK.pairs,bK.set,tX.intTime,tX.floatTime,tX.timestamp];yK.schema=fK});var h7=C((pK)=>{var k7=D1(),gK=M6(),b7=E1(),hK=d2(),uK=bX(),eX=yX(),$9=gX(),mK=K7(),dK=U7(),f7=dX(),i2=K6(),y7=pX(),v7=P6(),I7=C7(),g7=nX(),C6=sX(),j7=new Map([["core",mK.schema],["failsafe",[k7.map,b7.seq,hK.string]],["json",dK.schema],["yaml11",I7.schema],["yaml-1.1",I7.schema]]),x7={binary:f7.binary,bool:uK.boolTag,float:eX.float,floatExp:eX.floatExp,floatNaN:eX.floatNaN,floatTime:C6.floatTime,int:$9.int,intHex:$9.intHex,intOct:$9.intOct,intTime:C6.intTime,map:k7.map,merge:i2.merge,null:gK.nullTag,omap:y7.omap,pairs:v7.pairs,seq:b7.seq,set:g7.set,timestamp:C6.timestamp},cK={"tag:yaml.org,2002:binary":f7.binary,"tag:yaml.org,2002:merge":i2.merge,"tag:yaml.org,2002:omap":y7.omap,"tag:yaml.org,2002:pairs":v7.pairs,"tag:yaml.org,2002:set":g7.set,"tag:yaml.org,2002:timestamp":C6.timestamp};function lK($,Z,X){let Y=j7.get(Z);if(Y&&!$)return X&&!Y.includes(i2.merge)?Y.concat(i2.merge):Y.slice();let G=Y;if(!G)if(Array.isArray($))G=[];else{let z=Array.from(j7.keys()).filter((J)=>J!=="yaml11").map((J)=>JSON.stringify(J)).join(", ");throw Error(`Unknown schema "${Z}"; use one of ${z} or define customTags array`)}if(Array.isArray($))for(let z of $)G=G.concat(z);else if(typeof $==="function")G=$(G.slice());if(X)G=G.concat(i2.merge);return G.reduce((z,J)=>{let Q=typeof J==="string"?x7[J]:J;if(!Q){let W=JSON.stringify(J),V=Object.keys(x7).map((K)=>JSON.stringify(K)).join(", ");throw Error(`Unknown custom tag ${W}; use one of ${V}`)}if(!z.includes(Q))z.push(Q);return z},[])}pK.coreKnownTags=cK;pK.getTags=lK});var Y9=C((tK)=>{var Z9=m(),nK=D1(),rK=E1(),sK=d2(),I6=h7(),oK=($,Z)=>$.key<Z.key?-1:$.key>Z.key?1:0;class X9{constructor({compat:$,customTags:Z,merge:X,resolveKnownTags:Y,schema:G,sortMapEntries:z,toStringDefaults:J}){this.compat=Array.isArray($)?I6.getTags($,"compat"):$?I6.getTags(null,$):null,this.name=typeof G==="string"&&G||"core",this.knownTags=Y?I6.coreKnownTags:{},this.tags=I6.getTags(Z,this.name,X),this.toStringOptions=J??null,Object.defineProperty(this,Z9.MAP,{value:nK.map}),Object.defineProperty(this,Z9.SCALAR,{value:sK.string}),Object.defineProperty(this,Z9.SEQ,{value:rK.seq}),this.sortMapEntries=typeof z==="function"?z:z===!0?oK:null}clone(){let $=Object.create(X9.prototype,Object.getOwnPropertyDescriptors(this));return $.tags=this.tags.slice(),$}}tK.Schema=X9});var u7=C((XB)=>{var $B=m(),G9=g2(),a2=f2();function ZB($,Z){let X=[],Y=Z.directives===!0;if(Z.directives!==!1&&$.directives){let W=$.directives.toString($);if(W)X.push(W),Y=!0;else if($.directives.docStart)Y=!0}if(Y)X.push("---");let G=G9.createStringifyContext($,Z),{commentString:z}=G.options;if($.commentBefore){if(X.length!==1)X.unshift("");let W=z($.commentBefore);X.unshift(a2.indentComment(W,""))}let J=!1,Q=null;if($.contents){if($B.isNode($.contents)){if($.contents.spaceBefore&&Y)X.push("");if($.contents.commentBefore){let K=z($.contents.commentBefore);X.push(a2.indentComment(K,""))}G.forceBlockIndent=!!$.comment,Q=$.contents.comment}let W=Q?void 0:()=>J=!0,V=G9.stringify($.contents,G,()=>Q=null,W);if(Q)V+=a2.lineComment(V,"",z(Q));if((V[0]==="|"||V[0]===">")&&X[X.length-1]==="---")X[X.length-1]=`--- ${V}`;else X.push(V)}else X.push(G9.stringify($.contents,G));if($.directives?.docEnd)if($.comment){let W=z($.comment);if(W.includes(`
|
|
82
|
-
`))X.push("..."),X.push(
|
|
81
|
+
${z.comment}`:Y.comment}Y=G}$.items[X]=NZ.isPair(Y)?Y:new c9.Pair(Y)}else Z("Expected a sequence for this tag");return $}function F7($,Z,X){let{replacer:Y}=X,G=new uH.YAMLSeq($);G.tag="tag:yaml.org,2002:pairs";let z=0;if(Z&&Symbol.iterator in Object(Z))for(let J of Z){if(typeof Y==="function")J=Y.call(Z,String(z++),J);let Q,W;if(Array.isArray(J))if(J.length===2)Q=J[0],W=J[1];else throw TypeError(`Expected [key, value] tuple: ${J}`);else if(J&&J instanceof Object){let V=Object.keys(J);if(V.length===1)Q=V[0],W=J[Q];else throw TypeError(`Expected tuple with one key, not ${V.length} keys`)}else Q=J;G.items.push(c9.createPair(Q,W,X))}return G}var mH={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:T7,createNode:F7};dH.createPairs=F7;dH.pairs=mH;dH.resolvePairs=T7});var p9=C((nH)=>{var L7=m(),l9=H$(),m2=T$(),iH=F$(),M7=_Z();class u$ extends iH.YAMLSeq{constructor(){super();this.add=m2.YAMLMap.prototype.add.bind(this),this.delete=m2.YAMLMap.prototype.delete.bind(this),this.get=m2.YAMLMap.prototype.get.bind(this),this.has=m2.YAMLMap.prototype.has.bind(this),this.set=m2.YAMLMap.prototype.set.bind(this),this.tag=u$.tag}toJSON($,Z){if(!Z)return super.toJSON($);let X=new Map;if(Z?.onCreate)Z.onCreate(X);for(let Y of this.items){let G,z;if(L7.isPair(Y))G=l9.toJS(Y.key,"",Z),z=l9.toJS(Y.value,G,Z);else G=l9.toJS(Y,"",Z);if(X.has(G))throw Error("Ordered maps must not include duplicate keys");X.set(G,z)}return X}static from($,Z,X){let Y=M7.createPairs($,Z,X),G=new this;return G.items=Y.items,G}}u$.tag="tag:yaml.org,2002:omap";var aH={collection:"seq",identify:($)=>$ instanceof Map,nodeClass:u$,default:!1,tag:"tag:yaml.org,2002:omap",resolve($,Z){let X=M7.resolvePairs($,Z),Y=[];for(let{key:G}of X.items)if(L7.isScalar(G))if(Y.includes(G.value))Z(`Ordered maps must not include duplicate keys: ${G.value}`);else Y.push(G.value);return Object.assign(new u$,X)},createNode:($,Z,X)=>u$.from($,Z,X)};nH.YAMLOMap=u$;nH.omap=aH});var P7=C((oH)=>{var w7=t();function O7({value:$,source:Z},X){if(Z&&($?N7:_7).test.test(Z))return Z;return $?X.options.trueStr:X.options.falseStr}var N7={identify:($)=>$===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new w7.Scalar(!0),stringify:O7},_7={identify:($)=>$===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new w7.Scalar(!1),stringify:O7};oH.falseTag=_7;oH.trueTag=N7});var D7=C((GK)=>{var $K=t(),i9=P1(),ZK={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:($)=>$.slice(-3).toLowerCase()==="nan"?NaN:$[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:i9.stringifyNumber},XK={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:($)=>parseFloat($.replace(/_/g,"")),stringify($){let Z=Number($.value);return isFinite(Z)?Z.toExponential():i9.stringifyNumber($)}},YK={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve($){let Z=new $K.Scalar(parseFloat($.replace(/_/g,""))),X=$.indexOf(".");if(X!==-1){let Y=$.substring(X+1).replace(/_/g,"");if(Y[Y.length-1]==="0")Z.minFractionDigits=Y.length}return Z},stringify:i9.stringifyNumber};GK.float=YK;GK.floatExp=XK;GK.floatNaN=ZK});var R7=C((UK)=>{var E7=P1(),d2=($)=>typeof $==="bigint"||Number.isInteger($);function PZ($,Z,X,{intAsBigInt:Y}){let G=$[0];if(G==="-"||G==="+")Z+=1;if($=$.substring(Z).replace(/_/g,""),Y){switch(X){case 2:$=`0b${$}`;break;case 8:$=`0o${$}`;break;case 16:$=`0x${$}`;break}let J=BigInt($);return G==="-"?BigInt(-1)*J:J}let z=parseInt($,X);return G==="-"?-1*z:z}function a9($,Z,X){let{value:Y}=$;if(d2(Y)){let G=Y.toString(Z);return Y<0?"-"+X+G.substr(1):X+G}return E7.stringifyNumber($)}var WK={identify:d2,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:($,Z,X)=>PZ($,2,2,X),stringify:($)=>a9($,2,"0b")},VK={identify:d2,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:($,Z,X)=>PZ($,1,8,X),stringify:($)=>a9($,8,"0")},HK={identify:d2,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:($,Z,X)=>PZ($,0,10,X),stringify:E7.stringifyNumber},KK={identify:d2,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:($,Z,X)=>PZ($,2,16,X),stringify:($)=>a9($,16,"0x")};UK.int=HK;UK.intBin=WK;UK.intHex=KK;UK.intOct=VK});var n9=C((MK)=>{var RZ=m(),DZ=B$(),EZ=T$();class m$ extends EZ.YAMLMap{constructor($){super($);this.tag=m$.tag}add($){let Z;if(RZ.isPair($))Z=$;else if($&&typeof $==="object"&&"key"in $&&"value"in $&&$.value===null)Z=new DZ.Pair($.key,null);else Z=new DZ.Pair($,null);if(!EZ.findPair(this.items,Z.key))this.items.push(Z)}get($,Z){let X=EZ.findPair(this.items,$);return!Z&&RZ.isPair(X)?RZ.isScalar(X.key)?X.key.value:X.key:X}set($,Z){if(typeof Z!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof Z}`);let X=EZ.findPair(this.items,$);if(X&&!Z)this.items.splice(this.items.indexOf(X),1);else if(!X&&Z)this.items.push(new DZ.Pair($))}toJSON($,Z){return super.toJSON($,Z,Set)}toString($,Z,X){if(!$)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},$,{allNullValues:!0}),Z,X);else throw Error("Set items must all have null values")}static from($,Z,X){let{replacer:Y}=X,G=new this($);if(Z&&Symbol.iterator in Object(Z))for(let z of Z){if(typeof Y==="function")z=Y.call(Z,z,z);G.items.push(DZ.createPair(z,null,X))}return G}}m$.tag="tag:yaml.org,2002:set";var LK={collection:"map",identify:($)=>$ instanceof Set,nodeClass:m$,default:!1,tag:"tag:yaml.org,2002:set",createNode:($,Z,X)=>m$.from($,Z,X),resolve($,Z){if(RZ.isMap($))if($.hasAllNullValues(!0))return Object.assign(new m$,$);else Z("Set items must all have null values");else Z("Expected a mapping for this tag");return $}};MK.YAMLSet=m$;MK.set=LK});var s9=C((DK)=>{var NK=P1();function r9($,Z){let X=$[0],Y=X==="-"||X==="+"?$.substring(1):$,G=(J)=>Z?BigInt(J):Number(J),z=Y.replace(/_/g,"").split(":").reduce((J,Q)=>J*G(60)+G(Q),G(0));return X==="-"?G(-1)*z:z}function A7($){let{value:Z}=$,X=(J)=>J;if(typeof Z==="bigint")X=(J)=>BigInt(J);else if(isNaN(Z)||!isFinite(Z))return NK.stringifyNumber($);let Y="";if(Z<0)Y="-",Z*=X(-1);let G=X(60),z=[Z%G];if(Z<60)z.unshift(0);else if(Z=(Z-z[0])/G,z.unshift(Z%G),Z>=60)Z=(Z-z[0])/G,z.unshift(Z);return Y+z.map((J)=>String(J).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var _K={identify:($)=>typeof $==="bigint"||Number.isInteger($),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:($,Z,{intAsBigInt:X})=>r9($,X),stringify:A7},PK={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:($)=>r9($,!1),stringify:A7},S7={identify:($)=>$ instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve($){let Z=$.match(S7.test);if(!Z)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,X,Y,G,z,J,Q]=Z.map(Number),W=Z[7]?Number((Z[7]+"00").substr(1,3)):0,V=Date.UTC(X,Y-1,G,z||0,J||0,Q||0,W),K=Z[8];if(K&&K!=="Z"){let H=r9(K,!1);if(Math.abs(H)<30)H*=60;V-=60000*H}return new Date(V)},stringify:({value:$})=>$?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};DK.floatTime=PK;DK.intTime=_K;DK.timestamp=S7});var I7=C((gK)=>{var SK=N1(),CK=MZ(),IK=_1(),jK=h2(),xK=d9(),C7=P7(),o9=D7(),AZ=R7(),kK=HZ(),bK=p9(),fK=_Z(),yK=n9(),t9=s9(),vK=[SK.map,IK.seq,jK.string,CK.nullTag,C7.trueTag,C7.falseTag,AZ.intBin,AZ.intOct,AZ.int,AZ.intHex,o9.floatNaN,o9.floatExp,o9.float,xK.binary,kK.merge,bK.omap,fK.pairs,yK.set,t9.intTime,t9.floatTime,t9.timestamp];gK.schema=vK});var u7=C((aK)=>{var b7=N1(),uK=MZ(),f7=_1(),mK=h2(),dK=b9(),e9=y9(),$X=g9(),cK=U7(),lK=q7(),y7=d9(),c2=HZ(),v7=p9(),g7=_Z(),j7=I7(),h7=n9(),SZ=s9(),x7=new Map([["core",cK.schema],["failsafe",[b7.map,f7.seq,mK.string]],["json",lK.schema],["yaml11",j7.schema],["yaml-1.1",j7.schema]]),k7={binary:y7.binary,bool:dK.boolTag,float:e9.float,floatExp:e9.floatExp,floatNaN:e9.floatNaN,floatTime:SZ.floatTime,int:$X.int,intHex:$X.intHex,intOct:$X.intOct,intTime:SZ.intTime,map:b7.map,merge:c2.merge,null:uK.nullTag,omap:v7.omap,pairs:g7.pairs,seq:f7.seq,set:h7.set,timestamp:SZ.timestamp},pK={"tag:yaml.org,2002:binary":y7.binary,"tag:yaml.org,2002:merge":c2.merge,"tag:yaml.org,2002:omap":v7.omap,"tag:yaml.org,2002:pairs":g7.pairs,"tag:yaml.org,2002:set":h7.set,"tag:yaml.org,2002:timestamp":SZ.timestamp};function iK($,Z,X){let Y=x7.get(Z);if(Y&&!$)return X&&!Y.includes(c2.merge)?Y.concat(c2.merge):Y.slice();let G=Y;if(!G)if(Array.isArray($))G=[];else{let z=Array.from(x7.keys()).filter((J)=>J!=="yaml11").map((J)=>JSON.stringify(J)).join(", ");throw Error(`Unknown schema "${Z}"; use one of ${z} or define customTags array`)}if(Array.isArray($))for(let z of $)G=G.concat(z);else if(typeof $==="function")G=$(G.slice());if(X)G=G.concat(c2.merge);return G.reduce((z,J)=>{let Q=typeof J==="string"?k7[J]:J;if(!Q){let W=JSON.stringify(J),V=Object.keys(k7).map((K)=>JSON.stringify(K)).join(", ");throw Error(`Unknown custom tag ${W}; use one of ${V}`)}if(!z.includes(Q))z.push(Q);return z},[])}aK.coreKnownTags=pK;aK.getTags=iK});var YX=C(($U)=>{var ZX=m(),sK=N1(),oK=_1(),tK=h2(),CZ=u7(),eK=($,Z)=>$.key<Z.key?-1:$.key>Z.key?1:0;class XX{constructor({compat:$,customTags:Z,merge:X,resolveKnownTags:Y,schema:G,sortMapEntries:z,toStringDefaults:J}){this.compat=Array.isArray($)?CZ.getTags($,"compat"):$?CZ.getTags(null,$):null,this.name=typeof G==="string"&&G||"core",this.knownTags=Y?CZ.coreKnownTags:{},this.tags=CZ.getTags(Z,this.name,X),this.toStringOptions=J??null,Object.defineProperty(this,ZX.MAP,{value:sK.map}),Object.defineProperty(this,ZX.SCALAR,{value:tK.string}),Object.defineProperty(this,ZX.SEQ,{value:oK.seq}),this.sortMapEntries=typeof z==="function"?z:z===!0?eK:null}clone(){let $=Object.create(XX.prototype,Object.getOwnPropertyDescriptors(this));return $.tags=this.tags.slice(),$}}$U.Schema=XX});var m7=C((GU)=>{var XU=m(),GX=f2(),l2=x2();function YU($,Z){let X=[],Y=Z.directives===!0;if(Z.directives!==!1&&$.directives){let W=$.directives.toString($);if(W)X.push(W),Y=!0;else if($.directives.docStart)Y=!0}if(Y)X.push("---");let G=GX.createStringifyContext($,Z),{commentString:z}=G.options;if($.commentBefore){if(X.length!==1)X.unshift("");let W=z($.commentBefore);X.unshift(l2.indentComment(W,""))}let J=!1,Q=null;if($.contents){if(XU.isNode($.contents)){if($.contents.spaceBefore&&Y)X.push("");if($.contents.commentBefore){let K=z($.contents.commentBefore);X.push(l2.indentComment(K,""))}G.forceBlockIndent=!!$.comment,Q=$.contents.comment}let W=Q?void 0:()=>J=!0,V=GX.stringify($.contents,G,()=>Q=null,W);if(Q)V+=l2.lineComment(V,"",z(Q));if((V[0]==="|"||V[0]===">")&&X[X.length-1]==="---")X[X.length-1]=`--- ${V}`;else X.push(V)}else X.push(GX.stringify($.contents,G));if($.directives?.docEnd)if($.comment){let W=z($.comment);if(W.includes(`
|
|
82
|
+
`))X.push("..."),X.push(l2.indentComment(W,""));else X.push(`... ${W}`)}else X.push("...");else{let W=$.comment;if(W&&J)W=W.replace(/^\n+/,"");if(W){if((!J||Q)&&X[X.length-1]!=="")X.push("");X.push(l2.indentComment(z(W),""))}}return X.join(`
|
|
83
83
|
`)+`
|
|
84
|
-
`}
|
|
84
|
+
`}GU.stringifyDocument=YU});var p2=C((BU)=>{var JU=I2(),D1=GZ(),S0=m(),QU=B$(),WU=H$(),VU=YX(),HU=m7(),zX=ZZ(),KU=D9(),UU=j2(),JX=P9();class QX{constructor($,Z,X){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,S0.NODE_TYPE,{value:S0.DOC});let Y=null;if(typeof Z==="function"||Array.isArray(Z))Y=Z;else if(X===void 0&&Z)X=Z,Z=void 0;let G=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},X);this.options=G;let{version:z}=G;if(X?._directives){if(this.directives=X._directives.atDocument(),this.directives.yaml.explicit)z=this.directives.yaml.version}else this.directives=new JX.Directives({version:z});this.setSchema(z,X),this.contents=$===void 0?null:this.createNode($,Y,X)}clone(){let $=Object.create(QX.prototype,{[S0.NODE_TYPE]:{value:S0.DOC}});if($.commentBefore=this.commentBefore,$.comment=this.comment,$.errors=this.errors.slice(),$.warnings=this.warnings.slice(),$.options=Object.assign({},this.options),this.directives)$.directives=this.directives.clone();if($.schema=this.schema.clone(),$.contents=S0.isNode(this.contents)?this.contents.clone($.schema):this.contents,this.range)$.range=this.range.slice();return $}add($){if(E1(this.contents))this.contents.add($)}addIn($,Z){if(E1(this.contents))this.contents.addIn($,Z)}createAlias($,Z){if(!$.anchor){let X=zX.anchorNames(this);$.anchor=!Z||X.has(Z)?zX.findNewAnchor(Z||"a",X):Z}return new JU.Alias($.anchor)}createNode($,Z,X){let Y=void 0;if(typeof Z==="function")$=Z.call({"":$},"",$),Y=Z;else if(Array.isArray(Z)){let F=(O)=>typeof O==="number"||O instanceof String||O instanceof Number,M=Z.filter(F).map(String);if(M.length>0)Z=Z.concat(M);Y=Z}else if(X===void 0&&Z)X=Z,Z=void 0;let{aliasDuplicateObjects:G,anchorPrefix:z,flow:J,keepUndefined:Q,onTagObj:W,tag:V}=X??{},{onAnchor:K,setAnchors:H,sourceObjects:U}=zX.createNodeAnchors(this,z||"a"),B={aliasDuplicateObjects:G??!0,keepUndefined:Q??!1,onAnchor:K,onTagObj:W,replacer:Y,schema:this.schema,sourceObjects:U},T=UU.createNode($,V,B);if(J&&S0.isCollection(T))T.flow=!0;return H(),T}createPair($,Z,X={}){let Y=this.createNode($,null,X),G=this.createNode(Z,null,X);return new QU.Pair(Y,G)}delete($){return E1(this.contents)?this.contents.delete($):!1}deleteIn($){if(D1.isEmptyPath($)){if(this.contents==null)return!1;return this.contents=null,!0}return E1(this.contents)?this.contents.deleteIn($):!1}get($,Z){return S0.isCollection(this.contents)?this.contents.get($,Z):void 0}getIn($,Z){if(D1.isEmptyPath($))return!Z&&S0.isScalar(this.contents)?this.contents.value:this.contents;return S0.isCollection(this.contents)?this.contents.getIn($,Z):void 0}has($){return S0.isCollection(this.contents)?this.contents.has($):!1}hasIn($){if(D1.isEmptyPath($))return this.contents!==void 0;return S0.isCollection(this.contents)?this.contents.hasIn($):!1}set($,Z){if(this.contents==null)this.contents=D1.collectionFromPath(this.schema,[$],Z);else if(E1(this.contents))this.contents.set($,Z)}setIn($,Z){if(D1.isEmptyPath($))this.contents=Z;else if(this.contents==null)this.contents=D1.collectionFromPath(this.schema,Array.from($),Z);else if(E1(this.contents))this.contents.setIn($,Z)}setSchema($,Z={}){if(typeof $==="number")$=String($);let X;switch($){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new JX.Directives({version:"1.1"});X={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=$;else this.directives=new JX.Directives({version:$});X={resolveKnownTags:!0,schema:"core"};break;case null:if(this.directives)delete this.directives;X=null;break;default:{let Y=JSON.stringify($);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${Y}`)}}if(Z.schema instanceof Object)this.schema=Z.schema;else if(X)this.schema=new VU.Schema(Object.assign(X,Z));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:$,jsonArg:Z,mapAsMap:X,maxAliasCount:Y,onAnchor:G,reviver:z}={}){let J={anchors:new Map,doc:this,keep:!$,mapAsMap:X===!0,mapKeyWarned:!1,maxAliasCount:typeof Y==="number"?Y:100},Q=WU.toJS(this.contents,Z??"",J);if(typeof G==="function")for(let{count:W,res:V}of J.anchors.values())G(V,W);return typeof z==="function"?KU.applyReviver(z,{"":Q},"",Q):Q}toJSON($,Z){return this.toJS({json:!0,jsonArg:$,mapAsMap:!1,onAnchor:Z})}toString($={}){if(this.errors.length>0)throw Error("Document with errors cannot be stringified");if("indent"in $&&(!Number.isInteger($.indent)||Number($.indent)<=0)){let Z=JSON.stringify($.indent);throw Error(`"indent" option must be a positive integer, not ${Z}`)}return HU.stringifyDocument(this,$)}}function E1($){if(S0.isCollection($))return!0;throw Error("Expected a YAML collection as document contents")}BU.Document=QX});var i2=C((FU)=>{class IZ extends Error{constructor($,Z,X,Y){super();this.name=$,this.code=X,this.message=Y,this.pos=Z}}class d7 extends IZ{constructor($,Z,X){super("YAMLParseError",$,Z,X)}}class c7 extends IZ{constructor($,Z,X){super("YAMLWarning",$,Z,X)}}var TU=($,Z)=>(X)=>{if(X.pos[0]===-1)return;X.linePos=X.pos.map((Q)=>Z.linePos(Q));let{line:Y,col:G}=X.linePos[0];X.message+=` at line ${Y}, column ${G}`;let z=G-1,J=$.substring(Z.lineStarts[Y-1],Z.lineStarts[Y]).replace(/[\n\r]+$/,"");if(z>=60&&J.length>80){let Q=Math.min(z-39,J.length-79);J="\u2026"+J.substring(Q),z-=Q-1}if(J.length>80)J=J.substring(0,79)+"\u2026";if(Y>1&&/^ *$/.test(J.substring(0,z))){let Q=$.substring(Z.lineStarts[Y-2],Z.lineStarts[Y-1]);if(Q.length>80)Q=Q.substring(0,79)+`\u2026
|
|
85
85
|
`;J=Q+J}if(/[^ ]/.test(J)){let Q=1,W=X.linePos[1];if(W?.line===Y&&W.col>G)Q=Math.max(1,Math.min(W.col-G,80-z));let V=" ".repeat(z)+"^".repeat(Q);X.message+=`:
|
|
86
86
|
|
|
87
87
|
${J}
|
|
88
88
|
${V}
|
|
89
|
-
`}};
|
|
90
|
-
`))return!0;if($.end){for(let Z of $.end)if(Z.type==="newline")return!0}return!1;case"flow-collection":for(let Z of $.items){for(let X of Z.start)if(X.type==="newline")return!0;if(Z.sep){for(let X of Z.sep)if(X.type==="newline")return!0}if(
|
|
91
|
-
`+
|
|
92
|
-
`+_.comment;else N.comment=_.comment;let P=new
|
|
93
|
-
`+A.comment;else V.comment=A.comment;H=A.end;continue}if(!J&&X.options.strict&&
|
|
94
|
-
`+S;else D.comment=S;A.comment=A.comment.substring(S.length+1)}}}if(!J&&!P&&!A.found){let S=R?$(X,R,A,G):Z(X,A.end,P,null,A,G);if(V.items.push(S),H=S.range[2],
|
|
95
|
-
`+k.comment;else D.comment=k.comment;let i=new
|
|
96
|
-
`+
|
|
97
|
-
`.repeat(Math.max(1,J.length-1)):"",
|
|
98
|
-
`;for(let
|
|
99
|
-
`;else if(
|
|
100
|
-
`;else if(!U
|
|
101
|
-
`)
|
|
89
|
+
`}};FU.YAMLError=IZ;FU.YAMLParseError=d7;FU.YAMLWarning=c7;FU.prettifyError=TU});var a2=C((_U)=>{function NU($,{flow:Z,indicator:X,next:Y,offset:G,onError:z,parentIndent:J,startOnNewline:Q}){let W=!1,V=Q,K=Q,H="",U="",B=!1,T=!1,F=null,M=null,O=null,N=null,_=null,P=null,R=null;for(let D of $){if(T){if(D.type!=="space"&&D.type!=="newline"&&D.type!=="comma")z(D.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");T=!1}if(F){if(V&&D.type!=="comment"&&D.type!=="newline")z(F,"TAB_AS_INDENT","Tabs are not allowed as indentation");F=null}switch(D.type){case"space":if(!Z&&(X!=="doc-start"||Y?.type!=="flow-collection")&&D.source.includes("\t"))F=D;K=!0;break;case"comment":{if(!K)z(D,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let k=D.source.substring(1)||" ";if(!H)H=k;else H+=U+k;U="",V=!1;break}case"newline":if(V){if(H)H+=D.source;else if(!P||X!=="seq-item-ind")W=!0}else U+=D.source;if(V=!0,B=!0,M||O)N=D;K=!0;break;case"anchor":if(M)z(D,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(D.source.endsWith(":"))z(D.offset+D.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);M=D,R??(R=D.offset),V=!1,K=!1,T=!0;break;case"tag":{if(O)z(D,"MULTIPLE_TAGS","A node can have at most one tag");O=D,R??(R=D.offset),V=!1,K=!1,T=!0;break}case X:if(M||O)z(D,"BAD_PROP_ORDER",`Anchors and tags must be after the ${D.source} indicator`);if(P)z(D,"UNEXPECTED_TOKEN",`Unexpected ${D.source} in ${Z??"collection"}`);P=D,V=X==="seq-item-ind"||X==="explicit-key-ind",K=!1;break;case"comma":if(Z){if(_)z(D,"UNEXPECTED_TOKEN",`Unexpected , in ${Z}`);_=D,V=!1,K=!1;break}default:z(D,"UNEXPECTED_TOKEN",`Unexpected ${D.type} token`),V=!1,K=!1}}let A=$[$.length-1],S=A?A.offset+A.source.length:G;if(T&&Y&&Y.type!=="space"&&Y.type!=="newline"&&Y.type!=="comma"&&(Y.type!=="scalar"||Y.source!==""))z(Y.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(F&&(V&&F.indent<=J||Y?.type==="block-map"||Y?.type==="block-seq"))z(F,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:_,found:P,spaceBefore:W,comment:H,hasNewline:B,anchor:M,tag:O,newlineAfterProp:N,end:S,start:R??S}}_U.resolveProps=NU});var jZ=C((DU)=>{function WX($){if(!$)return null;switch($.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if($.source.includes(`
|
|
90
|
+
`))return!0;if($.end){for(let Z of $.end)if(Z.type==="newline")return!0}return!1;case"flow-collection":for(let Z of $.items){for(let X of Z.start)if(X.type==="newline")return!0;if(Z.sep){for(let X of Z.sep)if(X.type==="newline")return!0}if(WX(Z.key)||WX(Z.value))return!0}return!1;default:return!0}}DU.containsNewline=WX});var VX=C((SU)=>{var RU=jZ();function AU($,Z,X){if(Z?.type==="flow-collection"){let Y=Z.end[0];if(Y.indent===$&&(Y.source==="]"||Y.source==="}")&&RU.containsNewline(Z))X(Y,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}SU.flowIndentCheck=AU});var HX=C((jU)=>{var l7=m();function IU($,Z,X){let{uniqueKeys:Y}=$.options;if(Y===!1)return!1;let G=typeof Y==="function"?Y:(z,J)=>z===J||l7.isScalar(z)&&l7.isScalar(J)&&z.value===J.value;return Z.some((z)=>G(z.key,X))}jU.mapIncludes=IU});var r7=C((vU)=>{var p7=B$(),kU=T$(),i7=a2(),bU=jZ(),a7=VX(),fU=HX(),n7="All mapping items must start at the same column";function yU({composeNode:$,composeEmptyNode:Z},X,Y,G,z){let Q=new(z?.nodeClass??kU.YAMLMap)(X.schema);if(X.atRoot)X.atRoot=!1;let W=Y.offset,V=null;for(let K of Y.items){let{start:H,key:U,sep:B,value:T}=K,F=i7.resolveProps(H,{indicator:"explicit-key-ind",next:U??B?.[0],offset:W,onError:G,parentIndent:Y.indent,startOnNewline:!0}),M=!F.found;if(M){if(U){if(U.type==="block-seq")G(W,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in U&&U.indent!==Y.indent)G(W,"BAD_INDENT",n7)}if(!F.anchor&&!F.tag&&!B){if(V=F.end,F.comment)if(Q.comment)Q.comment+=`
|
|
91
|
+
`+F.comment;else Q.comment=F.comment;continue}if(F.newlineAfterProp||bU.containsNewline(U))G(U??H[H.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(F.found?.indent!==Y.indent)G(W,"BAD_INDENT",n7);X.atKey=!0;let O=F.end,N=U?$(X,U,F,G):Z(X,O,H,null,F,G);if(X.schema.compat)a7.flowIndentCheck(Y.indent,U,G);if(X.atKey=!1,fU.mapIncludes(X,Q.items,N))G(O,"DUPLICATE_KEY","Map keys must be unique");let _=i7.resolveProps(B??[],{indicator:"map-value-ind",next:T,offset:N.range[2],onError:G,parentIndent:Y.indent,startOnNewline:!U||U.type==="block-scalar"});if(W=_.end,_.found){if(M){if(T?.type==="block-map"&&!_.hasNewline)G(W,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(X.options.strict&&F.start<_.found.offset-1024)G(N.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let P=T?$(X,T,_,G):Z(X,W,B,null,_,G);if(X.schema.compat)a7.flowIndentCheck(Y.indent,T,G);W=P.range[2];let R=new p7.Pair(N,P);if(X.options.keepSourceTokens)R.srcToken=K;Q.items.push(R)}else{if(M)G(N.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(_.comment)if(N.comment)N.comment+=`
|
|
92
|
+
`+_.comment;else N.comment=_.comment;let P=new p7.Pair(N);if(X.options.keepSourceTokens)P.srcToken=K;Q.items.push(P)}}if(V&&V<W)G(V,"IMPOSSIBLE","Map comment with trailing content");return Q.range=[Y.offset,W,V??W],Q}vU.resolveBlockMap=yU});var s7=C((cU)=>{var hU=F$(),uU=a2(),mU=VX();function dU({composeNode:$,composeEmptyNode:Z},X,Y,G,z){let Q=new(z?.nodeClass??hU.YAMLSeq)(X.schema);if(X.atRoot)X.atRoot=!1;if(X.atKey)X.atKey=!1;let W=Y.offset,V=null;for(let{start:K,value:H}of Y.items){let U=uU.resolveProps(K,{indicator:"seq-item-ind",next:H,offset:W,onError:G,parentIndent:Y.indent,startOnNewline:!0});if(!U.found)if(U.anchor||U.tag||H)if(H?.type==="block-seq")G(U.end,"BAD_INDENT","All sequence items must start at the same column");else G(W,"MISSING_CHAR","Sequence item without - indicator");else{if(V=U.end,U.comment)Q.comment=U.comment;continue}let B=H?$(X,H,U,G):Z(X,U.end,K,null,U,G);if(X.schema.compat)mU.flowIndentCheck(Y.indent,H,G);W=B.range[2],Q.items.push(B)}return Q.range=[Y.offset,W,V??W],Q}cU.resolveBlockSeq=dU});var R1=C((iU)=>{function pU($,Z,X,Y){let G="";if($){let z=!1,J="";for(let Q of $){let{source:W,type:V}=Q;switch(V){case"space":z=!0;break;case"comment":{if(X&&!z)Y(Q,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let K=W.substring(1)||" ";if(!G)G=K;else G+=J+K;J="";break}case"newline":if(G)J+=W;z=!0;break;default:Y(Q,"UNEXPECTED_TOKEN",`Unexpected ${V} at node end`)}Z+=W.length}}return{comment:G,offset:Z}}iU.resolveEnd=pU});var e7=C((ZB)=>{var nU=m(),rU=B$(),o7=T$(),sU=F$(),oU=R1(),t7=a2(),tU=jZ(),eU=HX(),KX="Block collections are not allowed within flow collections",UX=($)=>$&&($.type==="block-map"||$.type==="block-seq");function $B({composeNode:$,composeEmptyNode:Z},X,Y,G,z){let J=Y.start.source==="{",Q=J?"flow map":"flow sequence",V=new(z?.nodeClass??(J?o7.YAMLMap:sU.YAMLSeq))(X.schema);V.flow=!0;let K=X.atRoot;if(K)X.atRoot=!1;if(X.atKey)X.atKey=!1;let H=Y.offset+Y.start.source.length;for(let M=0;M<Y.items.length;++M){let O=Y.items[M],{start:N,key:_,sep:P,value:R}=O,A=t7.resolveProps(N,{flow:Q,indicator:"explicit-key-ind",next:_??P?.[0],offset:H,onError:G,parentIndent:Y.indent,startOnNewline:!1});if(!A.found){if(!A.anchor&&!A.tag&&!P&&!R){if(M===0&&A.comma)G(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${Q}`);else if(M<Y.items.length-1)G(A.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${Q}`);if(A.comment)if(V.comment)V.comment+=`
|
|
93
|
+
`+A.comment;else V.comment=A.comment;H=A.end;continue}if(!J&&X.options.strict&&tU.containsNewline(_))G(_,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(M===0){if(A.comma)G(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${Q}`)}else{if(!A.comma)G(A.start,"MISSING_CHAR",`Missing , between ${Q} items`);if(A.comment){let S="";$:for(let D of N)switch(D.type){case"comma":case"space":break;case"comment":S=D.source.substring(1);break $;default:break $}if(S){let D=V.items[V.items.length-1];if(nU.isPair(D))D=D.value??D.key;if(D.comment)D.comment+=`
|
|
94
|
+
`+S;else D.comment=S;A.comment=A.comment.substring(S.length+1)}}}if(!J&&!P&&!A.found){let S=R?$(X,R,A,G):Z(X,A.end,P,null,A,G);if(V.items.push(S),H=S.range[2],UX(R))G(S.range,"BLOCK_IN_FLOW",KX)}else{X.atKey=!0;let S=A.end,D=_?$(X,_,A,G):Z(X,S,N,null,A,G);if(UX(_))G(D.range,"BLOCK_IN_FLOW",KX);X.atKey=!1;let k=t7.resolveProps(P??[],{flow:Q,indicator:"map-value-ind",next:R,offset:D.range[2],onError:G,parentIndent:Y.indent,startOnNewline:!1});if(k.found){if(!J&&!A.found&&X.options.strict){if(P)for(let c of P){if(c===k.found)break;if(c.type==="newline"){G(c,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(A.start<k.found.offset-1024)G(k.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(R)if("source"in R&&R.source?.[0]===":")G(R,"MISSING_CHAR",`Missing space after : in ${Q}`);else G(k.start,"MISSING_CHAR",`Missing , or : between ${Q} items`);let b=R?$(X,R,k,G):k.found?Z(X,k.end,P,null,k,G):null;if(b){if(UX(R))G(b.range,"BLOCK_IN_FLOW",KX)}else if(k.comment)if(D.comment)D.comment+=`
|
|
95
|
+
`+k.comment;else D.comment=k.comment;let i=new rU.Pair(D,b);if(X.options.keepSourceTokens)i.srcToken=O;if(J){let c=V;if(eU.mapIncludes(X,c.items,D))G(S,"DUPLICATE_KEY","Map keys must be unique");c.items.push(i)}else{let c=new o7.YAMLMap(X.schema);c.flow=!0,c.items.push(i);let M0=(b??D).range;c.range=[D.range[0],M0[1],M0[2]],V.items.push(c)}H=b?b.range[2]:k.end}}let U=J?"}":"]",[B,...T]=Y.end,F=H;if(B?.source===U)F=B.offset+B.source.length;else{let M=Q[0].toUpperCase()+Q.substring(1),O=K?`${M} must end with a ${U}`:`${M} in block collection must be sufficiently indented and end with a ${U}`;if(G(H,K?"MISSING_CHAR":"BAD_INDENT",O),B&&B.source.length!==1)T.unshift(B)}if(T.length>0){let M=oU.resolveEnd(T,F,X.options.strict,G);if(M.comment)if(V.comment)V.comment+=`
|
|
96
|
+
`+M.comment;else V.comment=M.comment;V.range=[Y.offset,F,M.offset]}else V.range=[Y.offset,F,F];return V}ZB.resolveFlowCollection=$B});var $Y=C((KB)=>{var YB=m(),GB=t(),zB=T$(),JB=F$(),QB=r7(),WB=s7(),VB=e7();function BX($,Z,X,Y,G,z){let J=X.type==="block-map"?QB.resolveBlockMap($,Z,X,Y,z):X.type==="block-seq"?WB.resolveBlockSeq($,Z,X,Y,z):VB.resolveFlowCollection($,Z,X,Y,z),Q=J.constructor;if(G==="!"||G===Q.tagName)return J.tag=Q.tagName,J;if(G)J.tag=G;return J}function HB($,Z,X,Y,G){let z=Y.tag,J=!z?null:Z.directives.tagName(z.source,(U)=>G(z,"TAG_RESOLVE_FAILED",U));if(X.type==="block-seq"){let{anchor:U,newlineAfterProp:B}=Y,T=U&&z?U.offset>z.offset?U:z:U??z;if(T&&(!B||B.offset<T.offset))G(T,"MISSING_CHAR","Missing newline after block sequence props")}let Q=X.type==="block-map"?"map":X.type==="block-seq"?"seq":X.start.source==="{"?"map":"seq";if(!z||!J||J==="!"||J===zB.YAMLMap.tagName&&Q==="map"||J===JB.YAMLSeq.tagName&&Q==="seq")return BX($,Z,X,G,J);let W=Z.schema.tags.find((U)=>U.tag===J&&U.collection===Q);if(!W){let U=Z.schema.knownTags[J];if(U?.collection===Q)Z.schema.tags.push(Object.assign({},U,{default:!1})),W=U;else{if(U)G(z,"BAD_COLLECTION_TYPE",`${U.tag} used for ${Q} collection, but expects ${U.collection??"scalar"}`,!0);else G(z,"TAG_RESOLVE_FAILED",`Unresolved tag: ${J}`,!0);return BX($,Z,X,G,J)}}let V=BX($,Z,X,G,J,W),K=W.resolve?.(V,(U)=>G(z,"TAG_RESOLVE_FAILED",U),Z.options)??V,H=YB.isNode(K)?K:new GB.Scalar(K);if(H.range=V.range,H.tag=J,W?.format)H.format=W.format;return H}KB.composeCollection=HB});var TX=C((FB)=>{var qX=t();function BB($,Z,X){let Y=Z.offset,G=qB(Z,$.options.strict,X);if(!G)return{value:"",type:null,comment:"",range:[Y,Y,Y]};let z=G.mode===">"?qX.Scalar.BLOCK_FOLDED:qX.Scalar.BLOCK_LITERAL,J=Z.source?TB(Z.source):[],Q=J.length;for(let F=J.length-1;F>=0;--F){let M=J[F][1];if(M===""||M==="\r")Q=F;else break}if(Q===0){let F=G.chomp==="+"&&J.length>0?`
|
|
97
|
+
`.repeat(Math.max(1,J.length-1)):"",M=Y+G.length;if(Z.source)M+=Z.source.length;return{value:F,type:z,comment:G.comment,range:[Y,M,M]}}let W=Z.indent+G.indent,V=Z.offset+G.length,K=0;for(let F=0;F<Q;++F){let[M,O]=J[F];if(O===""||O==="\r"){if(G.indent===0&&M.length>W)W=M.length}else{if(M.length<W)X(V+M.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(G.indent===0)W=M.length;if(K=F,W===0&&!$.atRoot)X(V,"BAD_INDENT","Block scalar values in collections must be indented");break}V+=M.length+O.length+1}for(let F=J.length-1;F>=Q;--F)if(J[F][0].length>W)Q=F+1;let H="",U="",B=!1;for(let F=0;F<K;++F)H+=J[F][0].slice(W)+`
|
|
98
|
+
`;for(let F=K;F<Q;++F){let[M,O]=J[F];V+=M.length+O.length+1;let N=O[O.length-1]==="\r";if(N)O=O.slice(0,-1);if(O&&M.length<W){let P=`Block scalar lines must not be less indented than their ${G.indent?"explicit indentation indicator":"first line"}`;X(V-O.length-(N?2:1),"BAD_INDENT",P),M=""}if(z===qX.Scalar.BLOCK_LITERAL)H+=U+M.slice(W)+O,U=`
|
|
99
|
+
`;else if(M.length>W||O[0]==="\t"){if(U===" ")U=`
|
|
100
|
+
`;else if(!B&&U===`
|
|
101
|
+
`)U=`
|
|
102
102
|
|
|
103
|
-
`;H+=
|
|
104
|
-
`,
|
|
103
|
+
`;H+=U+M.slice(W)+O,U=`
|
|
104
|
+
`,B=!0}else if(O==="")if(U===`
|
|
105
105
|
`)H+=`
|
|
106
|
-
`;else
|
|
107
|
-
`;else H+=
|
|
108
|
-
`+J[
|
|
106
|
+
`;else U=`
|
|
107
|
+
`;else H+=U+O,U=" ",B=!1}switch(G.chomp){case"-":break;case"+":for(let F=Q;F<J.length;++F)H+=`
|
|
108
|
+
`+J[F][0].slice(W);if(H[H.length-1]!==`
|
|
109
109
|
`)H+=`
|
|
110
110
|
`;break;default:H+=`
|
|
111
|
-
`}let
|
|
111
|
+
`}let T=Y+G.length+Z.source.length;return{value:H,type:z,comment:G.comment,range:[Y,T,T]}}function qB({offset:$,props:Z},X,Y){if(Z[0].type!=="block-scalar-header")return Y(Z[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:G}=Z[0],z=G[0],J=0,Q="",W=-1;for(let U=1;U<G.length;++U){let B=G[U];if(!Q&&(B==="-"||B==="+"))Q=B;else{let T=Number(B);if(!J&&T)J=T;else if(W===-1)W=$+U}}if(W!==-1)Y(W,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${G}`);let V=!1,K="",H=G.length;for(let U=1;U<Z.length;++U){let B=Z[U];switch(B.type){case"space":V=!0;case"newline":H+=B.source.length;break;case"comment":if(X&&!V)Y(B,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");H+=B.source.length,K=B.source.substring(1);break;case"error":Y(B,"UNEXPECTED_TOKEN",B.message),H+=B.source.length;break;default:{let T=`Unexpected token in block scalar header: ${B.type}`;Y(B,"UNEXPECTED_TOKEN",T);let F=B.source;if(F&&typeof F==="string")H+=F.length}}}return{mode:z,indent:J,chomp:Q,comment:K,length:H}}function TB($){let Z=$.split(/\n( *)/),X=Z[0],Y=X.match(/^( *)/),z=[Y?.[1]?[Y[1],X.slice(Y[1].length)]:["",X]];for(let J=1;J<Z.length;J+=2)z.push([Z[J],Z[J+1]]);return z}FB.resolveBlockScalar=BB});var LX=C((RB)=>{var FX=t(),MB=R1();function wB($,Z,X){let{offset:Y,type:G,source:z,end:J}=$,Q,W,V=(U,B,T)=>X(Y+U,B,T);switch(G){case"scalar":Q=FX.Scalar.PLAIN,W=OB(z,V);break;case"single-quoted-scalar":Q=FX.Scalar.QUOTE_SINGLE,W=NB(z,V);break;case"double-quoted-scalar":Q=FX.Scalar.QUOTE_DOUBLE,W=_B(z,V);break;default:return X($,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${G}`),{value:"",type:null,comment:"",range:[Y,Y+z.length,Y+z.length]}}let K=Y+z.length,H=MB.resolveEnd(J,K,Z,X);return{value:W,type:Q,comment:H.comment,range:[Y,K,H.offset]}}function OB($,Z){let X="";switch($[0]){case"\t":X="a tab character";break;case",":X="flow indicator character ,";break;case"%":X="directive indicator character %";break;case"|":case">":{X=`block scalar indicator ${$[0]}`;break}case"@":case"`":{X=`reserved character ${$[0]}`;break}}if(X)Z(0,"BAD_SCALAR_START",`Plain value cannot start with ${X}`);return ZY($)}function NB($,Z){if($[$.length-1]!=="'"||$.length===1)Z($.length,"MISSING_CHAR","Missing closing 'quote");return ZY($.slice(1,-1)).replace(/''/g,"'")}function ZY($){let Z,X;try{Z=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
112
112
|
`,"sy"),X=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
113
113
|
`,"sy")}catch{Z=/(.*?)[ \t]*\r?\n/sy,X=/[ \t]*(.*?)[ \t]*\r?\n/sy}let Y=Z.exec($);if(!Y)return $;let G=Y[1],z=" ",J=Z.lastIndex;X.lastIndex=J;while(Y=X.exec($)){if(Y[1]==="")if(z===`
|
|
114
114
|
`)G+=z;else z=`
|
|
115
|
-
`;else G+=z+Y[1],z=" ";J=X.lastIndex}let Q=/[ \t]*(.*)/sy;return Q.lastIndex=J,Y=Q.exec($),G+z+(Y?.[1]??"")}function
|
|
115
|
+
`;else G+=z+Y[1],z=" ";J=X.lastIndex}let Q=/[ \t]*(.*)/sy;return Q.lastIndex=J,Y=Q.exec($),G+z+(Y?.[1]??"")}function _B($,Z){let X="";for(let Y=1;Y<$.length-1;++Y){let G=$[Y];if(G==="\r"&&$[Y+1]===`
|
|
116
116
|
`)continue;if(G===`
|
|
117
|
-
`){let{fold:z,offset:J}=
|
|
117
|
+
`){let{fold:z,offset:J}=PB($,Y);X+=z,Y=J}else if(G==="\\"){let z=$[++Y],J=DB[z];if(J)X+=J;else if(z===`
|
|
118
118
|
`){z=$[Y+1];while(z===" "||z==="\t")z=$[++Y+1]}else if(z==="\r"&&$[Y+1]===`
|
|
119
|
-
`){z=$[++Y+1];while(z===" "||z==="\t")z=$[++Y+1]}else if(z==="x"||z==="u"||z==="U"){let Q={x:2,u:4,U:8}[z];X+=
|
|
119
|
+
`){z=$[++Y+1];while(z===" "||z==="\t")z=$[++Y+1]}else if(z==="x"||z==="u"||z==="U"){let Q={x:2,u:4,U:8}[z];X+=EB($,Y+1,Q,Z),Y+=Q}else{let Q=$.substr(Y-1,2);Z(Y-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${Q}`),X+=Q}}else if(G===" "||G==="\t"){let z=Y,J=$[Y+1];while(J===" "||J==="\t")J=$[++Y+1];if(J!==`
|
|
120
120
|
`&&!(J==="\r"&&$[Y+2]===`
|
|
121
|
-
`))X+=Y>z?$.slice(z,Y+1):G}else X+=G}if($[$.length-1]!=='"'||$.length===1)Z($.length,"MISSING_CHAR",'Missing closing "quote');return X}function
|
|
121
|
+
`))X+=Y>z?$.slice(z,Y+1):G}else X+=G}if($[$.length-1]!=='"'||$.length===1)Z($.length,"MISSING_CHAR",'Missing closing "quote');return X}function PB($,Z){let X="",Y=$[Z+1];while(Y===" "||Y==="\t"||Y===`
|
|
122
122
|
`||Y==="\r"){if(Y==="\r"&&$[Z+2]!==`
|
|
123
123
|
`)break;if(Y===`
|
|
124
124
|
`)X+=`
|
|
125
|
-
`;Z+=1,Y=$[Z+1]}if(!X)X=" ";return{fold:X,offset:Z}}var
|
|
126
|
-
`,r:"\r",t:"\t",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function
|
|
125
|
+
`;Z+=1,Y=$[Z+1]}if(!X)X=" ";return{fold:X,offset:Z}}var DB={"0":"\x00",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
126
|
+
`,r:"\r",t:"\t",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function EB($,Z,X,Y){let G=$.substr(Z,X),J=G.length===X&&/^[0-9a-fA-F]+$/.test(G)?parseInt(G,16):NaN;if(isNaN(J)){let Q=$.substr(Z-2,X+2);return Y(Z-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${Q}`),Q}return String.fromCodePoint(J)}RB.resolveFlowScalar=wB});var YY=C((kB)=>{var d$=m(),XY=t(),SB=TX(),CB=LX();function IB($,Z,X,Y){let{value:G,type:z,comment:J,range:Q}=Z.type==="block-scalar"?SB.resolveBlockScalar($,Z,Y):CB.resolveFlowScalar(Z,$.options.strict,Y),W=X?$.directives.tagName(X.source,(H)=>Y(X,"TAG_RESOLVE_FAILED",H)):null,V;if($.options.stringKeys&&$.atKey)V=$.schema[d$.SCALAR];else if(W)V=jB($.schema,G,W,X,Y);else if(Z.type==="scalar")V=xB($,G,Z,Y);else V=$.schema[d$.SCALAR];let K;try{let H=V.resolve(G,(U)=>Y(X??Z,"TAG_RESOLVE_FAILED",U),$.options);K=d$.isScalar(H)?H:new XY.Scalar(H)}catch(H){let U=H instanceof Error?H.message:String(H);Y(X??Z,"TAG_RESOLVE_FAILED",U),K=new XY.Scalar(G)}if(K.range=Q,K.source=G,z)K.type=z;if(W)K.tag=W;if(V.format)K.format=V.format;if(J)K.comment=J;return K}function jB($,Z,X,Y,G){if(X==="!")return $[d$.SCALAR];let z=[];for(let Q of $.tags)if(!Q.collection&&Q.tag===X)if(Q.default&&Q.test)z.push(Q);else return Q;for(let Q of z)if(Q.test?.test(Z))return Q;let J=$.knownTags[X];if(J&&!J.collection)return $.tags.push(Object.assign({},J,{default:!1,test:void 0})),J;return G(Y,"TAG_RESOLVE_FAILED",`Unresolved tag: ${X}`,X!=="tag:yaml.org,2002:str"),$[d$.SCALAR]}function xB({atKey:$,directives:Z,schema:X},Y,G,z){let J=X.tags.find((Q)=>(Q.default===!0||$&&Q.default==="key")&&Q.test?.test(Y))||X[d$.SCALAR];if(X.compat){let Q=X.compat.find((W)=>W.default&&W.test?.test(Y))??X[d$.SCALAR];if(J.tag!==Q.tag){let W=Z.tagString(J.tag),V=Z.tagString(Q.tag),K=`Value may be parsed as either ${W} or ${V}`;z(G,"TAG_RESOLVE_FAILED",K,!0)}}return J}kB.composeScalar=IB});var GY=C((yB)=>{function fB($,Z,X){if(Z){X??(X=Z.length);for(let Y=X-1;Y>=0;--Y){let G=Z[Y];switch(G.type){case"space":case"comment":case"newline":$-=G.source.length;continue}G=Z[++Y];while(G?.type==="space")$+=G.source.length,G=Z[++Y];break}}return $}yB.emptyScalarPosition=fB});var QY=C((pB)=>{var gB=I2(),hB=m(),uB=$Y(),zY=YY(),mB=R1(),dB=GY(),cB={composeNode:JY,composeEmptyNode:MX};function JY($,Z,X,Y){let G=$.atKey,{spaceBefore:z,comment:J,anchor:Q,tag:W}=X,V,K=!0;switch(Z.type){case"alias":if(V=lB($,Z,Y),Q||W)Y(Z,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":if(V=zY.composeScalar($,Z,W,Y),Q)V.anchor=Q.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":if(V=uB.composeCollection(cB,$,Z,X,Y),Q)V.anchor=Q.source.substring(1);break;default:{let H=Z.type==="error"?Z.message:`Unsupported token (type: ${Z.type})`;Y(Z,"UNEXPECTED_TOKEN",H),V=MX($,Z.offset,void 0,null,X,Y),K=!1}}if(Q&&V.anchor==="")Y(Q,"BAD_ALIAS","Anchor cannot be an empty string");if(G&&$.options.stringKeys&&(!hB.isScalar(V)||typeof V.value!=="string"||V.tag&&V.tag!=="tag:yaml.org,2002:str"))Y(W??Z,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(z)V.spaceBefore=!0;if(J)if(Z.type==="scalar"&&Z.source==="")V.comment=J;else V.commentBefore=J;if($.options.keepSourceTokens&&K)V.srcToken=Z;return V}function MX($,Z,X,Y,{spaceBefore:G,comment:z,anchor:J,tag:Q,end:W},V){let K={type:"scalar",offset:dB.emptyScalarPosition(Z,X,Y),indent:-1,source:""},H=zY.composeScalar($,K,Q,V);if(J){if(H.anchor=J.source.substring(1),H.anchor==="")V(J,"BAD_ALIAS","Anchor cannot be an empty string")}if(G)H.spaceBefore=!0;if(z)H.comment=z,H.range[2]=W;return H}function lB({options:$},{offset:Z,source:X,end:Y},G){let z=new gB.Alias(X.substring(1));if(z.source==="")G(Z,"BAD_ALIAS","Alias cannot be an empty string");if(z.source.endsWith(":"))G(Z+X.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let J=Z+X.length,Q=mB.resolveEnd(Y,J,$.strict,G);if(z.range=[Z,J,Q.offset],Q.comment)z.comment=Q.comment;return z}pB.composeEmptyNode=MX;pB.composeNode=JY});var VY=C((tB)=>{var nB=p2(),WY=QY(),rB=R1(),sB=a2();function oB($,Z,{offset:X,start:Y,value:G,end:z},J){let Q=Object.assign({_directives:Z},$),W=new nB.Document(void 0,Q),V={atKey:!1,atRoot:!0,directives:W.directives,options:W.options,schema:W.schema},K=sB.resolveProps(Y,{indicator:"doc-start",next:G??z?.[0],offset:X,onError:J,parentIndent:0,startOnNewline:!0});if(K.found){if(W.directives.docStart=!0,G&&(G.type==="block-map"||G.type==="block-seq")&&!K.hasNewline)J(K.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}W.contents=G?WY.composeNode(V,G,K,J):WY.composeEmptyNode(V,K.end,Y,null,K,J);let H=W.contents.range[2],U=rB.resolveEnd(z,H,!1,J);if(U.comment)W.comment=U.comment;return W.range=[X,H,U.offset],W}tB.composeDoc=oB});var wX=C((zq)=>{var $q=n0("process"),Zq=P9(),Xq=p2(),n2=i2(),HY=m(),Yq=VY(),Gq=R1();function r2($){if(typeof $==="number")return[$,$+1];if(Array.isArray($))return $.length===2?$:[$[0],$[1]];let{offset:Z,source:X}=$;return[Z,Z+(typeof X==="string"?X.length:1)]}function KY($){let Z="",X=!1,Y=!1;for(let G=0;G<$.length;++G){let z=$[G];switch(z[0]){case"#":Z+=(Z===""?"":Y?`
|
|
127
127
|
|
|
128
128
|
`:`
|
|
129
|
-
`)+(z.substring(1)||" "),X=!0,Y=!1;break;case"%":if($[G+1]?.[0]!=="#")G+=1;X=!1;break;default:if(!X)Y=!0;X=!1}}return{comment:Z,afterEmptyLine:Y}}class
|
|
130
|
-
${X}`:X;else if(Y||$.directives.docStart||!G)$.commentBefore=X;else if(
|
|
129
|
+
`)+(z.substring(1)||" "),X=!0,Y=!1;break;case"%":if($[G+1]?.[0]!=="#")G+=1;X=!1;break;default:if(!X)Y=!0;X=!1}}return{comment:Z,afterEmptyLine:Y}}class UY{constructor($={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(Z,X,Y,G)=>{let z=r2(Z);if(G)this.warnings.push(new n2.YAMLWarning(z,X,Y));else this.errors.push(new n2.YAMLParseError(z,X,Y))},this.directives=new Zq.Directives({version:$.version||"1.2"}),this.options=$}decorate($,Z){let{comment:X,afterEmptyLine:Y}=KY(this.prelude);if(X){let G=$.contents;if(Z)$.comment=$.comment?`${$.comment}
|
|
130
|
+
${X}`:X;else if(Y||$.directives.docStart||!G)$.commentBefore=X;else if(HY.isCollection(G)&&!G.flow&&G.items.length>0){let z=G.items[0];if(HY.isPair(z))z=z.key;let J=z.commentBefore;z.commentBefore=J?`${X}
|
|
131
131
|
${J}`:X}else{let z=G.commentBefore;G.commentBefore=z?`${X}
|
|
132
|
-
${z}`:X}}if(Z)Array.prototype.push.apply($.errors,this.errors),Array.prototype.push.apply($.warnings,this.warnings);else $.errors=this.errors,$.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
133
|
-
${Z.comment}`:Z.comment}this.doc.range[2]=Z.offset;break}default:this.errors.push(new
|
|
132
|
+
${z}`:X}}if(Z)Array.prototype.push.apply($.errors,this.errors),Array.prototype.push.apply($.warnings,this.warnings);else $.errors=this.errors,$.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:KY(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose($,Z=!1,X=-1){for(let Y of $)yield*this.next(Y);yield*this.end(Z,X)}*next($){if($q.env.LOG_STREAM)console.dir($,{depth:null});switch($.type){case"directive":this.directives.add($.source,(Z,X,Y)=>{let G=r2($);G[0]+=Z,this.onError(G,"BAD_DIRECTIVE",X,Y)}),this.prelude.push($.source),this.atDirectives=!0;break;case"document":{let Z=Yq.composeDoc(this.options,this.directives,$,this.onError);if(this.atDirectives&&!Z.directives.docStart)this.onError($,"MISSING_CHAR","Missing directives-end/doc-start indicator line");if(this.decorate(Z,!1),this.doc)yield this.doc;this.doc=Z,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push($.source);break;case"error":{let Z=$.source?`${$.message}: ${JSON.stringify($.source)}`:$.message,X=new n2.YAMLParseError(r2($),"UNEXPECTED_TOKEN",Z);if(this.atDirectives||!this.doc)this.errors.push(X);else this.doc.errors.push(X);break}case"doc-end":{if(!this.doc){this.errors.push(new n2.YAMLParseError(r2($),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let Z=Gq.resolveEnd($.end,$.offset+$.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),Z.comment){let X=this.doc.comment;this.doc.comment=X?`${X}
|
|
133
|
+
${Z.comment}`:Z.comment}this.doc.range[2]=Z.offset;break}default:this.errors.push(new n2.YAMLParseError(r2($),"UNEXPECTED_TOKEN",`Unsupported token ${$.type}`))}}*end($=!1,Z=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if($){let X=Object.assign({_directives:this.directives},this.options),Y=new Xq.Document(void 0,X);if(this.atDirectives)this.onError(Z,"MISSING_CHAR","Missing directives-end indicator line");Y.range=[0,Z,Z],this.decorate(Y,!1),yield Y}}}zq.Composer=UY});var TY=C((qq)=>{var Qq=TX(),Wq=LX(),Vq=i2(),BY=b2();function Hq($,Z=!0,X){if($){let Y=(G,z,J)=>{let Q=typeof G==="number"?G:Array.isArray(G)?G[0]:G.offset;if(X)X(Q,z,J);else throw new Vq.YAMLParseError([Q,Q+1],z,J)};switch($.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Wq.resolveFlowScalar($,Z,Y);case"block-scalar":return Qq.resolveBlockScalar({options:{strict:Z}},$,Y)}}return null}function Kq($,Z){let{implicitKey:X=!1,indent:Y,inFlow:G=!1,offset:z=-1,type:J="PLAIN"}=Z,Q=BY.stringifyString({type:J,value:$},{implicitKey:X,indent:Y>0?" ".repeat(Y):"",inFlow:G,options:{blockQuote:!0,lineWidth:-1}}),W=Z.end??[{type:"newline",offset:-1,indent:Y,source:`
|
|
134
134
|
`}];switch(Q[0]){case"|":case">":{let V=Q.indexOf(`
|
|
135
135
|
`),K=Q.substring(0,V),H=Q.substring(V+1)+`
|
|
136
|
-
`,
|
|
137
|
-
`});return{type:"block-scalar",offset:z,indent:Y,props:
|
|
136
|
+
`,U=[{type:"block-scalar-header",offset:z,indent:Y,source:K}];if(!qY(U,W))U.push({type:"newline",offset:-1,indent:Y,source:`
|
|
137
|
+
`});return{type:"block-scalar",offset:z,indent:Y,props:U,source:H}}case'"':return{type:"double-quoted-scalar",offset:z,indent:Y,source:Q,end:W};case"'":return{type:"single-quoted-scalar",offset:z,indent:Y,source:Q,end:W};default:return{type:"scalar",offset:z,indent:Y,source:Q,end:W}}}function Uq($,Z,X={}){let{afterKey:Y=!1,implicitKey:G=!1,inFlow:z=!1,type:J}=X,Q="indent"in $?$.indent:null;if(Y&&typeof Q==="number")Q+=2;if(!J)switch($.type){case"single-quoted-scalar":J="QUOTE_SINGLE";break;case"double-quoted-scalar":J="QUOTE_DOUBLE";break;case"block-scalar":{let V=$.props[0];if(V.type!=="block-scalar-header")throw Error("Invalid block scalar header");J=V.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:J="PLAIN"}let W=BY.stringifyString({type:J,value:Z},{implicitKey:G||Q===null,indent:Q!==null&&Q>0?" ".repeat(Q):"",inFlow:z,options:{blockQuote:!0,lineWidth:-1}});switch(W[0]){case"|":case">":Bq($,W);break;case'"':OX($,W,"double-quoted-scalar");break;case"'":OX($,W,"single-quoted-scalar");break;default:OX($,W,"scalar")}}function Bq($,Z){let X=Z.indexOf(`
|
|
138
138
|
`),Y=Z.substring(0,X),G=Z.substring(X+1)+`
|
|
139
|
-
`;if($.type==="block-scalar"){let z=$.props[0];if(z.type!=="block-scalar-header")throw Error("Invalid block scalar header");z.source=Y,$.source=G}else{let{offset:z}=$,J="indent"in $?$.indent:-1,Q=[{type:"block-scalar-header",offset:z,indent:J,source:Y}];if(!
|
|
140
|
-
`});for(let W of Object.keys($))if(W!=="type"&&W!=="offset")delete $[W];Object.assign($,{type:"block-scalar",indent:J,props:Q,source:G})}}function
|
|
141
|
-
`};delete $.items,Object.assign($,{type:X,source:Z,end:[G]});break}default:{let Y="indent"in $?$.indent:-1,G="end"in $&&Array.isArray($.end)?$.end.filter((z)=>z.type==="space"||z.type==="comment"||z.type==="newline"):[];for(let z of Object.keys($))if(z!=="type"&&z!=="offset")delete $[z];Object.assign($,{type:X,indent:Y,source:Z,end:G})}}}
|
|
139
|
+
`;if($.type==="block-scalar"){let z=$.props[0];if(z.type!=="block-scalar-header")throw Error("Invalid block scalar header");z.source=Y,$.source=G}else{let{offset:z}=$,J="indent"in $?$.indent:-1,Q=[{type:"block-scalar-header",offset:z,indent:J,source:Y}];if(!qY(Q,"end"in $?$.end:void 0))Q.push({type:"newline",offset:-1,indent:J,source:`
|
|
140
|
+
`});for(let W of Object.keys($))if(W!=="type"&&W!=="offset")delete $[W];Object.assign($,{type:"block-scalar",indent:J,props:Q,source:G})}}function qY($,Z){if(Z)for(let X of Z)switch(X.type){case"space":case"comment":$.push(X);break;case"newline":return $.push(X),!0}return!1}function OX($,Z,X){switch($.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":$.type=X,$.source=Z;break;case"block-scalar":{let Y=$.props.slice(1),G=Z.length;if($.props[0].type==="block-scalar-header")G-=$.props[0].source.length;for(let z of Y)z.offset+=G;delete $.props,Object.assign($,{type:X,source:Z,end:Y});break}case"block-map":case"block-seq":{let G={type:"newline",offset:$.offset+Z.length,indent:$.indent,source:`
|
|
141
|
+
`};delete $.items,Object.assign($,{type:X,source:Z,end:[G]});break}default:{let Y="indent"in $?$.indent:-1,G="end"in $&&Array.isArray($.end)?$.end.filter((z)=>z.type==="space"||z.type==="comment"||z.type==="newline"):[];for(let z of Object.keys($))if(z!=="type"&&z!=="offset")delete $[z];Object.assign($,{type:X,indent:Y,source:Z,end:G})}}}qq.createScalarToken=Kq;qq.resolveAsScalar=Hq;qq.setScalarValue=Uq});var FY=C((wq)=>{var Mq=($)=>("type"in $)?kZ($):xZ($);function kZ($){switch($.type){case"block-scalar":{let Z="";for(let X of $.props)Z+=kZ(X);return Z+$.source}case"block-map":case"block-seq":{let Z="";for(let X of $.items)Z+=xZ(X);return Z}case"flow-collection":{let Z=$.start.source;for(let X of $.items)Z+=xZ(X);for(let X of $.end)Z+=X.source;return Z}case"document":{let Z=xZ($);if($.end)for(let X of $.end)Z+=X.source;return Z}default:{let Z=$.source;if("end"in $&&$.end)for(let X of $.end)Z+=X.source;return Z}}}function xZ({start:$,key:Z,sep:X,value:Y}){let G="";for(let z of $)G+=z.source;if(Z)G+=kZ(Z);if(X)for(let z of X)G+=z.source;if(Y)G+=kZ(Y);return G}wq.stringify=Mq});var wY=C((_q)=>{var NX=Symbol("break visit"),Nq=Symbol("skip children"),LY=Symbol("remove item");function c$($,Z){if("type"in $&&$.type==="document")$={start:$.start,value:$.value};MY(Object.freeze([]),$,Z)}c$.BREAK=NX;c$.SKIP=Nq;c$.REMOVE=LY;c$.itemAtPath=($,Z)=>{let X=$;for(let[Y,G]of Z){let z=X?.[Y];if(z&&"items"in z)X=z.items[G];else return}return X};c$.parentCollection=($,Z)=>{let X=c$.itemAtPath($,Z.slice(0,-1)),Y=Z[Z.length-1][0],G=X?.[Y];if(G&&"items"in G)return G;throw Error("Parent collection not found")};function MY($,Z,X){let Y=X(Z,$);if(typeof Y==="symbol")return Y;for(let G of["key","value"]){let z=Z[G];if(z&&"items"in z){for(let J=0;J<z.items.length;++J){let Q=MY(Object.freeze($.concat([[G,J]])),z.items[J],X);if(typeof Q==="number")J=Q-1;else if(Q===NX)return NX;else if(Q===LY)z.items.splice(J,1),J-=1}if(typeof Y==="function"&&G==="key")Y=Y(Z,$)}}return typeof Y==="function"?Y(Z,$):Y}_q.visit=c$});var bZ=C((Iq)=>{var _X=TY(),Dq=FY(),Eq=wY(),PX="\uFEFF",DX="\x02",EX="\x18",RX="\x1F",Rq=($)=>!!$&&("items"in $),Aq=($)=>!!$&&($.type==="scalar"||$.type==="single-quoted-scalar"||$.type==="double-quoted-scalar"||$.type==="block-scalar");function Sq($){switch($){case PX:return"<BOM>";case DX:return"<DOC>";case EX:return"<FLOW_END>";case RX:return"<SCALAR>";default:return JSON.stringify($)}}function Cq($){switch($){case PX:return"byte-order-mark";case DX:return"doc-mode";case EX:return"flow-error-end";case RX:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
142
142
|
`:case`\r
|
|
143
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch($[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}
|
|
144
|
-
`:case"\r":case"\t":return!0;default:return!1}}var
|
|
145
|
-
\r `),
|
|
143
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch($[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Iq.createScalarToken=_X.createScalarToken;Iq.resolveAsScalar=_X.resolveAsScalar;Iq.setScalarValue=_X.setScalarValue;Iq.stringify=Dq.stringify;Iq.visit=Eq.visit;Iq.BOM=PX;Iq.DOCUMENT=DX;Iq.FLOW_END=EX;Iq.SCALAR=RX;Iq.isCollection=Rq;Iq.isScalar=Aq;Iq.prettyToken=Sq;Iq.tokenType=Cq});var SX=C((iq)=>{var s2=bZ();function b0($){switch($){case void 0:case" ":case`
|
|
144
|
+
`:case"\r":case"\t":return!0;default:return!1}}var OY=new Set("0123456789ABCDEFabcdef"),lq=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),fZ=new Set(",[]{}"),pq=new Set(` ,[]{}
|
|
145
|
+
\r `),AX=($)=>!$||pq.has($);class NY{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex($,Z=!1){if($){if(typeof $!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+$:$,this.lineEndPos=null}this.atEnd=!Z;let X=this.next??"stream";while(X&&(Z||this.hasChars(1)))X=yield*this.parseNext(X)}atLineEnd(){let $=this.pos,Z=this.buffer[$];while(Z===" "||Z==="\t")Z=this.buffer[++$];if(!Z||Z==="#"||Z===`
|
|
146
146
|
`)return!0;if(Z==="\r")return this.buffer[$+1]===`
|
|
147
147
|
`;return!1}charAt($){return this.buffer[this.pos+$]}continueScalar($){let Z=this.buffer[$];if(this.indentNext>0){let X=0;while(Z===" ")Z=this.buffer[++X+$];if(Z==="\r"){let Y=this.buffer[X+$+1];if(Y===`
|
|
148
148
|
`||!Y&&!this.atEnd)return $+X+1}return Z===`
|
|
149
|
-
`||X>=this.indentNext||!Z&&!this.atEnd?$+X:-1}if(Z==="-"||Z==="."){let X=this.buffer.substr($,3);if((X==="---"||X==="...")&&
|
|
150
|
-
`,this.pos),this.lineEndPos=$;if($===-1)return this.atEnd?this.buffer.substring(this.pos):null;if(this.buffer[$-1]==="\r")$-=1;return this.buffer.substring(this.pos,$)}hasChars($){return this.pos+$<=this.buffer.length}setNext($){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=$,null}peek($){return this.buffer.substr(this.pos,$)}*parseNext($){switch($){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let $=this.getLine();if($===null)return this.setNext("stream");if($[0]===
|
|
149
|
+
`||X>=this.indentNext||!Z&&!this.atEnd?$+X:-1}if(Z==="-"||Z==="."){let X=this.buffer.substr($,3);if((X==="---"||X==="...")&&b0(this.buffer[$+3]))return-1}return $}getLine(){let $=this.lineEndPos;if(typeof $!=="number"||$!==-1&&$<this.pos)$=this.buffer.indexOf(`
|
|
150
|
+
`,this.pos),this.lineEndPos=$;if($===-1)return this.atEnd?this.buffer.substring(this.pos):null;if(this.buffer[$-1]==="\r")$-=1;return this.buffer.substring(this.pos,$)}hasChars($){return this.pos+$<=this.buffer.length}setNext($){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=$,null}peek($){return this.buffer.substr(this.pos,$)}*parseNext($){switch($){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let $=this.getLine();if($===null)return this.setNext("stream");if($[0]===s2.BOM)yield*this.pushCount(1),$=$.substring(1);if($[0]==="%"){let Z=$.length,X=$.indexOf("#");while(X!==-1){let G=$[X-1];if(G===" "||G==="\t"){Z=X-1;break}else X=$.indexOf("#",X+1)}while(!0){let G=$[Z-1];if(G===" "||G==="\t")Z-=1;else break}let Y=(yield*this.pushCount(Z))+(yield*this.pushSpaces(!0));return yield*this.pushCount($.length-Y),this.pushNewline(),"stream"}if(this.atLineEnd()){let Z=yield*this.pushSpaces(!0);return yield*this.pushCount($.length-Z),yield*this.pushNewline(),"stream"}return yield s2.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let $=this.charAt(0);if(!$&&!this.atEnd)return this.setNext("line-start");if($==="-"||$==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let Z=this.peek(3);if((Z==="---"||Z==="...")&&b0(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,Z==="---"?"doc":"stream"}if(this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!b0(this.charAt(1)))this.indentNext=this.indentValue;return yield*this.parseBlockStart()}*parseBlockStart(){let[$,Z]=this.peek(2);if(!Z&&!this.atEnd)return this.setNext("block-start");if(($==="-"||$==="?"||$===":")&&b0(Z)){let X=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=X,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let $=this.getLine();if($===null)return this.setNext("doc");let Z=yield*this.pushIndicators();switch($[Z]){case"#":yield*this.pushCount($.length-Z);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(AX),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return Z+=yield*this.parseBlockScalarHeader(),Z+=yield*this.pushSpaces(!0),yield*this.pushCount($.length-Z),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let $,Z,X=-1;do{if($=yield*this.pushNewline(),$>0)Z=yield*this.pushSpaces(!1),this.indentValue=X=Z;else Z=0;Z+=yield*this.pushSpaces(!0)}while($+Z>0);let Y=this.getLine();if(Y===null)return this.setNext("flow");if(X!==-1&&X<this.indentNext&&Y[0]!=="#"||X===0&&(Y.startsWith("---")||Y.startsWith("..."))&&b0(Y[3])){if(!(X===this.indentNext-1&&this.flowLevel===1&&(Y[0]==="]"||Y[0]==="}")))return this.flowLevel=0,yield s2.FLOW_END,yield*this.parseLineStart()}let G=0;while(Y[G]===",")G+=yield*this.pushCount(1),G+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(G+=yield*this.pushIndicators(),Y[G]){case void 0:return"flow";case"#":return yield*this.pushCount(Y.length-G),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(AX),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let z=this.charAt(1);if(this.flowKey||b0(z)||z===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let $=this.charAt(0),Z=this.buffer.indexOf($,this.pos+1);if($==="'")while(Z!==-1&&this.buffer[Z+1]==="'")Z=this.buffer.indexOf("'",Z+2);else while(Z!==-1){let G=0;while(this.buffer[Z-1-G]==="\\")G+=1;if(G%2===0)break;Z=this.buffer.indexOf('"',Z+1)}let X=this.buffer.substring(0,Z),Y=X.indexOf(`
|
|
151
151
|
`,this.pos);if(Y!==-1){while(Y!==-1){let G=this.continueScalar(Y+1);if(G===-1)break;Y=X.indexOf(`
|
|
152
|
-
`,G)}if(Y!==-1)Z=Y-(X[Y-1]==="\r"?2:1)}if(Z===-1){if(!this.atEnd)return this.setNext("quoted-scalar");Z=this.buffer.length}return yield*this.pushToIndex(Z+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let $=this.pos;while(!0){let Z=this.buffer[++$];if(Z==="+")this.blockScalarKeep=!0;else if(Z>"0"&&Z<="9")this.blockScalarIndent=Number(Z)-1;else if(Z!=="-")break}return yield*this.pushUntil((Z)=>
|
|
152
|
+
`,G)}if(Y!==-1)Z=Y-(X[Y-1]==="\r"?2:1)}if(Z===-1){if(!this.atEnd)return this.setNext("quoted-scalar");Z=this.buffer.length}return yield*this.pushToIndex(Z+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let $=this.pos;while(!0){let Z=this.buffer[++$];if(Z==="+")this.blockScalarKeep=!0;else if(Z>"0"&&Z<="9")this.blockScalarIndent=Number(Z)-1;else if(Z!=="-")break}return yield*this.pushUntil((Z)=>b0(Z)||Z==="#")}*parseBlockScalar(){let $=this.pos-1,Z=0,X;$:for(let G=this.pos;X=this.buffer[G];++G)switch(X){case" ":Z+=1;break;case`
|
|
153
153
|
`:$=G,Z=0;break;case"\r":{let z=this.buffer[G+1];if(!z&&!this.atEnd)return this.setNext("block-scalar");if(z===`
|
|
154
154
|
`)break}default:break $}if(!X&&!this.atEnd)return this.setNext("block-scalar");if(Z>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=Z;else this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let G=this.continueScalar($+1);if(G===-1)break;$=this.buffer.indexOf(`
|
|
155
155
|
`,G)}while($!==-1);if($===-1){if(!this.atEnd)return this.setNext("block-scalar");$=this.buffer.length}}let Y=$+1;X=this.buffer[Y];while(X===" ")X=this.buffer[++Y];if(X==="\t"){while(X==="\t"||X===" "||X==="\r"||X===`
|
|
156
156
|
`)X=this.buffer[++Y];$=Y-1}else if(!this.blockScalarKeep)do{let G=$-1,z=this.buffer[G];if(z==="\r")z=this.buffer[--G];let J=G;while(z===" ")z=this.buffer[--G];if(z===`
|
|
157
|
-
`&&G>=this.pos&&G+1+Z>J)$=G;else break}while(!0);return yield
|
|
157
|
+
`&&G>=this.pos&&G+1+Z>J)$=G;else break}while(!0);return yield s2.SCALAR,yield*this.pushToIndex($+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let $=this.flowLevel>0,Z=this.pos-1,X=this.pos-1,Y;while(Y=this.buffer[++X])if(Y===":"){let G=this.buffer[X+1];if(b0(G)||$&&fZ.has(G))break;Z=X}else if(b0(Y)){let G=this.buffer[X+1];if(Y==="\r")if(G===`
|
|
158
158
|
`)X+=1,Y=`
|
|
159
|
-
`,G=this.buffer[X+1];else Z=X;if(G==="#"||$&&
|
|
160
|
-
`){let z=this.continueScalar(X+1);if(z===-1)break;X=Math.max(X,z-2)}}else{if($&&
|
|
159
|
+
`,G=this.buffer[X+1];else Z=X;if(G==="#"||$&&fZ.has(G))break;if(Y===`
|
|
160
|
+
`){let z=this.continueScalar(X+1);if(z===-1)break;X=Math.max(X,z-2)}}else{if($&&fZ.has(Y))break;Z=X}if(!Y&&!this.atEnd)return this.setNext("plain-scalar");return yield s2.SCALAR,yield*this.pushToIndex(Z+1,!0),$?"flow":"doc"}*pushCount($){if($>0)return yield this.buffer.substr(this.pos,$),this.pos+=$,$;return 0}*pushToIndex($,Z){let X=this.buffer.slice(this.pos,$);if(X)return yield X,this.pos+=X.length,X.length;else if(Z)yield"";return 0}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(AX))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let $=this.flowLevel>0,Z=this.charAt(1);if(b0(Z)||$&&fZ.has(Z)){if(!$)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=!1;return(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}}return 0}*pushTag(){if(this.charAt(1)==="<"){let $=this.pos+2,Z=this.buffer[$];while(!b0(Z)&&Z!==">")Z=this.buffer[++$];return yield*this.pushToIndex(Z===">"?$+1:$,!1)}else{let $=this.pos+1,Z=this.buffer[$];while(Z)if(lq.has(Z))Z=this.buffer[++$];else if(Z==="%"&&OY.has(this.buffer[$+1])&&OY.has(this.buffer[$+2]))Z=this.buffer[$+=3];else break;return yield*this.pushToIndex($,!1)}}*pushNewline(){let $=this.buffer[this.pos];if($===`
|
|
161
161
|
`)return yield*this.pushCount(1);else if($==="\r"&&this.charAt(1)===`
|
|
162
|
-
`)return yield*this.pushCount(2);else return 0}*pushSpaces($){let Z=this.pos-1,X;do X=this.buffer[++Z];while(X===" "||$&&X==="\t");let Y=Z-this.pos;if(Y>0)yield this.buffer.substr(this.pos,Y),this.pos=Z;return Y}*pushUntil($){let Z=this.pos,X=this.buffer[Z];while(!$(X))X=this.buffer[++Z];return yield*this.pushToIndex(Z,!1)}}
|
|
162
|
+
`)return yield*this.pushCount(2);else return 0}*pushSpaces($){let Z=this.pos-1,X;do X=this.buffer[++Z];while(X===" "||$&&X==="\t");let Y=Z-this.pos;if(Y>0)yield this.buffer.substr(this.pos,Y),this.pos=Z;return Y}*pushUntil($){let Z=this.pos,X=this.buffer[Z];while(!$(X))X=this.buffer[++Z];return yield*this.pushToIndex(Z,!1)}}iq.Lexer=NY});var CX=C((nq)=>{class _Y{constructor(){this.lineStarts=[],this.addNewLine=($)=>this.lineStarts.push($),this.linePos=($)=>{let Z=0,X=this.lineStarts.length;while(Z<X){let G=Z+X>>1;if(this.lineStarts[G]<$)Z=G+1;else X=G}if(this.lineStarts[Z]===$)return{line:Z+1,col:1};if(Z===0)return{line:0,col:$};let Y=this.lineStarts[Z-1];return{line:Z,col:$-Y+1}}}}nq.LineCounter=_Y});var IX=C((tq)=>{var sq=n0("process"),PY=bZ(),oq=SX();function L$($,Z){for(let X=0;X<$.length;++X)if($[X].type===Z)return!0;return!1}function DY($){for(let Z=0;Z<$.length;++Z)switch($[Z].type){case"space":case"comment":case"newline":break;default:return Z}return-1}function RY($){switch($?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function yZ($){switch($.type){case"document":return $.start;case"block-map":{let Z=$.items[$.items.length-1];return Z.sep??Z.start}case"block-seq":return $.items[$.items.length-1].start;default:return[]}}function A1($){if($.length===0)return[];let Z=$.length;$:while(--Z>=0)switch($[Z].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break $}while($[++Z]?.type==="space");return $.splice(Z,$.length)}function EY($){if($.start.type==="flow-seq-start"){for(let Z of $.items)if(Z.sep&&!Z.value&&!L$(Z.start,"explicit-key-ind")&&!L$(Z.sep,"map-value-ind")){if(Z.key)Z.value=Z.key;if(delete Z.key,RY(Z.value))if(Z.value.end)Array.prototype.push.apply(Z.value.end,Z.sep);else Z.value.end=Z.sep;else Array.prototype.push.apply(Z.start,Z.sep);delete Z.sep}}}class AY{constructor($){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new oq.Lexer,this.onNewLine=$}*parse($,Z=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let X of this.lexer.lex($,Z))yield*this.next(X);if(!Z)yield*this.end()}*next($){if(this.source=$,sq.env.LOG_TOKENS)console.log("|",PY.prettyToken($));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=$.length;return}let Z=PY.tokenType($);if(!Z){let X=`Not a YAML token: ${$}`;yield*this.pop({type:"error",offset:this.offset,message:X,source:$}),this.offset+=$.length}else if(Z==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=Z,yield*this.step(),Z){case"newline":if(this.atNewLine=!0,this.indent=0,this.onNewLine)this.onNewLine(this.offset+$.length);break;case"space":if(this.atNewLine&&$[0]===" ")this.indent+=$.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=$.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=$.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let $=this.peek(1);if(this.type==="doc-end"&&$?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!$)return yield*this.stream();switch($.type){case"document":return yield*this.document($);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar($);case"block-scalar":return yield*this.blockScalar($);case"block-map":return yield*this.blockMap($);case"block-seq":return yield*this.blockSequence($);case"flow-collection":return yield*this.flowCollection($);case"doc-end":return yield*this.documentEnd($)}yield*this.pop()}peek($){return this.stack[this.stack.length-$]}*pop($){let Z=$??this.stack.pop();if(!Z)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield Z;else{let X=this.peek(1);if(Z.type==="block-scalar")Z.indent="indent"in X?X.indent:0;else if(Z.type==="flow-collection"&&X.type==="document")Z.indent=0;if(Z.type==="flow-collection")EY(Z);switch(X.type){case"document":X.value=Z;break;case"block-scalar":X.props.push(Z);break;case"block-map":{let Y=X.items[X.items.length-1];if(Y.value){X.items.push({start:[],key:Z,sep:[]}),this.onKeyLine=!0;return}else if(Y.sep)Y.value=Z;else{Object.assign(Y,{key:Z,sep:[]}),this.onKeyLine=!Y.explicitKey;return}break}case"block-seq":{let Y=X.items[X.items.length-1];if(Y.value)X.items.push({start:[],value:Z});else Y.value=Z;break}case"flow-collection":{let Y=X.items[X.items.length-1];if(!Y||Y.value)X.items.push({start:[],key:Z,sep:[]});else if(Y.sep)Y.value=Z;else Object.assign(Y,{key:Z,sep:[]});return}default:yield*this.pop(),yield*this.pop(Z)}if((X.type==="document"||X.type==="block-map"||X.type==="block-seq")&&(Z.type==="block-map"||Z.type==="block-seq")){let Y=Z.items[Z.items.length-1];if(Y&&!Y.sep&&!Y.value&&Y.start.length>0&&DY(Y.start)===-1&&(Z.indent===0||Y.start.every((G)=>G.type!=="comment"||G.indent<Z.indent))){if(X.type==="document")X.end=Y.start;else X.items.push({start:Y.start});Z.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let $={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")$.start.push(this.sourceToken);this.stack.push($);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document($){if($.value)return yield*this.lineEnd($);switch(this.type){case"doc-start":{if(DY($.start)!==-1)yield*this.pop(),yield*this.step();else $.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":$.start.push(this.sourceToken);return}let Z=this.startBlockValue($);if(Z)this.stack.push(Z);else yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar($){if(this.type==="map-value-ind"){let Z=yZ(this.peek(2)),X=A1(Z),Y;if($.end)Y=$.end,Y.push(this.sourceToken),delete $.end;else Y=[this.sourceToken];let G={type:"block-map",offset:$.offset,indent:$.indent,items:[{start:X,key:$,sep:Y}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=G}else yield*this.lineEnd($)}*blockScalar($){switch(this.type){case"space":case"comment":case"newline":$.props.push(this.sourceToken);return;case"scalar":if($.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let Z=this.source.indexOf(`
|
|
163
163
|
`)+1;while(Z!==0)this.onNewLine(this.offset+Z),Z=this.source.indexOf(`
|
|
164
|
-
`,Z)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap($){let Z=$.items[$.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,Z.value){let X="end"in Z.value?Z.value.end:void 0;if((Array.isArray(X)?X[X.length-1]:void 0)?.type==="comment")X?.push(this.sourceToken);else $.items.push({start:[this.sourceToken]})}else if(Z.sep)Z.sep.push(this.sourceToken);else Z.start.push(this.sourceToken);return;case"space":case"comment":if(Z.value)$.items.push({start:[this.sourceToken]});else if(Z.sep)Z.sep.push(this.sourceToken);else{if(this.atIndentedComment(Z.start,$.indent)){let Y=$.items[$.items.length-2]?.value?.end;if(Array.isArray(Y)){Array.prototype.push.apply(Y,Z.start),Y.push(this.sourceToken),$.items.pop();return}}Z.start.push(this.sourceToken)}return}if(this.indent>=$.indent){let X=!this.onKeyLine&&this.indent===$.indent,Y=X&&(Z.sep||Z.explicitKey)&&this.type!=="seq-item-ind",G=[];if(Y&&Z.sep&&!Z.value){let z=[];for(let J=0;J<Z.sep.length;++J){let Q=Z.sep[J];switch(Q.type){case"newline":z.push(J);break;case"space":break;case"comment":if(Q.indent>$.indent)z.length=0;break;default:z.length=0}}if(z.length>=2)G=Z.sep.splice(z[1])}switch(this.type){case"anchor":case"tag":if(Y||Z.value)G.push(this.sourceToken),$.items.push({start:G}),this.onKeyLine=!0;else if(Z.sep)Z.sep.push(this.sourceToken);else Z.start.push(this.sourceToken);return;case"explicit-key-ind":if(!Z.sep&&!Z.explicitKey)Z.start.push(this.sourceToken),Z.explicitKey=!0;else if(Y||Z.value)G.push(this.sourceToken),$.items.push({start:G,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(Z.explicitKey)if(!Z.sep)if(
|
|
164
|
+
`,Z)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap($){let Z=$.items[$.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,Z.value){let X="end"in Z.value?Z.value.end:void 0;if((Array.isArray(X)?X[X.length-1]:void 0)?.type==="comment")X?.push(this.sourceToken);else $.items.push({start:[this.sourceToken]})}else if(Z.sep)Z.sep.push(this.sourceToken);else Z.start.push(this.sourceToken);return;case"space":case"comment":if(Z.value)$.items.push({start:[this.sourceToken]});else if(Z.sep)Z.sep.push(this.sourceToken);else{if(this.atIndentedComment(Z.start,$.indent)){let Y=$.items[$.items.length-2]?.value?.end;if(Array.isArray(Y)){Array.prototype.push.apply(Y,Z.start),Y.push(this.sourceToken),$.items.pop();return}}Z.start.push(this.sourceToken)}return}if(this.indent>=$.indent){let X=!this.onKeyLine&&this.indent===$.indent,Y=X&&(Z.sep||Z.explicitKey)&&this.type!=="seq-item-ind",G=[];if(Y&&Z.sep&&!Z.value){let z=[];for(let J=0;J<Z.sep.length;++J){let Q=Z.sep[J];switch(Q.type){case"newline":z.push(J);break;case"space":break;case"comment":if(Q.indent>$.indent)z.length=0;break;default:z.length=0}}if(z.length>=2)G=Z.sep.splice(z[1])}switch(this.type){case"anchor":case"tag":if(Y||Z.value)G.push(this.sourceToken),$.items.push({start:G}),this.onKeyLine=!0;else if(Z.sep)Z.sep.push(this.sourceToken);else Z.start.push(this.sourceToken);return;case"explicit-key-ind":if(!Z.sep&&!Z.explicitKey)Z.start.push(this.sourceToken),Z.explicitKey=!0;else if(Y||Z.value)G.push(this.sourceToken),$.items.push({start:G,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(Z.explicitKey)if(!Z.sep)if(L$(Z.start,"newline"))Object.assign(Z,{key:null,sep:[this.sourceToken]});else{let z=A1(Z.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:z,key:null,sep:[this.sourceToken]}]})}else if(Z.value)$.items.push({start:[],key:null,sep:[this.sourceToken]});else if(L$(Z.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:G,key:null,sep:[this.sourceToken]}]});else if(RY(Z.key)&&!L$(Z.sep,"newline")){let z=A1(Z.start),J=Z.key,Q=Z.sep;Q.push(this.sourceToken),delete Z.key,delete Z.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:z,key:J,sep:Q}]})}else if(G.length>0)Z.sep=Z.sep.concat(G,this.sourceToken);else Z.sep.push(this.sourceToken);else if(!Z.sep)Object.assign(Z,{key:null,sep:[this.sourceToken]});else if(Z.value||Y)$.items.push({start:G,key:null,sep:[this.sourceToken]});else if(L$(Z.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else Z.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let z=this.flowScalar(this.type);if(Y||Z.value)$.items.push({start:G,key:z,sep:[]}),this.onKeyLine=!0;else if(Z.sep)this.stack.push(z);else Object.assign(Z,{key:z,sep:[]}),this.onKeyLine=!0;return}default:{let z=this.startBlockValue($);if(z){if(z.type==="block-seq"){if(!Z.explicitKey&&Z.sep&&!L$(Z.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(X)$.items.push({start:G});this.stack.push(z);return}}}}yield*this.pop(),yield*this.step()}*blockSequence($){let Z=$.items[$.items.length-1];switch(this.type){case"newline":if(Z.value){let X="end"in Z.value?Z.value.end:void 0;if((Array.isArray(X)?X[X.length-1]:void 0)?.type==="comment")X?.push(this.sourceToken);else $.items.push({start:[this.sourceToken]})}else Z.start.push(this.sourceToken);return;case"space":case"comment":if(Z.value)$.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(Z.start,$.indent)){let Y=$.items[$.items.length-2]?.value?.end;if(Array.isArray(Y)){Array.prototype.push.apply(Y,Z.start),Y.push(this.sourceToken),$.items.pop();return}}Z.start.push(this.sourceToken)}return;case"anchor":case"tag":if(Z.value||this.indent<=$.indent)break;Z.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==$.indent)break;if(Z.value||L$(Z.start,"seq-item-ind"))$.items.push({start:[this.sourceToken]});else Z.start.push(this.sourceToken);return}if(this.indent>$.indent){let X=this.startBlockValue($);if(X){this.stack.push(X);return}}yield*this.pop(),yield*this.step()}*flowCollection($){let Z=$.items[$.items.length-1];if(this.type==="flow-error-end"){let X;do yield*this.pop(),X=this.peek(1);while(X?.type==="flow-collection")}else if($.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!Z||Z.sep)$.items.push({start:[this.sourceToken]});else Z.start.push(this.sourceToken);return;case"map-value-ind":if(!Z||Z.value)$.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Z.sep)Z.sep.push(this.sourceToken);else Object.assign(Z,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!Z||Z.value)$.items.push({start:[this.sourceToken]});else if(Z.sep)Z.sep.push(this.sourceToken);else Z.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let Y=this.flowScalar(this.type);if(!Z||Z.value)$.items.push({start:[],key:Y,sep:[]});else if(Z.sep)this.stack.push(Y);else Object.assign(Z,{key:Y,sep:[]});return}case"flow-map-end":case"flow-seq-end":$.end.push(this.sourceToken);return}let X=this.startBlockValue($);if(X)this.stack.push(X);else yield*this.pop(),yield*this.step()}else{let X=this.peek(2);if(X.type==="block-map"&&(this.type==="map-value-ind"&&X.indent===$.indent||this.type==="newline"&&!X.items[X.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&X.type!=="flow-collection"){let Y=yZ(X),G=A1(Y);EY($);let z=$.end.splice(1,$.end.length);z.push(this.sourceToken);let J={type:"block-map",offset:$.offset,indent:$.indent,items:[{start:G,key:$,sep:z}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=J}else yield*this.lineEnd($)}}flowScalar($){if(this.onNewLine){let Z=this.source.indexOf(`
|
|
165
165
|
`)+1;while(Z!==0)this.onNewLine(this.offset+Z),Z=this.source.indexOf(`
|
|
166
|
-
`,Z)+1}return{type:$,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue($){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let Z=v6($),X=I1(Z);return X.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:X,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let Z=v6($),X=I1(Z);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:X,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment($,Z){if(this.type!=="comment")return!1;if(this.indent<=Z)return!1;return $.every((X)=>X.type==="newline"||X.type==="space")}*documentEnd($){if(this.type!=="doc-mode"){if($.end)$.end.push(this.sourceToken);else $.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd($){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if($.end)$.end.push(this.sourceToken);else $.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}sq.Parser=RY});var jY=C((zT)=>{var AY=M9(),tq=n2(),$4=r2(),eq=CX(),$T=m(),ZT=C9(),SY=I9();function CY($){let Z=$.prettyErrors!==!1;return{lineCounter:$.lineCounter||Z&&new ZT.LineCounter||null,prettyErrors:Z}}function XT($,Z={}){let{lineCounter:X,prettyErrors:Y}=CY(Z),G=new SY.Parser(X?.addNewLine),z=new AY.Composer(Z),J=Array.from(z.compose(G.parse($)));if(Y&&X)for(let Q of J)Q.errors.forEach($4.prettifyError($,X)),Q.warnings.forEach($4.prettifyError($,X));if(J.length>0)return J;return Object.assign([],{empty:!0},z.streamInfo())}function IY($,Z={}){let{lineCounter:X,prettyErrors:Y}=CY(Z),G=new SY.Parser(X?.addNewLine),z=new AY.Composer(Z),J=null;for(let Q of z.compose(G.parse($),!0,$.length))if(!J)J=Q;else if(J.options.logLevel!=="silent"){J.errors.push(new $4.YAMLParseError(Q.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(Y&&X)J.errors.forEach($4.prettifyError($,X)),J.warnings.forEach($4.prettifyError($,X));return J}function YT($,Z,X){let Y=void 0;if(typeof Z==="function")Y=Z;else if(X===void 0&&Z&&typeof Z==="object")X=Z;let G=IY($,X);if(!G)return null;if(G.warnings.forEach((z)=>eq.warn(G.options.logLevel,z)),G.errors.length>0)if(G.options.logLevel!=="silent")throw G.errors[0];else G.errors=[];return G.toJS(Object.assign({reviver:Y},X))}function GT($,Z,X){let Y=null;if(typeof Z==="function"||Array.isArray(Z))Y=Z;else if(X===void 0&&Z)X=Z;if(typeof X==="string")X=X.length;if(typeof X==="number"){let G=Math.round(X);X=G<1?void 0:G>8?{indent:8}:{indent:G}}if($===void 0){let{keepUndefined:G}=X??Z??{};if(!G)return}if($T.isDocument($)&&!Y)return $.toString(X);return new tq.Document($,Y,X).toString(X)}zT.parse=YT;zT.parseAllDocuments=XT;zT.parseDocument=IY;zT.stringify=GT});var kY=C((_T)=>{var HT=M9(),KT=n2(),BT=Y9(),j9=r2(),UT=k2(),M$=m(),qT=q$(),TT=o(),FT=F$(),LT=L$(),wT=f6(),MT=S9(),OT=C9(),NT=I9(),g6=jY(),xY=j2();_T.Composer=HT.Composer;_T.Document=KT.Document;_T.Schema=BT.Schema;_T.YAMLError=j9.YAMLError;_T.YAMLParseError=j9.YAMLParseError;_T.YAMLWarning=j9.YAMLWarning;_T.Alias=UT.Alias;_T.isAlias=M$.isAlias;_T.isCollection=M$.isCollection;_T.isDocument=M$.isDocument;_T.isMap=M$.isMap;_T.isNode=M$.isNode;_T.isPair=M$.isPair;_T.isScalar=M$.isScalar;_T.isSeq=M$.isSeq;_T.Pair=qT.Pair;_T.Scalar=TT.Scalar;_T.YAMLMap=FT.YAMLMap;_T.YAMLSeq=LT.YAMLSeq;_T.CST=wT;_T.Lexer=MT.Lexer;_T.LineCounter=OT.LineCounter;_T.Parser=NT.Parser;_T.parse=g6.parse;_T.parseAllDocuments=g6.parseAllDocuments;_T.parseDocument=g6.parseDocument;_T.stringify=g6.stringify;_T.visit=xY.visit;_T.visitAsync=xY.visitAsync});var P3=J3(_3(),1),{program:M1,createCommand:uO,createArgument:mO,createOption:dO,CommanderError:cO,InvalidArgumentError:lO,InvalidOptionArgumentError:pO,Command:iO,Argument:aO,Option:wX,Help:nO}=P3.default;var D3={name:"@pickled-dev/cli",version:"0.25.0",description:"Test what agents actually understand about your product",module:"dist/index.js",type:"module",bin:{pickled:"./dist/index.js"},files:["dist"],scripts:{dev:"bun run ./src/index.ts",build:"bun build ./src/index.ts --outdir ./dist --target bun --minify --external @anthropic-ai/claude-agent-sdk",release:"semantic-release"},dependencies:{commander:"^14.0.2",chalk:"^5.6.2","@anthropic-ai/claude-agent-sdk":"^0.3.0"},devDependencies:{"@pickled-dev/config":"workspace:*","@pickled-dev/core":"workspace:*","semantic-release":"^25.0.2","@semantic-release/commit-analyzer":"^13.0.1","@semantic-release/exec":"^7.1.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^12.0.2","@semantic-release/release-notes-generator":"^14.0.3"}};import PO from"path";var h0={category:"cli",provider:"claude-code",model:"sonnet"},MX=["Read","Glob","Grep","Bash"],OX=["Edit","MultiEdit","Write","NotebookEdit"];var bY=J3(kY(),1);async function j1($){let Z=`${$}/pickled.yml`,X=Bun.file(Z);if(!await X.exists())throw Error(`pickled.yml not found in ${$}`);let Y;try{let G=await X.text();Y=bY.default.parse(G)}catch(G){throw Error(`Failed to parse pickled.yml: ${G}`)}return Y=x9(Y),eT(Y),Y}var tT=/\$\{([A-Z_][A-Z0-9_]*)\}/g;function x9($){if(typeof $==="string")return $.replace(tT,(Z,X)=>process.env[X]??"");if(Array.isArray($))return $.map(x9);if($!==null&&typeof $==="object"){let Z={};for(let[X,Y]of Object.entries($))Z[X]=x9(Y);return Z}return $}function eT($){if(!$.tool?.name)throw Error("pickled.yml: 'tool.name' is required");if(!Array.isArray($.scenarios)||$.scenarios.length===0)throw Error("pickled.yml: 'scenarios' must be a non-empty array");if($.docs?.sources)for(let[X,Y]of Object.entries($.docs.sources)){if(X==="none")throw Error('pickled.yml: docs.sources cannot use the reserved id "none". That name represents the no-context matrix cell (model prior with toolset:none, or open discovery with toolset:web). Rename this source.');JF(X,Y)}if($.toolsets){if(typeof $.toolsets!=="object"||Array.isArray($.toolsets))throw Error("pickled.yml: 'toolsets' must be an object mapping name to configuration");for(let[X,Y]of Object.entries($.toolsets))if(typeof Y!=="object"||Y===null||Array.isArray(Y))throw Error(`pickled.yml: toolsets["${X}"] must be an object`)}if($.targets)for(let[X,Y]of Object.entries($.targets)){if(Y.systemPrompt!==void 0)throw Error(`pickled.yml: target "${X}" sets 'systemPrompt', which bypasses the citation contract. Remove it; custom prompts are not supported in citation mode.`);if(Y.provider==="codex-cli"){if(!Y.model)throw Error(`pickled.yml: target "${X}" (codex-cli) requires an explicit 'model' field. Codex's default model can change without notice; pin it for reproducible evals.`);if(Y.maxTurns!==void 0)throw Error(`pickled.yml: target "${X}" (codex-cli) sets 'maxTurns', but the codex CLI does not support a turn cap. Remove the field.`)}if(Y.category==="api"){if(!Y.model)throw Error(`pickled.yml: target "${X}" (api/${Y.provider}) requires an explicit 'model' field. Pickled does not substitute a default; reproducible evals depend on pinning the model.`);let G=["allowedTools","disallowedTools","mcpServers","permissionMode","maxTurns","maxThinkingTokens","maxBudgetUsd"];for(let z of G)if(Y[z]!==void 0)throw Error(`pickled.yml: target "${X}" (api/${Y.provider}) sets '${z}', which only applies to CLI/Agent SDK targets. Remove the field; API targets accept only model/temperature/maxTokens/threshold.`);if(Y.workspaceContext!==void 0)throw Error(`pickled.yml: target "${X}" (api/${Y.provider}) sets 'workspaceContext', which only applies to IDE targets. Remove the field.`)}}let Z=new Set(Object.keys($.docs?.sources??{}));for(let X of $.scenarios){if(!X.name||!X.prompt)throw Error("pickled.yml: every scenario needs 'name' and 'prompt'");if(X.requiredSources!==void 0){if(!Array.isArray(X.requiredSources))throw Error(`pickled.yml: scenario "${X.name}" has non-array 'requiredSources'. Omit the field to skip citation scoring, or set [] for "any cited source counts".`);for(let Y of X.requiredSources)if(!Z.has(Y))throw Error(`pickled.yml: scenario "${X.name}" references unknown source "${Y}". Declared sources: ${[...Z].join(", ")||"(none)"}`)}VF(X.name,X.traps),zF(X.name,X.compareSurfaces,Z),ZF(X.name,X.matrix,Z,new Set(Object.keys($.targets??{})),new Set(Object.keys($.toolsets??{none:{}}))),XF(X.name,X.expected),YF(X.name,X.verifiers,Z),GF(X)}$F($)}function $F($){if(!$.docs?.sources)return;let Z=[];for(let[Y,G]of Object.entries($.docs.sources)){if(typeof G==="string")continue;let z=G.audit?.traps;if(Array.isArray(z))Z.push({id:Y,list:z})}if(Z.length===0)return;let X=new Map;for(let Y of $.scenarios)for(let G of Y.traps??[]){let z=X.get(G.id);if(z!==void 0)throw Error(`pickled.yml: trap id "${G.id}" is declared in both scenario "${z}" and scenario "${Y.name}". Globally unique trap ids are required when any source uses list-form audit.traps suppression. Rename one of the traps.`);X.set(G.id,Y.name)}for(let{id:Y,list:G}of Z)for(let z of G)if(!X.has(z)){let J=[...X.keys()].join(", ")||"(none)";throw Error(`pickled.yml: docs.sources["${Y}"].audit.traps lists unknown trap id "${z}". Declared trap ids: ${J}`)}}function ZF($,Z,X,Y,G){if(Z===void 0)return;if(typeof Z!=="object"||Array.isArray(Z))throw Error(`pickled.yml: scenario "${$}" matrix must be an object with optional interfaces/sources/toolsets arrays`);let z=(J,Q,W)=>{let V=Z[J];if(V===void 0)return;if(!Array.isArray(V))throw Error(`pickled.yml: scenario "${$}" matrix.${J} must be an array of ${W} names`);if(V.length===0)throw Error(`pickled.yml: scenario "${$}" matrix.${J} cannot be empty (omit the field to use defaults)`);for(let K of V){if(typeof K!=="string")throw Error(`pickled.yml: scenario "${$}" matrix.${J} entries must be strings`);if(!Q.has(K))throw Error(`pickled.yml: scenario "${$}" matrix.${J} references unknown ${W} "${K}". Declared: ${[...Q].join(", ")||"(none)"}`)}};z("interfaces",Y,"target"),z("sources",new Set([...X,"none"]),"source"),z("toolsets",G,"toolset")}function XF($,Z){if(Z===void 0)return;if(typeof Z!=="object"||Array.isArray(Z))throw Error(`pickled.yml: scenario "${$}" expected must be an object with optional includes/excludes arrays`);let X=(Y)=>{let G=Z[Y];if(G===void 0)return;if(!Array.isArray(G))throw Error(`pickled.yml: scenario "${$}" expected.${Y} must be an array of strings`);if(G.length===0)throw Error(`pickled.yml: scenario "${$}" expected.${Y} cannot be empty (omit the field instead)`);for(let z=0;z<G.length;z++)if(typeof G[z]!=="string"||G[z].length===0)throw Error(`pickled.yml: scenario "${$}" expected.${Y}[${z}] must be a non-empty string`)};X("includes"),X("excludes")}function YF($,Z,X){if(Z===void 0)return;if(typeof Z!=="object"||Array.isArray(Z))throw Error(`pickled.yml: scenario "${$}" verifiers must be an object`);let Y=Z.sources;if(Y===void 0)return;if(!Array.isArray(Y))throw Error(`pickled.yml: scenario "${$}" verifiers.sources must be an array of source IDs`);for(let G of Y){if(typeof G!=="string")throw Error(`pickled.yml: scenario "${$}" verifiers.sources entries must be strings`);if(!X.has(G))throw Error(`pickled.yml: scenario "${$}" verifiers.sources references unknown source "${G}"`)}}function GF($){let Z=$.requiredSources!==void 0,X=$.expected!==void 0&&($.expected.includes!==void 0&&$.expected.includes.length>0||$.expected.excludes!==void 0&&$.expected.excludes.length>0),Y=$.traps!==void 0&&$.traps.length>0;if(!Z&&!X&&!Y)throw Error(`pickled.yml: scenario "${$.name}" must declare at least one of requiredSources, expected.includes/excludes, or traps. A scenario with nothing to check has no verdict.`);let G=($.matrix?.toolsets??[]).filter((z)=>z!=="none");if(G.length>0&&!X&&!Y)throw Error(`pickled.yml: scenario "${$.name}" declares non-none toolsets [${G.join(", ")}] but has neither expected.includes/excludes nor traps. Non-none cells skip the citation contract because the source is not injected, so requiredSources alone leaves them with no actionable answer contract. Add expected or traps, or restrict matrix.toolsets to ["none"].`)}function zF($,Z,X){if(Z===void 0)return;if(!Array.isArray(Z))throw Error(`pickled.yml: scenario "${$}" compareSurfaces must be an array of source-id lists`);if(Z.length===0)throw Error(`pickled.yml: scenario "${$}" compareSurfaces cannot be empty (use a non-empty list of surfaces, or remove the field)`);for(let Y=0;Y<Z.length;Y++){let G=Z[Y];if(!Array.isArray(G))throw Error(`pickled.yml: scenario "${$}" compareSurfaces[${Y}] must be an array of source ids`);if(G.length===0)throw Error(`pickled.yml: scenario "${$}" compareSurfaces[${Y}] must be a non-empty list of source ids`);for(let z of G){if(typeof z!=="string")throw Error(`pickled.yml: scenario "${$}" compareSurfaces[${Y}] entries must be string source ids`);if(!X.has(z))throw Error(`pickled.yml: scenario "${$}" compareSurfaces[${Y}] references unknown source "${z}". Declared sources: ${[...X].join(", ")||"(none)"}`)}}}function JF($,Z){if(typeof Z==="string"){if(Z.length===0)throw Error(`pickled.yml: docs.sources["${$}"] string form must be a non-empty file path or URL`);return}if(!Z||typeof Z!=="object")throw Error(`pickled.yml: docs.sources["${$}"] must be a string (path/URL) or an object with a 'path' field`);let X=Z;if(typeof X.path!=="string"||X.path.length===0)throw Error(`pickled.yml: docs.sources["${$}"] object form requires a non-empty 'path' field`);if(X.audit!==void 0){if(typeof X.audit!=="object"||X.audit===null)throw Error(`pickled.yml: docs.sources["${$}"].audit must be an object`);let Y=X.audit;if(Y.traps!==void 0){let G=Y.traps;if(typeof G==="boolean");else if(Array.isArray(G)){if(G.length===0)throw Error(`pickled.yml: docs.sources["${$}"].audit.traps cannot be an empty array; use true (scan all) or false (skip all) instead`);for(let z=0;z<G.length;z++)if(typeof G[z]!=="string")throw Error(`pickled.yml: docs.sources["${$}"].audit.traps[${z}] must be a string trap id`)}else throw Error(`pickled.yml: docs.sources["${$}"].audit.traps must be a boolean or an array of trap ids`)}for(let G of Object.keys(Y))if(G!=="traps")throw Error(`pickled.yml: docs.sources["${$}"].audit has unknown field "${G}"`)}if(X.type!==void 0){if(X.type!=="file"&&X.type!=="url"&&X.type!=="codebase")throw Error(`pickled.yml: docs.sources["${$}"].type must be "file", "url", or "codebase"`)}if(X.type==="codebase"){if(typeof X.path==="string"&&X.path.split("/").includes(".."))throw Error(`pickled.yml: docs.sources["${$}"].path must not contain ".." segments. Codebase loader stays within the project root.`);if(X.exclude!==void 0){if(!Array.isArray(X.exclude))throw Error(`pickled.yml: docs.sources["${$}"].exclude must be an array of glob patterns`);for(let Y=0;Y<X.exclude.length;Y++)if(typeof X.exclude[Y]!=="string")throw Error(`pickled.yml: docs.sources["${$}"].exclude[${Y}] must be a string glob pattern`)}if(X.maxBytes!==void 0){if(typeof X.maxBytes!=="number"||!Number.isFinite(X.maxBytes)||X.maxBytes<=0)throw Error(`pickled.yml: docs.sources["${$}"].maxBytes must be a positive number of bytes`)}}else{if(X.exclude!==void 0)throw Error(`pickled.yml: docs.sources["${$}"].exclude only applies to type: codebase sources`);if(X.maxBytes!==void 0)throw Error(`pickled.yml: docs.sources["${$}"].maxBytes only applies to type: codebase sources`)}for(let Y of Object.keys(X))if(Y!=="path"&&Y!=="audit"&&Y!=="type"&&Y!=="exclude"&&Y!=="maxBytes")throw Error(`pickled.yml: docs.sources["${$}"] has unknown field "${Y}"`)}var QF=new Set(["g","y"]),WF=new Set(["i","m","s","u","v"]);function VF($,Z){if(Z===void 0)return;if(!Array.isArray(Z))throw Error(`pickled.yml: scenario "${$}" has non-array 'traps'`);let X=new Set;for(let Y of Z){if(!Y.id||typeof Y.id!=="string")throw Error(`pickled.yml: scenario "${$}" has a trap missing 'id'`);if(X.has(Y.id))throw Error(`pickled.yml: scenario "${$}" has duplicate trap id "${Y.id}"`);if(X.add(Y.id),!Y.reason||typeof Y.reason!=="string")throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" requires non-empty 'reason'`);if(Y.auditSeverity!==void 0&&Y.auditSeverity!=="warning"&&Y.auditSeverity!=="error")throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" auditSeverity must be "warning" or "error"`);let G=typeof Y.match==="string",z=typeof Y.pattern==="string";if(G===z)throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" must set exactly one of 'match' or 'pattern'`);if(G){if(Y.match==="")throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" has empty 'match'`);if(Y.flags!==void 0)throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" sets 'flags' without 'pattern'`)}else{let J=Y.pattern;if(typeof J!=="string")throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" must set 'pattern'`);if(J==="")throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" has empty 'pattern'`);if(Y.flags!==void 0){if(typeof Y.flags!=="string")throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" has non-string 'flags'`);for(let Q of Y.flags){if(QF.has(Q))throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" uses forbidden regex flag "${Q}" (g and y are not allowed)`);if(!WF.has(Q))throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" uses unsupported regex flag "${Q}"`)}}try{new RegExp(J,Y.flags??"")}catch(Q){throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" has invalid regex pattern: ${Q instanceof Error?Q.message:Q}`)}}}}function k9($,Z){let X=new Set([...Object.keys($.targets??{}),"default"]);if(!X.has(Z)){let Y=[...X].sort().join(", ");throw Error(`Unknown target: "${Z}". Available targets: ${Y}`)}return{...$,matrix:{...$.matrix,target:[Z]},scenarios:$.scenarios.filter((Y)=>!Y.target||Y.target===Z)}}function b9($){if(typeof $==="string")return{path:$,auditTraps:!0};return{path:$.path,auditTraps:$.audit?.traps??!0}}function h6($){let{config:Z,files:X,pairs:Y,findings:G}=$,z=[],J=G.filter((H)=>H.severity==="error").length,Q=G.filter((H)=>H.severity==="warning").length;if(z.push(`# Agent-context audit
|
|
166
|
+
`,Z)+1}return{type:$,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue($){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let Z=yZ($),X=A1(Z);return X.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:X,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let Z=yZ($),X=A1(Z);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:X,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment($,Z){if(this.type!=="comment")return!1;if(this.indent<=Z)return!1;return $.every((X)=>X.type==="newline"||X.type==="space")}*documentEnd($){if(this.type!=="doc-mode"){if($.end)$.end.push(this.sourceToken);else $.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd($){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if($.end)$.end.push(this.sourceToken);else $.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}tq.Parser=AY});var xY=C((QT)=>{var SY=wX(),$T=p2(),o2=i2(),ZT=C9(),XT=m(),YT=CX(),CY=IX();function IY($){let Z=$.prettyErrors!==!1;return{lineCounter:$.lineCounter||Z&&new YT.LineCounter||null,prettyErrors:Z}}function GT($,Z={}){let{lineCounter:X,prettyErrors:Y}=IY(Z),G=new CY.Parser(X?.addNewLine),z=new SY.Composer(Z),J=Array.from(z.compose(G.parse($)));if(Y&&X)for(let Q of J)Q.errors.forEach(o2.prettifyError($,X)),Q.warnings.forEach(o2.prettifyError($,X));if(J.length>0)return J;return Object.assign([],{empty:!0},z.streamInfo())}function jY($,Z={}){let{lineCounter:X,prettyErrors:Y}=IY(Z),G=new CY.Parser(X?.addNewLine),z=new SY.Composer(Z),J=null;for(let Q of z.compose(G.parse($),!0,$.length))if(!J)J=Q;else if(J.options.logLevel!=="silent"){J.errors.push(new o2.YAMLParseError(Q.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(Y&&X)J.errors.forEach(o2.prettifyError($,X)),J.warnings.forEach(o2.prettifyError($,X));return J}function zT($,Z,X){let Y=void 0;if(typeof Z==="function")Y=Z;else if(X===void 0&&Z&&typeof Z==="object")X=Z;let G=jY($,X);if(!G)return null;if(G.warnings.forEach((z)=>ZT.warn(G.options.logLevel,z)),G.errors.length>0)if(G.options.logLevel!=="silent")throw G.errors[0];else G.errors=[];return G.toJS(Object.assign({reviver:Y},X))}function JT($,Z,X){let Y=null;if(typeof Z==="function"||Array.isArray(Z))Y=Z;else if(X===void 0&&Z)X=Z;if(typeof X==="string")X=X.length;if(typeof X==="number"){let G=Math.round(X);X=G<1?void 0:G>8?{indent:8}:{indent:G}}if($===void 0){let{keepUndefined:G}=X??Z??{};if(!G)return}if(XT.isDocument($)&&!Y)return $.toString(X);return new $T.Document($,Y,X).toString(X)}QT.parse=zT;QT.parseAllDocuments=GT;QT.parseDocument=jY;QT.stringify=JT});var bY=C((DT)=>{var UT=wX(),BT=p2(),qT=YX(),jX=i2(),TT=I2(),M$=m(),FT=B$(),LT=t(),MT=T$(),wT=F$(),OT=bZ(),NT=SX(),_T=CX(),PT=IX(),vZ=xY(),kY=S2();DT.Composer=UT.Composer;DT.Document=BT.Document;DT.Schema=qT.Schema;DT.YAMLError=jX.YAMLError;DT.YAMLParseError=jX.YAMLParseError;DT.YAMLWarning=jX.YAMLWarning;DT.Alias=TT.Alias;DT.isAlias=M$.isAlias;DT.isCollection=M$.isCollection;DT.isDocument=M$.isDocument;DT.isMap=M$.isMap;DT.isNode=M$.isNode;DT.isPair=M$.isPair;DT.isScalar=M$.isScalar;DT.isSeq=M$.isSeq;DT.Pair=FT.Pair;DT.Scalar=LT.Scalar;DT.YAMLMap=MT.YAMLMap;DT.YAMLSeq=wT.YAMLSeq;DT.CST=OT;DT.Lexer=NT.Lexer;DT.LineCounter=_T.LineCounter;DT.Parser=PT.Parser;DT.parse=vZ.parse;DT.parseAllDocuments=vZ.parseAllDocuments;DT.parseDocument=vZ.parseDocument;DT.stringify=vZ.stringify;DT.visit=kY.visit;DT.visitAsync=kY.visitAsync});var D3=Q3(P3(),1),{program:F1,createCommand:cO,createArgument:lO,createOption:pO,CommanderError:iO,InvalidArgumentError:aO,InvalidOptionArgumentError:nO,Command:rO,Argument:sO,Option:M9,Help:oO}=D3.default;var E3={name:"@pickled-dev/cli",version:"0.26.0",description:"Test what agents actually understand about your product",module:"dist/index.js",type:"module",bin:{pickled:"./dist/index.js"},files:["dist"],scripts:{dev:"bun run ./src/index.ts",build:"bun build ./src/index.ts --outdir ./dist --target bun --minify --external @anthropic-ai/claude-agent-sdk",release:"semantic-release"},dependencies:{commander:"^14.0.2",chalk:"^5.6.2","@anthropic-ai/claude-agent-sdk":"^0.3.0"},devDependencies:{"@pickled-dev/config":"workspace:*","@pickled-dev/core":"workspace:*","semantic-release":"^25.0.2","@semantic-release/commit-analyzer":"^13.0.1","@semantic-release/exec":"^7.1.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^12.0.2","@semantic-release/release-notes-generator":"^14.0.3"}};import RO from"path";var v0={category:"cli",provider:"claude-code",model:"sonnet"},w9=["Read","Glob","Grep","Bash"],O9=["Edit","MultiEdit","Write","NotebookEdit"];var yY=Q3(bY(),1);async function S1($){let Z=`${$}/pickled.yml`,X=Bun.file(Z);if(!await X.exists())throw Error(`pickled.yml not found in ${$}`);let Y;try{let G=await X.text();Y=yY.default.parse(G)}catch(G){throw Error(`Failed to parse pickled.yml: ${G}`)}return Y=xX(Y),ZF(Y),Y}var $F=/\$\{([A-Z_][A-Z0-9_]*)\}/g;function xX($){if(typeof $==="string")return $.replace($F,(Z,X)=>process.env[X]??"");if(Array.isArray($))return $.map(xX);if($!==null&&typeof $==="object"){let Z={};for(let[X,Y]of Object.entries($))Z[X]=xX(Y);return Z}return $}function ZF($){if(!$.tool?.name)throw Error("pickled.yml: 'tool.name' is required");if(!Array.isArray($.scenarios)||$.scenarios.length===0)throw Error("pickled.yml: 'scenarios' must be a non-empty array");if($.docs?.sources)for(let[X,Y]of Object.entries($.docs.sources)){if(X==="none")throw Error('pickled.yml: docs.sources cannot use the reserved id "none". That name represents the no-context matrix cell (model prior with toolset:none, or open discovery with toolset:web). Rename this source.');WF(X,Y)}if($.toolsets){if(typeof $.toolsets!=="object"||Array.isArray($.toolsets))throw Error("pickled.yml: 'toolsets' must be an object mapping name to configuration");for(let[X,Y]of Object.entries($.toolsets))if(typeof Y!=="object"||Y===null||Array.isArray(Y))throw Error(`pickled.yml: toolsets["${X}"] must be an object`)}if($.targets)for(let[X,Y]of Object.entries($.targets)){if(Y.systemPrompt!==void 0)throw Error(`pickled.yml: target "${X}" sets 'systemPrompt', which bypasses the citation contract. Remove it; custom prompts are not supported in citation mode.`);if(Y.provider==="codex-cli"){if(!Y.model)throw Error(`pickled.yml: target "${X}" (codex-cli) requires an explicit 'model' field. Codex's default model can change without notice; pin it for reproducible evals.`);if(Y.maxTurns!==void 0)throw Error(`pickled.yml: target "${X}" (codex-cli) sets 'maxTurns', but the codex CLI does not support a turn cap. Remove the field.`)}if(Y.category==="api"){if(!Y.model)throw Error(`pickled.yml: target "${X}" (api/${Y.provider}) requires an explicit 'model' field. Pickled does not substitute a default; reproducible evals depend on pinning the model.`);let G=["allowedTools","disallowedTools","mcpServers","permissionMode","maxTurns","maxThinkingTokens","maxBudgetUsd"];for(let z of G)if(Y[z]!==void 0)throw Error(`pickled.yml: target "${X}" (api/${Y.provider}) sets '${z}', which only applies to CLI/Agent SDK targets. Remove the field; API targets accept only model/temperature/maxTokens/threshold.`);if(Y.workspaceContext!==void 0)throw Error(`pickled.yml: target "${X}" (api/${Y.provider}) sets 'workspaceContext', which only applies to IDE targets. Remove the field.`)}}let Z=new Set(Object.keys($.docs?.sources??{}));for(let X of $.scenarios){if(!X.name||!X.prompt)throw Error("pickled.yml: every scenario needs 'name' and 'prompt'");if(X.requiredSources!==void 0){if(!Array.isArray(X.requiredSources))throw Error(`pickled.yml: scenario "${X.name}" has non-array 'requiredSources'. Omit the field to skip citation scoring, or set [] for "any cited source counts".`);for(let Y of X.requiredSources)if(!Z.has(Y))throw Error(`pickled.yml: scenario "${X.name}" references unknown source "${Y}". Declared sources: ${[...Z].join(", ")||"(none)"}`)}KF(X.name,X.traps),QF(X.name,X.compareSurfaces,Z),YF(X.name,X.matrix,Z,new Set(Object.keys($.targets??{})),new Set(Object.keys($.toolsets??{none:{}}))),GF(X.name,X.expected),zF(X.name,X.verifiers,Z),JF(X)}XF($)}function XF($){if(!$.docs?.sources)return;let Z=[];for(let[Y,G]of Object.entries($.docs.sources)){if(typeof G==="string")continue;let z=G.audit?.traps;if(Array.isArray(z))Z.push({id:Y,list:z})}if(Z.length===0)return;let X=new Map;for(let Y of $.scenarios)for(let G of Y.traps??[]){let z=X.get(G.id);if(z!==void 0)throw Error(`pickled.yml: trap id "${G.id}" is declared in both scenario "${z}" and scenario "${Y.name}". Globally unique trap ids are required when any source uses list-form audit.traps suppression. Rename one of the traps.`);X.set(G.id,Y.name)}for(let{id:Y,list:G}of Z)for(let z of G)if(!X.has(z)){let J=[...X.keys()].join(", ")||"(none)";throw Error(`pickled.yml: docs.sources["${Y}"].audit.traps lists unknown trap id "${z}". Declared trap ids: ${J}`)}}function YF($,Z,X,Y,G){if(Z===void 0)return;if(typeof Z!=="object"||Array.isArray(Z))throw Error(`pickled.yml: scenario "${$}" matrix must be an object with optional interfaces/sources/toolsets arrays`);let z=(J,Q,W)=>{let V=Z[J];if(V===void 0)return;if(!Array.isArray(V))throw Error(`pickled.yml: scenario "${$}" matrix.${J} must be an array of ${W} names`);if(V.length===0)throw Error(`pickled.yml: scenario "${$}" matrix.${J} cannot be empty (omit the field to use defaults)`);for(let K of V){if(typeof K!=="string")throw Error(`pickled.yml: scenario "${$}" matrix.${J} entries must be strings`);if(!Q.has(K))throw Error(`pickled.yml: scenario "${$}" matrix.${J} references unknown ${W} "${K}". Declared: ${[...Q].join(", ")||"(none)"}`)}};z("interfaces",Y,"target"),z("sources",new Set([...X,"none"]),"source"),z("toolsets",G,"toolset")}var fY=["includes","excludes","symbols","paths","options","constraints"];function GF($,Z){if(Z===void 0)return;if(typeof Z!=="object"||Array.isArray(Z))throw Error(`pickled.yml: scenario "${$}" expected must be an object with optional ${fY.join("/")} arrays`);let X=(Y)=>{let G=Z[Y];if(G===void 0)return;if(!Array.isArray(G))throw Error(`pickled.yml: scenario "${$}" expected.${Y} must be an array of strings`);if(G.length===0)throw Error(`pickled.yml: scenario "${$}" expected.${Y} cannot be empty (omit the field instead)`);for(let z=0;z<G.length;z++)if(typeof G[z]!=="string"||G[z].length===0)throw Error(`pickled.yml: scenario "${$}" expected.${Y}[${z}] must be a non-empty string`)};for(let Y of fY)X(Y)}function zF($,Z,X){if(Z===void 0)return;if(typeof Z!=="object"||Array.isArray(Z))throw Error(`pickled.yml: scenario "${$}" verifiers must be an object`);let Y=Z.sources;if(Y===void 0)return;if(!Array.isArray(Y))throw Error(`pickled.yml: scenario "${$}" verifiers.sources must be an array of source IDs`);for(let G of Y){if(typeof G!=="string")throw Error(`pickled.yml: scenario "${$}" verifiers.sources entries must be strings`);if(!X.has(G))throw Error(`pickled.yml: scenario "${$}" verifiers.sources references unknown source "${G}"`)}}function JF($){let Z=$.requiredSources!==void 0,X=["includes","excludes","symbols","paths","options","constraints"],Y=$.expected!==void 0&&X.some((J)=>{let Q=$.expected?.[J];return Q!==void 0&&Q.length>0}),G=$.traps!==void 0&&$.traps.length>0;if(!Z&&!Y&&!G)throw Error(`pickled.yml: scenario "${$.name}" must declare at least one of requiredSources, expected checks (includes/excludes/symbols/paths/options/constraints), or traps. A scenario with nothing to check has no verdict.`);let z=($.matrix?.toolsets??[]).filter((J)=>J!=="none");if(z.length>0&&!Y&&!G)throw Error(`pickled.yml: scenario "${$.name}" declares non-none toolsets [${z.join(", ")}] but has no expected checks or traps. Non-none cells skip the citation contract because the source is not injected, so requiredSources alone leaves them with no actionable answer contract. Add expected (any of includes/excludes/symbols/paths/options/constraints) or traps, or restrict matrix.toolsets to ["none"].`)}function QF($,Z,X){if(Z===void 0)return;if(!Array.isArray(Z))throw Error(`pickled.yml: scenario "${$}" compareSurfaces must be an array of source-id lists`);if(Z.length===0)throw Error(`pickled.yml: scenario "${$}" compareSurfaces cannot be empty (use a non-empty list of surfaces, or remove the field)`);for(let Y=0;Y<Z.length;Y++){let G=Z[Y];if(!Array.isArray(G))throw Error(`pickled.yml: scenario "${$}" compareSurfaces[${Y}] must be an array of source ids`);if(G.length===0)throw Error(`pickled.yml: scenario "${$}" compareSurfaces[${Y}] must be a non-empty list of source ids`);for(let z of G){if(typeof z!=="string")throw Error(`pickled.yml: scenario "${$}" compareSurfaces[${Y}] entries must be string source ids`);if(!X.has(z))throw Error(`pickled.yml: scenario "${$}" compareSurfaces[${Y}] references unknown source "${z}". Declared sources: ${[...X].join(", ")||"(none)"}`)}}}function WF($,Z){if(typeof Z==="string"){if(Z.length===0)throw Error(`pickled.yml: docs.sources["${$}"] string form must be a non-empty file path or URL`);return}if(!Z||typeof Z!=="object")throw Error(`pickled.yml: docs.sources["${$}"] must be a string (path/URL) or an object with a 'path' field`);let X=Z;if(typeof X.path!=="string"||X.path.length===0)throw Error(`pickled.yml: docs.sources["${$}"] object form requires a non-empty 'path' field`);if(X.audit!==void 0){if(typeof X.audit!=="object"||X.audit===null)throw Error(`pickled.yml: docs.sources["${$}"].audit must be an object`);let Y=X.audit;if(Y.traps!==void 0){let G=Y.traps;if(typeof G==="boolean");else if(Array.isArray(G)){if(G.length===0)throw Error(`pickled.yml: docs.sources["${$}"].audit.traps cannot be an empty array; use true (scan all) or false (skip all) instead`);for(let z=0;z<G.length;z++)if(typeof G[z]!=="string")throw Error(`pickled.yml: docs.sources["${$}"].audit.traps[${z}] must be a string trap id`)}else throw Error(`pickled.yml: docs.sources["${$}"].audit.traps must be a boolean or an array of trap ids`)}for(let G of Object.keys(Y))if(G!=="traps")throw Error(`pickled.yml: docs.sources["${$}"].audit has unknown field "${G}"`)}if(X.type!==void 0){if(X.type!=="file"&&X.type!=="url"&&X.type!=="codebase")throw Error(`pickled.yml: docs.sources["${$}"].type must be "file", "url", or "codebase"`)}if(X.type==="codebase"){if(typeof X.path==="string"&&X.path.split("/").includes(".."))throw Error(`pickled.yml: docs.sources["${$}"].path must not contain ".." segments. Codebase loader stays within the project root.`);if(X.exclude!==void 0){if(!Array.isArray(X.exclude))throw Error(`pickled.yml: docs.sources["${$}"].exclude must be an array of glob patterns`);for(let Y=0;Y<X.exclude.length;Y++)if(typeof X.exclude[Y]!=="string")throw Error(`pickled.yml: docs.sources["${$}"].exclude[${Y}] must be a string glob pattern`)}if(X.maxBytes!==void 0){if(typeof X.maxBytes!=="number"||!Number.isFinite(X.maxBytes)||X.maxBytes<=0)throw Error(`pickled.yml: docs.sources["${$}"].maxBytes must be a positive number of bytes`)}}else{if(X.exclude!==void 0)throw Error(`pickled.yml: docs.sources["${$}"].exclude only applies to type: codebase sources`);if(X.maxBytes!==void 0)throw Error(`pickled.yml: docs.sources["${$}"].maxBytes only applies to type: codebase sources`)}for(let Y of Object.keys(X))if(Y!=="path"&&Y!=="audit"&&Y!=="type"&&Y!=="exclude"&&Y!=="maxBytes")throw Error(`pickled.yml: docs.sources["${$}"] has unknown field "${Y}"`)}var VF=new Set(["g","y"]),HF=new Set(["i","m","s","u","v"]);function KF($,Z){if(Z===void 0)return;if(!Array.isArray(Z))throw Error(`pickled.yml: scenario "${$}" has non-array 'traps'`);let X=new Set;for(let Y of Z){if(!Y.id||typeof Y.id!=="string")throw Error(`pickled.yml: scenario "${$}" has a trap missing 'id'`);if(X.has(Y.id))throw Error(`pickled.yml: scenario "${$}" has duplicate trap id "${Y.id}"`);if(X.add(Y.id),!Y.reason||typeof Y.reason!=="string")throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" requires non-empty 'reason'`);if(Y.auditSeverity!==void 0&&Y.auditSeverity!=="warning"&&Y.auditSeverity!=="error")throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" auditSeverity must be "warning" or "error"`);let G=typeof Y.match==="string",z=typeof Y.pattern==="string";if(G===z)throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" must set exactly one of 'match' or 'pattern'`);if(G){if(Y.match==="")throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" has empty 'match'`);if(Y.flags!==void 0)throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" sets 'flags' without 'pattern'`)}else{let J=Y.pattern;if(typeof J!=="string")throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" must set 'pattern'`);if(J==="")throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" has empty 'pattern'`);if(Y.flags!==void 0){if(typeof Y.flags!=="string")throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" has non-string 'flags'`);for(let Q of Y.flags){if(VF.has(Q))throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" uses forbidden regex flag "${Q}" (g and y are not allowed)`);if(!HF.has(Q))throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" uses unsupported regex flag "${Q}"`)}}try{new RegExp(J,Y.flags??"")}catch(Q){throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" has invalid regex pattern: ${Q instanceof Error?Q.message:Q}`)}}}}function kX($,Z){let X=new Set([...Object.keys($.targets??{}),"default"]);if(!X.has(Z)){let Y=[...X].sort().join(", ");throw Error(`Unknown target: "${Z}". Available targets: ${Y}`)}return{...$,matrix:{...$.matrix,target:[Z]},scenarios:$.scenarios.filter((Y)=>!Y.target||Y.target===Z)}}function bX($){if(typeof $==="string")return{path:$,auditTraps:!0};return{path:$.path,auditTraps:$.audit?.traps??!0}}function gZ($){let{config:Z,files:X,pairs:Y,findings:G}=$,z=[],J=G.filter((H)=>H.severity==="error").length,Q=G.filter((H)=>H.severity==="warning").length;if(z.push(`# Agent-context audit
|
|
167
167
|
`),z.push(`Target: \`${Z.targetRepo}\``),z.push(`Budgets: root \u2264 ${Z.budgets.rootLines} lines, nested warn at ${Z.budgets.nestedWarnLines} lines.`),z.push(`Found ${X.length} agent-doc files. ${J} error(s), ${Q} warning(s).
|
|
168
168
|
`),z.push(`## Inventory
|
|
169
169
|
`),X.length===0)z.push(`No agent-doc files found.
|
|
170
|
-
`);else{z.push("| File | Lines | Kind | Notes |"),z.push("|---|---|---|---|");let H=[...X].sort((B
|
|
170
|
+
`);else{z.push("| File | Lines | Kind | Notes |"),z.push("|---|---|---|---|");let H=[...X].sort((U,B)=>B.lineCount-U.lineCount);for(let U of H){let B=!U.relPath.includes("/"),T=vY(U.lineCount,B,Z),F=U.isSymlink?`symlink \u2192 ${U.symlinkTarget?.replace(`${Z.targetRepo}/`,"")??"?"}`:"file";z.push(`| \`${U.relPath}\` | ${U.lineCount} | ${F} | ${T} |`)}z.push("")}if(z.push(`## AGENTS.md / CLAUDE.md pairs
|
|
171
171
|
`),Y.length===0)z.push(`No pairs found.
|
|
172
172
|
`);else{z.push("| Directory | A | C | Class | Detail |"),z.push("|---|---|---|---|---|");for(let H of Y)z.push(`| \`${H.dir||"(root)"}\` | ${H.agentsExists?"\u2713":"\xB7"} | ${H.claudeExists?"\u2713":"\xB7"} | ${H.classification} | ${H.detail} |`);z.push("")}let W=X.filter((H)=>!H.isSymlink&&H.brokenPathRefs.length+H.brokenImports.length>0);if(z.push(`## Broken references
|
|
173
173
|
`),W.length===0)z.push(`None detected.
|
|
174
174
|
`);else for(let H of W){if(z.push(`### \`${H.relPath}\`
|
|
175
|
-
`),H.brokenPathRefs.length>0){z.push("Broken path references:");for(let
|
|
175
|
+
`),H.brokenPathRefs.length>0){z.push("Broken path references:");for(let U of H.brokenPathRefs)z.push(` - \`${U}\``);z.push("")}if(H.brokenImports.length>0){z.push("Broken `@`-imports:");for(let U of H.brokenImports)z.push(` - \`${U}\``);z.push("")}}let V=X.filter((H)=>!H.isSymlink&&H.unresolvedCommands.length>0);if(z.push(`## Unresolved package-manager commands (advisory)
|
|
176
176
|
`),z.push("Looks like a script command in markdown that did not match anything in the target `package.json` `scripts` or the `knownCommands` allowlist. Workspace-filtered commands check against root scripts, so false positives are expected. Review, do not fail CI on this.\n"),V.length===0)z.push(`None flagged.
|
|
177
177
|
`);else for(let H of V){z.push(`### \`${H.relPath}\`
|
|
178
|
-
`);for(let
|
|
178
|
+
`);for(let U of H.unresolvedCommands)z.push(` - \`${U}\``);z.push("")}let K=X.filter((H)=>{if(H.isSymlink)return!1;return!H.relPath.includes("/")?H.lineCount>Z.budgets.rootLines:H.lineCount>Z.budgets.nestedWarnLines});if(z.push(`## Section breakdown for files over budget
|
|
179
179
|
`),K.length===0)z.push(`All files within budget.
|
|
180
180
|
`);else for(let H of K){z.push(`### \`${H.relPath}\` (${H.lineCount} lines)
|
|
181
181
|
`),z.push(`Largest H2 sections (lines including any subsections):
|
|
182
|
-
`),z.push("| Section | Lines |"),z.push("|---|---|");for(let
|
|
182
|
+
`),z.push("| Section | Lines |"),z.push("|---|---|");for(let U of H.sections.slice(0,10))z.push(`| ${U.header} | ${U.lines} |`);z.push("")}if(z.push(`## Registered-source trap matches
|
|
183
183
|
`),z.push("Catches stale claims in `docs.sources` against declared traps. Per-source suppression: `audit.traps: false` skips all traps; `audit.traps: [<trap_id>, ...]` skips only the listed traps and keeps scanning the rest.\n"),$.sourceTrapMatches.length===0)z.push(`None.
|
|
184
184
|
`);else{for(let H of $.sourceTrapMatches)z.push(`- **${H.sourceId}** (\`${H.sourcePath}:L${H.line}\`) \u2014 trap \`${H.trapId}\` matched \`${H.matched}\` (${H.severity})`),z.push(` - reason: ${H.trapReason}`),z.push(` - fix: remove the stale claim, retire the trap, set \`audit.traps: ['${H.trapId}']\` to suppress just this one (other traps still apply), or set \`audit.traps: false\` if the source is deliberately stale`);z.push("")}return z.join(`
|
|
185
|
-
`)}function
|
|
186
|
-
`)}function
|
|
187
|
-
`;if(K.push(
|
|
185
|
+
`)}function hZ($){return JSON.stringify($,null,2)}function uZ($){let{config:Z,files:X,pairs:Y,findings:G}=$,z=[],J=G.filter((H)=>H.severity==="error").length,Q=G.filter((H)=>H.severity==="warning").length;if(z.push("pickled audit"),z.push(`Target: ${Z.targetRepo}`),z.push(`Budgets: root \u2264 ${Z.budgets.rootLines} lines, nested warn at ${Z.budgets.nestedWarnLines} lines.`),z.push(`Found: ${X.length} agent-doc file(s) \xB7 ${J} error(s) \xB7 ${Q} warning(s)`),z.push(""),z.push("Inventory"),X.length===0)z.push(" none");else{let H=[...X].sort((B,T)=>T.lineCount-B.lineCount),U=Math.max(...H.map((B)=>B.relPath.length));for(let B of H){let T=!B.relPath.includes("/"),F=vY(B.lineCount,T,Z),M=B.isSymlink?`symlink \u2192 ${B.symlinkTarget?.replace(`${Z.targetRepo}/`,"")??"?"}`:"file",O=`${B.lineCount}`.padStart(4),N=B.relPath.padEnd(U),_=F?` (${F})`:"";z.push(` ${N} ${O} lines ${M}${_}`)}}if(z.push(""),z.push("AGENTS.md / CLAUDE.md pairs"),Y.length===0)z.push(" none");else for(let H of Y){let U=H.dir||"(root)";z.push(` ${U}: ${H.classification} \xB7 ${H.detail}`)}z.push("");let W=X.filter((H)=>!H.isSymlink&&H.brokenPathRefs.length+H.brokenImports.length>0);if(z.push("Broken references"),W.length===0)z.push(" none");else for(let H of W){z.push(` ${H.relPath}:`);for(let U of H.brokenPathRefs)z.push(` path: ${U}`);for(let U of H.brokenImports)z.push(` @-import: ${U}`)}z.push("");let V=X.filter((H)=>!H.isSymlink&&H.unresolvedCommands.length>0);if(z.push("Unresolved package-manager commands (advisory)"),V.length===0)z.push(" none");else for(let H of V){z.push(` ${H.relPath}:`);for(let U of H.unresolvedCommands)z.push(` ${U}`)}z.push("");let K=X.filter((H)=>{if(H.isSymlink)return!1;return!H.relPath.includes("/")?H.lineCount>Z.budgets.rootLines:H.lineCount>Z.budgets.nestedWarnLines});if(z.push("Section breakdown for files over budget"),K.length===0)z.push(" all files within budget");else for(let H of K){z.push(` ${H.relPath} (${H.lineCount} lines):`);for(let U of H.sections.slice(0,10))z.push(` ${U.header.padEnd(40)} ${U.lines} lines`)}if(z.push(""),z.push("Registered-source trap matches"),$.sourceTrapMatches.length===0)z.push(" none");else for(let H of $.sourceTrapMatches){let U=H.severity==="error"?"error":"warning";z.push(` [${U}] ${H.sourceId} (${H.sourcePath}:L${H.line}): trap ${H.trapId} matched "${H.matched}"`),z.push(` reason: ${H.trapReason}`),z.push(` fix: remove the stale claim, retire the trap, set audit.traps: ['${H.trapId}'] to suppress just this trap (others still apply), or set audit.traps: false if deliberately stale`)}return z.join(`
|
|
186
|
+
`)}function vY($,Z,X){if(Z&&$>X.budgets.rootLines)return`over root budget (${$} > ${X.budgets.rootLines})`;if(!Z&&$>X.budgets.nestedWarnLines)return`over nested-warn (${$} > ${X.budgets.nestedWarnLines})`;return""}import{existsSync as I1,lstatSync as cY,readFileSync as lZ,readlinkSync as DF,statSync as EF}from"fs";import{dirname as pZ,isAbsolute as RF,join as fX,relative as AF,resolve as yX}from"path";var{Glob:dY}=globalThis.Bun;var mZ=["node_modules/**","**/node_modules/**",".git/**","**/.git/**","dist/**","**/dist/**","build/**","**/build/**",".next/**","**/.next/**",".source/**","**/.source/**","out/**","**/out/**",".turbo/**","**/.turbo/**",".cache/**","**/.cache/**",".runs/**","**/.runs/**","coverage/**","**/coverage/**","**/__fixtures__/**","**/tests/**/fixture/**","**/tests/**/fixtures/**","**/test/**/fixture/**","**/test/**/fixtures/**"],C1={targetRepo:".",budgets:{rootLines:120,nestedWarnLines:200},ignore:mZ,intentionalDifferentPairs:[],knownCommands:[]};function dZ($){if(!$)return C1;return{targetRepo:$.targetRepo??C1.targetRepo,budgets:{rootLines:$.budgets?.rootLines??C1.budgets.rootLines,nestedWarnLines:$.budgets?.nestedWarnLines??C1.budgets.nestedWarnLines},ignore:$.ignore??mZ,intentionalDifferentPairs:$.intentionalDifferentPairs??[],knownCommands:$.knownCommands??[]}}import{existsSync as wF}from"fs";import{join as OF,resolve as NF}from"path";function w$($){let Z=[],X=[];for(let Y of $.traps){let G=UF($.response,Y);if(G)Z.push(G);else X.push(Y.id)}return{fired:Z,avoided:X}}function UF($,Z){if(Z.match!==void 0){let X=$.indexOf(Z.match);if(X===-1)return null;return{id:Z.id,reason:Z.reason,matched:Z.match,snippet:gY($,X,Z.match.length),index:X}}if(Z.pattern!==void 0){let Y=new RegExp(Z.pattern,Z.flags??"").exec($);if(!Y)return null;return{id:Z.id,reason:Z.reason,matched:Y[0],snippet:gY($,Y.index,Y[0].length),index:Y.index}}return null}function gY($,Z,X){let Y=Math.max(0,Z-40),G=Math.min($.length,Z+X+40),z=$.slice(Y,G).replace(/\s+/g," ").trim();if(Y>0)z=`...${z}`;if(G<$.length)z=`${z}...`;return z}import cZ from"path";var{Glob:hY}=globalThis.Bun;var BF=262144,qF=4194304;function TF($){return $.startsWith("http://")||$.startsWith("https://")}async function FF($,Z,X){let Y=await fetch(Z);if(!Y.ok)throw Error(`Failed to fetch source "${$}" from ${Z}: ${Y.status} ${Y.statusText}`);let G=await Y.text();return{id:$,source:Z,content:G,name:new URL(Z).hostname+new URL(Z).pathname,type:"url",auditTraps:X}}async function LF($,Z,X,Y){let G=cZ.isAbsolute(Z)?Z:cZ.resolve(X,Z),z=Bun.file(G);if(!await z.exists())throw Error(`Source "${$}" not found at ${G}`);let J=await z.text();return{id:$,source:Z,content:J,name:cZ.basename(G),type:"file",auditTraps:Y}}async function MF($,Z,X,Y,G){let z=new hY(Z.path),J=(Z.exclude??[]).map((B)=>new hY(B)),Q=[];for await(let B of z.scan({cwd:X,onlyFiles:!0,followSymlinks:!1})){if(J.some((T)=>T.match(B)))continue;Q.push(B)}Q.sort();let W=Z.maxBytes??BF,V=Math.max(W,qF),K=[],H=0;for(let B of Q){let T=cZ.resolve(X,B),F=await Bun.file(T).text(),M=`// === ${B} ===
|
|
187
|
+
`;if(K.push(M,F),!F.endsWith(`
|
|
188
188
|
`))K.push(`
|
|
189
|
-
`);if(H+=
|
|
190
|
-
`)X++;return X}var
|
|
191
|
-
`)?K:K+1;return{relPath:Z,absPath:X,isSymlink:z,symlinkTarget:J,realRelPath:Q,lineCount:H,brokenPathRefs:
|
|
192
|
-
`),X=[],Y=null;if(Z.forEach((G,z)=>{if(/^##\s+/.test(G)){if(Y)X.push({header:Y.header,lines:z-Y.start});Y={header:G.replace(/^##\s+/,"").trim(),start:z}}}),Y){let G=Y;X.push({header:G.header,lines:Z.length-G.start})}return X.sort((G,z)=>z.lines-G.lines)}function vF($){if($.length===0||$.length>160)return!1;if(!$.includes("/"))return!1;if(/\s/.test($))return!1;if(/^https?:\/\//.test($))return!1;if(/[*?{}[\]<>]/.test($))return!1;if($.startsWith("@"))return!1;if($.startsWith("~/"))return!1;if(/^[a-z]+:\/\//i.test($))return!1;if(/^cdn\./.test($)||/^unpkg\./.test($)||/^npm\./.test($))return!1;if(/^\/[a-z]/.test($)&&/(?:icon|image|img|asset|file|path)/i.test($))return!1;if(/^(cd|pnpm|npm|yarn|bun|node|git|ls|cat|grep|find|sed|awk|mkdir|rm|mv|cp|echo|export|source|sudo|brew|docker|curl|wget)\b/.test($))return!1;return/[a-zA-Z0-9_.-]\/[a-zA-Z0-9_.-]/.test($)}function gF($){return $.replace(/```[\s\S]*?```/g,"")}function hF($,Z){let X=new Map;for(let z of $){let J=z.relPath.split("/").pop()??"";if(J!=="AGENTS.md"&&J!=="CLAUDE.md")continue;let Q=i6(z.relPath),W=X.get(Q)??{};if(J==="AGENTS.md")W.agents=z;if(J==="CLAUDE.md")W.claude=z;X.set(Q,W)}let Y=new Set(Z.intentionalDifferentPairs),G=[];for(let[z,J]of X){let Q=!!J.agents,W=!!J.claude;if(!Q&&!W)continue;if(!Q||!W){G.push({dir:z,agentsExists:Q,claudeExists:W,classification:"single",detail:Q?"only AGENTS.md":"only CLAUDE.md"});continue}let{agents:V,claude:K}=J,H=`${V.relPath}:${K.relPath}`,B=`${K.relPath}:${V.relPath}`;if(Y.has(H)||Y.has(B)){G.push({dir:z,agentsExists:Q,claudeExists:W,classification:"intentional-different",detail:`allowlisted: ${V.lineCount}L vs ${K.lineCount}L`});continue}if(V.isSymlink&&V.symlinkTarget===K.absPath||K.isSymlink&&K.symlinkTarget===V.absPath){let w=V.isSymlink?"CLAUDE.md":"AGENTS.md";G.push({dir:z,agentsExists:Q,claudeExists:W,classification:"linked",detail:`canonical: ${w}`});continue}let F=p6(V.absPath,"utf8"),T=p6(K.absPath,"utf8");if(F===T)G.push({dir:z,agentsExists:Q,claudeExists:W,classification:"unexpected-duplicate",detail:`byte-for-byte duplicate (${V.lineCount}L), not symlinked`});else G.push({dir:z,agentsExists:Q,claudeExists:W,classification:"unexpected-duplicate",detail:`divergent (${V.lineCount}L vs ${K.lineCount}L), not in intentional-different allowlist`})}return G.sort((z,J)=>z.dir.localeCompare(J.dir)),G}function uF($,Z,X){let Y=[];for(let G of $){if(G.isSymlink)continue;for(let Q of G.brokenImports)Y.push({severity:"error",category:"broken-import",file:G.relPath,message:`broken @-import: ${Q}`});for(let Q of G.brokenPathRefs)Y.push({severity:"error",category:"broken-path-ref",file:G.relPath,message:`broken path reference: ${Q}`});for(let Q of G.unresolvedCommands)Y.push({severity:"warning",category:"unresolved-command",file:G.relPath,message:`unresolved command: ${Q}`});let z=!G.relPath.includes("/"),J=z?X.budgets.rootLines:X.budgets.nestedWarnLines;if(G.lineCount>J)Y.push({severity:"warning",category:"over-budget",file:G.relPath,message:`${G.lineCount} lines exceeds ${z?"root":"nested"} budget of ${J}`})}for(let G of Z)if(G.classification==="unexpected-duplicate"){let z=G.detail.startsWith("divergent")?"error":"warning";Y.push({severity:z,category:z==="error"?"divergent-pair":"duplicate-pair",file:G.dir||"(root)",message:`AGENTS.md / CLAUDE.md ${G.detail}`})}return Y}function e0($){let Z=$.confidence;if($.error)return{icon:"\u2717",label:"Error",confidence:Z,tone:"error"};if($.traps.fired.length>0)return{icon:"\u2717",label:"Trap fired",confidence:Z,tone:"error"};if($.answerable==="YES")return{icon:"\u2713",label:Z>=90?"Well grounded":"Grounded",confidence:Z,tone:"success"};if($.answerable==="PARTIAL")return{icon:"\u26A0",label:"Partially grounded",confidence:Z,tone:"warning"};return{icon:"\u2717",label:"Ungrounded",confidence:Z,tone:"error"}}function mF($){let Z=2166136261;for(let X=0;X<$.length;X++)Z^=$.charCodeAt(X),Z=Math.imul(Z,16777619);return Z>>>0}function dF($){let Z=$>>>0;return()=>{Z=Z+1831565813>>>0;let X=Z;return X=Math.imul(X^X>>>15,X|1),X^=X+Math.imul(X^X>>>7,X|61),((X^X>>>14)>>>0)/4294967296}}function dY($,Z,X){if(Z<=0)return[];let Y=dF(mF(X)),G=new Map,z=[];for(let Q of $){if(!G.has(Q.scenario))G.set(Q.scenario,[]),z.push(Q.scenario);G.get(Q.scenario).push(Q)}let J=[];for(let Q of z){let W=G.get(Q);if(W.length<=Z){J.push(...W);continue}let V=W.slice();for(let H=0;H<Z;H++){let B=H+Math.floor(Y()*(V.length-H));[V[H],V[B]]=[V[B],V[H]]}let K=new Set(V.slice(0,Z));for(let H of W)if(K.has(H))J.push(H)}return J}function v9($){let Z=cF($);if(Z===null)return[];let X=[],Y=/^\s*-\s+\[([^\]]+)\]\s*(.*)$/gm,G=Y.exec(Z);while(G!==null)X.push({id:G[1].trim(),note:G[2].trim()||void 0}),G=Y.exec(Z);return X}function cF($){let X=/^##\s+Sources\s*$/im.exec($);if(!X)return null;let Y=X.index+X[0].length,G=$.slice(Y),z=/^##\s+/m.exec(G);return z?G.slice(0,z.index):G}function b1($){let Z=v9($.response),X=new Set(Z.map((B)=>B.id)),Y=new Set($.registeredIds),G=new Set($.requiredSources),z=[...X],J=[...G].filter((B)=>!X.has(B)),Q=[...X].filter((B)=>!Y.has(B)),W=[...G],V,K,H;if(z.length===0)V="NO",K=0,H="No citations in response";else if(Q.length===z.length)V="NO",K=0,H=`All cited sources are unknown: ${Q.join(", ")}`;else if(J.length===0&&Q.length===0)V="YES",K=100,H=W.length>0?`All required sources cited: ${W.join(", ")}`:`Cited registered sources: ${z.join(", ")}`;else{V="PARTIAL";let B=W.length>0?W.length:1,U=W.length-J.length,F=W.length>0?U/B*100:60,T=Q.length*15;K=Math.max(0,Math.min(100,Math.round(F-T)));let w=[];if(J.length>0)w.push(`missing: ${J.join(", ")}`);if(Q.length>0)w.push(`unknown: ${Q.join(", ")}`);H=w.join("; ")}return{answerable:V,confidence:K,reason:H,citations:{cited:z,required:W,missing:J,unknown:Q}}}function n6($){let Z=$.expected,X=(Z?.includes??[]).map((J)=>({value:J,satisfied:$.response.includes(J)})),Y=(Z?.excludes??[]).map((J)=>({value:J,satisfied:!$.response.includes(J)})),G=X.filter((J)=>J.satisfied).length+Y.filter((J)=>J.satisfied).length,z=X.length+Y.length;return{includes:X,excludes:Y,satisfied:G,total:z}}var n$="0.40.1";var cY=!1,r$=void 0,g9=void 0,lF=void 0,pF=void 0,iF=void 0,lY=void 0,aF=void 0,r6=void 0,h9=void 0,pY=void 0,u9=void 0,s6=void 0,iY=void 0;function aY($,Z={auto:!1}){if(cY)throw Error(`you must \`import '@anthropic-ai/sdk/shims/${$.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(r$)throw Error(`can't \`import '@anthropic-ai/sdk/shims/${$.kind}'\` after \`import '@anthropic-ai/sdk/shims/${r$}'\``);cY=Z.auto,r$=$.kind,g9=$.fetch,lF=$.Request,pF=$.Response,iF=$.Headers,lY=$.FormData,aF=$.Blob,r6=$.File,h9=$.ReadableStream,pY=$.getMultipartRequestOptions,u9=$.getDefaultAgent,s6=$.fileFromPath,iY=$.isFsReadStream}class m9{constructor($){this.body=$}get[Symbol.toStringTag](){return"MultipartBody"}}function nY({manuallyImported:$}={}){let Z=$?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n- `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n- `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n",X,Y,G,z;try{X=fetch,Y=Request,G=Response,z=Headers}catch(J){throw Error(`this environment is missing the following Web Fetch API type: ${J.message}. ${Z}`)}return{kind:"web",fetch:X,Request:Y,Response:G,Headers:z,FormData:typeof FormData<"u"?FormData:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${Z}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${Z}`)}},File:typeof File<"u"?File:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${Z}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${Z}`)}},getMultipartRequestOptions:async(J,Q)=>({...Q,body:new m9(J)}),getDefaultAgent:(J)=>{return},fileFromPath:()=>{throw Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:(J)=>!1}}import{ReadStream as rF}from"fs";function rY(){let $=nY();function Z(X){return X instanceof rF}return{...$,isFsReadStream:Z}}var d9=()=>{if(!r$)aY(rY(),{auto:!0})};d9();class v extends Error{}class e extends v{constructor($,Z,X,Y){super(`${e.makeMessage($,Z,X)}`);this.status=$,this.headers=Y,this.request_id=Y?.["request-id"],this.error=Z}static makeMessage($,Z,X){let Y=Z?.message?typeof Z.message==="string"?Z.message:JSON.stringify(Z.message):Z?JSON.stringify(Z):X;if($&&Y)return`${$} ${Y}`;if($)return`${$} status code (no body)`;if(Y)return Y;return"(no status code or body)"}static generate($,Z,X,Y){if(!$||!Y)return new s$({message:X,cause:z8(Z)});let G=Z;if($===400)return new o6($,G,X,Y);if($===401)return new t6($,G,X,Y);if($===403)return new e6($,G,X,Y);if($===404)return new $8($,G,X,Y);if($===409)return new Z8($,G,X,Y);if($===422)return new X8($,G,X,Y);if($===429)return new Y8($,G,X,Y);if($>=500)return new G8($,G,X,Y);return new e($,G,X,Y)}}class H0 extends e{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class s$ extends e{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class X4 extends s${constructor({message:$}={}){super({message:$??"Request timed out."})}}class o6 extends e{}class t6 extends e{}class e6 extends e{}class $8 extends e{}class Z8 extends e{}class X8 extends e{}class Y8 extends e{}class G8 extends e{}var J8=function($,Z,X,Y,G){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!G:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call($,X):G?G.value=X:Z.set($,X),X},o$=function($,Z,X,Y){if(X==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Y:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call($):Y?Y.value:Z.get($)},_0;class N${constructor(){_0.set(this,void 0),this.buffer=new Uint8Array,J8(this,_0,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?new TextEncoder().encode($):$,X=new Uint8Array(this.buffer.length+Z.length);X.set(this.buffer),X.set(Z,this.buffer.length),this.buffer=X;let Y=[],G;while((G=oF(this.buffer,o$(this,_0,"f")))!=null){if(G.carriage&&o$(this,_0,"f")==null){J8(this,_0,G.index,"f");continue}if(o$(this,_0,"f")!=null&&(G.index!==o$(this,_0,"f")+1||G.carriage)){Y.push(this.decodeText(this.buffer.slice(0,o$(this,_0,"f")-1))),this.buffer=this.buffer.slice(o$(this,_0,"f")),J8(this,_0,null,"f");continue}let z=o$(this,_0,"f")!==null?G.preceding-1:G.preceding,J=this.decodeText(this.buffer.slice(0,z));Y.push(J),this.buffer=this.buffer.slice(G.index),J8(this,_0,null,"f")}return Y}decodeText($){if($==null)return"";if(typeof $==="string")return $;if(typeof Buffer<"u"){if($ instanceof Buffer)return $.toString();if($ instanceof Uint8Array)return Buffer.from($).toString();throw new v(`Unexpected: received non-Uint8Array (${$.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if($ instanceof Uint8Array||$ instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode($);throw new v(`Unexpected: received non-Uint8Array/ArrayBuffer (${$.constructor.name}) in a web platform. Please report this error.`)}throw new v("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length)return[];return this.decode(`
|
|
193
|
-
`)}}
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],G}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,X,Y]=$L($,":");if(Y.startsWith(" "))Y=Y.substring(1);if(Z==="event")this.event=Y;else if(Z==="data")this.data.push(Y);return null}}function $L($,Z){let X=$.indexOf(Z);if(X!==-1)return[$.substring(0,X),Z,$.substring(X+Z.length)];return[$,"",""]}var ZL=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function",XL=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&G4($),G4=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function";async function tY($,Z,X){if($=await $,XL($))return $;if(ZL($)){let G=await $.blob();Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()??"unknown_file");let z=G4(G)?[await G.arrayBuffer()]:[G];return new r6(z,Z,X)}let Y=await YL($);if(Z||(Z=zL($)??"unknown_file"),!X?.type){let G=Y[0]?.type;if(typeof G==="string")X={...X,type:G}}return new r6(Y,Z,X)}async function YL($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(G4($))Z.push(await $.arrayBuffer());else if(JL($))for await(let X of $)Z.push(X);else throw Error(`Unexpected data type: ${typeof $}; constructor: ${$?.constructor?.name}; props: ${GL($)}`);return Z}function GL($){return`[${Object.getOwnPropertyNames($).map((X)=>`"${X}"`).join(", ")}]`}function zL($){return l9($.name)||l9($.filename)||l9($.path)?.split(/[\\/]/).pop()}var l9=($)=>{if(typeof $==="string")return $;if(typeof Buffer<"u"&&$ instanceof Buffer)return String($);return},JL=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function",p9=($)=>$&&typeof $==="object"&&$.body&&$[Symbol.toStringTag]==="MultipartBody";var WL=function($,Z,X,Y,G){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!G:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call($,X):G?G.value=X:Z.set($,X),X},VL=function($,Z,X,Y){if(X==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Y:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call($):Y?Y.value:Z.get($)},Q8;d9();async function YG($){let{response:Z}=$;if($.options.stream){if(f1("response",Z.status,Z.url,Z.headers,Z.body),$.options.__streamClass)return $.options.__streamClass.fromSSEResponse(Z,$.controller);return P0.fromSSEResponse(Z,$.controller)}if(Z.status===204)return null;if($.options.__binaryResponse)return Z;let Y=Z.headers.get("content-type")?.split(";")[0]?.trim();if(Y?.includes("application/json")||Y?.endsWith("+json")){let J=await Z.json();return f1("response",Z.status,Z.url,Z.headers,J),GG(J,Z)}let z=await Z.text();return f1("response",Z.status,Z.url,Z.headers,z),z}function GG($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}class V8 extends Promise{constructor($,Z=YG){super((X)=>{X(null)});this.responsePromise=$,this.parseResponse=Z}_thenUnwrap($){return new V8(this.responsePromise,async(Z)=>GG($(await this.parseResponse(Z),Z),Z.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,Z]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:Z,request_id:Z.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}class a9{constructor({baseURL:$,maxRetries:Z=2,timeout:X=600000,httpAgent:Y,fetch:G}){this.baseURL=$,this.maxRetries=i9("maxRetries",Z),this.timeout=i9("timeout",X),this.httpAgent=Y,this.fetch=G??g9}authHeaders($){return{}}defaultHeaders($){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...UL(),...this.authHeaders($)}}validateHeaders($,Z){}defaultIdempotencyKey(){return`stainless-node-retry-${wL()}`}get($,Z){return this.methodRequest("get",$,Z)}post($,Z){return this.methodRequest("post",$,Z)}patch($,Z){return this.methodRequest("patch",$,Z)}put($,Z){return this.methodRequest("put",$,Z)}delete($,Z){return this.methodRequest("delete",$,Z)}methodRequest($,Z,X){return this.request(Promise.resolve(X).then(async(Y)=>{let G=Y&&G4(Y?.body)?new DataView(await Y.body.arrayBuffer()):Y?.body instanceof DataView?Y.body:Y?.body instanceof ArrayBuffer?new DataView(Y.body):Y&&ArrayBuffer.isView(Y?.body)?new DataView(Y.body.buffer):Y?.body;return{method:$,path:Z,...Y,body:G}}))}getAPIList($,Z,X){return this.requestAPIList(Z,{method:"get",path:$,...X})}calculateContentLength($){if(typeof $==="string"){if(typeof Buffer<"u")return Buffer.byteLength($,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode($).length.toString()}else if(ArrayBuffer.isView($))return $.byteLength.toString();return null}buildRequest($,{retryCount:Z=0}={}){let X={...$},{method:Y,path:G,query:z,headers:J={}}=X,Q=ArrayBuffer.isView(X.body)||X.__binaryRequest&&typeof X.body==="string"?X.body:p9(X.body)?X.body.body:X.body?JSON.stringify(X.body,null,2):null,W=this.calculateContentLength(Q),V=this.buildURL(G,z);if("timeout"in X)i9("timeout",X.timeout);X.timeout=X.timeout??this.timeout;let K=X.httpAgent??this.httpAgent??u9(V),H=X.timeout+1000;if(typeof K?.options?.timeout==="number"&&H>(K.options.timeout??0))K.options.timeout=H;if(this.idempotencyHeader&&Y!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();J[this.idempotencyHeader]=$.idempotencyKey}let B=this.buildHeaders({options:X,headers:J,contentLength:W,retryCount:Z});return{req:{method:Y,...Q&&{body:Q},headers:B,...K&&{agent:K},signal:X.signal??null},url:V,timeout:X.timeout}}buildHeaders({options:$,headers:Z,contentLength:X,retryCount:Y}){let G={};if(X)G["content-length"]=X;let z=this.defaultHeaders($);if(XG(G,z),XG(G,Z),p9($.body)&&r$!=="node")delete G["content-type"];if(W8(z,"x-stainless-retry-count")===void 0&&W8(Z,"x-stainless-retry-count")===void 0)G["x-stainless-retry-count"]=String(Y);if(W8(z,"x-stainless-timeout")===void 0&&W8(Z,"x-stainless-timeout")===void 0&&$.timeout)G["x-stainless-timeout"]=String(Math.trunc($.timeout/1000));return this.validateHeaders(G,Z),G}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new v("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:Z,options:X}){}parseHeaders($){return!$?{}:(Symbol.iterator in $)?Object.fromEntries(Array.from($).map((Z)=>[...Z])):{...$}}makeStatusError($,Z,X,Y){return e.generate($,Z,X,Y)}request($,Z=null){return new V8(this.makeRequest($,Z))}async makeRequest($,Z){let X=await $,Y=X.maxRetries??this.maxRetries;if(Z==null)Z=Y;await this.prepareOptions(X);let{req:G,url:z,timeout:J}=this.buildRequest(X,{retryCount:Y-Z});if(await this.prepareRequest(G,{url:z,options:X}),f1("request",z,X,G.headers),X.signal?.aborted)throw new H0;let Q=new AbortController,W=await this.fetchWithTimeout(z,G,J,Q).catch(z8);if(W instanceof Error){if(X.signal?.aborted)throw new H0;if(Z)return this.retryRequest(X,Z);if(W.name==="AbortError")throw new X4;throw new s$({cause:W})}let V=c9(W.headers);if(!W.ok){if(Z&&this.shouldRetry(W)){let T=`retrying, ${Z} attempts remaining`;return f1(`response (error; ${T})`,W.status,z,V),this.retryRequest(X,Z,V)}let K=await W.text().catch((T)=>z8(T).message),H=qL(K),B=H?void 0:K;throw f1(`response (error; ${Z?"(error; no more retries left)":"(error; not retryable)"})`,W.status,z,V,B),this.makeStatusError(W.status,H,B,V)}return{response:W,options:X,controller:Q}}requestAPIList($,Z){let X=this.makeRequest(Z,null);return new zG(this,X,$)}buildURL($,Z){let X=FL($)?new URL($):new URL(this.baseURL+(this.baseURL.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Y=this.defaultQuery();if(!JG(Y))Z={...Y,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))X.search=this.stringifyQuery(Z);return X.toString()}stringifyQuery($){return Object.entries($).filter(([Z,X])=>typeof X<"u").map(([Z,X])=>{if(typeof X==="string"||typeof X==="number"||typeof X==="boolean")return`${encodeURIComponent(Z)}=${encodeURIComponent(X)}`;if(X===null)return`${encodeURIComponent(Z)}=`;throw new v(`Cannot stringify type ${typeof X}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout($,Z,X,Y){let{signal:G,...z}=Z||{};if(G)G.addEventListener("abort",()=>Y.abort());let J=setTimeout(()=>Y.abort(),X),Q={signal:Y.signal,...z};if(Q.method)Q.method=Q.method.toUpperCase();let W=60000,V=setTimeout(()=>{if(Q&&Q?.agent?.sockets){for(let K of Object.values(Q?.agent?.sockets).flat())if(K?.setKeepAlive)K.setKeepAlive(!0,W)}},W);return this.fetch.call(void 0,$,Q).finally(()=>{clearTimeout(J),clearTimeout(V)})}shouldRetry($){let Z=$.headers.get("x-should-retry");if(Z==="true")return!0;if(Z==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,X){let Y,G=X?.["retry-after-ms"];if(G){let J=parseFloat(G);if(!Number.isNaN(J))Y=J}let z=X?.["retry-after"];if(z&&!Y){let J=parseFloat(z);if(!Number.isNaN(J))Y=J*1000;else Y=Date.parse(z)-Date.now()}if(!(Y&&0<=Y&&Y<60000)){let J=$.maxRetries??this.maxRetries;Y=this.calculateDefaultRetryTimeoutMillis(Z,J)}return await LL(Y),this.makeRequest($,Z-1)}calculateDefaultRetryTimeoutMillis($,Z){let G=Z-$,z=Math.min(0.5*Math.pow(2,G),8),J=1-Math.random()*0.25;return z*J*1000}getUserAgent(){return`${this.constructor.name}/JS ${n$}`}}class n9{constructor($,Z,X,Y){Q8.set(this,void 0),WL(this,Q8,$,"f"),this.options=Y,this.response=Z,this.body=X}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let $=this.nextPageInfo();if(!$)throw new v("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let Z={...this.options};if("params"in $&&typeof Z.query==="object")Z.query={...Z.query,...$.params};else if("url"in $){let X=[...Object.entries(Z.query||{}),...$.url.searchParams.entries()];for(let[Y,G]of X)$.url.searchParams.set(Y,G);Z.query=void 0,Z.path=$.url.toString()}return await VL(this,Q8,"f").requestAPIList(this.constructor,Z)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(Q8=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class zG extends V8{constructor($,Z,X){super(Z,async(Y)=>new X($,Y.response,await YG(Y),Y.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}var c9=($)=>{return new Proxy(Object.fromEntries($.entries()),{get(Z,X){let Y=X.toString();return Z[Y.toLowerCase()]||Z[Y]}})},HL={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},j0=($)=>{return typeof $==="object"&&$!==null&&!JG($)&&Object.keys($).every((Z)=>QG(HL,Z))},KL=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n$,"X-Stainless-OS":$G(Deno.build.os),"X-Stainless-Arch":eY(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n$,"X-Stainless-OS":$G(process.platform),"X-Stainless-Arch":eY(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let $=BL();if($)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${$.browser}`,"X-Stainless-Runtime-Version":$.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function BL(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Z,pattern:X}of $){let Y=X.exec(navigator.userAgent);if(Y){let G=Y[1]||0,z=Y[2]||0,J=Y[3]||0;return{browser:Z,version:`${G}.${z}.${J}`}}}return null}var eY=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},$G=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},ZG,UL=()=>{return ZG??(ZG=KL())},qL=($)=>{try{return JSON.parse($)}catch(Z){return}},TL=/^[a-z][a-z0-9+.-]*:/i,FL=($)=>{return TL.test($)},LL=($)=>new Promise((Z)=>setTimeout(Z,$)),i9=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new v(`${$} must be an integer`);if(Z<0)throw new v(`${$} must be a positive integer`);return Z},z8=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null)try{return Error(JSON.stringify($))}catch{}return Error(String($))};var H8=($)=>{if(typeof process<"u")return process.env?.[$]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.($)?.trim();return};function JG($){if(!$)return!0;for(let Z in $)return!1;return!0}function QG($,Z){return Object.prototype.hasOwnProperty.call($,Z)}function XG($,Z){for(let X in Z){if(!QG(Z,X))continue;let Y=X.toLowerCase();if(!Y)continue;let G=Z[X];if(G===null)delete $[Y];else if(G!==void 0)$[Y]=G}}function f1($,...Z){if(typeof process<"u"&&process?.env?.DEBUG==="true")console.log(`Anthropic:DEBUG:${$}`,...Z)}var wL=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,($)=>{let Z=Math.random()*16|0;return($==="x"?Z:Z&3|8).toString(16)})},WG=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},ML=($)=>{return typeof $?.get==="function"};var W8=($,Z)=>{let X=Z.toLowerCase();if(ML($)){let Y=Z[0]?.toUpperCase()+Z.substring(1).replace(/([^\w])(\w)/g,(G,z,J)=>z+J.toUpperCase());for(let G of[Z,X,Z.toUpperCase(),Y]){let z=$.get(G);if(z)return z}}for(let[Y,G]of Object.entries($))if(Y.toLowerCase()===X){if(Array.isArray(G)){if(G.length<=1)return G[0];return console.warn(`Received ${G.length} entries for the ${Z} header, using the first entry.`),G[0]}return G}return};class $$ extends n9{constructor($,Z,X,Y){super($,Z,X,Y);this.data=X.data||[],this.has_more=X.has_more||!1,this.first_id=X.first_id||null,this.last_id=X.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageParams(){let $=this.nextPageInfo();if(!$)return null;if("params"in $)return $.params;let Z=Object.fromEntries($.url.searchParams);if(!Object.keys(Z).length)return null;return Z}nextPageInfo(){if(this.options.query?.before_id){let Z=this.first_id;if(!Z)return null;return{params:{before_id:Z}}}let $=this.last_id;if(!$)return null;return{params:{after_id:$}}}}class W0{constructor($){this._client=$}}class y1 extends W0{retrieve($,Z){return this._client.get(`/v1/models/${$}?beta=true`,Z)}list($={},Z){if(j0($))return this.list({},$);return this._client.getAPIList("/v1/models?beta=true",z4,{query:$,...Z})}}class z4 extends $${}y1.BetaModelInfosPage=z4;class v1{constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new N$;for await(let Z of this.iterator)for(let X of $.decode(Z))yield JSON.parse(X);for(let Z of $.flush())yield JSON.parse(Z)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse($,Z){if(!$.body)throw Z.abort(),new v("Attempted to iterate over a response with no body");return new v1(Y4($.body),Z)}}class g1 extends W0{create($,Z){let{betas:X,...Y}=$;return this._client.post("/v1/messages/batches?beta=true",{body:Y,...Z,headers:{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),...Z?.headers}})}retrieve($,Z={},X){if(j0(Z))return this.retrieve($,{},Z);let{betas:Y}=Z;return this._client.get(`/v1/messages/batches/${$}?beta=true`,{...X,headers:{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString(),...X?.headers}})}list($={},Z){if(j0($))return this.list({},$);let{betas:X,...Y}=$;return this._client.getAPIList("/v1/messages/batches?beta=true",J4,{query:Y,...Z,headers:{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),...Z?.headers}})}delete($,Z={},X){if(j0(Z))return this.delete($,{},Z);let{betas:Y}=Z;return this._client.delete(`/v1/messages/batches/${$}?beta=true`,{...X,headers:{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString(),...X?.headers}})}cancel($,Z={},X){if(j0(Z))return this.cancel($,{},Z);let{betas:Y}=Z;return this._client.post(`/v1/messages/batches/${$}/cancel?beta=true`,{...X,headers:{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString(),...X?.headers}})}async results($,Z={},X){if(j0(Z))return this.results($,{},Z);let Y=await this.retrieve($);if(!Y.results_url)throw new v(`No batch \`results_url\`; Has it finished processing? ${Y.processing_status} - ${Y.id}`);let{betas:G}=Z;return this._client.get(Y.results_url,{...X,headers:{"anthropic-beta":[...G??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...X?.headers},stream:!0,__binaryResponse:!0})._thenUnwrap((z,J)=>v1.fromResponse(J.response,J.controller))}}class J4 extends $${}g1.BetaMessageBatchesPage=J4;var PL=($)=>{let Z=0,X=[];while(Z<$.length){let Y=$[Z];if(Y==="\\"){Z++;continue}if(Y==="{"){X.push({type:"brace",value:"{"}),Z++;continue}if(Y==="}"){X.push({type:"brace",value:"}"}),Z++;continue}if(Y==="["){X.push({type:"paren",value:"["}),Z++;continue}if(Y==="]"){X.push({type:"paren",value:"]"}),Z++;continue}if(Y===":"){X.push({type:"separator",value:":"}),Z++;continue}if(Y===","){X.push({type:"delimiter",value:","}),Z++;continue}if(Y==='"'){let Q="",W=!1;Y=$[++Z];while(Y!=='"'){if(Z===$.length){W=!0;break}if(Y==="\\"){if(Z++,Z===$.length){W=!0;break}Q+=Y+$[Z],Y=$[++Z]}else Q+=Y,Y=$[++Z]}if(Y=$[++Z],!W)X.push({type:"string",value:Q});continue}if(Y&&/\s/.test(Y)){Z++;continue}let z=/[0-9]/;if(Y&&z.test(Y)||Y==="-"||Y==="."){let Q="";if(Y==="-")Q+=Y,Y=$[++Z];while(Y&&z.test(Y)||Y===".")Q+=Y,Y=$[++Z];X.push({type:"number",value:Q});continue}let J=/[a-z]/i;if(Y&&J.test(Y)){let Q="";while(Y&&J.test(Y)){if(Z===$.length)break;Q+=Y,Y=$[++Z]}if(Q=="true"||Q=="false"||Q==="null")X.push({type:"name",value:Q});else{Z++;continue}continue}Z++}return X},h1=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),h1($);break;case"number":let X=Z.value[Z.value.length-1];if(X==="."||X==="-")return $=$.slice(0,$.length-1),h1($);case"string":let Y=$[$.length-2];if(Y?.type==="delimiter")return $=$.slice(0,$.length-1),h1($);else if(Y?.type==="brace"&&Y.value==="{")return $=$.slice(0,$.length-1),h1($);break;case"delimiter":return $=$.slice(0,$.length-1),h1($);break}return $},DL=($)=>{let Z=[];if($.map((X)=>{if(X.type==="brace")if(X.value==="{")Z.push("}");else Z.splice(Z.lastIndexOf("}"),1);if(X.type==="paren")if(X.value==="[")Z.push("]");else Z.splice(Z.lastIndexOf("]"),1)}),Z.length>0)Z.reverse().map((X)=>{if(X==="}")$.push({type:"brace",value:"}"});else if(X==="]")$.push({type:"paren",value:"]"})});return $},EL=($)=>{let Z="";return $.map((X)=>{switch(X.type){case"string":Z+='"'+X.value+'"';break;default:Z+=X.value;break}}),Z},K8=($)=>JSON.parse(EL(DL(h1(PL($)))));var K0=function($,Z,X,Y,G){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!G:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call($,X):G?G.value=X:Z.set($,X),X},h=function($,Z,X,Y){if(X==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Y:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call($):Y?Y.value:Z.get($)},x0,_$,Q4,B8,W4,V4,U8,H4,Z$,K4,q8,T8,u1,F8,L8,r9,VG,s9,o9,t9,e9,HG,KG="__json_buf";class B4{constructor(){x0.add(this),this.messages=[],this.receivedMessages=[],_$.set(this,void 0),this.controller=new AbortController,Q4.set(this,void 0),B8.set(this,()=>{}),W4.set(this,()=>{}),V4.set(this,void 0),U8.set(this,()=>{}),H4.set(this,()=>{}),Z$.set(this,{}),K4.set(this,!1),q8.set(this,!1),T8.set(this,!1),u1.set(this,!1),F8.set(this,void 0),L8.set(this,void 0),s9.set(this,($)=>{if(K0(this,q8,!0,"f"),$ instanceof Error&&$.name==="AbortError")$=new H0;if($ instanceof H0)return K0(this,T8,!0,"f"),this._emit("abort",$);if($ instanceof v)return this._emit("error",$);if($ instanceof Error){let Z=new v($.message);return Z.cause=$,this._emit("error",Z)}return this._emit("error",new v(String($)))}),K0(this,Q4,new Promise(($,Z)=>{K0(this,B8,$,"f"),K0(this,W4,Z,"f")}),"f"),K0(this,V4,new Promise(($,Z)=>{K0(this,U8,$,"f"),K0(this,H4,Z,"f")}),"f"),h(this,Q4,"f").catch(()=>{}),h(this,V4,"f").catch(()=>{})}get response(){return h(this,F8,"f")}get request_id(){return h(this,L8,"f")}async withResponse(){let $=await h(this,Q4,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let Z=new B4;return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,X){let Y=new B4;for(let G of Z.messages)Y._addMessageParam(G);return Y._run(()=>Y._createMessage($,{...Z,stream:!0},{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},h(this,s9,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}h(this,x0,"m",o9).call(this);let{response:G,data:z}=await $.create({...Z,stream:!0},{...X,signal:this.controller.signal}).withResponse();this._connected(G);for await(let J of z)h(this,x0,"m",t9).call(this,J);if(z.controller.signal?.aborted)throw new H0;h(this,x0,"m",e9).call(this)}_connected($){if(this.ended)return;K0(this,F8,$,"f"),K0(this,L8,$?.headers.get("request-id"),"f"),h(this,B8,"f").call(this,$),this._emit("connect")}get ended(){return h(this,K4,"f")}get errored(){return h(this,q8,"f")}get aborted(){return h(this,T8,"f")}abort(){this.controller.abort()}on($,Z){return(h(this,Z$,"f")[$]||(h(this,Z$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let X=h(this,Z$,"f")[$];if(!X)return this;let Y=X.findIndex((G)=>G.listener===Z);if(Y>=0)X.splice(Y,1);return this}once($,Z){return(h(this,Z$,"f")[$]||(h(this,Z$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,X)=>{if(K0(this,u1,!0,"f"),$!=="error")this.once("error",X);this.once($,Z)})}async done(){K0(this,u1,!0,"f"),await h(this,V4,"f")}get currentMessage(){return h(this,_$,"f")}async finalMessage(){return await this.done(),h(this,x0,"m",r9).call(this)}async finalText(){return await this.done(),h(this,x0,"m",VG).call(this)}_emit($,...Z){if(h(this,K4,"f"))return;if($==="end")K0(this,K4,!0,"f"),h(this,U8,"f").call(this);let X=h(this,Z$,"f")[$];if(X)h(this,Z$,"f")[$]=X.filter((Y)=>!Y.once),X.forEach(({listener:Y})=>Y(...Z));if($==="abort"){let Y=Z[0];if(!h(this,u1,"f")&&!X?.length)Promise.reject(Y);h(this,W4,"f").call(this,Y),h(this,H4,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!h(this,u1,"f")&&!X?.length)Promise.reject(Y);h(this,W4,"f").call(this,Y),h(this,H4,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",h(this,x0,"m",r9).call(this))}async _fromReadableStream($,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}h(this,x0,"m",o9).call(this),this._connected(null);let Y=P0.fromReadableStream($,this.controller);for await(let G of Y)h(this,x0,"m",t9).call(this,G);if(Y.controller.signal?.aborted)throw new H0;h(this,x0,"m",e9).call(this)}[(_$=new WeakMap,Q4=new WeakMap,B8=new WeakMap,W4=new WeakMap,V4=new WeakMap,U8=new WeakMap,H4=new WeakMap,Z$=new WeakMap,K4=new WeakMap,q8=new WeakMap,T8=new WeakMap,u1=new WeakMap,F8=new WeakMap,L8=new WeakMap,s9=new WeakMap,x0=new WeakSet,r9=function(){if(this.receivedMessages.length===0)throw new v("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},VG=function(){if(this.receivedMessages.length===0)throw new v("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((X)=>X.type==="text").map((X)=>X.text);if(Z.length===0)throw new v("stream ended without producing a content block with type=text");return Z.join(" ")},o9=function(){if(this.ended)return;K0(this,_$,void 0,"f")},t9=function(Z){if(this.ended)return;let X=h(this,x0,"m",HG).call(this,Z);switch(this._emit("streamEvent",Z,X),Z.type){case"content_block_delta":{let Y=X.content.at(-1);switch(Z.delta.type){case"text_delta":{if(Y.type==="text")this._emit("text",Z.delta.text,Y.text||"");break}case"citations_delta":{if(Y.type==="text")this._emit("citation",Z.delta.citation,Y.citations??[]);break}case"input_json_delta":{if(Y.type==="tool_use"&&Y.input)this._emit("inputJson",Z.delta.partial_json,Y.input);break}case"thinking_delta":{if(Y.type==="thinking")this._emit("thinking",Z.delta.thinking,Y.thinking);break}case"signature_delta":{if(Y.type==="thinking")this._emit("signature",Y.signature);break}default:BG(Z.delta)}break}case"message_stop":{this._addMessageParam(X),this._addMessage(X,!0);break}case"content_block_stop":{this._emit("contentBlock",X.content.at(-1));break}case"message_start":{K0(this,_$,X,"f");break}case"content_block_start":case"message_delta":break}},e9=function(){if(this.ended)throw new v("stream has ended, this shouldn't happen");let Z=h(this,_$,"f");if(!Z)throw new v("request ended without sending any chunks");return K0(this,_$,void 0,"f"),Z},HG=function(Z){let X=h(this,_$,"f");if(Z.type==="message_start"){if(X)throw new v(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!X)throw new v(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return X;case"message_delta":return X.stop_reason=Z.delta.stop_reason,X.stop_sequence=Z.delta.stop_sequence,X.usage.output_tokens=Z.usage.output_tokens,X;case"content_block_start":return X.content.push(Z.content_block),X;case"content_block_delta":{let Y=X.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Y?.type==="text")Y.text+=Z.delta.text;break}case"citations_delta":{if(Y?.type==="text")Y.citations??(Y.citations=[]),Y.citations.push(Z.delta.citation);break}case"input_json_delta":{if(Y?.type==="tool_use"){let G=Y[KG]||"";if(G+=Z.delta.partial_json,Object.defineProperty(Y,KG,{value:G,enumerable:!1,writable:!0}),G)Y.input=K8(G)}break}case"thinking_delta":{if(Y?.type==="thinking")Y.thinking+=Z.delta.thinking;break}case"signature_delta":{if(Y?.type==="thinking")Y.signature=Z.delta.signature;break}default:BG(Z.delta)}return X}case"content_block_stop":return X}},Symbol.asyncIterator)](){let $=[],Z=[],X=!1;return this.on("streamEvent",(Y)=>{let G=Z.shift();if(G)G.resolve(Y);else $.push(Y)}),this.on("end",()=>{X=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),this.on("error",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(X)return{value:void 0,done:!0};return new Promise((G,z)=>Z.push({resolve:G,reject:z})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new P0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function BG($){}var UG={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};class t$ extends W0{constructor(){super(...arguments);this.batches=new g1(this._client)}create($,Z){let{betas:X,...Y}=$;if(Y.model in UG)console.warn(`The model '${Y.model}' is deprecated and will reach end-of-life on ${UG[Y.model]}
|
|
197
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);return this._client.post("/v1/messages?beta=true",{body:Y,timeout:this._client._options.timeout??(Y.stream?600000:this._client._calculateNonstreamingTimeout(Y.max_tokens)),...Z,headers:{...X?.toString()!=null?{"anthropic-beta":X?.toString()}:void 0,...Z?.headers},stream:$.stream??!1})}stream($,Z){return B4.createMessage(this,$,Z)}countTokens($,Z){let{betas:X,...Y}=$;return this._client.post("/v1/messages/count_tokens?beta=true",{body:Y,...Z,headers:{"anthropic-beta":[...X??[],"token-counting-2024-11-01"].toString(),...Z?.headers}})}}t$.Batches=g1;t$.BetaMessageBatchesPage=J4;class X$ extends W0{constructor(){super(...arguments);this.models=new y1(this._client),this.messages=new t$(this._client)}}X$.Models=y1;X$.BetaModelInfosPage=z4;X$.Messages=t$;class m1 extends W0{create($,Z){return this._client.post("/v1/complete",{body:$,timeout:this._client._options.timeout??600000,...Z,stream:$.stream??!1})}}class d1 extends W0{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(`/v1/messages/batches/${$}`,Z)}list($={},Z){if(j0($))return this.list({},$);return this._client.getAPIList("/v1/messages/batches",U4,{query:$,...Z})}delete($,Z){return this._client.delete(`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let X=await this.retrieve($);if(!X.results_url)throw new v(`No batch \`results_url\`; Has it finished processing? ${X.processing_status} - ${X.id}`);return this._client.get(X.results_url,{...Z,headers:{Accept:"application/binary",...Z?.headers},__binaryResponse:!0})._thenUnwrap((Y,G)=>v1.fromResponse(G.response,G.controller))}}class U4 extends $${}d1.MessageBatchesPage=U4;var B0=function($,Z,X,Y,G){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!G:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call($,X):G?G.value=X:Z.set($,X),X},u=function($,Z,X,Y){if(X==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Y:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call($):Y?Y.value:Z.get($)},k0,P$,q4,w8,T4,F4,M8,L4,Y$,w4,O8,N8,c1,_8,P8,$5,qG,Z5,X5,Y5,G5,TG,FG="__json_buf";class M4{constructor(){k0.add(this),this.messages=[],this.receivedMessages=[],P$.set(this,void 0),this.controller=new AbortController,q4.set(this,void 0),w8.set(this,()=>{}),T4.set(this,()=>{}),F4.set(this,void 0),M8.set(this,()=>{}),L4.set(this,()=>{}),Y$.set(this,{}),w4.set(this,!1),O8.set(this,!1),N8.set(this,!1),c1.set(this,!1),_8.set(this,void 0),P8.set(this,void 0),Z5.set(this,($)=>{if(B0(this,O8,!0,"f"),$ instanceof Error&&$.name==="AbortError")$=new H0;if($ instanceof H0)return B0(this,N8,!0,"f"),this._emit("abort",$);if($ instanceof v)return this._emit("error",$);if($ instanceof Error){let Z=new v($.message);return Z.cause=$,this._emit("error",Z)}return this._emit("error",new v(String($)))}),B0(this,q4,new Promise(($,Z)=>{B0(this,w8,$,"f"),B0(this,T4,Z,"f")}),"f"),B0(this,F4,new Promise(($,Z)=>{B0(this,M8,$,"f"),B0(this,L4,Z,"f")}),"f"),u(this,q4,"f").catch(()=>{}),u(this,F4,"f").catch(()=>{})}get response(){return u(this,_8,"f")}get request_id(){return u(this,P8,"f")}async withResponse(){let $=await u(this,q4,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let Z=new M4;return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,X){let Y=new M4;for(let G of Z.messages)Y._addMessageParam(G);return Y._run(()=>Y._createMessage($,{...Z,stream:!0},{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},u(this,Z5,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}u(this,k0,"m",X5).call(this);let{response:G,data:z}=await $.create({...Z,stream:!0},{...X,signal:this.controller.signal}).withResponse();this._connected(G);for await(let J of z)u(this,k0,"m",Y5).call(this,J);if(z.controller.signal?.aborted)throw new H0;u(this,k0,"m",G5).call(this)}_connected($){if(this.ended)return;B0(this,_8,$,"f"),B0(this,P8,$?.headers.get("request-id"),"f"),u(this,w8,"f").call(this,$),this._emit("connect")}get ended(){return u(this,w4,"f")}get errored(){return u(this,O8,"f")}get aborted(){return u(this,N8,"f")}abort(){this.controller.abort()}on($,Z){return(u(this,Y$,"f")[$]||(u(this,Y$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let X=u(this,Y$,"f")[$];if(!X)return this;let Y=X.findIndex((G)=>G.listener===Z);if(Y>=0)X.splice(Y,1);return this}once($,Z){return(u(this,Y$,"f")[$]||(u(this,Y$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,X)=>{if(B0(this,c1,!0,"f"),$!=="error")this.once("error",X);this.once($,Z)})}async done(){B0(this,c1,!0,"f"),await u(this,F4,"f")}get currentMessage(){return u(this,P$,"f")}async finalMessage(){return await this.done(),u(this,k0,"m",$5).call(this)}async finalText(){return await this.done(),u(this,k0,"m",qG).call(this)}_emit($,...Z){if(u(this,w4,"f"))return;if($==="end")B0(this,w4,!0,"f"),u(this,M8,"f").call(this);let X=u(this,Y$,"f")[$];if(X)u(this,Y$,"f")[$]=X.filter((Y)=>!Y.once),X.forEach(({listener:Y})=>Y(...Z));if($==="abort"){let Y=Z[0];if(!u(this,c1,"f")&&!X?.length)Promise.reject(Y);u(this,T4,"f").call(this,Y),u(this,L4,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!u(this,c1,"f")&&!X?.length)Promise.reject(Y);u(this,T4,"f").call(this,Y),u(this,L4,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",u(this,k0,"m",$5).call(this))}async _fromReadableStream($,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}u(this,k0,"m",X5).call(this),this._connected(null);let Y=P0.fromReadableStream($,this.controller);for await(let G of Y)u(this,k0,"m",Y5).call(this,G);if(Y.controller.signal?.aborted)throw new H0;u(this,k0,"m",G5).call(this)}[(P$=new WeakMap,q4=new WeakMap,w8=new WeakMap,T4=new WeakMap,F4=new WeakMap,M8=new WeakMap,L4=new WeakMap,Y$=new WeakMap,w4=new WeakMap,O8=new WeakMap,N8=new WeakMap,c1=new WeakMap,_8=new WeakMap,P8=new WeakMap,Z5=new WeakMap,k0=new WeakSet,$5=function(){if(this.receivedMessages.length===0)throw new v("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},qG=function(){if(this.receivedMessages.length===0)throw new v("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((X)=>X.type==="text").map((X)=>X.text);if(Z.length===0)throw new v("stream ended without producing a content block with type=text");return Z.join(" ")},X5=function(){if(this.ended)return;B0(this,P$,void 0,"f")},Y5=function(Z){if(this.ended)return;let X=u(this,k0,"m",TG).call(this,Z);switch(this._emit("streamEvent",Z,X),Z.type){case"content_block_delta":{let Y=X.content.at(-1);switch(Z.delta.type){case"text_delta":{if(Y.type==="text")this._emit("text",Z.delta.text,Y.text||"");break}case"citations_delta":{if(Y.type==="text")this._emit("citation",Z.delta.citation,Y.citations??[]);break}case"input_json_delta":{if(Y.type==="tool_use"&&Y.input)this._emit("inputJson",Z.delta.partial_json,Y.input);break}case"thinking_delta":{if(Y.type==="thinking")this._emit("thinking",Z.delta.thinking,Y.thinking);break}case"signature_delta":{if(Y.type==="thinking")this._emit("signature",Y.signature);break}default:LG(Z.delta)}break}case"message_stop":{this._addMessageParam(X),this._addMessage(X,!0);break}case"content_block_stop":{this._emit("contentBlock",X.content.at(-1));break}case"message_start":{B0(this,P$,X,"f");break}case"content_block_start":case"message_delta":break}},G5=function(){if(this.ended)throw new v("stream has ended, this shouldn't happen");let Z=u(this,P$,"f");if(!Z)throw new v("request ended without sending any chunks");return B0(this,P$,void 0,"f"),Z},TG=function(Z){let X=u(this,P$,"f");if(Z.type==="message_start"){if(X)throw new v(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!X)throw new v(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return X;case"message_delta":return X.stop_reason=Z.delta.stop_reason,X.stop_sequence=Z.delta.stop_sequence,X.usage.output_tokens=Z.usage.output_tokens,X;case"content_block_start":return X.content.push(Z.content_block),X;case"content_block_delta":{let Y=X.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Y?.type==="text")Y.text+=Z.delta.text;break}case"citations_delta":{if(Y?.type==="text")Y.citations??(Y.citations=[]),Y.citations.push(Z.delta.citation);break}case"input_json_delta":{if(Y?.type==="tool_use"){let G=Y[FG]||"";if(G+=Z.delta.partial_json,Object.defineProperty(Y,FG,{value:G,enumerable:!1,writable:!0}),G)Y.input=K8(G)}break}case"thinking_delta":{if(Y?.type==="thinking")Y.thinking+=Z.delta.thinking;break}case"signature_delta":{if(Y?.type==="thinking")Y.signature=Z.delta.signature;break}default:LG(Z.delta)}return X}case"content_block_stop":return X}},Symbol.asyncIterator)](){let $=[],Z=[],X=!1;return this.on("streamEvent",(Y)=>{let G=Z.shift();if(G)G.resolve(Y);else $.push(Y)}),this.on("end",()=>{X=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),this.on("error",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(X)return{value:void 0,done:!0};return new Promise((G,z)=>Z.push({resolve:G,reject:z})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new P0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function LG($){}class D$ extends W0{constructor(){super(...arguments);this.batches=new d1(this._client)}create($,Z){if($.model in wG)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${wG[$.model]}
|
|
198
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);return this._client.post("/v1/messages",{body:$,timeout:this._client._options.timeout??($.stream?600000:this._client._calculateNonstreamingTimeout($.max_tokens)),...Z,stream:$.stream??!1})}stream($,Z){return M4.createMessage(this,$,Z)}countTokens($,Z){return this._client.post("/v1/messages/count_tokens",{body:$,...Z})}}var wG={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};D$.Batches=d1;D$.MessageBatchesPage=U4;class e$ extends W0{retrieve($,Z){return this._client.get(`/v1/models/${$}`,Z)}list($={},Z){if(j0($))return this.list({},$);return this._client.getAPIList("/v1/models",l1,{query:$,...Z})}}class l1 extends $${}e$.ModelInfosPage=l1;var MG;class p extends a9{constructor({baseURL:$=H8("ANTHROPIC_BASE_URL"),apiKey:Z=H8("ANTHROPIC_API_KEY")??null,authToken:X=H8("ANTHROPIC_AUTH_TOKEN")??null,...Y}={}){let G={apiKey:Z,authToken:X,...Y,baseURL:$||"https://api.anthropic.com"};if(!G.dangerouslyAllowBrowser&&WG())throw new v(`It looks like you're running in a browser-like environment.
|
|
189
|
+
`);if(H+=M.length+F.length,H>V)throw Error(`Codebase source "${$}" exceeded hard cap of ${V} bytes (matched glob ${Z.path}). Tighten the glob or raise the limit via maxBytes (and accept the request-size risk).`)}if(H>W)G?.(` warn: codebase source [${$}] is ${H} bytes (soft cap ${W}); consider tightening the glob`);let U=K.join("");return{id:$,source:Z.path,content:U,name:`${Q.length} file${Q.length===1?"":"s"} in ${Z.path}`,type:"codebase",auditTraps:Y,matchedFiles:Q}}async function uY($,Z,X,Y){let{path:G,auditTraps:z}=bX(Z);if(typeof Z!=="string"&&Z.type==="codebase")return MF($,Z,X,z,Y);if(TF(G))return FF($,G,z);return LF($,G,X,z)}async function t2($,Z,X){let Y=Object.entries($);return await Promise.all(Y.map(([z,J])=>uY(z,J,Z,X)))}async function mY($){if(!wF(OF($,"pickled.yml")))return{matches:[],findings:[]};let Z=await S1($),X=Z.docs?.sources;if(!X||Object.keys(X).length===0)return{matches:[],findings:[]};let Y={};for(let[V,K]of Object.entries(X)){let H=typeof K==="string"?K:K.path;if(H.startsWith("http://")||H.startsWith("https://"))continue;Y[V]=K}if(Object.keys(Y).length===0)return{matches:[],findings:[]};let G=[],z=new Map;for(let V of Z.scenarios)for(let K of V.traps??[])G.push(K),z.set(K,K.auditSeverity??"warning");if(G.length===0)return{matches:[],findings:[]};let J=await t2(Y,$),Q=[],W=[];for(let V of J){let K=V.auditTraps;if(K===!1)continue;let H=Array.isArray(K)?new Set(K):null,U=V.type==="codebase"&&V.matchedFiles?await _F(V.matchedFiles,$,V.source):[{path:V.source,content:V.content}];for(let B of U)for(let T of G){if(H?.has(T.id))continue;let{fired:F}=w$({response:B.content,traps:[T]}),M=F[0];if(!M)continue;let O=PF(B.content,M.index),N=z.get(T)??"warning";Q.push({sourceId:V.id,sourcePath:B.path,trapId:M.id,trapReason:M.reason,matched:M.matched,snippet:M.snippet,line:O,severity:N}),W.push({severity:N,category:"trap-source-match",file:B.path,message:`source [${V.id}] matches trap '${M.id}' ("${M.matched}") in ${B.path}. ${M.reason} Fix: remove the stale claim from the source, retire the trap if no longer relevant, set audit.traps: ['${M.id}'] on the source to suppress just this trap (other traps still apply), or set audit.traps: false if the source is deliberately stale or test-only.`})}}return{matches:Q,findings:W}}async function _F($,Z,X){let Y=[];for(let G of $)try{let z=await Bun.file(NF(Z,G)).text();Y.push({path:G,content:z})}catch{}return Y}function PF($,Z){let X=1,Y=Math.min(Z,$.length);for(let G=0;G<Y;G++)if($[G]===`
|
|
190
|
+
`)X++;return X}var SF=["AGENTS.md","CLAUDE.md","CLAUDE.local.md","llms.txt","llms-full.txt",".claude/CLAUDE.md",".claude/rules/*.md","**/AGENTS.md","**/CLAUDE.md","**/CLAUDE.local.md","**/llms.txt","**/llms-full.txt","**/.claude/CLAUDE.md","**/.claude/rules/*.md"];async function iZ($){let Z=dZ($),X=yX(Z.targetRepo);if(!I1(X))throw Error(`targetRepo does not exist: ${X}`);let Y=new Set;for(let V of SF){let K=new dY(V);for await(let H of K.scan({cwd:X,dot:!0,onlyFiles:!1,followSymlinks:!1})){if(Z.ignore.some((T)=>new dY(T).match(H)))continue;let U=fX(X,H),B=cY(U);if(B.isFile()){Y.add(H);continue}if(B.isSymbolicLink())try{if(EF(U).isFile())Y.add(H)}catch{}}}let G=[];for(let V of[...Y].sort())G.push(await CF(X,V,fX(X,V),Z));let z=mF(G,Z),J=dF(G,z,Z),{matches:Q,findings:W}=await mY(X);return{config:Z,files:G,pairs:z,findings:[...J,...W],sourceTrapMatches:Q}}async function CF($,Z,X,Y){let z=cY(X).isSymbolicLink(),J=null,Q=Z;if(z){let U=DF(X),B=RF(U)?U:yX(pZ(X),U);if(J=B,I1(B))Q=AF($,B)}let W=z&&J&&I1(J)?J:X,V=lZ(W,"utf8"),K=(V.match(/\n/g)??[]).length,H=V.endsWith(`
|
|
191
|
+
`)?K:K+1;return{relPath:Z,absPath:X,isSymlink:z,symlinkTarget:J,realRelPath:Q,lineCount:H,brokenPathRefs:jF(V,$,Z),brokenImports:kF(V,pZ(X)),unresolvedCommands:vF(V,$,Y.knownCommands),sections:gF(V)}}function IF($){let Z=$.split("/");if(Z.length<2)return null;if(Z[0]==="packages"||Z[0]==="apps"||Z[0]==="shared")return`${Z[0]}/${Z[1]}`;if(Z[0]==="tests")return Z.slice(0,2).join("/");return null}function jF($,Z,X){let Y=uF($),G=pZ(X),z=IF(X),J=new Set,Q=/`([^`\n]{2,200})`/g,W;W=Q.exec(Y);while(W!==null){let V=W[1].trim().replace(/[#?].*$/,"");if(hF(V)&&!xF(Z,V,G,z).found)J.add(V);W=Q.exec(Y)}return[...J].sort()}function xF($,Z,X,Y){let G=[Z];if(X&&X!==".")G.push(`${X}/${Z}`);if(Y)G.push(`${Y}/${Z}`);G.push(`packages/${Z}`,`apps/${Z}`,`shared/${Z}`);for(let z of G){let J=z.replace(/\/+/g,"/");if(I1(`${$}/${J}`))return{found:!0,resolvedAs:J}}return{found:!1}}function kF($,Z){let X=new Set,Y=/@([\w./@~-]+\.md)/g,G;G=Y.exec($);while(G!==null){let z=G[1];if(z.startsWith("~/")){G=Y.exec($);continue}let J=z.startsWith("/")?z:yX(Z,z);if(!I1(J))X.add(z);G=Y.exec($)}return[...X].sort()}var bF=["bun","pnpm","npm","yarn"],fF=new Set(["install","add","remove","update","i","audit","list","ls","why","outdated","exec","run","create","init","x"]),yF={bun:new Set(["build","test","link","unlink","upgrade"])};function vF($,Z,X){let Y=new Set,G=fX(Z,"package.json"),z=new Set;if(I1(G))try{let Q=JSON.parse(lZ(G,"utf8"));z=new Set(Object.keys(Q.scripts??{}))}catch{}let J=new Set(X.map((Q)=>Q.trim()));for(let Q of bF){let W=new RegExp(`\\b${Q}\\s+(?:run\\s+|--filter\\s+\\S+\\s+(?:run\\s+)?)?([a-zA-Z][\\w:.\\-]*)`,"g"),V;V=W.exec($);while(V!==null){let K=V[1];if(!z.has(K)&&!J.has(`${Q} ${K}`)&&!J.has(`${Q} run ${K}`)&&!fF.has(K)&&!yF[Q]?.has(K))Y.add(`${Q} ${K}`);V=W.exec($)}}return[...Y].sort()}function gF($){let Z=$.split(`
|
|
192
|
+
`),X=[],Y=null;if(Z.forEach((G,z)=>{if(/^##\s+/.test(G)){if(Y)X.push({header:Y.header,lines:z-Y.start});Y={header:G.replace(/^##\s+/,"").trim(),start:z}}}),Y){let G=Y;X.push({header:G.header,lines:Z.length-G.start})}return X.sort((G,z)=>z.lines-G.lines)}function hF($){if($.length===0||$.length>160)return!1;if(!$.includes("/"))return!1;if(/\s/.test($))return!1;if(/^https?:\/\//.test($))return!1;if(/[*?{}[\]<>]/.test($))return!1;if($.startsWith("@"))return!1;if($.startsWith("~/"))return!1;if(/^[a-z]+:\/\//i.test($))return!1;if(/^cdn\./.test($)||/^unpkg\./.test($)||/^npm\./.test($))return!1;if(/^\/[a-z]/.test($)&&/(?:icon|image|img|asset|file|path)/i.test($))return!1;if(/^(cd|pnpm|npm|yarn|bun|node|git|ls|cat|grep|find|sed|awk|mkdir|rm|mv|cp|echo|export|source|sudo|brew|docker|curl|wget)\b/.test($))return!1;return/[a-zA-Z0-9_.-]\/[a-zA-Z0-9_.-]/.test($)}function uF($){return $.replace(/```[\s\S]*?```/g,"")}function mF($,Z){let X=new Map;for(let z of $){let J=z.relPath.split("/").pop()??"";if(J!=="AGENTS.md"&&J!=="CLAUDE.md")continue;let Q=pZ(z.relPath),W=X.get(Q)??{};if(J==="AGENTS.md")W.agents=z;if(J==="CLAUDE.md")W.claude=z;X.set(Q,W)}let Y=new Set(Z.intentionalDifferentPairs),G=[];for(let[z,J]of X){let Q=!!J.agents,W=!!J.claude;if(!Q&&!W)continue;if(!Q||!W){G.push({dir:z,agentsExists:Q,claudeExists:W,classification:"single",detail:Q?"only AGENTS.md":"only CLAUDE.md"});continue}let{agents:V,claude:K}=J,H=`${V.relPath}:${K.relPath}`,U=`${K.relPath}:${V.relPath}`;if(Y.has(H)||Y.has(U)){G.push({dir:z,agentsExists:Q,claudeExists:W,classification:"intentional-different",detail:`allowlisted: ${V.lineCount}L vs ${K.lineCount}L`});continue}if(V.isSymlink&&V.symlinkTarget===K.absPath||K.isSymlink&&K.symlinkTarget===V.absPath){let M=V.isSymlink?"CLAUDE.md":"AGENTS.md";G.push({dir:z,agentsExists:Q,claudeExists:W,classification:"linked",detail:`canonical: ${M}`});continue}let T=lZ(V.absPath,"utf8"),F=lZ(K.absPath,"utf8");if(T===F)G.push({dir:z,agentsExists:Q,claudeExists:W,classification:"unexpected-duplicate",detail:`byte-for-byte duplicate (${V.lineCount}L), not symlinked`});else G.push({dir:z,agentsExists:Q,claudeExists:W,classification:"unexpected-duplicate",detail:`divergent (${V.lineCount}L vs ${K.lineCount}L), not in intentional-different allowlist`})}return G.sort((z,J)=>z.dir.localeCompare(J.dir)),G}function dF($,Z,X){let Y=[];for(let G of $){if(G.isSymlink)continue;for(let Q of G.brokenImports)Y.push({severity:"error",category:"broken-import",file:G.relPath,message:`broken @-import: ${Q}`});for(let Q of G.brokenPathRefs)Y.push({severity:"error",category:"broken-path-ref",file:G.relPath,message:`broken path reference: ${Q}`});for(let Q of G.unresolvedCommands)Y.push({severity:"warning",category:"unresolved-command",file:G.relPath,message:`unresolved command: ${Q}`});let z=!G.relPath.includes("/"),J=z?X.budgets.rootLines:X.budgets.nestedWarnLines;if(G.lineCount>J)Y.push({severity:"warning",category:"over-budget",file:G.relPath,message:`${G.lineCount} lines exceeds ${z?"root":"nested"} budget of ${J}`})}for(let G of Z)if(G.classification==="unexpected-duplicate"){let z=G.detail.startsWith("divergent")?"error":"warning";Y.push({severity:z,category:z==="error"?"divergent-pair":"duplicate-pair",file:G.dir||"(root)",message:`AGENTS.md / CLAUDE.md ${G.detail}`})}return Y}function t0($){let Z=$.confidence;if($.error)return{icon:"\u2717",label:"Error",confidence:Z,tone:"error"};if($.traps.fired.length>0)return{icon:"\u2717",label:"Trap fired",confidence:Z,tone:"error"};if($.answerable==="YES")return{icon:"\u2713",label:Z>=90?"Well grounded":"Grounded",confidence:Z,tone:"success"};if($.answerable==="PARTIAL")return{icon:"\u26A0",label:"Partially grounded",confidence:Z,tone:"warning"};return{icon:"\u2717",label:"Ungrounded",confidence:Z,tone:"error"}}function cF($){let Z=2166136261;for(let X=0;X<$.length;X++)Z^=$.charCodeAt(X),Z=Math.imul(Z,16777619);return Z>>>0}function lF($){let Z=$>>>0;return()=>{Z=Z+1831565813>>>0;let X=Z;return X=Math.imul(X^X>>>15,X|1),X^=X+Math.imul(X^X>>>7,X|61),((X^X>>>14)>>>0)/4294967296}}function lY($,Z,X){if(Z<=0)return[];let Y=lF(cF(X)),G=new Map,z=[];for(let Q of $){if(!G.has(Q.scenario))G.set(Q.scenario,[]),z.push(Q.scenario);G.get(Q.scenario).push(Q)}let J=[];for(let Q of z){let W=G.get(Q);if(W.length<=Z){J.push(...W);continue}let V=W.slice();for(let H=0;H<Z;H++){let U=H+Math.floor(Y()*(V.length-H));[V[H],V[U]]=[V[U],V[H]]}let K=new Set(V.slice(0,Z));for(let H of W)if(K.has(H))J.push(H)}return J}function vX($){let Z=pF($);if(Z===null)return[];let X=[],Y=/^\s*-\s+\[([^\]]+)\]\s*(.*)$/gm,G=Y.exec(Z);while(G!==null)X.push({id:G[1].trim(),note:G[2].trim()||void 0}),G=Y.exec(Z);return X}function pF($){let X=/^##\s+Sources\s*$/im.exec($);if(!X)return null;let Y=X.index+X[0].length,G=$.slice(Y),z=/^##\s+/m.exec(G);return z?G.slice(0,z.index):G}function j1($){let Z=vX($.response),X=new Set(Z.map((U)=>U.id)),Y=new Set($.registeredIds),G=new Set($.requiredSources),z=[...X],J=[...G].filter((U)=>!X.has(U)),Q=[...X].filter((U)=>!Y.has(U)),W=[...G],V,K,H;if(z.length===0)V="NO",K=0,H="No citations in response";else if(Q.length===z.length)V="NO",K=0,H=`All cited sources are unknown: ${Q.join(", ")}`;else if(J.length===0&&Q.length===0)V="YES",K=100,H=W.length>0?`All required sources cited: ${W.join(", ")}`:`Cited registered sources: ${z.join(", ")}`;else{V="PARTIAL";let U=W.length>0?W.length:1,B=W.length-J.length,T=W.length>0?B/U*100:60,F=Q.length*15;K=Math.max(0,Math.min(100,Math.round(T-F)));let M=[];if(J.length>0)M.push(`missing: ${J.join(", ")}`);if(Q.length>0)M.push(`unknown: ${Q.join(", ")}`);H=M.join("; ")}return{answerable:V,confidence:K,reason:H,citations:{cited:z,required:W,missing:J,unknown:Q}}}function aZ($,Z){let X=Z.filter((z)=>z.type==="codebase");if(X.length===0){for(let z of $.symbols)z.existsInCodebase=null;for(let z of $.paths)z.existsInCodebase=null;return}let Y=X.map((z)=>z.content).join(`
|
|
193
|
+
`);for(let z of $.symbols)z.existsInCodebase=Y.includes(z.value);let G=X.flatMap((z)=>z.matchedFiles??[]);for(let z of $.paths)z.existsInCodebase=G.some((J)=>J===z.value||J.endsWith(`/${z.value}`))}function e2($){let Z=[];for(let X of["symbols","paths"]){let Y=$[X].filter((G)=>G.existsInCodebase===!1).map((G)=>`"${G.value}"`);if(Y.length>0)Z.push(`declared ${X} missing from codebase: ${Y.join(", ")}`)}return Z}var iF=["includes","symbols","paths","options","constraints"];function nZ($){let{response:Z,expected:X}=$,Y=(B)=>(X?.[B]??[]).map((T)=>({value:T,satisfied:Z.includes(T)})),G=Y("includes"),z=Y("symbols"),J=Y("paths"),Q=Y("options"),W=Y("constraints"),V=(X?.excludes??[]).map((B)=>({value:B,satisfied:!Z.includes(B)})),K=[G,z,J,Q,W,V],H=K.reduce((B,T)=>B+T.filter((F)=>F.satisfied).length,0),U=K.reduce((B,T)=>B+T.length,0);return{includes:G,excludes:V,symbols:z,paths:J,options:Q,constraints:W,satisfied:H,total:U}}function $4($){if($.total===0)return[];let Z=[];for(let Y of iF){let G=$[Y].filter((z)=>!z.satisfied).map((z)=>`"${z.value}"`);if(G.length>0)Z.push({label:`missing ${Y}`,misses:G})}let X=$.excludes.filter((Y)=>!Y.satisfied).map((Y)=>`"${Y.value}"`);if(X.length>0)Z.push({label:"hit excludes",misses:X});if(Z.length===0)return[`expected checks satisfied (${$.satisfied}/${$.total})`];return[Z.map((Y)=>`${Y.label}: ${Y.misses.join(", ")}`).join("; ")]}var l$="0.40.1";var pY=!1,p$=void 0,gX=void 0,aF=void 0,nF=void 0,rF=void 0,iY=void 0,sF=void 0,rZ=void 0,hX=void 0,aY=void 0,uX=void 0,sZ=void 0,nY=void 0;function rY($,Z={auto:!1}){if(pY)throw Error(`you must \`import '@anthropic-ai/sdk/shims/${$.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(p$)throw Error(`can't \`import '@anthropic-ai/sdk/shims/${$.kind}'\` after \`import '@anthropic-ai/sdk/shims/${p$}'\``);pY=Z.auto,p$=$.kind,gX=$.fetch,aF=$.Request,nF=$.Response,rF=$.Headers,iY=$.FormData,sF=$.Blob,rZ=$.File,hX=$.ReadableStream,aY=$.getMultipartRequestOptions,uX=$.getDefaultAgent,sZ=$.fileFromPath,nY=$.isFsReadStream}class mX{constructor($){this.body=$}get[Symbol.toStringTag](){return"MultipartBody"}}function sY({manuallyImported:$}={}){let Z=$?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n- `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n- `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n",X,Y,G,z;try{X=fetch,Y=Request,G=Response,z=Headers}catch(J){throw Error(`this environment is missing the following Web Fetch API type: ${J.message}. ${Z}`)}return{kind:"web",fetch:X,Request:Y,Response:G,Headers:z,FormData:typeof FormData<"u"?FormData:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${Z}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${Z}`)}},File:typeof File<"u"?File:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${Z}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${Z}`)}},getMultipartRequestOptions:async(J,Q)=>({...Q,body:new mX(J)}),getDefaultAgent:(J)=>{return},fileFromPath:()=>{throw Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:(J)=>!1}}import{ReadStream as tF}from"fs";function oY(){let $=sY();function Z(X){return X instanceof tF}return{...$,isFsReadStream:Z}}var dX=()=>{if(!p$)rY(oY(),{auto:!0})};dX();class v extends Error{}class $0 extends v{constructor($,Z,X,Y){super(`${$0.makeMessage($,Z,X)}`);this.status=$,this.headers=Y,this.request_id=Y?.["request-id"],this.error=Z}static makeMessage($,Z,X){let Y=Z?.message?typeof Z.message==="string"?Z.message:JSON.stringify(Z.message):Z?JSON.stringify(Z):X;if($&&Y)return`${$} ${Y}`;if($)return`${$} status code (no body)`;if(Y)return Y;return"(no status code or body)"}static generate($,Z,X,Y){if(!$||!Y)return new i$({message:X,cause:z8(Z)});let G=Z;if($===400)return new oZ($,G,X,Y);if($===401)return new tZ($,G,X,Y);if($===403)return new eZ($,G,X,Y);if($===404)return new $8($,G,X,Y);if($===409)return new Z8($,G,X,Y);if($===422)return new X8($,G,X,Y);if($===429)return new Y8($,G,X,Y);if($>=500)return new G8($,G,X,Y);return new $0($,G,X,Y)}}class V0 extends $0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class i$ extends $0{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class Z4 extends i${constructor({message:$}={}){super({message:$??"Request timed out."})}}class oZ extends $0{}class tZ extends $0{}class eZ extends $0{}class $8 extends $0{}class Z8 extends $0{}class X8 extends $0{}class Y8 extends $0{}class G8 extends $0{}var J8=function($,Z,X,Y,G){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!G:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call($,X):G?G.value=X:Z.set($,X),X},a$=function($,Z,X,Y){if(X==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Y:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call($):Y?Y.value:Z.get($)},N0;class O${constructor(){N0.set(this,void 0),this.buffer=new Uint8Array,J8(this,N0,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?new TextEncoder().encode($):$,X=new Uint8Array(this.buffer.length+Z.length);X.set(this.buffer),X.set(Z,this.buffer.length),this.buffer=X;let Y=[],G;while((G=$L(this.buffer,a$(this,N0,"f")))!=null){if(G.carriage&&a$(this,N0,"f")==null){J8(this,N0,G.index,"f");continue}if(a$(this,N0,"f")!=null&&(G.index!==a$(this,N0,"f")+1||G.carriage)){Y.push(this.decodeText(this.buffer.slice(0,a$(this,N0,"f")-1))),this.buffer=this.buffer.slice(a$(this,N0,"f")),J8(this,N0,null,"f");continue}let z=a$(this,N0,"f")!==null?G.preceding-1:G.preceding,J=this.decodeText(this.buffer.slice(0,z));Y.push(J),this.buffer=this.buffer.slice(G.index),J8(this,N0,null,"f")}return Y}decodeText($){if($==null)return"";if(typeof $==="string")return $;if(typeof Buffer<"u"){if($ instanceof Buffer)return $.toString();if($ instanceof Uint8Array)return Buffer.from($).toString();throw new v(`Unexpected: received non-Uint8Array (${$.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if($ instanceof Uint8Array||$ instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode($);throw new v(`Unexpected: received non-Uint8Array/ArrayBuffer (${$.constructor.name}) in a web platform. Please report this error.`)}throw new v("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length)return[];return this.decode(`
|
|
194
|
+
`)}}N0=new WeakMap;O$.NEWLINE_CHARS=new Set([`
|
|
195
|
+
`,"\r"]);O$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function $L($,Z){for(let G=Z??0;G<$.length;G++){if($[G]===10)return{preceding:G,index:G+1,carriage:!1};if($[G]===13)return{preceding:G,index:G+1,carriage:!0}}return null}function tY($){for(let Y=0;Y<$.length-1;Y++){if($[Y]===10&&$[Y+1]===10)return Y+2;if($[Y]===13&&$[Y+1]===13)return Y+2;if($[Y]===13&&$[Y+1]===10&&Y+3<$.length&&$[Y+2]===13&&$[Y+3]===10)return Y+4}return-1}function X4($){if($[Symbol.asyncIterator])return $;let Z=$.getReader();return{async next(){try{let X=await Z.read();if(X?.done)Z.releaseLock();return X}catch(X){throw Z.releaseLock(),X}},async return(){let X=Z.cancel();return Z.releaseLock(),await X,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}class _0{constructor($,Z){this.iterator=$,this.controller=Z}static fromSSEResponse($,Z){let X=!1;async function*Y(){if(X)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let G=!1;try{for await(let z of ZL($,Z)){if(z.event==="completion")try{yield JSON.parse(z.data)}catch(J){throw console.error("Could not parse message into JSON:",z.data),console.error("From chunk:",z.raw),J}if(z.event==="message_start"||z.event==="message_delta"||z.event==="message_stop"||z.event==="content_block_start"||z.event==="content_block_delta"||z.event==="content_block_stop")try{yield JSON.parse(z.data)}catch(J){throw console.error("Could not parse message into JSON:",z.data),console.error("From chunk:",z.raw),J}if(z.event==="ping")continue;if(z.event==="error")throw $0.generate(void 0,`SSE Error: ${z.data}`,z.data,cX($.headers))}G=!0}catch(z){if(z instanceof Error&&z.name==="AbortError")return;throw z}finally{if(!G)Z.abort()}}return new _0(Y,Z)}static fromReadableStream($,Z){let X=!1;async function*Y(){let z=new O$,J=X4($);for await(let Q of J)for(let W of z.decode(Q))yield W;for(let Q of z.flush())yield Q}async function*G(){if(X)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let z=!1;try{for await(let J of Y()){if(z)continue;if(J)yield JSON.parse(J)}z=!0}catch(J){if(J instanceof Error&&J.name==="AbortError")return;throw J}finally{if(!z)Z.abort()}}return new _0(G,Z)}[Symbol.asyncIterator](){return this.iterator()}tee(){let $=[],Z=[],X=this.iterator(),Y=(G)=>{return{next:()=>{if(G.length===0){let z=X.next();$.push(z),Z.push(z)}return G.shift()}}};return[new _0(()=>Y($),this.controller),new _0(()=>Y(Z),this.controller)]}toReadableStream(){let $=this,Z,X=new TextEncoder;return new hX({async start(){Z=$[Symbol.asyncIterator]()},async pull(Y){try{let{value:G,done:z}=await Z.next();if(z)return Y.close();let J=X.encode(JSON.stringify(G)+`
|
|
196
|
+
`);Y.enqueue(J)}catch(G){Y.error(G)}},async cancel(){await Z.return?.()}})}}async function*ZL($,Z){if(!$.body)throw Z.abort(),new v("Attempted to iterate over a response with no body");let X=new eY,Y=new O$,G=X4($.body);for await(let z of XL(G))for(let J of Y.decode(z)){let Q=X.decode(J);if(Q)yield Q}for(let z of Y.flush()){let J=X.decode(z);if(J)yield J}}async function*XL($){let Z=new Uint8Array;for await(let X of $){if(X==null)continue;let Y=X instanceof ArrayBuffer?new Uint8Array(X):typeof X==="string"?new TextEncoder().encode(X):X,G=new Uint8Array(Z.length+Y.length);G.set(Z),G.set(Y,Z.length),Z=G;let z;while((z=tY(Z))!==-1)yield Z.slice(0,z),Z=Z.slice(z)}if(Z.length>0)yield Z}class eY{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let G={event:this.event,data:this.data.join(`
|
|
197
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],G}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,X,Y]=YL($,":");if(Y.startsWith(" "))Y=Y.substring(1);if(Z==="event")this.event=Y;else if(Z==="data")this.data.push(Y);return null}}function YL($,Z){let X=$.indexOf(Z);if(X!==-1)return[$.substring(0,X),Z,$.substring(X+Z.length)];return[$,"",""]}var GL=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function",zL=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&Y4($),Y4=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function";async function $G($,Z,X){if($=await $,zL($))return $;if(GL($)){let G=await $.blob();Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()??"unknown_file");let z=Y4(G)?[await G.arrayBuffer()]:[G];return new rZ(z,Z,X)}let Y=await JL($);if(Z||(Z=WL($)??"unknown_file"),!X?.type){let G=Y[0]?.type;if(typeof G==="string")X={...X,type:G}}return new rZ(Y,Z,X)}async function JL($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(Y4($))Z.push(await $.arrayBuffer());else if(VL($))for await(let X of $)Z.push(X);else throw Error(`Unexpected data type: ${typeof $}; constructor: ${$?.constructor?.name}; props: ${QL($)}`);return Z}function QL($){return`[${Object.getOwnPropertyNames($).map((X)=>`"${X}"`).join(", ")}]`}function WL($){return lX($.name)||lX($.filename)||lX($.path)?.split(/[\\/]/).pop()}var lX=($)=>{if(typeof $==="string")return $;if(typeof Buffer<"u"&&$ instanceof Buffer)return String($);return},VL=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function",pX=($)=>$&&typeof $==="object"&&$.body&&$[Symbol.toStringTag]==="MultipartBody";var KL=function($,Z,X,Y,G){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!G:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call($,X):G?G.value=X:Z.set($,X),X},UL=function($,Z,X,Y){if(X==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Y:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call($):Y?Y.value:Z.get($)},Q8;dX();async function zG($){let{response:Z}=$;if($.options.stream){if(x1("response",Z.status,Z.url,Z.headers,Z.body),$.options.__streamClass)return $.options.__streamClass.fromSSEResponse(Z,$.controller);return _0.fromSSEResponse(Z,$.controller)}if(Z.status===204)return null;if($.options.__binaryResponse)return Z;let Y=Z.headers.get("content-type")?.split(";")[0]?.trim();if(Y?.includes("application/json")||Y?.endsWith("+json")){let J=await Z.json();return x1("response",Z.status,Z.url,Z.headers,J),JG(J,Z)}let z=await Z.text();return x1("response",Z.status,Z.url,Z.headers,z),z}function JG($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}class V8 extends Promise{constructor($,Z=zG){super((X)=>{X(null)});this.responsePromise=$,this.parseResponse=Z}_thenUnwrap($){return new V8(this.responsePromise,async(Z)=>JG($(await this.parseResponse(Z),Z),Z.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,Z]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:Z,request_id:Z.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}class aX{constructor({baseURL:$,maxRetries:Z=2,timeout:X=600000,httpAgent:Y,fetch:G}){this.baseURL=$,this.maxRetries=iX("maxRetries",Z),this.timeout=iX("timeout",X),this.httpAgent=Y,this.fetch=G??gX}authHeaders($){return{}}defaultHeaders($){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...FL(),...this.authHeaders($)}}validateHeaders($,Z){}defaultIdempotencyKey(){return`stainless-node-retry-${NL()}`}get($,Z){return this.methodRequest("get",$,Z)}post($,Z){return this.methodRequest("post",$,Z)}patch($,Z){return this.methodRequest("patch",$,Z)}put($,Z){return this.methodRequest("put",$,Z)}delete($,Z){return this.methodRequest("delete",$,Z)}methodRequest($,Z,X){return this.request(Promise.resolve(X).then(async(Y)=>{let G=Y&&Y4(Y?.body)?new DataView(await Y.body.arrayBuffer()):Y?.body instanceof DataView?Y.body:Y?.body instanceof ArrayBuffer?new DataView(Y.body):Y&&ArrayBuffer.isView(Y?.body)?new DataView(Y.body.buffer):Y?.body;return{method:$,path:Z,...Y,body:G}}))}getAPIList($,Z,X){return this.requestAPIList(Z,{method:"get",path:$,...X})}calculateContentLength($){if(typeof $==="string"){if(typeof Buffer<"u")return Buffer.byteLength($,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode($).length.toString()}else if(ArrayBuffer.isView($))return $.byteLength.toString();return null}buildRequest($,{retryCount:Z=0}={}){let X={...$},{method:Y,path:G,query:z,headers:J={}}=X,Q=ArrayBuffer.isView(X.body)||X.__binaryRequest&&typeof X.body==="string"?X.body:pX(X.body)?X.body.body:X.body?JSON.stringify(X.body,null,2):null,W=this.calculateContentLength(Q),V=this.buildURL(G,z);if("timeout"in X)iX("timeout",X.timeout);X.timeout=X.timeout??this.timeout;let K=X.httpAgent??this.httpAgent??uX(V),H=X.timeout+1000;if(typeof K?.options?.timeout==="number"&&H>(K.options.timeout??0))K.options.timeout=H;if(this.idempotencyHeader&&Y!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();J[this.idempotencyHeader]=$.idempotencyKey}let U=this.buildHeaders({options:X,headers:J,contentLength:W,retryCount:Z});return{req:{method:Y,...Q&&{body:Q},headers:U,...K&&{agent:K},signal:X.signal??null},url:V,timeout:X.timeout}}buildHeaders({options:$,headers:Z,contentLength:X,retryCount:Y}){let G={};if(X)G["content-length"]=X;let z=this.defaultHeaders($);if(GG(G,z),GG(G,Z),pX($.body)&&p$!=="node")delete G["content-type"];if(W8(z,"x-stainless-retry-count")===void 0&&W8(Z,"x-stainless-retry-count")===void 0)G["x-stainless-retry-count"]=String(Y);if(W8(z,"x-stainless-timeout")===void 0&&W8(Z,"x-stainless-timeout")===void 0&&$.timeout)G["x-stainless-timeout"]=String(Math.trunc($.timeout/1000));return this.validateHeaders(G,Z),G}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new v("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:Z,options:X}){}parseHeaders($){return!$?{}:(Symbol.iterator in $)?Object.fromEntries(Array.from($).map((Z)=>[...Z])):{...$}}makeStatusError($,Z,X,Y){return $0.generate($,Z,X,Y)}request($,Z=null){return new V8(this.makeRequest($,Z))}async makeRequest($,Z){let X=await $,Y=X.maxRetries??this.maxRetries;if(Z==null)Z=Y;await this.prepareOptions(X);let{req:G,url:z,timeout:J}=this.buildRequest(X,{retryCount:Y-Z});if(await this.prepareRequest(G,{url:z,options:X}),x1("request",z,X,G.headers),X.signal?.aborted)throw new V0;let Q=new AbortController,W=await this.fetchWithTimeout(z,G,J,Q).catch(z8);if(W instanceof Error){if(X.signal?.aborted)throw new V0;if(Z)return this.retryRequest(X,Z);if(W.name==="AbortError")throw new Z4;throw new i$({cause:W})}let V=cX(W.headers);if(!W.ok){if(Z&&this.shouldRetry(W)){let F=`retrying, ${Z} attempts remaining`;return x1(`response (error; ${F})`,W.status,z,V),this.retryRequest(X,Z,V)}let K=await W.text().catch((F)=>z8(F).message),H=LL(K),U=H?void 0:K;throw x1(`response (error; ${Z?"(error; no more retries left)":"(error; not retryable)"})`,W.status,z,V,U),this.makeStatusError(W.status,H,U,V)}return{response:W,options:X,controller:Q}}requestAPIList($,Z){let X=this.makeRequest(Z,null);return new QG(this,X,$)}buildURL($,Z){let X=wL($)?new URL($):new URL(this.baseURL+(this.baseURL.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Y=this.defaultQuery();if(!WG(Y))Z={...Y,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))X.search=this.stringifyQuery(Z);return X.toString()}stringifyQuery($){return Object.entries($).filter(([Z,X])=>typeof X<"u").map(([Z,X])=>{if(typeof X==="string"||typeof X==="number"||typeof X==="boolean")return`${encodeURIComponent(Z)}=${encodeURIComponent(X)}`;if(X===null)return`${encodeURIComponent(Z)}=`;throw new v(`Cannot stringify type ${typeof X}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout($,Z,X,Y){let{signal:G,...z}=Z||{};if(G)G.addEventListener("abort",()=>Y.abort());let J=setTimeout(()=>Y.abort(),X),Q={signal:Y.signal,...z};if(Q.method)Q.method=Q.method.toUpperCase();let W=60000,V=setTimeout(()=>{if(Q&&Q?.agent?.sockets){for(let K of Object.values(Q?.agent?.sockets).flat())if(K?.setKeepAlive)K.setKeepAlive(!0,W)}},W);return this.fetch.call(void 0,$,Q).finally(()=>{clearTimeout(J),clearTimeout(V)})}shouldRetry($){let Z=$.headers.get("x-should-retry");if(Z==="true")return!0;if(Z==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,X){let Y,G=X?.["retry-after-ms"];if(G){let J=parseFloat(G);if(!Number.isNaN(J))Y=J}let z=X?.["retry-after"];if(z&&!Y){let J=parseFloat(z);if(!Number.isNaN(J))Y=J*1000;else Y=Date.parse(z)-Date.now()}if(!(Y&&0<=Y&&Y<60000)){let J=$.maxRetries??this.maxRetries;Y=this.calculateDefaultRetryTimeoutMillis(Z,J)}return await OL(Y),this.makeRequest($,Z-1)}calculateDefaultRetryTimeoutMillis($,Z){let G=Z-$,z=Math.min(0.5*Math.pow(2,G),8),J=1-Math.random()*0.25;return z*J*1000}getUserAgent(){return`${this.constructor.name}/JS ${l$}`}}class nX{constructor($,Z,X,Y){Q8.set(this,void 0),KL(this,Q8,$,"f"),this.options=Y,this.response=Z,this.body=X}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let $=this.nextPageInfo();if(!$)throw new v("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let Z={...this.options};if("params"in $&&typeof Z.query==="object")Z.query={...Z.query,...$.params};else if("url"in $){let X=[...Object.entries(Z.query||{}),...$.url.searchParams.entries()];for(let[Y,G]of X)$.url.searchParams.set(Y,G);Z.query=void 0,Z.path=$.url.toString()}return await UL(this,Q8,"f").requestAPIList(this.constructor,Z)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(Q8=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class QG extends V8{constructor($,Z,X){super(Z,async(Y)=>new X($,Y.response,await zG(Y),Y.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}var cX=($)=>{return new Proxy(Object.fromEntries($.entries()),{get(Z,X){let Y=X.toString();return Z[Y.toLowerCase()]||Z[Y]}})},BL={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},C0=($)=>{return typeof $==="object"&&$!==null&&!WG($)&&Object.keys($).every((Z)=>VG(BL,Z))},qL=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":l$,"X-Stainless-OS":XG(Deno.build.os),"X-Stainless-Arch":ZG(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":l$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":l$,"X-Stainless-OS":XG(process.platform),"X-Stainless-Arch":ZG(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let $=TL();if($)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":l$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${$.browser}`,"X-Stainless-Runtime-Version":$.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":l$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function TL(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Z,pattern:X}of $){let Y=X.exec(navigator.userAgent);if(Y){let G=Y[1]||0,z=Y[2]||0,J=Y[3]||0;return{browser:Z,version:`${G}.${z}.${J}`}}}return null}var ZG=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},XG=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},YG,FL=()=>{return YG??(YG=qL())},LL=($)=>{try{return JSON.parse($)}catch(Z){return}},ML=/^[a-z][a-z0-9+.-]*:/i,wL=($)=>{return ML.test($)},OL=($)=>new Promise((Z)=>setTimeout(Z,$)),iX=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new v(`${$} must be an integer`);if(Z<0)throw new v(`${$} must be a positive integer`);return Z},z8=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null)try{return Error(JSON.stringify($))}catch{}return Error(String($))};var H8=($)=>{if(typeof process<"u")return process.env?.[$]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.($)?.trim();return};function WG($){if(!$)return!0;for(let Z in $)return!1;return!0}function VG($,Z){return Object.prototype.hasOwnProperty.call($,Z)}function GG($,Z){for(let X in Z){if(!VG(Z,X))continue;let Y=X.toLowerCase();if(!Y)continue;let G=Z[X];if(G===null)delete $[Y];else if(G!==void 0)$[Y]=G}}function x1($,...Z){if(typeof process<"u"&&process?.env?.DEBUG==="true")console.log(`Anthropic:DEBUG:${$}`,...Z)}var NL=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,($)=>{let Z=Math.random()*16|0;return($==="x"?Z:Z&3|8).toString(16)})},HG=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},_L=($)=>{return typeof $?.get==="function"};var W8=($,Z)=>{let X=Z.toLowerCase();if(_L($)){let Y=Z[0]?.toUpperCase()+Z.substring(1).replace(/([^\w])(\w)/g,(G,z,J)=>z+J.toUpperCase());for(let G of[Z,X,Z.toUpperCase(),Y]){let z=$.get(G);if(z)return z}}for(let[Y,G]of Object.entries($))if(Y.toLowerCase()===X){if(Array.isArray(G)){if(G.length<=1)return G[0];return console.warn(`Received ${G.length} entries for the ${Z} header, using the first entry.`),G[0]}return G}return};class e0 extends nX{constructor($,Z,X,Y){super($,Z,X,Y);this.data=X.data||[],this.has_more=X.has_more||!1,this.first_id=X.first_id||null,this.last_id=X.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageParams(){let $=this.nextPageInfo();if(!$)return null;if("params"in $)return $.params;let Z=Object.fromEntries($.url.searchParams);if(!Object.keys(Z).length)return null;return Z}nextPageInfo(){if(this.options.query?.before_id){let Z=this.first_id;if(!Z)return null;return{params:{before_id:Z}}}let $=this.last_id;if(!$)return null;return{params:{after_id:$}}}}class J0{constructor($){this._client=$}}class k1 extends J0{retrieve($,Z){return this._client.get(`/v1/models/${$}?beta=true`,Z)}list($={},Z){if(C0($))return this.list({},$);return this._client.getAPIList("/v1/models?beta=true",G4,{query:$,...Z})}}class G4 extends e0{}k1.BetaModelInfosPage=G4;class b1{constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new O$;for await(let Z of this.iterator)for(let X of $.decode(Z))yield JSON.parse(X);for(let Z of $.flush())yield JSON.parse(Z)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse($,Z){if(!$.body)throw Z.abort(),new v("Attempted to iterate over a response with no body");return new b1(X4($.body),Z)}}class f1 extends J0{create($,Z){let{betas:X,...Y}=$;return this._client.post("/v1/messages/batches?beta=true",{body:Y,...Z,headers:{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),...Z?.headers}})}retrieve($,Z={},X){if(C0(Z))return this.retrieve($,{},Z);let{betas:Y}=Z;return this._client.get(`/v1/messages/batches/${$}?beta=true`,{...X,headers:{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString(),...X?.headers}})}list($={},Z){if(C0($))return this.list({},$);let{betas:X,...Y}=$;return this._client.getAPIList("/v1/messages/batches?beta=true",z4,{query:Y,...Z,headers:{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),...Z?.headers}})}delete($,Z={},X){if(C0(Z))return this.delete($,{},Z);let{betas:Y}=Z;return this._client.delete(`/v1/messages/batches/${$}?beta=true`,{...X,headers:{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString(),...X?.headers}})}cancel($,Z={},X){if(C0(Z))return this.cancel($,{},Z);let{betas:Y}=Z;return this._client.post(`/v1/messages/batches/${$}/cancel?beta=true`,{...X,headers:{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString(),...X?.headers}})}async results($,Z={},X){if(C0(Z))return this.results($,{},Z);let Y=await this.retrieve($);if(!Y.results_url)throw new v(`No batch \`results_url\`; Has it finished processing? ${Y.processing_status} - ${Y.id}`);let{betas:G}=Z;return this._client.get(Y.results_url,{...X,headers:{"anthropic-beta":[...G??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...X?.headers},stream:!0,__binaryResponse:!0})._thenUnwrap((z,J)=>b1.fromResponse(J.response,J.controller))}}class z4 extends e0{}f1.BetaMessageBatchesPage=z4;var RL=($)=>{let Z=0,X=[];while(Z<$.length){let Y=$[Z];if(Y==="\\"){Z++;continue}if(Y==="{"){X.push({type:"brace",value:"{"}),Z++;continue}if(Y==="}"){X.push({type:"brace",value:"}"}),Z++;continue}if(Y==="["){X.push({type:"paren",value:"["}),Z++;continue}if(Y==="]"){X.push({type:"paren",value:"]"}),Z++;continue}if(Y===":"){X.push({type:"separator",value:":"}),Z++;continue}if(Y===","){X.push({type:"delimiter",value:","}),Z++;continue}if(Y==='"'){let Q="",W=!1;Y=$[++Z];while(Y!=='"'){if(Z===$.length){W=!0;break}if(Y==="\\"){if(Z++,Z===$.length){W=!0;break}Q+=Y+$[Z],Y=$[++Z]}else Q+=Y,Y=$[++Z]}if(Y=$[++Z],!W)X.push({type:"string",value:Q});continue}if(Y&&/\s/.test(Y)){Z++;continue}let z=/[0-9]/;if(Y&&z.test(Y)||Y==="-"||Y==="."){let Q="";if(Y==="-")Q+=Y,Y=$[++Z];while(Y&&z.test(Y)||Y===".")Q+=Y,Y=$[++Z];X.push({type:"number",value:Q});continue}let J=/[a-z]/i;if(Y&&J.test(Y)){let Q="";while(Y&&J.test(Y)){if(Z===$.length)break;Q+=Y,Y=$[++Z]}if(Q=="true"||Q=="false"||Q==="null")X.push({type:"name",value:Q});else{Z++;continue}continue}Z++}return X},y1=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),y1($);break;case"number":let X=Z.value[Z.value.length-1];if(X==="."||X==="-")return $=$.slice(0,$.length-1),y1($);case"string":let Y=$[$.length-2];if(Y?.type==="delimiter")return $=$.slice(0,$.length-1),y1($);else if(Y?.type==="brace"&&Y.value==="{")return $=$.slice(0,$.length-1),y1($);break;case"delimiter":return $=$.slice(0,$.length-1),y1($);break}return $},AL=($)=>{let Z=[];if($.map((X)=>{if(X.type==="brace")if(X.value==="{")Z.push("}");else Z.splice(Z.lastIndexOf("}"),1);if(X.type==="paren")if(X.value==="[")Z.push("]");else Z.splice(Z.lastIndexOf("]"),1)}),Z.length>0)Z.reverse().map((X)=>{if(X==="}")$.push({type:"brace",value:"}"});else if(X==="]")$.push({type:"paren",value:"]"})});return $},SL=($)=>{let Z="";return $.map((X)=>{switch(X.type){case"string":Z+='"'+X.value+'"';break;default:Z+=X.value;break}}),Z},K8=($)=>JSON.parse(SL(AL(y1(RL($)))));var H0=function($,Z,X,Y,G){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!G:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call($,X):G?G.value=X:Z.set($,X),X},h=function($,Z,X,Y){if(X==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Y:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call($):Y?Y.value:Z.get($)},I0,N$,J4,U8,Q4,W4,B8,V4,$$,H4,q8,T8,v1,F8,L8,rX,KG,sX,oX,tX,eX,UG,BG="__json_buf";class K4{constructor(){I0.add(this),this.messages=[],this.receivedMessages=[],N$.set(this,void 0),this.controller=new AbortController,J4.set(this,void 0),U8.set(this,()=>{}),Q4.set(this,()=>{}),W4.set(this,void 0),B8.set(this,()=>{}),V4.set(this,()=>{}),$$.set(this,{}),H4.set(this,!1),q8.set(this,!1),T8.set(this,!1),v1.set(this,!1),F8.set(this,void 0),L8.set(this,void 0),sX.set(this,($)=>{if(H0(this,q8,!0,"f"),$ instanceof Error&&$.name==="AbortError")$=new V0;if($ instanceof V0)return H0(this,T8,!0,"f"),this._emit("abort",$);if($ instanceof v)return this._emit("error",$);if($ instanceof Error){let Z=new v($.message);return Z.cause=$,this._emit("error",Z)}return this._emit("error",new v(String($)))}),H0(this,J4,new Promise(($,Z)=>{H0(this,U8,$,"f"),H0(this,Q4,Z,"f")}),"f"),H0(this,W4,new Promise(($,Z)=>{H0(this,B8,$,"f"),H0(this,V4,Z,"f")}),"f"),h(this,J4,"f").catch(()=>{}),h(this,W4,"f").catch(()=>{})}get response(){return h(this,F8,"f")}get request_id(){return h(this,L8,"f")}async withResponse(){let $=await h(this,J4,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let Z=new K4;return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,X){let Y=new K4;for(let G of Z.messages)Y._addMessageParam(G);return Y._run(()=>Y._createMessage($,{...Z,stream:!0},{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},h(this,sX,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}h(this,I0,"m",oX).call(this);let{response:G,data:z}=await $.create({...Z,stream:!0},{...X,signal:this.controller.signal}).withResponse();this._connected(G);for await(let J of z)h(this,I0,"m",tX).call(this,J);if(z.controller.signal?.aborted)throw new V0;h(this,I0,"m",eX).call(this)}_connected($){if(this.ended)return;H0(this,F8,$,"f"),H0(this,L8,$?.headers.get("request-id"),"f"),h(this,U8,"f").call(this,$),this._emit("connect")}get ended(){return h(this,H4,"f")}get errored(){return h(this,q8,"f")}get aborted(){return h(this,T8,"f")}abort(){this.controller.abort()}on($,Z){return(h(this,$$,"f")[$]||(h(this,$$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let X=h(this,$$,"f")[$];if(!X)return this;let Y=X.findIndex((G)=>G.listener===Z);if(Y>=0)X.splice(Y,1);return this}once($,Z){return(h(this,$$,"f")[$]||(h(this,$$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,X)=>{if(H0(this,v1,!0,"f"),$!=="error")this.once("error",X);this.once($,Z)})}async done(){H0(this,v1,!0,"f"),await h(this,W4,"f")}get currentMessage(){return h(this,N$,"f")}async finalMessage(){return await this.done(),h(this,I0,"m",rX).call(this)}async finalText(){return await this.done(),h(this,I0,"m",KG).call(this)}_emit($,...Z){if(h(this,H4,"f"))return;if($==="end")H0(this,H4,!0,"f"),h(this,B8,"f").call(this);let X=h(this,$$,"f")[$];if(X)h(this,$$,"f")[$]=X.filter((Y)=>!Y.once),X.forEach(({listener:Y})=>Y(...Z));if($==="abort"){let Y=Z[0];if(!h(this,v1,"f")&&!X?.length)Promise.reject(Y);h(this,Q4,"f").call(this,Y),h(this,V4,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!h(this,v1,"f")&&!X?.length)Promise.reject(Y);h(this,Q4,"f").call(this,Y),h(this,V4,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",h(this,I0,"m",rX).call(this))}async _fromReadableStream($,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}h(this,I0,"m",oX).call(this),this._connected(null);let Y=_0.fromReadableStream($,this.controller);for await(let G of Y)h(this,I0,"m",tX).call(this,G);if(Y.controller.signal?.aborted)throw new V0;h(this,I0,"m",eX).call(this)}[(N$=new WeakMap,J4=new WeakMap,U8=new WeakMap,Q4=new WeakMap,W4=new WeakMap,B8=new WeakMap,V4=new WeakMap,$$=new WeakMap,H4=new WeakMap,q8=new WeakMap,T8=new WeakMap,v1=new WeakMap,F8=new WeakMap,L8=new WeakMap,sX=new WeakMap,I0=new WeakSet,rX=function(){if(this.receivedMessages.length===0)throw new v("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},KG=function(){if(this.receivedMessages.length===0)throw new v("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((X)=>X.type==="text").map((X)=>X.text);if(Z.length===0)throw new v("stream ended without producing a content block with type=text");return Z.join(" ")},oX=function(){if(this.ended)return;H0(this,N$,void 0,"f")},tX=function(Z){if(this.ended)return;let X=h(this,I0,"m",UG).call(this,Z);switch(this._emit("streamEvent",Z,X),Z.type){case"content_block_delta":{let Y=X.content.at(-1);switch(Z.delta.type){case"text_delta":{if(Y.type==="text")this._emit("text",Z.delta.text,Y.text||"");break}case"citations_delta":{if(Y.type==="text")this._emit("citation",Z.delta.citation,Y.citations??[]);break}case"input_json_delta":{if(Y.type==="tool_use"&&Y.input)this._emit("inputJson",Z.delta.partial_json,Y.input);break}case"thinking_delta":{if(Y.type==="thinking")this._emit("thinking",Z.delta.thinking,Y.thinking);break}case"signature_delta":{if(Y.type==="thinking")this._emit("signature",Y.signature);break}default:qG(Z.delta)}break}case"message_stop":{this._addMessageParam(X),this._addMessage(X,!0);break}case"content_block_stop":{this._emit("contentBlock",X.content.at(-1));break}case"message_start":{H0(this,N$,X,"f");break}case"content_block_start":case"message_delta":break}},eX=function(){if(this.ended)throw new v("stream has ended, this shouldn't happen");let Z=h(this,N$,"f");if(!Z)throw new v("request ended without sending any chunks");return H0(this,N$,void 0,"f"),Z},UG=function(Z){let X=h(this,N$,"f");if(Z.type==="message_start"){if(X)throw new v(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!X)throw new v(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return X;case"message_delta":return X.stop_reason=Z.delta.stop_reason,X.stop_sequence=Z.delta.stop_sequence,X.usage.output_tokens=Z.usage.output_tokens,X;case"content_block_start":return X.content.push(Z.content_block),X;case"content_block_delta":{let Y=X.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Y?.type==="text")Y.text+=Z.delta.text;break}case"citations_delta":{if(Y?.type==="text")Y.citations??(Y.citations=[]),Y.citations.push(Z.delta.citation);break}case"input_json_delta":{if(Y?.type==="tool_use"){let G=Y[BG]||"";if(G+=Z.delta.partial_json,Object.defineProperty(Y,BG,{value:G,enumerable:!1,writable:!0}),G)Y.input=K8(G)}break}case"thinking_delta":{if(Y?.type==="thinking")Y.thinking+=Z.delta.thinking;break}case"signature_delta":{if(Y?.type==="thinking")Y.signature=Z.delta.signature;break}default:qG(Z.delta)}return X}case"content_block_stop":return X}},Symbol.asyncIterator)](){let $=[],Z=[],X=!1;return this.on("streamEvent",(Y)=>{let G=Z.shift();if(G)G.resolve(Y);else $.push(Y)}),this.on("end",()=>{X=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),this.on("error",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(X)return{value:void 0,done:!0};return new Promise((G,z)=>Z.push({resolve:G,reject:z})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new _0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function qG($){}var TG={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};class n$ extends J0{constructor(){super(...arguments);this.batches=new f1(this._client)}create($,Z){let{betas:X,...Y}=$;if(Y.model in TG)console.warn(`The model '${Y.model}' is deprecated and will reach end-of-life on ${TG[Y.model]}
|
|
198
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);return this._client.post("/v1/messages?beta=true",{body:Y,timeout:this._client._options.timeout??(Y.stream?600000:this._client._calculateNonstreamingTimeout(Y.max_tokens)),...Z,headers:{...X?.toString()!=null?{"anthropic-beta":X?.toString()}:void 0,...Z?.headers},stream:$.stream??!1})}stream($,Z){return K4.createMessage(this,$,Z)}countTokens($,Z){let{betas:X,...Y}=$;return this._client.post("/v1/messages/count_tokens?beta=true",{body:Y,...Z,headers:{"anthropic-beta":[...X??[],"token-counting-2024-11-01"].toString(),...Z?.headers}})}}n$.Batches=f1;n$.BetaMessageBatchesPage=z4;class Z$ extends J0{constructor(){super(...arguments);this.models=new k1(this._client),this.messages=new n$(this._client)}}Z$.Models=k1;Z$.BetaModelInfosPage=G4;Z$.Messages=n$;class g1 extends J0{create($,Z){return this._client.post("/v1/complete",{body:$,timeout:this._client._options.timeout??600000,...Z,stream:$.stream??!1})}}class h1 extends J0{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(`/v1/messages/batches/${$}`,Z)}list($={},Z){if(C0($))return this.list({},$);return this._client.getAPIList("/v1/messages/batches",U4,{query:$,...Z})}delete($,Z){return this._client.delete(`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let X=await this.retrieve($);if(!X.results_url)throw new v(`No batch \`results_url\`; Has it finished processing? ${X.processing_status} - ${X.id}`);return this._client.get(X.results_url,{...Z,headers:{Accept:"application/binary",...Z?.headers},__binaryResponse:!0})._thenUnwrap((Y,G)=>b1.fromResponse(G.response,G.controller))}}class U4 extends e0{}h1.MessageBatchesPage=U4;var K0=function($,Z,X,Y,G){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!G:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call($,X):G?G.value=X:Z.set($,X),X},u=function($,Z,X,Y){if(X==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Y:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call($):Y?Y.value:Z.get($)},j0,_$,B4,M8,q4,T4,w8,F4,X$,L4,O8,N8,u1,_8,P8,$5,FG,Z5,X5,Y5,G5,LG,MG="__json_buf";class M4{constructor(){j0.add(this),this.messages=[],this.receivedMessages=[],_$.set(this,void 0),this.controller=new AbortController,B4.set(this,void 0),M8.set(this,()=>{}),q4.set(this,()=>{}),T4.set(this,void 0),w8.set(this,()=>{}),F4.set(this,()=>{}),X$.set(this,{}),L4.set(this,!1),O8.set(this,!1),N8.set(this,!1),u1.set(this,!1),_8.set(this,void 0),P8.set(this,void 0),Z5.set(this,($)=>{if(K0(this,O8,!0,"f"),$ instanceof Error&&$.name==="AbortError")$=new V0;if($ instanceof V0)return K0(this,N8,!0,"f"),this._emit("abort",$);if($ instanceof v)return this._emit("error",$);if($ instanceof Error){let Z=new v($.message);return Z.cause=$,this._emit("error",Z)}return this._emit("error",new v(String($)))}),K0(this,B4,new Promise(($,Z)=>{K0(this,M8,$,"f"),K0(this,q4,Z,"f")}),"f"),K0(this,T4,new Promise(($,Z)=>{K0(this,w8,$,"f"),K0(this,F4,Z,"f")}),"f"),u(this,B4,"f").catch(()=>{}),u(this,T4,"f").catch(()=>{})}get response(){return u(this,_8,"f")}get request_id(){return u(this,P8,"f")}async withResponse(){let $=await u(this,B4,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let Z=new M4;return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,X){let Y=new M4;for(let G of Z.messages)Y._addMessageParam(G);return Y._run(()=>Y._createMessage($,{...Z,stream:!0},{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},u(this,Z5,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}u(this,j0,"m",X5).call(this);let{response:G,data:z}=await $.create({...Z,stream:!0},{...X,signal:this.controller.signal}).withResponse();this._connected(G);for await(let J of z)u(this,j0,"m",Y5).call(this,J);if(z.controller.signal?.aborted)throw new V0;u(this,j0,"m",G5).call(this)}_connected($){if(this.ended)return;K0(this,_8,$,"f"),K0(this,P8,$?.headers.get("request-id"),"f"),u(this,M8,"f").call(this,$),this._emit("connect")}get ended(){return u(this,L4,"f")}get errored(){return u(this,O8,"f")}get aborted(){return u(this,N8,"f")}abort(){this.controller.abort()}on($,Z){return(u(this,X$,"f")[$]||(u(this,X$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let X=u(this,X$,"f")[$];if(!X)return this;let Y=X.findIndex((G)=>G.listener===Z);if(Y>=0)X.splice(Y,1);return this}once($,Z){return(u(this,X$,"f")[$]||(u(this,X$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,X)=>{if(K0(this,u1,!0,"f"),$!=="error")this.once("error",X);this.once($,Z)})}async done(){K0(this,u1,!0,"f"),await u(this,T4,"f")}get currentMessage(){return u(this,_$,"f")}async finalMessage(){return await this.done(),u(this,j0,"m",$5).call(this)}async finalText(){return await this.done(),u(this,j0,"m",FG).call(this)}_emit($,...Z){if(u(this,L4,"f"))return;if($==="end")K0(this,L4,!0,"f"),u(this,w8,"f").call(this);let X=u(this,X$,"f")[$];if(X)u(this,X$,"f")[$]=X.filter((Y)=>!Y.once),X.forEach(({listener:Y})=>Y(...Z));if($==="abort"){let Y=Z[0];if(!u(this,u1,"f")&&!X?.length)Promise.reject(Y);u(this,q4,"f").call(this,Y),u(this,F4,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!u(this,u1,"f")&&!X?.length)Promise.reject(Y);u(this,q4,"f").call(this,Y),u(this,F4,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",u(this,j0,"m",$5).call(this))}async _fromReadableStream($,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}u(this,j0,"m",X5).call(this),this._connected(null);let Y=_0.fromReadableStream($,this.controller);for await(let G of Y)u(this,j0,"m",Y5).call(this,G);if(Y.controller.signal?.aborted)throw new V0;u(this,j0,"m",G5).call(this)}[(_$=new WeakMap,B4=new WeakMap,M8=new WeakMap,q4=new WeakMap,T4=new WeakMap,w8=new WeakMap,F4=new WeakMap,X$=new WeakMap,L4=new WeakMap,O8=new WeakMap,N8=new WeakMap,u1=new WeakMap,_8=new WeakMap,P8=new WeakMap,Z5=new WeakMap,j0=new WeakSet,$5=function(){if(this.receivedMessages.length===0)throw new v("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},FG=function(){if(this.receivedMessages.length===0)throw new v("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((X)=>X.type==="text").map((X)=>X.text);if(Z.length===0)throw new v("stream ended without producing a content block with type=text");return Z.join(" ")},X5=function(){if(this.ended)return;K0(this,_$,void 0,"f")},Y5=function(Z){if(this.ended)return;let X=u(this,j0,"m",LG).call(this,Z);switch(this._emit("streamEvent",Z,X),Z.type){case"content_block_delta":{let Y=X.content.at(-1);switch(Z.delta.type){case"text_delta":{if(Y.type==="text")this._emit("text",Z.delta.text,Y.text||"");break}case"citations_delta":{if(Y.type==="text")this._emit("citation",Z.delta.citation,Y.citations??[]);break}case"input_json_delta":{if(Y.type==="tool_use"&&Y.input)this._emit("inputJson",Z.delta.partial_json,Y.input);break}case"thinking_delta":{if(Y.type==="thinking")this._emit("thinking",Z.delta.thinking,Y.thinking);break}case"signature_delta":{if(Y.type==="thinking")this._emit("signature",Y.signature);break}default:wG(Z.delta)}break}case"message_stop":{this._addMessageParam(X),this._addMessage(X,!0);break}case"content_block_stop":{this._emit("contentBlock",X.content.at(-1));break}case"message_start":{K0(this,_$,X,"f");break}case"content_block_start":case"message_delta":break}},G5=function(){if(this.ended)throw new v("stream has ended, this shouldn't happen");let Z=u(this,_$,"f");if(!Z)throw new v("request ended without sending any chunks");return K0(this,_$,void 0,"f"),Z},LG=function(Z){let X=u(this,_$,"f");if(Z.type==="message_start"){if(X)throw new v(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!X)throw new v(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return X;case"message_delta":return X.stop_reason=Z.delta.stop_reason,X.stop_sequence=Z.delta.stop_sequence,X.usage.output_tokens=Z.usage.output_tokens,X;case"content_block_start":return X.content.push(Z.content_block),X;case"content_block_delta":{let Y=X.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Y?.type==="text")Y.text+=Z.delta.text;break}case"citations_delta":{if(Y?.type==="text")Y.citations??(Y.citations=[]),Y.citations.push(Z.delta.citation);break}case"input_json_delta":{if(Y?.type==="tool_use"){let G=Y[MG]||"";if(G+=Z.delta.partial_json,Object.defineProperty(Y,MG,{value:G,enumerable:!1,writable:!0}),G)Y.input=K8(G)}break}case"thinking_delta":{if(Y?.type==="thinking")Y.thinking+=Z.delta.thinking;break}case"signature_delta":{if(Y?.type==="thinking")Y.signature=Z.delta.signature;break}default:wG(Z.delta)}return X}case"content_block_stop":return X}},Symbol.asyncIterator)](){let $=[],Z=[],X=!1;return this.on("streamEvent",(Y)=>{let G=Z.shift();if(G)G.resolve(Y);else $.push(Y)}),this.on("end",()=>{X=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),this.on("error",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(X)return{value:void 0,done:!0};return new Promise((G,z)=>Z.push({resolve:G,reject:z})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new _0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function wG($){}class P$ extends J0{constructor(){super(...arguments);this.batches=new h1(this._client)}create($,Z){if($.model in OG)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${OG[$.model]}
|
|
199
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);return this._client.post("/v1/messages",{body:$,timeout:this._client._options.timeout??($.stream?600000:this._client._calculateNonstreamingTimeout($.max_tokens)),...Z,stream:$.stream??!1})}stream($,Z){return M4.createMessage(this,$,Z)}countTokens($,Z){return this._client.post("/v1/messages/count_tokens",{body:$,...Z})}}var OG={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};P$.Batches=h1;P$.MessageBatchesPage=U4;class r$ extends J0{retrieve($,Z){return this._client.get(`/v1/models/${$}`,Z)}list($={},Z){if(C0($))return this.list({},$);return this._client.getAPIList("/v1/models",m1,{query:$,...Z})}}class m1 extends e0{}r$.ModelInfosPage=m1;var NG;class p extends aX{constructor({baseURL:$=H8("ANTHROPIC_BASE_URL"),apiKey:Z=H8("ANTHROPIC_API_KEY")??null,authToken:X=H8("ANTHROPIC_AUTH_TOKEN")??null,...Y}={}){let G={apiKey:Z,authToken:X,...Y,baseURL:$||"https://api.anthropic.com"};if(!G.dangerouslyAllowBrowser&&HG())throw new v(`It looks like you're running in a browser-like environment.
|
|
199
200
|
|
|
200
201
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
201
202
|
If you understand the risks and have appropriate mitigations in place,
|
|
202
203
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
203
204
|
|
|
204
205
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
205
|
-
`);super({baseURL:G.baseURL,timeout:G.timeout??600000,httpAgent:G.httpAgent,maxRetries:G.maxRetries,fetch:G.fetch});this.completions=new
|
|
206
|
+
`);super({baseURL:G.baseURL,timeout:G.timeout??600000,httpAgent:G.httpAgent,maxRetries:G.maxRetries,fetch:G.fetch});this.completions=new g1(this),this.messages=new P$(this),this.models=new r$(this),this.beta=new Z$(this),this._options=G,this.apiKey=Z,this.authToken=X}defaultQuery(){return this._options.defaultQuery}defaultHeaders($){return{...super.defaultHeaders($),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders($,Z){if(this.apiKey&&$["x-api-key"])return;if(Z["x-api-key"]===null)return;if(this.authToken&&$.authorization)return;if(Z.authorization===null)return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders($){return{...this.apiKeyAuth($),...this.bearerAuth($)}}apiKeyAuth($){if(this.apiKey==null)return{};return{"X-Api-Key":this.apiKey}}bearerAuth($){if(this.authToken==null)return{};return{Authorization:`Bearer ${this.authToken}`}}}NG=p;p.Anthropic=NG;p.HUMAN_PROMPT=`
|
|
206
207
|
|
|
207
208
|
Human:`;p.AI_PROMPT=`
|
|
208
209
|
|
|
209
|
-
Assistant:`;p.DEFAULT_TIMEOUT=600000;p.AnthropicError=v;p.APIError
|
|
210
|
+
Assistant:`;p.DEFAULT_TIMEOUT=600000;p.AnthropicError=v;p.APIError=$0;p.APIConnectionError=i$;p.APIConnectionTimeoutError=Z4;p.APIUserAbortError=V0;p.NotFoundError=$8;p.ConflictError=Z8;p.RateLimitError=Y8;p.BadRequestError=oZ;p.AuthenticationError=tZ;p.InternalServerError=G8;p.PermissionDeniedError=eZ;p.UnprocessableEntityError=X8;p.toFile=$G;p.fileFromPath=sZ;p.Completions=g1;p.Messages=P$;p.Models=r$;p.ModelInfosPage=m1;p.Beta=Z$;var _G=p;function D$($,Z,X){let Y=Z.length>0?Z.map((J)=>`- ${J.id}: ${J.name} (${J.source})`).join(`
|
|
210
211
|
`):"(no sources provided)",G=Z.map((J)=>`<source id="${J.id}">
|
|
211
212
|
${J.content.trimEnd()}
|
|
212
213
|
</source>`).join(`
|
|
@@ -231,27 +232,27 @@ End your response with a "## Sources" section that lists every source you actual
|
|
|
231
232
|
Rules:
|
|
232
233
|
- Only cite IDs that appear in the inventory above. Do not invent IDs.
|
|
233
234
|
- If you cannot answer from the provided sources, say so explicitly and write an empty "## Sources" section (just the heading, no bullets).
|
|
234
|
-
- The "## Sources" heading must be the last heading in your response.`}function
|
|
235
|
+
- The "## Sources" heading must be the last heading in your response.`}function d1($,Z){let X=Z&&Z.length>0?`
|
|
235
236
|
The canonical source for this question is: ${Z}
|
|
236
237
|
Use it as the primary reference; consult related authoritative sources if needed.`:`
|
|
237
238
|
Research the answer using authoritative sources you can reach with your tools.`;return`You are answering a question about the tool "${$.name}": ${$.description}.
|
|
238
239
|
|
|
239
240
|
Use the tools available to you to research the answer. Be specific and accurate; do not invent facts.${X}
|
|
240
241
|
|
|
241
|
-
If you cannot find the answer with the available tools, say so explicitly rather than guessing.`}class z5{category="api";provider="anthropic";name;config;clientFactory;constructor($,Z,X){this.name=$,this.config=Z,this.clientFactory=X??(()=>new OG)}async run($,Z){let{tool:X,docs:Y,requiredSources:G,discovery:z,webTools:J}=Z;if(!this.config.model)throw Error(`API target "${this.name}" missing 'model'. API targets must declare an explicit model.`);let Q=z?p1(X,z.sourceHint):E$(X,Y,G),W=this.clientFactory(),V=J?.search?[{type:"web_search_20250305",name:"web_search"}]:void 0,K=await W.messages.create({model:this.config.model,max_tokens:this.config.maxTokens??4096,temperature:this.config.temperature??0,system:Q,messages:[{role:"user",content:$}],...V?{tools:V}:{}}),H=CL(K.content),B=IL(K.content);return{response:H,allResponses:H?[{type:"final",text:H}]:[],toolsUsed:B,sources:[],metadata:{model:this.config.model,category:this.category,provider:this.provider,target:this.name}}}}function CL($){if(!Array.isArray($))return"";let Z=[];for(let X of $)if(X.type==="text"&&typeof X.text==="string")Z.push(X.text);return Z.join("")}function IL($){if(!Array.isArray($))return[];let Z=new Set;for(let X of $)if(X.type==="server_tool_use"&&typeof X.name==="string")Z.add(X.name);return Array.from(Z)}function x($,Z,X,Y,G){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!G:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call($,X):G?G.value=X:Z.set($,X),X}function M($,Z,X,Y){if(X==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Y:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call($):Y?Y.value:Z.get($)}var J5=function(){let{crypto:$}=globalThis;if($?.randomUUID)return J5=$.randomUUID.bind($),$.randomUUID();let Z=new Uint8Array(1),X=$?()=>$.getRandomValues(Z)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Y)=>(+Y^X()&15>>+Y/4).toString(16))};function O4($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var N4=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let Z=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)Z.stack=$.stack;if($.cause&&!Z.cause)Z.cause=$.cause;if($.name)Z.name=$.name;return Z}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class I extends Error{}class r extends I{constructor($,Z,X,Y){super(`${r.makeMessage($,Z,X)}`);this.status=$,this.headers=Y,this.requestID=Y?.get("x-request-id"),this.error=Z;let G=Z;this.code=G?.code,this.param=G?.param,this.type=G?.type}static makeMessage($,Z,X){let Y=Z?.message?typeof Z.message==="string"?Z.message:JSON.stringify(Z.message):Z?JSON.stringify(Z):X;if($&&Y)return`${$} ${Y}`;if($)return`${$} status code (no body)`;if(Y)return Y;return"(no status code or body)"}static generate($,Z,X,Y){if(!$||!Y)return new $1({message:X,cause:N4(Z)});let G=Z?.error;if($===400)return new _4($,G,X,Y);if($===401)return new P4($,G,X,Y);if($===403)return new D4($,G,X,Y);if($===404)return new E4($,G,X,Y);if($===409)return new R4($,G,X,Y);if($===422)return new A4($,G,X,Y);if($===429)return new S4($,G,X,Y);if($>=500)return new C4($,G,X,Y);return new r($,G,X,Y)}}class $0 extends r{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class $1 extends r{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class Z1 extends $1{constructor({message:$}={}){super({message:$??"Request timed out."})}}class _4 extends r{}class P4 extends r{}class D4 extends r{}class E4 extends r{}class R4 extends r{}class A4 extends r{}class S4 extends r{}class C4 extends r{}class I4 extends I{constructor(){super("Could not parse response content as the length limit was reached")}}class j4 extends I{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class G$ extends Error{constructor($){super($)}}class i1 extends r{constructor($,Z,X){let Y="OAuth2 authentication error",G=void 0;if(Z&&typeof Z==="object"){let z=Z;G=z.error;let J=z.error_description;if(J&&typeof J==="string")Y=J;else if(G)Y=G}super($,Z,Y,X);this.error_code=G}}class D8 extends I{constructor($,Z,X){super($);this.provider=Z,this.cause=X}}var xL=/^[a-z][a-z0-9+.-]*:/i,NG=($)=>{return xL.test($)},U0=($)=>(U0=Array.isArray,U0($)),Q5=U0;function E8($){if(typeof $!=="object")return{};return $??{}}function W5($){if(!$)return!0;for(let Z in $)return!1;return!0}function _G($,Z){return Object.prototype.hasOwnProperty.call($,Z)}function x4($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var PG=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new I(`${$} must be an integer`);if(Z<0)throw new I(`${$} must be a positive integer`);return Z};var DG=($)=>{try{return JSON.parse($)}catch(Z){return}};var d0=($)=>new Promise((Z)=>setTimeout(Z,$));var R$="6.39.0";var SG=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function kL(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var bL=()=>{let $=kL();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":R$,"X-Stainless-OS":RG(Deno.build.os),"X-Stainless-Arch":EG(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":R$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if($==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":R$,"X-Stainless-OS":RG(globalThis.process.platform??"unknown"),"X-Stainless-Arch":EG(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=fL();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":R$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Z.browser}`,"X-Stainless-Runtime-Version":Z.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":R$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function fL(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Z,pattern:X}of $){let Y=X.exec(navigator.userAgent);if(Y){let G=Y[1]||0,z=Y[2]||0,J=Y[3]||0;return{browser:Z,version:`${G}.${z}.${J}`}}}return null}var EG=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},RG=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},AG,CG=()=>{return AG??(AG=bL())};function R8(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function V5(...$){let Z=globalThis.ReadableStream;if(typeof Z>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Z(...$)}function A8($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return V5({start(){},async pull(X){let{done:Y,value:G}=await Z.next();if(Y)X.close();else X.enqueue(G)},async cancel(){await Z.return?.()}})}function H5($){if($[Symbol.asyncIterator])return $;let Z=$.getReader();return{async next(){try{let X=await Z.read();if(X?.done)Z.releaseLock();return X}catch(X){throw Z.releaseLock(),X}},async return(){let X=Z.cancel();return Z.releaseLock(),await X,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function K5($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),X=Z.cancel();Z.releaseLock(),await X}var jG=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};var B5="RFC3986",U5=($)=>String($),q5={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:U5},xG="RFC1738";var S8=($,Z)=>(S8=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),S8($,Z)),c0=(()=>{let $=[];for(let Z=0;Z<256;++Z)$.push("%"+((Z<16?"0":"")+Z.toString(16)).toUpperCase());return $})();var T5=1024,kG=($,Z,X,Y,G)=>{if($.length===0)return $;let z=$;if(typeof $==="symbol")z=Symbol.prototype.toString.call($);else if(typeof $!=="string")z=String($);if(X==="iso-8859-1")return escape(z).replace(/%u[0-9a-f]{4}/gi,function(Q){return"%26%23"+parseInt(Q.slice(2),16)+"%3B"});let J="";for(let Q=0;Q<z.length;Q+=T5){let W=z.length>=T5?z.slice(Q,Q+T5):z,V=[];for(let K=0;K<W.length;++K){let H=W.charCodeAt(K);if(H===45||H===46||H===95||H===126||H>=48&&H<=57||H>=65&&H<=90||H>=97&&H<=122||G===xG&&(H===40||H===41)){V[V.length]=W.charAt(K);continue}if(H<128){V[V.length]=c0[H];continue}if(H<2048){V[V.length]=c0[192|H>>6]+c0[128|H&63];continue}if(H<55296||H>=57344){V[V.length]=c0[224|H>>12]+c0[128|H>>6&63]+c0[128|H&63];continue}K+=1,H=65536+((H&1023)<<10|W.charCodeAt(K)&1023),V[V.length]=c0[240|H>>18]+c0[128|H>>12&63]+c0[128|H>>6&63]+c0[128|H&63]}J+=V.join("")}return J};function bG($){if(!$||typeof $!=="object")return!1;return!!($.constructor&&$.constructor.isBuffer&&$.constructor.isBuffer($))}function F5($,Z){if(U0($)){let X=[];for(let Y=0;Y<$.length;Y+=1)X.push(Z($[Y]));return X}return Z($)}var yG={brackets($){return String($)+"[]"},comma:"comma",indices($,Z){return String($)+"["+Z+"]"},repeat($){return String($)}},vG=function($,Z){Array.prototype.push.apply($,U0(Z)?Z:[Z])},fG,Z0={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:kG,encodeValuesOnly:!1,format:B5,formatter:U5,indices:!1,serializeDate($){return(fG??(fG=Function.prototype.call.bind(Date.prototype.toISOString)))($)},skipNulls:!1,strictNullHandling:!1};function vL($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}var L5={};function gG($,Z,X,Y,G,z,J,Q,W,V,K,H,B,U,F,T,w,O){let N=$,_=O,P=0,R=!1;while((_=_.get(L5))!==void 0&&!R){let b=_.get($);if(P+=1,typeof b<"u")if(b===P)throw RangeError("Cyclic object value");else R=!0;if(typeof _.get(L5)>"u")P=0}if(typeof V==="function")N=V(Z,N);else if(N instanceof Date)N=B?.(N);else if(X==="comma"&&U0(N))N=F5(N,function(b){if(b instanceof Date)return B?.(b);return b});if(N===null){if(z)return W&&!T?W(Z,Z0.encoder,w,"key",U):Z;N=""}if(vL(N)||bG(N)){if(W){let b=T?Z:W(Z,Z0.encoder,w,"key",U);return[F?.(b)+"="+F?.(W(N,Z0.encoder,w,"value",U))]}return[F?.(Z)+"="+F?.(String(N))]}let A=[];if(typeof N>"u")return A;let S;if(X==="comma"&&U0(N)){if(T&&W)N=F5(N,W);S=[{value:N.length>0?N.join(",")||null:void 0}]}else if(U0(V))S=V;else{let b=Object.keys(N);S=K?b.sort(K):b}let D=Q?String(Z).replace(/\./g,"%2E"):String(Z),k=Y&&U0(N)&&N.length===1?D+"[]":D;if(G&&U0(N)&&N.length===0)return k+"[]";for(let b=0;b<S.length;++b){let i=S[b],c=typeof i==="object"&&typeof i.value<"u"?i.value:N[i];if(J&&c===null)continue;let M0=H&&Q?i.replace(/\./g,"%2E"):i,v$=U0(N)?typeof X==="function"?X(k,M0):k:k+(H?"."+M0:"["+M0+"]");O.set($,P);let N0=new WeakMap;N0.set(L5,O),vG(A,gG(c,v$,X,Y,G,z,J,Q,X==="comma"&&T&&U0(N)?null:W,V,K,H,B,U,F,T,w,N0))}return A}function gL($=Z0){if(typeof $.allowEmptyArrays<"u"&&typeof $.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof $.encodeDotInKeys<"u"&&typeof $.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if($.encoder!==null&&typeof $.encoder<"u"&&typeof $.encoder!=="function")throw TypeError("Encoder has to be a function.");let Z=$.charset||Z0.charset;if(typeof $.charset<"u"&&$.charset!=="utf-8"&&$.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let X=B5;if(typeof $.format<"u"){if(!S8(q5,$.format))throw TypeError("Unknown format option provided.");X=$.format}let Y=q5[X],G=Z0.filter;if(typeof $.filter==="function"||U0($.filter))G=$.filter;let z;if($.arrayFormat&&$.arrayFormat in yG)z=$.arrayFormat;else if("indices"in $)z=$.indices?"indices":"repeat";else z=Z0.arrayFormat;if("commaRoundTrip"in $&&typeof $.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let J=typeof $.allowDots>"u"?!!$.encodeDotInKeys===!0?!0:Z0.allowDots:!!$.allowDots;return{addQueryPrefix:typeof $.addQueryPrefix==="boolean"?$.addQueryPrefix:Z0.addQueryPrefix,allowDots:J,allowEmptyArrays:typeof $.allowEmptyArrays==="boolean"?!!$.allowEmptyArrays:Z0.allowEmptyArrays,arrayFormat:z,charset:Z,charsetSentinel:typeof $.charsetSentinel==="boolean"?$.charsetSentinel:Z0.charsetSentinel,commaRoundTrip:!!$.commaRoundTrip,delimiter:typeof $.delimiter>"u"?Z0.delimiter:$.delimiter,encode:typeof $.encode==="boolean"?$.encode:Z0.encode,encodeDotInKeys:typeof $.encodeDotInKeys==="boolean"?$.encodeDotInKeys:Z0.encodeDotInKeys,encoder:typeof $.encoder==="function"?$.encoder:Z0.encoder,encodeValuesOnly:typeof $.encodeValuesOnly==="boolean"?$.encodeValuesOnly:Z0.encodeValuesOnly,filter:G,format:X,formatter:Y,serializeDate:typeof $.serializeDate==="function"?$.serializeDate:Z0.serializeDate,skipNulls:typeof $.skipNulls==="boolean"?$.skipNulls:Z0.skipNulls,sort:typeof $.sort==="function"?$.sort:null,strictNullHandling:typeof $.strictNullHandling==="boolean"?$.strictNullHandling:Z0.strictNullHandling}}function hG($,Z={}){let X=$,Y=gL(Z),G,z;if(typeof Y.filter==="function")z=Y.filter,X=z("",X);else if(U0(Y.filter))z=Y.filter,G=z;let J=[];if(typeof X!=="object"||X===null)return"";let Q=yG[Y.arrayFormat],W=Q==="comma"&&Y.commaRoundTrip;if(!G)G=Object.keys(X);if(Y.sort)G.sort(Y.sort);let V=new WeakMap;for(let B=0;B<G.length;++B){let U=G[B];if(Y.skipNulls&&X[U]===null)continue;vG(J,gG(X[U],U,Q,W,Y.allowEmptyArrays,Y.strictNullHandling,Y.skipNulls,Y.encodeDotInKeys,Y.encode?Y.encoder:null,Y.filter,Y.sort,Y.allowDots,Y.serializeDate,Y.format,Y.formatter,Y.encodeValuesOnly,Y.charset,V))}let K=J.join(Y.delimiter),H=Y.addQueryPrefix===!0?"?":"";if(Y.charsetSentinel)if(Y.charset==="iso-8859-1")H+="utf8=%26%2310003%3B&";else H+="utf8=%E2%9C%93&";return K.length>0?H+K:""}function uG($){return hG($,{arrayFormat:"brackets"})}function cG($){let Z=0;for(let G of $)Z+=G.length;let X=new Uint8Array(Z),Y=0;for(let G of $)X.set(G,Y),Y+=G.length;return X}var mG;function a1($){let Z;return(mG??(Z=new globalThis.TextEncoder,mG=Z.encode.bind(Z)))($)}var dG;function w5($){let Z;return(dG??(Z=new globalThis.TextDecoder,dG=Z.decode.bind(Z)))($)}var D0,E0;class n1{constructor(){D0.set(this,void 0),E0.set(this,void 0),x(this,D0,new Uint8Array,"f"),x(this,E0,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?a1($):$;x(this,D0,cG([M(this,D0,"f"),Z]),"f");let X=[],Y;while((Y=uL(M(this,D0,"f"),M(this,E0,"f")))!=null){if(Y.carriage&&M(this,E0,"f")==null){x(this,E0,Y.index,"f");continue}if(M(this,E0,"f")!=null&&(Y.index!==M(this,E0,"f")+1||Y.carriage)){X.push(w5(M(this,D0,"f").subarray(0,M(this,E0,"f")-1))),x(this,D0,M(this,D0,"f").subarray(M(this,E0,"f")),"f"),x(this,E0,null,"f");continue}let G=M(this,E0,"f")!==null?Y.preceding-1:Y.preceding,z=w5(M(this,D0,"f").subarray(0,G));X.push(z),x(this,D0,M(this,D0,"f").subarray(Y.index),"f"),x(this,E0,null,"f")}return X}flush(){if(!M(this,D0,"f").length)return[];return this.decode(`
|
|
242
|
-
`)}}
|
|
243
|
-
`,"\r"]);
|
|
244
|
-
`);X.enqueue(z)}catch(Y){X.error(Y)}},async cancel(){await Z.return?.()}})}}async function*
|
|
245
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],G}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,X,Y]=lL($,":");if(Y.startsWith(" "))Y=Y.substring(1);if(Z==="event")this.event=Y;else if(Z==="data")this.data.push(Y);return null}}function lL($,Z){let X=$.indexOf(Z);if(X!==-1)return[$.substring(0,X),Z,$.substring(X+Z.length)];return[$,"",""]}async function j8($,Z){let{response:X,requestLogID:Y,retryOfRequestLogID:G,startTime:z}=Z,J=await(async()=>{if(Z.options.stream){if(s($).debug("response",X.status,X.url,X.headers,X.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(X,Z.controller,$,Z.options.__synthesizeEventData);return R0.fromSSEResponse(X,Z.controller,$,Z.options.__synthesizeEventData)}if(X.status===204)return null;if(Z.options.__binaryResponse)return X;let W=X.headers.get("content-type")?.split(";")[0]?.trim();if(W?.includes("application/json")||W?.endsWith("+json")){if(X.headers.get("content-length")==="0")return;let B=await X.json();return O5(B,X)}return await X.text()})();return s($).debug(`[${Y}] response parsed`,z$({retryOfRequestLogID:G,url:X.url,status:X.status,body:J,durationMs:Date.now()-z})),J}function O5($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("x-request-id"),enumerable:!1})}var f4;class X1 extends Promise{constructor($,Z,X=j8){super((Y)=>{Y(null)});this.responsePromise=Z,this.parseResponse=X,f4.set(this,void 0),x(this,f4,$,"f")}_thenUnwrap($){return new X1(M(this,f4,"f"),this.responsePromise,async(Z,X)=>O5($(await this.parseResponse(Z,X),X),X.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,Z]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:Z,request_id:Z.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(M(this,f4,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}f4=new WeakMap;var x8;class y4{constructor($,Z,X,Y){x8.set(this,void 0),x(this,x8,$,"f"),this.options=Y,this.response=Z,this.body=X}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new I("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await M(this,x8,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(x8=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class k8 extends X1{constructor($,Z,X){super($,Z,async(Y,G)=>new X(Y,G.response,await j8(Y,G),G.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class L0 extends y4{constructor($,Z,X,Y){super($,Z,X,Y);this.data=X.data||[],this.object=X.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class y extends y4{constructor($,Z,X,Y){super($,Z,X,Y);this.data=X.data||[],this.has_more=X.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.getPaginatedItems(),Z=$[$.length-1]?.id;if(!Z)return null;return{...this.options,query:{...E8(this.options.query),after:Z}}}}class d extends y4{constructor($,Z,X,Y){super($,Z,X,Y);this.data=X.data||[],this.has_more=X.has_more||!1,this.last_id=X.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.last_id;if(!$)return null;return{...this.options,query:{...E8(this.options.query),after:$}}}}class X0 extends y4{constructor($,Z,X,Y){super($,Z,X,Y);this.data=X.data||[],this.has_more=X.has_more||!1,this.next=X.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.next;if(!$)return null;return{...this.options,query:{...E8(this.options.query),after:$}}}}var iL={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},aL="urn:ietf:params:oauth:grant-type:token-exchange";class N5{constructor($,Z){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=$,this.fetch=Z??R8()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}if(this.needsRefresh(this.cachedToken)&&!this.refreshPromise)this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null});return this.cachedToken.token}async refreshToken(){let $=await this.config.provider.getToken(),Z={grant_type:aL,subject_token:$,subject_token_type:iL[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};if(this.config.clientId)Z.client_id=this.config.clientId;let X=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!X.ok){let J=await X.text(),Q=void 0;try{Q=JSON.parse(J)}catch{}if(X.status===400||X.status===401||X.status===403)throw new i1(X.status,Q,X.headers);throw r.generate(X.status,Q,`Token exchange failed with status ${X.status}`,X.headers)}let Y=await X.json(),G=Y.expires_in||3600,z=Date.now()+G*1000;return this.cachedToken={token:Y.access_token,expiresAt:z},Y.access_token}isTokenExpired($){return Date.now()>=$.expiresAt}needsRefresh($){let X=(this.config.refreshBufferSeconds??1200)*1000;return Date.now()>=$.expiresAt-X}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}}var D5=()=>{if(typeof File>"u"){let{process:$}=globalThis,Z=typeof $?.versions?.node==="string"&&parseInt($.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(Z?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function r1($,Z,X){return D5(),new File($,Z??"unknown_file",X)}function v4($){return(typeof $==="object"&&$!==null&&(("name"in $)&&$.name&&String($.name)||("url"in $)&&$.url&&String($.url)||("filename"in $)&&$.filename&&String($.filename)||("path"in $)&&$.path&&String($.path))||"").split(/[\\/]/).pop()||void 0}var b8=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function",A$=async($,Z)=>{if(!_5($.body))return $;return{...$,body:await nG($.body,Z)}},q0=async($,Z)=>{return{...$,body:await nG($.body,Z)}},aG=new WeakMap;function nL($){let Z=typeof $==="function"?$:$.fetch,X=aG.get(Z);if(X)return X;let Y=(async()=>{try{let G="Response"in Z?Z.Response:(await Z("data:,")).constructor,z=new FormData;if(z.toString()===await new G(z).text())return!1;return!0}catch{return!0}})();return aG.set(Z,Y),Y}var nG=async($,Z)=>{if(!await nL(Z))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let X=new FormData;return await Promise.all(Object.entries($||{}).map(([Y,G])=>P5(X,Y,G))),X},rG=($)=>$ instanceof Blob&&("name"in $),rL=($)=>typeof $==="object"&&$!==null&&($ instanceof Response||b8($)||rG($)),_5=($)=>{if(rL($))return!0;if(Array.isArray($))return $.some(_5);if($&&typeof $==="object"){for(let Z in $)if(_5($[Z]))return!0}return!1},P5=async($,Z,X)=>{if(X===void 0)return;if(X==null)throw TypeError(`Received null for "${Z}"; to pass null in FormData, you must use the string 'null'`);if(typeof X==="string"||typeof X==="number"||typeof X==="boolean")$.append(Z,String(X));else if(X instanceof Response)$.append(Z,r1([await X.blob()],v4(X)));else if(b8(X))$.append(Z,r1([await new Response(A8(X)).blob()],v4(X)));else if(rG(X))$.append(Z,X,v4(X));else if(Array.isArray(X))await Promise.all(X.map((Y)=>P5($,Z+"[]",Y)));else if(typeof X==="object")await Promise.all(Object.entries(X).map(([Y,G])=>P5($,`${Z}[${Y}]`,G)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${X} instead`)};var sG=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",sL=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&sG($),oL=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function f8($,Z,X){if(D5(),$=await $,sL($)){if($ instanceof File)return $;return r1([await $.arrayBuffer()],$.name)}if(oL($)){let G=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),r1(await E5(G),Z,X)}let Y=await E5($);if(Z||(Z=v4($)),!X?.type){let G=Y.find((z)=>typeof z==="object"&&("type"in z)&&z.type);if(typeof G==="string")X={...X,type:G}}return r1(Y,Z,X)}async function E5($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(sG($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(b8($))for await(let X of $)Z.push(...await E5(X));else{let X=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${X?`; constructor: ${X}`:""}${tL($)}`)}return Z}function tL($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((X)=>`"${X}"`).join(", ")}]`}class L{constructor($){this._client=$}}function tG($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var oG=Object.freeze(Object.create(null)),$w=($=tG)=>function(X,...Y){if(X.length===1)return X[0];let G=!1,z=[],J=X.reduce((K,H,B)=>{if(/[?#]/.test(H))G=!0;let U=Y[B],F=(G?encodeURIComponent:$)(""+U);if(B!==Y.length&&(U==null||typeof U==="object"&&U.toString===Object.getPrototypeOf(Object.getPrototypeOf(U.hasOwnProperty??oG)??oG)?.toString))F=U+"",z.push({start:K.length+H.length,length:F.length,error:`Value of type ${Object.prototype.toString.call(U).slice(8,-1)} is not a valid path parameter`});return K+H+(B===Y.length?"":F)},""),Q=J.split(/[?#]/,1)[0],W=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,V;while((V=W.exec(Q))!==null)z.push({start:V.index,length:V[0].length,error:`Value "${V[0]}" can't be safely passed as a path parameter`});if(z.sort((K,H)=>K.start-H.start),z.length>0){let K=0,H=z.reduce((B,U)=>{let F=" ".repeat(U.start-K),T="^".repeat(U.length);return K=U.start+U.length,B+F+T},"");throw new I(`Path parameters result in path with invalid segments:
|
|
246
|
-
${z.map((
|
|
242
|
+
If you cannot find the answer with the available tools, say so explicitly rather than guessing.`}class z5{category="api";provider="anthropic";name;config;clientFactory;constructor($,Z,X){this.name=$,this.config=Z,this.clientFactory=X??(()=>new _G)}async run($,Z){let{tool:X,docs:Y,requiredSources:G,discovery:z,webTools:J}=Z;if(!this.config.model)throw Error(`API target "${this.name}" missing 'model'. API targets must declare an explicit model.`);let Q=z?d1(X,z.sourceHint):D$(X,Y,G),W=this.clientFactory(),V=J?.search?[{type:"web_search_20250305",name:"web_search"}]:void 0,K=await W.messages.create({model:this.config.model,max_tokens:this.config.maxTokens??4096,temperature:this.config.temperature??0,system:Q,messages:[{role:"user",content:$}],...V?{tools:V}:{}}),H=xL(K.content),U=kL(K.content);return{response:H,allResponses:H?[{type:"final",text:H}]:[],toolsUsed:U,sources:[],metadata:{model:this.config.model,category:this.category,provider:this.provider,target:this.name}}}}function xL($){if(!Array.isArray($))return"";let Z=[];for(let X of $)if(X.type==="text"&&typeof X.text==="string")Z.push(X.text);return Z.join("")}function kL($){if(!Array.isArray($))return[];let Z=new Set;for(let X of $)if(X.type==="server_tool_use"&&typeof X.name==="string")Z.add(X.name);return Array.from(Z)}function x($,Z,X,Y,G){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!G:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?G.call($,X):G?G.value=X:Z.set($,X),X}function w($,Z,X,Y){if(X==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Y:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call($):Y?Y.value:Z.get($)}var J5=function(){let{crypto:$}=globalThis;if($?.randomUUID)return J5=$.randomUUID.bind($),$.randomUUID();let Z=new Uint8Array(1),X=$?()=>$.getRandomValues(Z)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Y)=>(+Y^X()&15>>+Y/4).toString(16))};function w4($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var O4=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let Z=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)Z.stack=$.stack;if($.cause&&!Z.cause)Z.cause=$.cause;if($.name)Z.name=$.name;return Z}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class I extends Error{}class r extends I{constructor($,Z,X,Y){super(`${r.makeMessage($,Z,X)}`);this.status=$,this.headers=Y,this.requestID=Y?.get("x-request-id"),this.error=Z;let G=Z;this.code=G?.code,this.param=G?.param,this.type=G?.type}static makeMessage($,Z,X){let Y=Z?.message?typeof Z.message==="string"?Z.message:JSON.stringify(Z.message):Z?JSON.stringify(Z):X;if($&&Y)return`${$} ${Y}`;if($)return`${$} status code (no body)`;if(Y)return Y;return"(no status code or body)"}static generate($,Z,X,Y){if(!$||!Y)return new s$({message:X,cause:O4(Z)});let G=Z?.error;if($===400)return new N4($,G,X,Y);if($===401)return new _4($,G,X,Y);if($===403)return new P4($,G,X,Y);if($===404)return new D4($,G,X,Y);if($===409)return new E4($,G,X,Y);if($===422)return new R4($,G,X,Y);if($===429)return new A4($,G,X,Y);if($>=500)return new S4($,G,X,Y);return new r($,G,X,Y)}}class Z0 extends r{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class s$ extends r{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class o$ extends s${constructor({message:$}={}){super({message:$??"Request timed out."})}}class N4 extends r{}class _4 extends r{}class P4 extends r{}class D4 extends r{}class E4 extends r{}class R4 extends r{}class A4 extends r{}class S4 extends r{}class C4 extends I{constructor(){super("Could not parse response content as the length limit was reached")}}class I4 extends I{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Y$ extends Error{constructor($){super($)}}class c1 extends r{constructor($,Z,X){let Y="OAuth2 authentication error",G=void 0;if(Z&&typeof Z==="object"){let z=Z;G=z.error;let J=z.error_description;if(J&&typeof J==="string")Y=J;else if(G)Y=G}super($,Z,Y,X);this.error_code=G}}class D8 extends I{constructor($,Z,X){super($);this.provider=Z,this.cause=X}}var fL=/^[a-z][a-z0-9+.-]*:/i,PG=($)=>{return fL.test($)},U0=($)=>(U0=Array.isArray,U0($)),Q5=U0;function E8($){if(typeof $!=="object")return{};return $??{}}function W5($){if(!$)return!0;for(let Z in $)return!1;return!0}function DG($,Z){return Object.prototype.hasOwnProperty.call($,Z)}function j4($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var EG=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new I(`${$} must be an integer`);if(Z<0)throw new I(`${$} must be a positive integer`);return Z};var RG=($)=>{try{return JSON.parse($)}catch(Z){return}};var u0=($)=>new Promise((Z)=>setTimeout(Z,$));var E$="6.39.0";var IG=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function yL(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var vL=()=>{let $=yL();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E$,"X-Stainless-OS":SG(Deno.build.os),"X-Stainless-Arch":AG(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if($==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E$,"X-Stainless-OS":SG(globalThis.process.platform??"unknown"),"X-Stainless-Arch":AG(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=gL();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Z.browser}`,"X-Stainless-Runtime-Version":Z.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function gL(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Z,pattern:X}of $){let Y=X.exec(navigator.userAgent);if(Y){let G=Y[1]||0,z=Y[2]||0,J=Y[3]||0;return{browser:Z,version:`${G}.${z}.${J}`}}}return null}var AG=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},SG=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},CG,jG=()=>{return CG??(CG=vL())};function R8(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function V5(...$){let Z=globalThis.ReadableStream;if(typeof Z>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Z(...$)}function A8($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return V5({start(){},async pull(X){let{done:Y,value:G}=await Z.next();if(Y)X.close();else X.enqueue(G)},async cancel(){await Z.return?.()}})}function H5($){if($[Symbol.asyncIterator])return $;let Z=$.getReader();return{async next(){try{let X=await Z.read();if(X?.done)Z.releaseLock();return X}catch(X){throw Z.releaseLock(),X}},async return(){let X=Z.cancel();return Z.releaseLock(),await X,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function K5($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),X=Z.cancel();Z.releaseLock(),await X}var kG=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};var U5="RFC3986",B5=($)=>String($),q5={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:B5},bG="RFC1738";var S8=($,Z)=>(S8=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),S8($,Z)),m0=(()=>{let $=[];for(let Z=0;Z<256;++Z)$.push("%"+((Z<16?"0":"")+Z.toString(16)).toUpperCase());return $})();var T5=1024,fG=($,Z,X,Y,G)=>{if($.length===0)return $;let z=$;if(typeof $==="symbol")z=Symbol.prototype.toString.call($);else if(typeof $!=="string")z=String($);if(X==="iso-8859-1")return escape(z).replace(/%u[0-9a-f]{4}/gi,function(Q){return"%26%23"+parseInt(Q.slice(2),16)+"%3B"});let J="";for(let Q=0;Q<z.length;Q+=T5){let W=z.length>=T5?z.slice(Q,Q+T5):z,V=[];for(let K=0;K<W.length;++K){let H=W.charCodeAt(K);if(H===45||H===46||H===95||H===126||H>=48&&H<=57||H>=65&&H<=90||H>=97&&H<=122||G===bG&&(H===40||H===41)){V[V.length]=W.charAt(K);continue}if(H<128){V[V.length]=m0[H];continue}if(H<2048){V[V.length]=m0[192|H>>6]+m0[128|H&63];continue}if(H<55296||H>=57344){V[V.length]=m0[224|H>>12]+m0[128|H>>6&63]+m0[128|H&63];continue}K+=1,H=65536+((H&1023)<<10|W.charCodeAt(K)&1023),V[V.length]=m0[240|H>>18]+m0[128|H>>12&63]+m0[128|H>>6&63]+m0[128|H&63]}J+=V.join("")}return J};function yG($){if(!$||typeof $!=="object")return!1;return!!($.constructor&&$.constructor.isBuffer&&$.constructor.isBuffer($))}function F5($,Z){if(U0($)){let X=[];for(let Y=0;Y<$.length;Y+=1)X.push(Z($[Y]));return X}return Z($)}var gG={brackets($){return String($)+"[]"},comma:"comma",indices($,Z){return String($)+"["+Z+"]"},repeat($){return String($)}},hG=function($,Z){Array.prototype.push.apply($,U0(Z)?Z:[Z])},vG,X0={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:fG,encodeValuesOnly:!1,format:U5,formatter:B5,indices:!1,serializeDate($){return(vG??(vG=Function.prototype.call.bind(Date.prototype.toISOString)))($)},skipNulls:!1,strictNullHandling:!1};function uL($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}var L5={};function uG($,Z,X,Y,G,z,J,Q,W,V,K,H,U,B,T,F,M,O){let N=$,_=O,P=0,R=!1;while((_=_.get(L5))!==void 0&&!R){let b=_.get($);if(P+=1,typeof b<"u")if(b===P)throw RangeError("Cyclic object value");else R=!0;if(typeof _.get(L5)>"u")P=0}if(typeof V==="function")N=V(Z,N);else if(N instanceof Date)N=U?.(N);else if(X==="comma"&&U0(N))N=F5(N,function(b){if(b instanceof Date)return U?.(b);return b});if(N===null){if(z)return W&&!F?W(Z,X0.encoder,M,"key",B):Z;N=""}if(uL(N)||yG(N)){if(W){let b=F?Z:W(Z,X0.encoder,M,"key",B);return[T?.(b)+"="+T?.(W(N,X0.encoder,M,"value",B))]}return[T?.(Z)+"="+T?.(String(N))]}let A=[];if(typeof N>"u")return A;let S;if(X==="comma"&&U0(N)){if(F&&W)N=F5(N,W);S=[{value:N.length>0?N.join(",")||null:void 0}]}else if(U0(V))S=V;else{let b=Object.keys(N);S=K?b.sort(K):b}let D=Q?String(Z).replace(/\./g,"%2E"):String(Z),k=Y&&U0(N)&&N.length===1?D+"[]":D;if(G&&U0(N)&&N.length===0)return k+"[]";for(let b=0;b<S.length;++b){let i=S[b],c=typeof i==="object"&&typeof i.value<"u"?i.value:N[i];if(J&&c===null)continue;let M0=H&&Q?i.replace(/\./g,"%2E"):i,y$=U0(N)?typeof X==="function"?X(k,M0):k:k+(H?"."+M0:"["+M0+"]");O.set($,P);let O0=new WeakMap;O0.set(L5,O),hG(A,uG(c,y$,X,Y,G,z,J,Q,X==="comma"&&F&&U0(N)?null:W,V,K,H,U,B,T,F,M,O0))}return A}function mL($=X0){if(typeof $.allowEmptyArrays<"u"&&typeof $.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof $.encodeDotInKeys<"u"&&typeof $.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if($.encoder!==null&&typeof $.encoder<"u"&&typeof $.encoder!=="function")throw TypeError("Encoder has to be a function.");let Z=$.charset||X0.charset;if(typeof $.charset<"u"&&$.charset!=="utf-8"&&$.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let X=U5;if(typeof $.format<"u"){if(!S8(q5,$.format))throw TypeError("Unknown format option provided.");X=$.format}let Y=q5[X],G=X0.filter;if(typeof $.filter==="function"||U0($.filter))G=$.filter;let z;if($.arrayFormat&&$.arrayFormat in gG)z=$.arrayFormat;else if("indices"in $)z=$.indices?"indices":"repeat";else z=X0.arrayFormat;if("commaRoundTrip"in $&&typeof $.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let J=typeof $.allowDots>"u"?!!$.encodeDotInKeys===!0?!0:X0.allowDots:!!$.allowDots;return{addQueryPrefix:typeof $.addQueryPrefix==="boolean"?$.addQueryPrefix:X0.addQueryPrefix,allowDots:J,allowEmptyArrays:typeof $.allowEmptyArrays==="boolean"?!!$.allowEmptyArrays:X0.allowEmptyArrays,arrayFormat:z,charset:Z,charsetSentinel:typeof $.charsetSentinel==="boolean"?$.charsetSentinel:X0.charsetSentinel,commaRoundTrip:!!$.commaRoundTrip,delimiter:typeof $.delimiter>"u"?X0.delimiter:$.delimiter,encode:typeof $.encode==="boolean"?$.encode:X0.encode,encodeDotInKeys:typeof $.encodeDotInKeys==="boolean"?$.encodeDotInKeys:X0.encodeDotInKeys,encoder:typeof $.encoder==="function"?$.encoder:X0.encoder,encodeValuesOnly:typeof $.encodeValuesOnly==="boolean"?$.encodeValuesOnly:X0.encodeValuesOnly,filter:G,format:X,formatter:Y,serializeDate:typeof $.serializeDate==="function"?$.serializeDate:X0.serializeDate,skipNulls:typeof $.skipNulls==="boolean"?$.skipNulls:X0.skipNulls,sort:typeof $.sort==="function"?$.sort:null,strictNullHandling:typeof $.strictNullHandling==="boolean"?$.strictNullHandling:X0.strictNullHandling}}function mG($,Z={}){let X=$,Y=mL(Z),G,z;if(typeof Y.filter==="function")z=Y.filter,X=z("",X);else if(U0(Y.filter))z=Y.filter,G=z;let J=[];if(typeof X!=="object"||X===null)return"";let Q=gG[Y.arrayFormat],W=Q==="comma"&&Y.commaRoundTrip;if(!G)G=Object.keys(X);if(Y.sort)G.sort(Y.sort);let V=new WeakMap;for(let U=0;U<G.length;++U){let B=G[U];if(Y.skipNulls&&X[B]===null)continue;hG(J,uG(X[B],B,Q,W,Y.allowEmptyArrays,Y.strictNullHandling,Y.skipNulls,Y.encodeDotInKeys,Y.encode?Y.encoder:null,Y.filter,Y.sort,Y.allowDots,Y.serializeDate,Y.format,Y.formatter,Y.encodeValuesOnly,Y.charset,V))}let K=J.join(Y.delimiter),H=Y.addQueryPrefix===!0?"?":"";if(Y.charsetSentinel)if(Y.charset==="iso-8859-1")H+="utf8=%26%2310003%3B&";else H+="utf8=%E2%9C%93&";return K.length>0?H+K:""}function dG($){return mG($,{arrayFormat:"brackets"})}function pG($){let Z=0;for(let G of $)Z+=G.length;let X=new Uint8Array(Z),Y=0;for(let G of $)X.set(G,Y),Y+=G.length;return X}var cG;function l1($){let Z;return(cG??(Z=new globalThis.TextEncoder,cG=Z.encode.bind(Z)))($)}var lG;function M5($){let Z;return(lG??(Z=new globalThis.TextDecoder,lG=Z.decode.bind(Z)))($)}var P0,D0;class p1{constructor(){P0.set(this,void 0),D0.set(this,void 0),x(this,P0,new Uint8Array,"f"),x(this,D0,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?l1($):$;x(this,P0,pG([w(this,P0,"f"),Z]),"f");let X=[],Y;while((Y=cL(w(this,P0,"f"),w(this,D0,"f")))!=null){if(Y.carriage&&w(this,D0,"f")==null){x(this,D0,Y.index,"f");continue}if(w(this,D0,"f")!=null&&(Y.index!==w(this,D0,"f")+1||Y.carriage)){X.push(M5(w(this,P0,"f").subarray(0,w(this,D0,"f")-1))),x(this,P0,w(this,P0,"f").subarray(w(this,D0,"f")),"f"),x(this,D0,null,"f");continue}let G=w(this,D0,"f")!==null?Y.preceding-1:Y.preceding,z=M5(w(this,P0,"f").subarray(0,G));X.push(z),x(this,P0,w(this,P0,"f").subarray(Y.index),"f"),x(this,D0,null,"f")}return X}flush(){if(!w(this,P0,"f").length)return[];return this.decode(`
|
|
243
|
+
`)}}P0=new WeakMap,D0=new WeakMap;p1.NEWLINE_CHARS=new Set([`
|
|
244
|
+
`,"\r"]);p1.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function cL($,Z){for(let G=Z??0;G<$.length;G++){if($[G]===10)return{preceding:G,index:G+1,carriage:!1};if($[G]===13)return{preceding:G,index:G+1,carriage:!0}}return null}function iG($){for(let Y=0;Y<$.length-1;Y++){if($[Y]===10&&$[Y+1]===10)return Y+2;if($[Y]===13&&$[Y+1]===13)return Y+2;if($[Y]===13&&$[Y+1]===10&&Y+3<$.length&&$[Y+2]===13&&$[Y+3]===10)return Y+4}return-1}var I8={off:0,error:200,warn:300,info:400,debug:500},w5=($,Z,X)=>{if(!$)return;if(DG(I8,$))return $;s(X).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(I8))}`);return};function x4(){}function C8($,Z,X){if(!Z||I8[$]>I8[X])return x4;else return Z[$].bind(Z)}var lL={error:x4,warn:x4,info:x4,debug:x4},aG=new WeakMap;function s($){let Z=$.logger,X=$.logLevel??"off";if(!Z)return lL;let Y=aG.get(Z);if(Y&&Y[0]===X)return Y[1];let G={error:C8("error",Z,X),warn:C8("warn",Z,X),info:C8("info",Z,X),debug:C8("debug",Z,X)};return aG.set(Z,[X,G]),G}var G$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([Z,X])=>[Z,Z.toLowerCase()==="authorization"||Z.toLowerCase()==="api-key"||Z.toLowerCase()==="x-api-key"||Z.toLowerCase()==="cookie"||Z.toLowerCase()==="set-cookie"?"***":X]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var k4;class E0{constructor($,Z,X){this.iterator=$,k4.set(this,void 0),this.controller=Z,x(this,k4,X,"f")}static fromSSEResponse($,Z,X,Y){let G=!1,z=X?s(X):console;async function*J(){if(G)throw new I("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");G=!0;let Q=!1;try{for await(let W of pL($,Z)){if(Q)continue;if(W.data.startsWith("[DONE]")){Q=!0;continue}if(W.event===null||!W.event.startsWith("thread.")){let V;try{V=JSON.parse(W.data)}catch(K){throw z.error("Could not parse message into JSON:",W.data),z.error("From chunk:",W.raw),K}if(V&&V.error)throw new r(void 0,V.error,void 0,$.headers);yield Y?{event:W.event,data:V}:V}else{let V;try{V=JSON.parse(W.data)}catch(K){throw console.error("Could not parse message into JSON:",W.data),console.error("From chunk:",W.raw),K}if(W.event=="error")throw new r(void 0,V.error,V.message,void 0);yield{event:W.event,data:V}}}Q=!0}catch(W){if(w4(W))return;throw W}finally{if(!Q)Z.abort()}}return new E0(J,Z,X)}static fromReadableStream($,Z,X){let Y=!1;async function*G(){let J=new p1,Q=H5($);for await(let W of Q)for(let V of J.decode(W))yield V;for(let W of J.flush())yield W}async function*z(){if(Y)throw new I("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Y=!0;let J=!1;try{for await(let Q of G()){if(J)continue;if(Q)yield JSON.parse(Q)}J=!0}catch(Q){if(w4(Q))return;throw Q}finally{if(!J)Z.abort()}}return new E0(z,Z,X)}[(k4=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],Z=[],X=this.iterator(),Y=(G)=>{return{next:()=>{if(G.length===0){let z=X.next();$.push(z),Z.push(z)}return G.shift()}}};return[new E0(()=>Y($),this.controller,w(this,k4,"f")),new E0(()=>Y(Z),this.controller,w(this,k4,"f"))]}toReadableStream(){let $=this,Z;return V5({async start(){Z=$[Symbol.asyncIterator]()},async pull(X){try{let{value:Y,done:G}=await Z.next();if(G)return X.close();let z=l1(JSON.stringify(Y)+`
|
|
245
|
+
`);X.enqueue(z)}catch(Y){X.error(Y)}},async cancel(){await Z.return?.()}})}}async function*pL($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new I("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new I("Attempted to iterate over a response with no body")}let X=new nG,Y=new p1,G=H5($.body);for await(let z of iL(G))for(let J of Y.decode(z)){let Q=X.decode(J);if(Q)yield Q}for(let z of Y.flush()){let J=X.decode(z);if(J)yield J}}async function*iL($){let Z=new Uint8Array;for await(let X of $){if(X==null)continue;let Y=X instanceof ArrayBuffer?new Uint8Array(X):typeof X==="string"?l1(X):X,G=new Uint8Array(Z.length+Y.length);G.set(Z),G.set(Y,Z.length),Z=G;let z;while((z=iG(Z))!==-1)yield Z.slice(0,z),Z=Z.slice(z)}if(Z.length>0)yield Z}class nG{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let G={event:this.event,data:this.data.join(`
|
|
246
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],G}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,X,Y]=aL($,":");if(Y.startsWith(" "))Y=Y.substring(1);if(Z==="event")this.event=Y;else if(Z==="data")this.data.push(Y);return null}}function aL($,Z){let X=$.indexOf(Z);if(X!==-1)return[$.substring(0,X),Z,$.substring(X+Z.length)];return[$,"",""]}async function j8($,Z){let{response:X,requestLogID:Y,retryOfRequestLogID:G,startTime:z}=Z,J=await(async()=>{if(Z.options.stream){if(s($).debug("response",X.status,X.url,X.headers,X.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(X,Z.controller,$,Z.options.__synthesizeEventData);return E0.fromSSEResponse(X,Z.controller,$,Z.options.__synthesizeEventData)}if(X.status===204)return null;if(Z.options.__binaryResponse)return X;let W=X.headers.get("content-type")?.split(";")[0]?.trim();if(W?.includes("application/json")||W?.endsWith("+json")){if(X.headers.get("content-length")==="0")return;let U=await X.json();return O5(U,X)}return await X.text()})();return s($).debug(`[${Y}] response parsed`,G$({retryOfRequestLogID:G,url:X.url,status:X.status,body:J,durationMs:Date.now()-z})),J}function O5($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("x-request-id"),enumerable:!1})}var b4;class t$ extends Promise{constructor($,Z,X=j8){super((Y)=>{Y(null)});this.responsePromise=Z,this.parseResponse=X,b4.set(this,void 0),x(this,b4,$,"f")}_thenUnwrap($){return new t$(w(this,b4,"f"),this.responsePromise,async(Z,X)=>O5($(await this.parseResponse(Z,X),X),X.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,Z]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:Z,request_id:Z.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(w(this,b4,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}b4=new WeakMap;var x8;class f4{constructor($,Z,X,Y){x8.set(this,void 0),x(this,x8,$,"f"),this.options=Y,this.response=Z,this.body=X}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new I("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await w(this,x8,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(x8=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class k8 extends t${constructor($,Z,X){super($,Z,async(Y,G)=>new X(Y,G.response,await j8(Y,G),G.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class F0 extends f4{constructor($,Z,X,Y){super($,Z,X,Y);this.data=X.data||[],this.object=X.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class y extends f4{constructor($,Z,X,Y){super($,Z,X,Y);this.data=X.data||[],this.has_more=X.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.getPaginatedItems(),Z=$[$.length-1]?.id;if(!Z)return null;return{...this.options,query:{...E8(this.options.query),after:Z}}}}class d extends f4{constructor($,Z,X,Y){super($,Z,X,Y);this.data=X.data||[],this.has_more=X.has_more||!1,this.last_id=X.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.last_id;if(!$)return null;return{...this.options,query:{...E8(this.options.query),after:$}}}}class Y0 extends f4{constructor($,Z,X,Y){super($,Z,X,Y);this.data=X.data||[],this.has_more=X.has_more||!1,this.next=X.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.next;if(!$)return null;return{...this.options,query:{...E8(this.options.query),after:$}}}}var rL={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},sL="urn:ietf:params:oauth:grant-type:token-exchange";class N5{constructor($,Z){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=$,this.fetch=Z??R8()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}if(this.needsRefresh(this.cachedToken)&&!this.refreshPromise)this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null});return this.cachedToken.token}async refreshToken(){let $=await this.config.provider.getToken(),Z={grant_type:sL,subject_token:$,subject_token_type:rL[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};if(this.config.clientId)Z.client_id=this.config.clientId;let X=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!X.ok){let J=await X.text(),Q=void 0;try{Q=JSON.parse(J)}catch{}if(X.status===400||X.status===401||X.status===403)throw new c1(X.status,Q,X.headers);throw r.generate(X.status,Q,`Token exchange failed with status ${X.status}`,X.headers)}let Y=await X.json(),G=Y.expires_in||3600,z=Date.now()+G*1000;return this.cachedToken={token:Y.access_token,expiresAt:z},Y.access_token}isTokenExpired($){return Date.now()>=$.expiresAt}needsRefresh($){let X=(this.config.refreshBufferSeconds??1200)*1000;return Date.now()>=$.expiresAt-X}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}}var D5=()=>{if(typeof File>"u"){let{process:$}=globalThis,Z=typeof $?.versions?.node==="string"&&parseInt($.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(Z?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function i1($,Z,X){return D5(),new File($,Z??"unknown_file",X)}function y4($){return(typeof $==="object"&&$!==null&&(("name"in $)&&$.name&&String($.name)||("url"in $)&&$.url&&String($.url)||("filename"in $)&&$.filename&&String($.filename)||("path"in $)&&$.path&&String($.path))||"").split(/[\\/]/).pop()||void 0}var b8=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function",R$=async($,Z)=>{if(!_5($.body))return $;return{...$,body:await sG($.body,Z)}},B0=async($,Z)=>{return{...$,body:await sG($.body,Z)}},rG=new WeakMap;function oL($){let Z=typeof $==="function"?$:$.fetch,X=rG.get(Z);if(X)return X;let Y=(async()=>{try{let G="Response"in Z?Z.Response:(await Z("data:,")).constructor,z=new FormData;if(z.toString()===await new G(z).text())return!1;return!0}catch{return!0}})();return rG.set(Z,Y),Y}var sG=async($,Z)=>{if(!await oL(Z))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let X=new FormData;return await Promise.all(Object.entries($||{}).map(([Y,G])=>P5(X,Y,G))),X},oG=($)=>$ instanceof Blob&&("name"in $),tL=($)=>typeof $==="object"&&$!==null&&($ instanceof Response||b8($)||oG($)),_5=($)=>{if(tL($))return!0;if(Array.isArray($))return $.some(_5);if($&&typeof $==="object"){for(let Z in $)if(_5($[Z]))return!0}return!1},P5=async($,Z,X)=>{if(X===void 0)return;if(X==null)throw TypeError(`Received null for "${Z}"; to pass null in FormData, you must use the string 'null'`);if(typeof X==="string"||typeof X==="number"||typeof X==="boolean")$.append(Z,String(X));else if(X instanceof Response)$.append(Z,i1([await X.blob()],y4(X)));else if(b8(X))$.append(Z,i1([await new Response(A8(X)).blob()],y4(X)));else if(oG(X))$.append(Z,X,y4(X));else if(Array.isArray(X))await Promise.all(X.map((Y)=>P5($,Z+"[]",Y)));else if(typeof X==="object")await Promise.all(Object.entries(X).map(([Y,G])=>P5($,`${Z}[${Y}]`,G)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${X} instead`)};var tG=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",eL=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&tG($),$M=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function f8($,Z,X){if(D5(),$=await $,eL($)){if($ instanceof File)return $;return i1([await $.arrayBuffer()],$.name)}if($M($)){let G=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),i1(await E5(G),Z,X)}let Y=await E5($);if(Z||(Z=y4($)),!X?.type){let G=Y.find((z)=>typeof z==="object"&&("type"in z)&&z.type);if(typeof G==="string")X={...X,type:G}}return i1(Y,Z,X)}async function E5($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(tG($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(b8($))for await(let X of $)Z.push(...await E5(X));else{let X=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${X?`; constructor: ${X}`:""}${ZM($)}`)}return Z}function ZM($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((X)=>`"${X}"`).join(", ")}]`}class L{constructor($){this._client=$}}function $z($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var eG=Object.freeze(Object.create(null)),YM=($=$z)=>function(X,...Y){if(X.length===1)return X[0];let G=!1,z=[],J=X.reduce((K,H,U)=>{if(/[?#]/.test(H))G=!0;let B=Y[U],T=(G?encodeURIComponent:$)(""+B);if(U!==Y.length&&(B==null||typeof B==="object"&&B.toString===Object.getPrototypeOf(Object.getPrototypeOf(B.hasOwnProperty??eG)??eG)?.toString))T=B+"",z.push({start:K.length+H.length,length:T.length,error:`Value of type ${Object.prototype.toString.call(B).slice(8,-1)} is not a valid path parameter`});return K+H+(U===Y.length?"":T)},""),Q=J.split(/[?#]/,1)[0],W=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,V;while((V=W.exec(Q))!==null)z.push({start:V.index,length:V[0].length,error:`Value "${V[0]}" can't be safely passed as a path parameter`});if(z.sort((K,H)=>K.start-H.start),z.length>0){let K=0,H=z.reduce((U,B)=>{let T=" ".repeat(B.start-K),F="^".repeat(B.length);return K=B.start+B.length,U+T+F},"");throw new I(`Path parameters result in path with invalid segments:
|
|
247
|
+
${z.map((U)=>U.error).join(`
|
|
247
248
|
`)}
|
|
248
249
|
${J}
|
|
249
|
-
${H}`)}return J},q=$w(tG);class s1 extends L{list($,Z={},X){return this._client.getAPIList(q`/chat/completions/${$}/messages`,y,{query:Z,...X,__security:{bearerAuth:!0}})}}function g4($){return $!==void 0&&"function"in $&&$.function!==void 0}function h4($){return $?.$brand==="auto-parseable-response-format"}function Y1($){return $?.$brand==="auto-parseable-tool"}function eG($,Z){if(!Z||!R5(Z))return{...$,choices:$.choices.map((X)=>{return Zz(X.message.tool_calls),{...X,message:{...X.message,parsed:null,...X.message.tool_calls?{tool_calls:X.message.tool_calls}:void 0}}})};return u4($,Z)}function u4($,Z){let X=$.choices.map((Y)=>{if(Y.finish_reason==="length")throw new I4;if(Y.finish_reason==="content_filter")throw new j4;return Zz(Y.message.tool_calls),{...Y,message:{...Y.message,...Y.message.tool_calls?{tool_calls:Y.message.tool_calls?.map((G)=>Gw(Z,G))??void 0}:void 0,parsed:Y.message.content&&!Y.message.refusal?Yw(Z,Y.message.content):null}}});return{...$,choices:X}}function Yw($,Z){if($.response_format?.type!=="json_schema")return null;if($.response_format?.type==="json_schema"){if("$parseRaw"in $.response_format)return $.response_format.$parseRaw(Z);return JSON.parse(Z)}return null}function Gw($,Z){let X=$.tools?.find((Y)=>g4(Y)&&Y.function?.name===Z.function.name);return{...Z,function:{...Z.function,parsed_arguments:Y1(X)?X.$parseRaw(Z.function.arguments):X?.function.strict?JSON.parse(Z.function.arguments):null}}}function $z($,Z){if(!$||!("tools"in $)||!$.tools)return!1;let X=$.tools?.find((Y)=>g4(Y)&&Y.function?.name===Z.function.name);return g4(X)&&(Y1(X)||X?.function.strict||!1)}function R5($){if(h4($.response_format))return!0;return $.tools?.some((Z)=>Y1(Z)||Z.type==="function"&&Z.function.strict===!0)??!1}function Zz($){for(let Z of $||[])if(Z.type!=="function")throw new I(`Currently only \`function\` tool calls are supported; Received \`${Z.type}\``)}function Xz($){for(let Z of $??[]){if(Z.type!=="function")throw new I(`Currently only \`function\` tool types support auto-parsing; Received \`${Z.type}\``);if(Z.function.strict!==!0)throw new I(`The \`${Z.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var o1=($)=>{return $?.role==="assistant"},A5=($)=>{return $?.role==="tool"};var S5,y8,v8,m4,d4,g8,c4,J$,l4,h8,u8,t1,Yz;class G1{constructor(){S5.add(this),this.controller=new AbortController,y8.set(this,void 0),v8.set(this,()=>{}),m4.set(this,()=>{}),d4.set(this,void 0),g8.set(this,()=>{}),c4.set(this,()=>{}),J$.set(this,{}),l4.set(this,!1),h8.set(this,!1),u8.set(this,!1),t1.set(this,!1),x(this,y8,new Promise(($,Z)=>{x(this,v8,$,"f"),x(this,m4,Z,"f")}),"f"),x(this,d4,new Promise(($,Z)=>{x(this,g8,$,"f"),x(this,c4,Z,"f")}),"f"),M(this,y8,"f").catch(()=>{}),M(this,d4,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},M(this,S5,"m",Yz).bind(this))},0)}_connected(){if(this.ended)return;M(this,v8,"f").call(this),this._emit("connect")}get ended(){return M(this,l4,"f")}get errored(){return M(this,h8,"f")}get aborted(){return M(this,u8,"f")}abort(){this.controller.abort()}on($,Z){return(M(this,J$,"f")[$]||(M(this,J$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let X=M(this,J$,"f")[$];if(!X)return this;let Y=X.findIndex((G)=>G.listener===Z);if(Y>=0)X.splice(Y,1);return this}once($,Z){return(M(this,J$,"f")[$]||(M(this,J$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,X)=>{if(x(this,t1,!0,"f"),$!=="error")this.once("error",X);this.once($,Z)})}async done(){x(this,t1,!0,"f"),await M(this,d4,"f")}_emit($,...Z){if(M(this,l4,"f"))return;if($==="end")x(this,l4,!0,"f"),M(this,g8,"f").call(this);let X=M(this,J$,"f")[$];if(X)M(this,J$,"f")[$]=X.filter((Y)=>!Y.once),X.forEach(({listener:Y})=>Y(...Z));if($==="abort"){let Y=Z[0];if(!M(this,t1,"f")&&!X?.length)Promise.reject(Y);M(this,m4,"f").call(this,Y),M(this,c4,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!M(this,t1,"f")&&!X?.length)Promise.reject(Y);M(this,m4,"f").call(this,Y),M(this,c4,"f").call(this,Y),this._emit("end")}}_emitFinal(){}}y8=new WeakMap,v8=new WeakMap,m4=new WeakMap,d4=new WeakMap,g8=new WeakMap,c4=new WeakMap,J$=new WeakMap,l4=new WeakMap,h8=new WeakMap,u8=new WeakMap,t1=new WeakMap,S5=new WeakSet,Yz=function(Z){if(x(this,h8,!0,"f"),Z instanceof Error&&Z.name==="AbortError")Z=new $0;if(Z instanceof $0)return x(this,u8,!0,"f"),this._emit("abort",Z);if(Z instanceof I)return this._emit("error",Z);if(Z instanceof Error){let X=new I(Z.message);return X.cause=Z,this._emit("error",X)}return this._emit("error",new I(String(Z)))};function Gz($){return typeof $.parse==="function"}var w0,C5,m8,I5,j5,x5,zz,Jz,zw=10;class p4 extends G1{constructor(){super(...arguments);w0.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion($){this._chatCompletions.push($),this._emit("chatCompletion",$);let Z=$.choices[0]?.message;if(Z)this._addMessage(Z);return $}_addMessage($,Z=!0){if(!("content"in $))$.content=null;if(this.messages.push($),Z){if(this._emit("message",$),A5($)&&$.content)this._emit("functionToolCallResult",$.content);else if(o1($)&&$.tool_calls){for(let X of $.tool_calls)if(X.type==="function")this._emit("functionToolCall",X.function)}}}async finalChatCompletion(){await this.done();let $=this._chatCompletions[this._chatCompletions.length-1];if(!$)throw new I("stream ended without producing a ChatCompletion");return $}async finalContent(){return await this.done(),M(this,w0,"m",C5).call(this)}async finalMessage(){return await this.done(),M(this,w0,"m",m8).call(this)}async finalFunctionToolCall(){return await this.done(),M(this,w0,"m",I5).call(this)}async finalFunctionToolCallResult(){return await this.done(),M(this,w0,"m",j5).call(this)}async totalUsage(){return await this.done(),M(this,w0,"m",x5).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let $=this._chatCompletions[this._chatCompletions.length-1];if($)this._emit("finalChatCompletion",$);let Z=M(this,w0,"m",m8).call(this);if(Z)this._emit("finalMessage",Z);let X=M(this,w0,"m",C5).call(this);if(X)this._emit("finalContent",X);let Y=M(this,w0,"m",I5).call(this);if(Y)this._emit("finalFunctionToolCall",Y);let G=M(this,w0,"m",j5).call(this);if(G!=null)this._emit("finalFunctionToolCallResult",G);if(this._chatCompletions.some((z)=>z.usage))this._emit("totalUsage",M(this,w0,"m",x5).call(this))}async _createChatCompletion($,Z,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}M(this,w0,"m",zz).call(this,Z);let G=await $.chat.completions.create({...Z,stream:!1},{...X,signal:this.controller.signal});return this._connected(),this._addChatCompletion(u4(G,Z))}async _runChatCompletion($,Z,X){for(let Y of Z.messages)this._addMessage(Y,!1);return await this._createChatCompletion($,Z,X)}async _runTools($,Z,X){let{tool_choice:G="auto",stream:z,...J}=Z,Q=typeof G!=="string"&&G.type==="function"&&G?.function?.name,{maxChatCompletions:W=zw}=X||{},V=Z.tools.map((B)=>{if(Y1(B)){if(!B.$callback)throw new I("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:B.$callback,name:B.function.name,description:B.function.description||"",parameters:B.function.parameters,parse:B.$parseRaw,strict:!0}}}return B}),K={};for(let B of V)if(B.type==="function")K[B.function.name||B.function.function.name]=B.function;let H="tools"in Z?V.map((B)=>B.type==="function"?{type:"function",function:{name:B.function.name||B.function.function.name,parameters:B.function.parameters,description:B.function.description,strict:B.function.strict}}:B):void 0;for(let B of Z.messages)this._addMessage(B,!1);for(let B=0;B<W;++B){let F=(await this._createChatCompletion($,{...J,tool_choice:G,tools:H,messages:[...this.messages]},X)).choices[0]?.message;if(!F)throw new I("missing message in ChatCompletion response");if(!F.tool_calls?.length)return;for(let T of F.tool_calls){if(T.type!=="function")continue;let w=T.id,{name:O,arguments:N}=T.function,_=K[O];if(!_){let S=`Invalid tool_call: ${JSON.stringify(O)}. Available options are: ${Object.keys(K).map((D)=>JSON.stringify(D)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:w,content:S});continue}else if(Q&&Q!==O){let S=`Invalid tool_call: ${JSON.stringify(O)}. ${JSON.stringify(Q)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:w,content:S});continue}let P;try{P=Gz(_)?await _.parse(N):N}catch(S){let D=S instanceof Error?S.message:String(S);this._addMessage({role:"tool",tool_call_id:w,content:D});continue}let R=await _.function(P,this),A=M(this,w0,"m",Jz).call(this,R);if(this._addMessage({role:"tool",tool_call_id:w,content:A}),Q)return}}return}}w0=new WeakSet,C5=function(){return M(this,w0,"m",m8).call(this).content??null},m8=function(){let Z=this.messages.length;while(Z-- >0){let X=this.messages[Z];if(o1(X))return{...X,content:X.content??null,refusal:X.refusal??null}}throw new I("stream ended without producing a ChatCompletionMessage with role=assistant")},I5=function(){for(let Z=this.messages.length-1;Z>=0;Z--){let X=this.messages[Z];if(o1(X)&&X?.tool_calls?.length)return X.tool_calls.filter((Y)=>Y.type==="function").at(-1)?.function}return},j5=function(){for(let Z=this.messages.length-1;Z>=0;Z--){let X=this.messages[Z];if(A5(X)&&X.content!=null&&typeof X.content==="string"&&this.messages.some((Y)=>Y.role==="assistant"&&Y.tool_calls?.some((G)=>G.type==="function"&&G.id===X.tool_call_id)))return X.content}return},x5=function(){let Z={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:X}of this._chatCompletions)if(X)Z.completion_tokens+=X.completion_tokens,Z.prompt_tokens+=X.prompt_tokens,Z.total_tokens+=X.total_tokens;return Z},zz=function(Z){if(Z.n!=null&&Z.n>1)throw new I("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Jz=function(Z){return typeof Z==="string"?Z:Z===void 0?"undefined":JSON.stringify(Z)};class i4 extends p4{static runTools($,Z,X){let Y=new i4,G={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runTools"}};return Y._run(()=>Y._runTools($,Z,G)),Y}_addMessage($,Z=!0){if(super._addMessage($,Z),o1($)&&$.content)this._emit("content",$.content)}}var J0={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class Qz extends Error{}class Wz extends Error{}function Jw($,Z=J0.ALL){if(typeof $!=="string")throw TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw Error(`${$} is empty`);return Qw($.trim(),Z)}var Qw=($,Z)=>{let X=$.length,Y=0,G=(B)=>{throw new Qz(`${B} at position ${Y}`)},z=(B)=>{throw new Wz(`${B} at position ${Y}`)},J=()=>{if(H(),Y>=X)G("Unexpected end of input");if($[Y]==='"')return Q();if($[Y]==="{")return W();if($[Y]==="[")return V();if($.substring(Y,Y+4)==="null"||J0.NULL&Z&&X-Y<4&&"null".startsWith($.substring(Y)))return Y+=4,null;if($.substring(Y,Y+4)==="true"||J0.BOOL&Z&&X-Y<4&&"true".startsWith($.substring(Y)))return Y+=4,!0;if($.substring(Y,Y+5)==="false"||J0.BOOL&Z&&X-Y<5&&"false".startsWith($.substring(Y)))return Y+=5,!1;if($.substring(Y,Y+8)==="Infinity"||J0.INFINITY&Z&&X-Y<8&&"Infinity".startsWith($.substring(Y)))return Y+=8,1/0;if($.substring(Y,Y+9)==="-Infinity"||J0.MINUS_INFINITY&Z&&1<X-Y&&X-Y<9&&"-Infinity".startsWith($.substring(Y)))return Y+=9,-1/0;if($.substring(Y,Y+3)==="NaN"||J0.NAN&Z&&X-Y<3&&"NaN".startsWith($.substring(Y)))return Y+=3,NaN;return K()},Q=()=>{let B=Y,U=!1;Y++;while(Y<X&&($[Y]!=='"'||U&&$[Y-1]==="\\"))U=$[Y]==="\\"?!U:!1,Y++;if($.charAt(Y)=='"')try{return JSON.parse($.substring(B,++Y-Number(U)))}catch(F){z(String(F))}else if(J0.STR&Z)try{return JSON.parse($.substring(B,Y-Number(U))+'"')}catch(F){return JSON.parse($.substring(B,$.lastIndexOf("\\"))+'"')}G("Unterminated string literal")},W=()=>{Y++,H();let B={};try{while($[Y]!=="}"){if(H(),Y>=X&&J0.OBJ&Z)return B;let U=Q();H(),Y++;try{let F=J();Object.defineProperty(B,U,{value:F,writable:!0,enumerable:!0,configurable:!0})}catch(F){if(J0.OBJ&Z)return B;else throw F}if(H(),$[Y]===",")Y++}}catch(U){if(J0.OBJ&Z)return B;else G("Expected '}' at end of object")}return Y++,B},V=()=>{Y++;let B=[];try{while($[Y]!=="]")if(B.push(J()),H(),$[Y]===",")Y++}catch(U){if(J0.ARR&Z)return B;G("Expected ']' at end of array")}return Y++,B},K=()=>{if(Y===0){if($==="-"&&J0.NUM&Z)G("Not sure what '-' is");try{return JSON.parse($)}catch(U){if(J0.NUM&Z)try{if($[$.length-1]===".")return JSON.parse($.substring(0,$.lastIndexOf(".")));return JSON.parse($.substring(0,$.lastIndexOf("e")))}catch(F){}z(String(U))}}let B=Y;if($[Y]==="-")Y++;while($[Y]&&!",]}".includes($[Y]))Y++;if(Y==X&&!(J0.NUM&Z))G("Unterminated number literal");try{return JSON.parse($.substring(B,Y))}catch(U){if($.substring(B,Y)==="-"&&J0.NUM&Z)G("Not sure what '-' is");try{return JSON.parse($.substring(B,$.lastIndexOf("e")))}catch(F){z(String(F))}}},H=()=>{while(Y<X&&`
|
|
250
|
-
\r `.includes($[Y]))Y++};return J()},k5=($)=>
|
|
250
|
+
${H}`)}return J},q=YM($z);class a1 extends L{list($,Z={},X){return this._client.getAPIList(q`/chat/completions/${$}/messages`,y,{query:Z,...X,__security:{bearerAuth:!0}})}}function v4($){return $!==void 0&&"function"in $&&$.function!==void 0}function g4($){return $?.$brand==="auto-parseable-response-format"}function e$($){return $?.$brand==="auto-parseable-tool"}function Zz($,Z){if(!Z||!R5(Z))return{...$,choices:$.choices.map((X)=>{return Yz(X.message.tool_calls),{...X,message:{...X.message,parsed:null,...X.message.tool_calls?{tool_calls:X.message.tool_calls}:void 0}}})};return h4($,Z)}function h4($,Z){let X=$.choices.map((Y)=>{if(Y.finish_reason==="length")throw new C4;if(Y.finish_reason==="content_filter")throw new I4;return Yz(Y.message.tool_calls),{...Y,message:{...Y.message,...Y.message.tool_calls?{tool_calls:Y.message.tool_calls?.map((G)=>QM(Z,G))??void 0}:void 0,parsed:Y.message.content&&!Y.message.refusal?JM(Z,Y.message.content):null}}});return{...$,choices:X}}function JM($,Z){if($.response_format?.type!=="json_schema")return null;if($.response_format?.type==="json_schema"){if("$parseRaw"in $.response_format)return $.response_format.$parseRaw(Z);return JSON.parse(Z)}return null}function QM($,Z){let X=$.tools?.find((Y)=>v4(Y)&&Y.function?.name===Z.function.name);return{...Z,function:{...Z.function,parsed_arguments:e$(X)?X.$parseRaw(Z.function.arguments):X?.function.strict?JSON.parse(Z.function.arguments):null}}}function Xz($,Z){if(!$||!("tools"in $)||!$.tools)return!1;let X=$.tools?.find((Y)=>v4(Y)&&Y.function?.name===Z.function.name);return v4(X)&&(e$(X)||X?.function.strict||!1)}function R5($){if(g4($.response_format))return!0;return $.tools?.some((Z)=>e$(Z)||Z.type==="function"&&Z.function.strict===!0)??!1}function Yz($){for(let Z of $||[])if(Z.type!=="function")throw new I(`Currently only \`function\` tool calls are supported; Received \`${Z.type}\``)}function Gz($){for(let Z of $??[]){if(Z.type!=="function")throw new I(`Currently only \`function\` tool types support auto-parsing; Received \`${Z.type}\``);if(Z.function.strict!==!0)throw new I(`The \`${Z.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var n1=($)=>{return $?.role==="assistant"},A5=($)=>{return $?.role==="tool"};var S5,y8,v8,u4,m4,g8,d4,z$,c4,h8,u8,r1,zz;class $1{constructor(){S5.add(this),this.controller=new AbortController,y8.set(this,void 0),v8.set(this,()=>{}),u4.set(this,()=>{}),m4.set(this,void 0),g8.set(this,()=>{}),d4.set(this,()=>{}),z$.set(this,{}),c4.set(this,!1),h8.set(this,!1),u8.set(this,!1),r1.set(this,!1),x(this,y8,new Promise(($,Z)=>{x(this,v8,$,"f"),x(this,u4,Z,"f")}),"f"),x(this,m4,new Promise(($,Z)=>{x(this,g8,$,"f"),x(this,d4,Z,"f")}),"f"),w(this,y8,"f").catch(()=>{}),w(this,m4,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},w(this,S5,"m",zz).bind(this))},0)}_connected(){if(this.ended)return;w(this,v8,"f").call(this),this._emit("connect")}get ended(){return w(this,c4,"f")}get errored(){return w(this,h8,"f")}get aborted(){return w(this,u8,"f")}abort(){this.controller.abort()}on($,Z){return(w(this,z$,"f")[$]||(w(this,z$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let X=w(this,z$,"f")[$];if(!X)return this;let Y=X.findIndex((G)=>G.listener===Z);if(Y>=0)X.splice(Y,1);return this}once($,Z){return(w(this,z$,"f")[$]||(w(this,z$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,X)=>{if(x(this,r1,!0,"f"),$!=="error")this.once("error",X);this.once($,Z)})}async done(){x(this,r1,!0,"f"),await w(this,m4,"f")}_emit($,...Z){if(w(this,c4,"f"))return;if($==="end")x(this,c4,!0,"f"),w(this,g8,"f").call(this);let X=w(this,z$,"f")[$];if(X)w(this,z$,"f")[$]=X.filter((Y)=>!Y.once),X.forEach(({listener:Y})=>Y(...Z));if($==="abort"){let Y=Z[0];if(!w(this,r1,"f")&&!X?.length)Promise.reject(Y);w(this,u4,"f").call(this,Y),w(this,d4,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!w(this,r1,"f")&&!X?.length)Promise.reject(Y);w(this,u4,"f").call(this,Y),w(this,d4,"f").call(this,Y),this._emit("end")}}_emitFinal(){}}y8=new WeakMap,v8=new WeakMap,u4=new WeakMap,m4=new WeakMap,g8=new WeakMap,d4=new WeakMap,z$=new WeakMap,c4=new WeakMap,h8=new WeakMap,u8=new WeakMap,r1=new WeakMap,S5=new WeakSet,zz=function(Z){if(x(this,h8,!0,"f"),Z instanceof Error&&Z.name==="AbortError")Z=new Z0;if(Z instanceof Z0)return x(this,u8,!0,"f"),this._emit("abort",Z);if(Z instanceof I)return this._emit("error",Z);if(Z instanceof Error){let X=new I(Z.message);return X.cause=Z,this._emit("error",X)}return this._emit("error",new I(String(Z)))};function Jz($){return typeof $.parse==="function"}var L0,C5,m8,I5,j5,x5,Qz,Wz,WM=10;class l4 extends $1{constructor(){super(...arguments);L0.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion($){this._chatCompletions.push($),this._emit("chatCompletion",$);let Z=$.choices[0]?.message;if(Z)this._addMessage(Z);return $}_addMessage($,Z=!0){if(!("content"in $))$.content=null;if(this.messages.push($),Z){if(this._emit("message",$),A5($)&&$.content)this._emit("functionToolCallResult",$.content);else if(n1($)&&$.tool_calls){for(let X of $.tool_calls)if(X.type==="function")this._emit("functionToolCall",X.function)}}}async finalChatCompletion(){await this.done();let $=this._chatCompletions[this._chatCompletions.length-1];if(!$)throw new I("stream ended without producing a ChatCompletion");return $}async finalContent(){return await this.done(),w(this,L0,"m",C5).call(this)}async finalMessage(){return await this.done(),w(this,L0,"m",m8).call(this)}async finalFunctionToolCall(){return await this.done(),w(this,L0,"m",I5).call(this)}async finalFunctionToolCallResult(){return await this.done(),w(this,L0,"m",j5).call(this)}async totalUsage(){return await this.done(),w(this,L0,"m",x5).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let $=this._chatCompletions[this._chatCompletions.length-1];if($)this._emit("finalChatCompletion",$);let Z=w(this,L0,"m",m8).call(this);if(Z)this._emit("finalMessage",Z);let X=w(this,L0,"m",C5).call(this);if(X)this._emit("finalContent",X);let Y=w(this,L0,"m",I5).call(this);if(Y)this._emit("finalFunctionToolCall",Y);let G=w(this,L0,"m",j5).call(this);if(G!=null)this._emit("finalFunctionToolCallResult",G);if(this._chatCompletions.some((z)=>z.usage))this._emit("totalUsage",w(this,L0,"m",x5).call(this))}async _createChatCompletion($,Z,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}w(this,L0,"m",Qz).call(this,Z);let G=await $.chat.completions.create({...Z,stream:!1},{...X,signal:this.controller.signal});return this._connected(),this._addChatCompletion(h4(G,Z))}async _runChatCompletion($,Z,X){for(let Y of Z.messages)this._addMessage(Y,!1);return await this._createChatCompletion($,Z,X)}async _runTools($,Z,X){let{tool_choice:G="auto",stream:z,...J}=Z,Q=typeof G!=="string"&&G.type==="function"&&G?.function?.name,{maxChatCompletions:W=WM}=X||{},V=Z.tools.map((U)=>{if(e$(U)){if(!U.$callback)throw new I("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:U.$callback,name:U.function.name,description:U.function.description||"",parameters:U.function.parameters,parse:U.$parseRaw,strict:!0}}}return U}),K={};for(let U of V)if(U.type==="function")K[U.function.name||U.function.function.name]=U.function;let H="tools"in Z?V.map((U)=>U.type==="function"?{type:"function",function:{name:U.function.name||U.function.function.name,parameters:U.function.parameters,description:U.function.description,strict:U.function.strict}}:U):void 0;for(let U of Z.messages)this._addMessage(U,!1);for(let U=0;U<W;++U){let T=(await this._createChatCompletion($,{...J,tool_choice:G,tools:H,messages:[...this.messages]},X)).choices[0]?.message;if(!T)throw new I("missing message in ChatCompletion response");if(!T.tool_calls?.length)return;for(let F of T.tool_calls){if(F.type!=="function")continue;let M=F.id,{name:O,arguments:N}=F.function,_=K[O];if(!_){let S=`Invalid tool_call: ${JSON.stringify(O)}. Available options are: ${Object.keys(K).map((D)=>JSON.stringify(D)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:M,content:S});continue}else if(Q&&Q!==O){let S=`Invalid tool_call: ${JSON.stringify(O)}. ${JSON.stringify(Q)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:M,content:S});continue}let P;try{P=Jz(_)?await _.parse(N):N}catch(S){let D=S instanceof Error?S.message:String(S);this._addMessage({role:"tool",tool_call_id:M,content:D});continue}let R=await _.function(P,this),A=w(this,L0,"m",Wz).call(this,R);if(this._addMessage({role:"tool",tool_call_id:M,content:A}),Q)return}}return}}L0=new WeakSet,C5=function(){return w(this,L0,"m",m8).call(this).content??null},m8=function(){let Z=this.messages.length;while(Z-- >0){let X=this.messages[Z];if(n1(X))return{...X,content:X.content??null,refusal:X.refusal??null}}throw new I("stream ended without producing a ChatCompletionMessage with role=assistant")},I5=function(){for(let Z=this.messages.length-1;Z>=0;Z--){let X=this.messages[Z];if(n1(X)&&X?.tool_calls?.length)return X.tool_calls.filter((Y)=>Y.type==="function").at(-1)?.function}return},j5=function(){for(let Z=this.messages.length-1;Z>=0;Z--){let X=this.messages[Z];if(A5(X)&&X.content!=null&&typeof X.content==="string"&&this.messages.some((Y)=>Y.role==="assistant"&&Y.tool_calls?.some((G)=>G.type==="function"&&G.id===X.tool_call_id)))return X.content}return},x5=function(){let Z={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:X}of this._chatCompletions)if(X)Z.completion_tokens+=X.completion_tokens,Z.prompt_tokens+=X.prompt_tokens,Z.total_tokens+=X.total_tokens;return Z},Qz=function(Z){if(Z.n!=null&&Z.n>1)throw new I("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Wz=function(Z){return typeof Z==="string"?Z:Z===void 0?"undefined":JSON.stringify(Z)};class p4 extends l4{static runTools($,Z,X){let Y=new p4,G={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runTools"}};return Y._run(()=>Y._runTools($,Z,G)),Y}_addMessage($,Z=!0){if(super._addMessage($,Z),n1($)&&$.content)this._emit("content",$.content)}}var z0={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class Vz extends Error{}class Hz extends Error{}function VM($,Z=z0.ALL){if(typeof $!=="string")throw TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw Error(`${$} is empty`);return HM($.trim(),Z)}var HM=($,Z)=>{let X=$.length,Y=0,G=(U)=>{throw new Vz(`${U} at position ${Y}`)},z=(U)=>{throw new Hz(`${U} at position ${Y}`)},J=()=>{if(H(),Y>=X)G("Unexpected end of input");if($[Y]==='"')return Q();if($[Y]==="{")return W();if($[Y]==="[")return V();if($.substring(Y,Y+4)==="null"||z0.NULL&Z&&X-Y<4&&"null".startsWith($.substring(Y)))return Y+=4,null;if($.substring(Y,Y+4)==="true"||z0.BOOL&Z&&X-Y<4&&"true".startsWith($.substring(Y)))return Y+=4,!0;if($.substring(Y,Y+5)==="false"||z0.BOOL&Z&&X-Y<5&&"false".startsWith($.substring(Y)))return Y+=5,!1;if($.substring(Y,Y+8)==="Infinity"||z0.INFINITY&Z&&X-Y<8&&"Infinity".startsWith($.substring(Y)))return Y+=8,1/0;if($.substring(Y,Y+9)==="-Infinity"||z0.MINUS_INFINITY&Z&&1<X-Y&&X-Y<9&&"-Infinity".startsWith($.substring(Y)))return Y+=9,-1/0;if($.substring(Y,Y+3)==="NaN"||z0.NAN&Z&&X-Y<3&&"NaN".startsWith($.substring(Y)))return Y+=3,NaN;return K()},Q=()=>{let U=Y,B=!1;Y++;while(Y<X&&($[Y]!=='"'||B&&$[Y-1]==="\\"))B=$[Y]==="\\"?!B:!1,Y++;if($.charAt(Y)=='"')try{return JSON.parse($.substring(U,++Y-Number(B)))}catch(T){z(String(T))}else if(z0.STR&Z)try{return JSON.parse($.substring(U,Y-Number(B))+'"')}catch(T){return JSON.parse($.substring(U,$.lastIndexOf("\\"))+'"')}G("Unterminated string literal")},W=()=>{Y++,H();let U={};try{while($[Y]!=="}"){if(H(),Y>=X&&z0.OBJ&Z)return U;let B=Q();H(),Y++;try{let T=J();Object.defineProperty(U,B,{value:T,writable:!0,enumerable:!0,configurable:!0})}catch(T){if(z0.OBJ&Z)return U;else throw T}if(H(),$[Y]===",")Y++}}catch(B){if(z0.OBJ&Z)return U;else G("Expected '}' at end of object")}return Y++,U},V=()=>{Y++;let U=[];try{while($[Y]!=="]")if(U.push(J()),H(),$[Y]===",")Y++}catch(B){if(z0.ARR&Z)return U;G("Expected ']' at end of array")}return Y++,U},K=()=>{if(Y===0){if($==="-"&&z0.NUM&Z)G("Not sure what '-' is");try{return JSON.parse($)}catch(B){if(z0.NUM&Z)try{if($[$.length-1]===".")return JSON.parse($.substring(0,$.lastIndexOf(".")));return JSON.parse($.substring(0,$.lastIndexOf("e")))}catch(T){}z(String(B))}}let U=Y;if($[Y]==="-")Y++;while($[Y]&&!",]}".includes($[Y]))Y++;if(Y==X&&!(z0.NUM&Z))G("Unterminated number literal");try{return JSON.parse($.substring(U,Y))}catch(B){if($.substring(U,Y)==="-"&&z0.NUM&Z)G("Not sure what '-' is");try{return JSON.parse($.substring(U,$.lastIndexOf("e")))}catch(T){z(String(T))}}},H=()=>{while(Y<X&&`
|
|
251
|
+
\r `.includes($[Y]))Y++};return J()},k5=($)=>VM($,z0.ALL^z0.NUM);var G0,J$,s1,A$,b5,d8,f5,y5,v5,c8,g5,Kz;class S$ extends l4{constructor($){super();G0.add(this),J$.set(this,void 0),s1.set(this,void 0),A$.set(this,void 0),x(this,J$,$,"f"),x(this,s1,[],"f")}get currentChatCompletionSnapshot(){return w(this,A$,"f")}static fromReadableStream($){let Z=new S$(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createChatCompletion($,Z,X){let Y=new S$(Z);return Y._run(()=>Y._runChatCompletion($,{...Z,stream:!0},{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}async _createChatCompletion($,Z,X){super._createChatCompletion;let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}w(this,G0,"m",b5).call(this);let G=await $.chat.completions.create({...Z,stream:!0},{...X,signal:this.controller.signal});this._connected();for await(let z of G)w(this,G0,"m",f5).call(this,z);if(G.controller.signal?.aborted)throw new Z0;return this._addChatCompletion(w(this,G0,"m",c8).call(this))}async _fromReadableStream($,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}w(this,G0,"m",b5).call(this),this._connected();let Y=E0.fromReadableStream($,this.controller),G;for await(let z of Y){if(G&&G!==z.id)this._addChatCompletion(w(this,G0,"m",c8).call(this));w(this,G0,"m",f5).call(this,z),G=z.id}if(Y.controller.signal?.aborted)throw new Z0;return this._addChatCompletion(w(this,G0,"m",c8).call(this))}[(J$=new WeakMap,s1=new WeakMap,A$=new WeakMap,G0=new WeakSet,b5=function(){if(this.ended)return;x(this,A$,void 0,"f")},d8=function(Z){let X=w(this,s1,"f")[Z.index];if(X)return X;return X={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},w(this,s1,"f")[Z.index]=X,X},f5=function(Z){if(this.ended)return;let X=w(this,G0,"m",Kz).call(this,Z);this._emit("chunk",Z,X);for(let Y of Z.choices){let G=X.choices[Y.index];if(Y.delta.content!=null&&G.message?.role==="assistant"&&G.message?.content)this._emit("content",Y.delta.content,G.message.content),this._emit("content.delta",{delta:Y.delta.content,snapshot:G.message.content,parsed:G.message.parsed});if(Y.delta.refusal!=null&&G.message?.role==="assistant"&&G.message?.refusal)this._emit("refusal.delta",{delta:Y.delta.refusal,snapshot:G.message.refusal});if(Y.logprobs?.content!=null&&G.message?.role==="assistant")this._emit("logprobs.content.delta",{content:Y.logprobs?.content,snapshot:G.logprobs?.content??[]});if(Y.logprobs?.refusal!=null&&G.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:Y.logprobs?.refusal,snapshot:G.logprobs?.refusal??[]});let z=w(this,G0,"m",d8).call(this,G);if(G.finish_reason){if(w(this,G0,"m",v5).call(this,G),z.current_tool_call_index!=null)w(this,G0,"m",y5).call(this,G,z.current_tool_call_index)}for(let J of Y.delta.tool_calls??[]){if(z.current_tool_call_index!==J.index){if(w(this,G0,"m",v5).call(this,G),z.current_tool_call_index!=null)w(this,G0,"m",y5).call(this,G,z.current_tool_call_index)}z.current_tool_call_index=J.index}for(let J of Y.delta.tool_calls??[]){let Q=G.message.tool_calls?.[J.index];if(!Q?.type)continue;if(Q?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:Q.function?.name,index:J.index,arguments:Q.function.arguments,parsed_arguments:Q.function.parsed_arguments,arguments_delta:J.function?.arguments??""});else Bz(Q?.type)}}},y5=function(Z,X){if(w(this,G0,"m",d8).call(this,Z).done_tool_calls.has(X))return;let G=Z.message.tool_calls?.[X];if(!G)throw Error("no tool call snapshot");if(!G.type)throw Error("tool call snapshot missing `type`");if(G.type==="function"){let z=w(this,J$,"f")?.tools?.find((J)=>v4(J)&&J.function.name===G.function.name);this._emit("tool_calls.function.arguments.done",{name:G.function.name,index:X,arguments:G.function.arguments,parsed_arguments:e$(z)?z.$parseRaw(G.function.arguments):z?.function.strict?JSON.parse(G.function.arguments):null})}else Bz(G.type)},v5=function(Z){let X=w(this,G0,"m",d8).call(this,Z);if(Z.message.content&&!X.content_done){X.content_done=!0;let Y=w(this,G0,"m",g5).call(this);this._emit("content.done",{content:Z.message.content,parsed:Y?Y.$parseRaw(Z.message.content):null})}if(Z.message.refusal&&!X.refusal_done)X.refusal_done=!0,this._emit("refusal.done",{refusal:Z.message.refusal});if(Z.logprobs?.content&&!X.logprobs_content_done)X.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:Z.logprobs.content});if(Z.logprobs?.refusal&&!X.logprobs_refusal_done)X.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:Z.logprobs.refusal})},c8=function(){if(this.ended)throw new I("stream has ended, this shouldn't happen");let Z=w(this,A$,"f");if(!Z)throw new I("request ended without sending any chunks");return x(this,A$,void 0,"f"),x(this,s1,[],"f"),KM(Z,w(this,J$,"f"))},g5=function(){let Z=w(this,J$,"f")?.response_format;if(g4(Z))return Z;return null},Kz=function(Z){var X,Y,G,z;let J=w(this,A$,"f"),{choices:Q,...W}=Z;if(!J)J=x(this,A$,{...W,choices:[]},"f");else Object.assign(J,W);for(let{delta:V,finish_reason:K,index:H,logprobs:U=null,...B}of Z.choices){let T=J.choices[H];if(!T)T=J.choices[H]={finish_reason:K,index:H,message:{},logprobs:U,...B};if(U)if(!T.logprobs)T.logprobs=Object.assign({},U);else{let{content:R,refusal:A,...S}=U;if(Uz(S),Object.assign(T.logprobs,S),R)(X=T.logprobs).content??(X.content=[]),T.logprobs.content.push(...R);if(A)(Y=T.logprobs).refusal??(Y.refusal=[]),T.logprobs.refusal.push(...A)}if(K){if(T.finish_reason=K,w(this,J$,"f")&&R5(w(this,J$,"f"))){if(K==="length")throw new C4;if(K==="content_filter")throw new I4}}if(Object.assign(T,B),!V)continue;let{content:F,refusal:M,function_call:O,role:N,tool_calls:_,...P}=V;if(Uz(P),Object.assign(T.message,P),M)T.message.refusal=(T.message.refusal||"")+M;if(N)T.message.role=N;if(O)if(!T.message.function_call)T.message.function_call=O;else{if(O.name)T.message.function_call.name=O.name;if(O.arguments)(G=T.message.function_call).arguments??(G.arguments=""),T.message.function_call.arguments+=O.arguments}if(F){if(T.message.content=(T.message.content||"")+F,!T.message.refusal&&w(this,G0,"m",g5).call(this))T.message.parsed=k5(T.message.content)}if(_){if(!T.message.tool_calls)T.message.tool_calls=[];for(let{index:R,id:A,type:S,function:D,...k}of _){let b=(z=T.message.tool_calls)[R]??(z[R]={});if(Object.assign(b,k),A)b.id=A;if(S)b.type=S;if(D)b.function??(b.function={name:D.name??"",arguments:""});if(D?.name)b.function.name=D.name;if(D?.arguments){if(b.function.arguments+=D.arguments,Xz(w(this,J$,"f"),b))b.function.parsed_arguments=k5(b.function.arguments)}}}}return J},Symbol.asyncIterator)](){let $=[],Z=[],X=!1;return this.on("chunk",(Y)=>{let G=Z.shift();if(G)G.resolve(Y);else $.push(Y)}),this.on("end",()=>{X=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),this.on("error",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(X)return{value:void 0,done:!0};return new Promise((G,z)=>Z.push({resolve:G,reject:z})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new E0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function KM($,Z){let{id:X,choices:Y,created:G,model:z,system_fingerprint:J,...Q}=$,W={...Q,id:X,choices:Y.map(({message:V,finish_reason:K,index:H,logprobs:U,...B})=>{if(!K)throw new I(`missing finish_reason for choice ${H}`);let{content:T=null,function_call:F,tool_calls:M,...O}=V,N=V.role;if(!N)throw new I(`missing role for choice ${H}`);if(F){let{arguments:_,name:P}=F;if(_==null)throw new I(`missing function_call.arguments for choice ${H}`);if(!P)throw new I(`missing function_call.name for choice ${H}`);return{...B,message:{content:T,function_call:{arguments:_,name:P},role:N,refusal:V.refusal??null},finish_reason:K,index:H,logprobs:U}}if(M)return{...B,index:H,finish_reason:K,logprobs:U,message:{...O,role:N,content:T,refusal:V.refusal??null,tool_calls:M.map((_,P)=>{let{function:R,type:A,id:S,...D}=_,{arguments:k,name:b,...i}=R||{};if(S==null)throw new I(`missing choices[${H}].tool_calls[${P}].id
|
|
251
252
|
${l8($)}`);if(A==null)throw new I(`missing choices[${H}].tool_calls[${P}].type
|
|
252
253
|
${l8($)}`);if(b==null)throw new I(`missing choices[${H}].tool_calls[${P}].function.name
|
|
253
254
|
${l8($)}`);if(k==null)throw new I(`missing choices[${H}].tool_calls[${P}].function.arguments
|
|
254
|
-
${l8($)}`);return{...D,id:S,type:A,function:{...i,name:b,arguments:k}}})}};return{...U,message:{...O,content:F,role:N,refusal:V.refusal??null},finish_reason:K,index:H,logprobs:B}}),created:G,model:z,object:"chat.completion",...J?{system_fingerprint:J}:{}};return eG(W,Z)}function l8($){return JSON.stringify($)}function Hz($){return}function Kz($){}class $2 extends C${static fromReadableStream($){let Z=new $2(null);return Z._run(()=>Z._fromReadableStream($)),Z}static runTools($,Z,X){let Y=new $2(Z),G={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runTools"}};return Y._run(()=>Y._runTools($,Z,G)),Y}}class I$ extends L{constructor(){super(...arguments);this.messages=new s1(this._client)}create($,Z){return this._client.post("/chat/completions",{body:$,...Z,stream:$.stream??!1,__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/chat/completions/${$}`,{...Z,__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/chat/completions/${$}`,{body:Z,...X,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/chat/completions",y,{query:$,...Z,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/chat/completions/${$}`,{...Z,__security:{bearerAuth:!0}})}parse($,Z){return Xz($.tools),this._client.chat.completions.create($,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((X)=>u4(X,$))}runTools($,Z){if($.stream)return $2.runTools(this._client,$,Z);return i4.runTools(this._client,$,Z)}stream($,Z){return C$.createChatCompletion(this._client,$,Z)}}I$.Messages=s1;class z1 extends L{constructor(){super(...arguments);this.completions=new I$(this._client)}}z1.Completions=I$;class a4 extends L{create($,Z){return this._client.post("/organization/admin_api_keys",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z){return this._client.get(q`/organization/admin_api_keys/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/admin_api_keys",y,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/admin_api_keys/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class n4 extends L{list($={},Z){return this._client.getAPIList("/organization/audit_logs",d,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}}class r4 extends L{create($,Z){return this._client.post("/organization/certificates",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z={},X){return this._client.get(q`/organization/certificates/${$}`,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/certificates/${$}`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/certificates",d,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/certificates/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}activate($,Z){return this._client.getAPIList("/organization/certificates/activate",L0,{body:$,method:"post",...Z,__security:{adminAPIKeyAuth:!0}})}deactivate($,Z){return this._client.getAPIList("/organization/certificates/deactivate",L0,{body:$,method:"post",...Z,__security:{adminAPIKeyAuth:!0}})}}class s4 extends L{retrieve($){return this._client.get("/organization/data_retention",{...$,__security:{adminAPIKeyAuth:!0}})}update($,Z){return this._client.post("/organization/data_retention",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}}class o4 extends L{create($,Z){return this._client.post("/organization/invites",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z){return this._client.get(q`/organization/invites/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/invites",d,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/invites/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class t4 extends L{create($,Z){return this._client.post("/organization/roles",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z){return this._client.get(q`/organization/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/roles/${$}`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/roles",X0,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class e4 extends L{create($,Z){return this._client.post("/organization/spend_alerts",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/spend_alerts/${$}`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/spend_alerts",d,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/spend_alerts/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class $Z extends L{audioSpeeches($,Z){return this._client.get("/organization/usage/audio_speeches",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions($,Z){return this._client.get("/organization/usage/audio_transcriptions",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions($,Z){return this._client.get("/organization/usage/code_interpreter_sessions",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}completions($,Z){return this._client.get("/organization/usage/completions",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}costs($,Z){return this._client.get("/organization/costs",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}embeddings($,Z){return this._client.get("/organization/usage/embeddings",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls($,Z){return this._client.get("/organization/usage/file_search_calls",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}images($,Z){return this._client.get("/organization/usage/images",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}moderations($,Z){return this._client.get("/organization/usage/moderations",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}vectorStores($,Z){return this._client.get("/organization/usage/vector_stores",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}webSearchCalls($,Z){return this._client.get("/organization/usage/web_search_calls",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}}class ZZ extends L{create($,Z,X){return this._client.post(q`/organization/groups/${$}/roles`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{group_id:Y}=Z;return this._client.get(q`/organization/groups/${Y}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/groups/${$}/roles`,X0,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{group_id:Y}=Z;return this._client.delete(q`/organization/groups/${Y}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class XZ extends L{create($,Z,X){return this._client.post(q`/organization/groups/${$}/users`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{group_id:Y}=Z;return this._client.get(q`/organization/groups/${Y}/users/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/groups/${$}/users`,X0,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{group_id:Y}=Z;return this._client.delete(q`/organization/groups/${Y}/users/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class J1 extends L{constructor(){super(...arguments);this.users=new XZ(this._client),this.roles=new ZZ(this._client)}create($,Z){return this._client.post("/organization/groups",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z){return this._client.get(q`/organization/groups/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/groups/${$}`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/groups",X0,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/groups/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}J1.Users=XZ;J1.Roles=ZZ;class YZ extends L{retrieve($,Z,X){let{project_id:Y}=Z;return this._client.get(q`/organization/projects/${Y}/api_keys/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/projects/${$}/api_keys`,d,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y}=Z;return this._client.delete(q`/organization/projects/${Y}/api_keys/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class GZ extends L{list($,Z={},X){return this._client.getAPIList(q`/organization/projects/${$}/certificates`,d,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}activate($,Z,X){return this._client.getAPIList(q`/organization/projects/${$}/certificates/activate`,L0,{body:Z,method:"post",...X,__security:{adminAPIKeyAuth:!0}})}deactivate($,Z,X){return this._client.getAPIList(q`/organization/projects/${$}/certificates/deactivate`,L0,{body:Z,method:"post",...X,__security:{adminAPIKeyAuth:!0}})}}class zZ extends L{retrieve($,Z){return this._client.get(q`/organization/projects/${$}/data_retention`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/projects/${$}/data_retention`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}}class JZ extends L{retrieve($,Z){return this._client.get(q`/organization/projects/${$}/hosted_tool_permissions`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/projects/${$}/hosted_tool_permissions`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}}class QZ extends L{retrieve($,Z){return this._client.get(q`/organization/projects/${$}/model_permissions`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/projects/${$}/model_permissions`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/projects/${$}/model_permissions`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class WZ extends L{listRateLimits($,Z={},X){return this._client.getAPIList(q`/organization/projects/${$}/rate_limits`,d,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}updateRateLimit($,Z,X){let{project_id:Y,...G}=Z;return this._client.post(q`/organization/projects/${Y}/rate_limits/${$}`,{body:G,...X,__security:{adminAPIKeyAuth:!0}})}}class VZ extends L{create($,Z,X){return this._client.post(q`/projects/${$}/roles`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{project_id:Y}=Z;return this._client.get(q`/projects/${Y}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){let{project_id:Y,...G}=Z;return this._client.post(q`/projects/${Y}/roles/${$}`,{body:G,...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/projects/${$}/roles`,X0,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y}=Z;return this._client.delete(q`/projects/${Y}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class HZ extends L{create($,Z,X){return this._client.post(q`/organization/projects/${$}/service_accounts`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{project_id:Y}=Z;return this._client.get(q`/organization/projects/${Y}/service_accounts/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){let{project_id:Y,...G}=Z;return this._client.post(q`/organization/projects/${Y}/service_accounts/${$}`,{body:G,...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/projects/${$}/service_accounts`,d,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y}=Z;return this._client.delete(q`/organization/projects/${Y}/service_accounts/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class KZ extends L{create($,Z,X){return this._client.post(q`/organization/projects/${$}/spend_alerts`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){let{project_id:Y,...G}=Z;return this._client.post(q`/organization/projects/${Y}/spend_alerts/${$}`,{body:G,...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/projects/${$}/spend_alerts`,d,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y}=Z;return this._client.delete(q`/organization/projects/${Y}/spend_alerts/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class BZ extends L{create($,Z,X){let{project_id:Y,...G}=Z;return this._client.post(q`/projects/${Y}/groups/${$}/roles`,{body:G,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{project_id:Y,group_id:G}=Z;return this._client.get(q`/projects/${Y}/groups/${G}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}list($,Z,X){let{project_id:Y,...G}=Z;return this._client.getAPIList(q`/projects/${Y}/groups/${$}/roles`,X0,{query:G,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y,group_id:G}=Z;return this._client.delete(q`/projects/${Y}/groups/${G}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class Z2 extends L{constructor(){super(...arguments);this.roles=new BZ(this._client)}create($,Z,X){return this._client.post(q`/organization/projects/${$}/groups`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{project_id:Y,...G}=Z;return this._client.get(q`/organization/projects/${Y}/groups/${$}`,{query:G,...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/projects/${$}/groups`,X0,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y}=Z;return this._client.delete(q`/organization/projects/${Y}/groups/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}Z2.Roles=BZ;class UZ extends L{create($,Z,X){let{project_id:Y,...G}=Z;return this._client.post(q`/projects/${Y}/users/${$}/roles`,{body:G,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{project_id:Y,user_id:G}=Z;return this._client.get(q`/projects/${Y}/users/${G}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}list($,Z,X){let{project_id:Y,...G}=Z;return this._client.getAPIList(q`/projects/${Y}/users/${$}/roles`,X0,{query:G,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y,user_id:G}=Z;return this._client.delete(q`/projects/${Y}/users/${G}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class X2 extends L{constructor(){super(...arguments);this.roles=new UZ(this._client)}create($,Z,X){return this._client.post(q`/organization/projects/${$}/users`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{project_id:Y}=Z;return this._client.get(q`/organization/projects/${Y}/users/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){let{project_id:Y,...G}=Z;return this._client.post(q`/organization/projects/${Y}/users/${$}`,{body:G,...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/projects/${$}/users`,d,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y}=Z;return this._client.delete(q`/organization/projects/${Y}/users/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}X2.Roles=UZ;class T0 extends L{constructor(){super(...arguments);this.users=new X2(this._client),this.serviceAccounts=new HZ(this._client),this.apiKeys=new YZ(this._client),this.rateLimits=new WZ(this._client),this.modelPermissions=new QZ(this._client),this.hostedToolPermissions=new JZ(this._client),this.groups=new Z2(this._client),this.roles=new VZ(this._client),this.dataRetention=new zZ(this._client),this.spendAlerts=new KZ(this._client),this.certificates=new GZ(this._client)}create($,Z){return this._client.post("/organization/projects",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z){return this._client.get(q`/organization/projects/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/projects/${$}`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/projects",d,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}archive($,Z){return this._client.post(q`/organization/projects/${$}/archive`,{...Z,__security:{adminAPIKeyAuth:!0}})}}T0.Users=X2;T0.ServiceAccounts=HZ;T0.APIKeys=YZ;T0.RateLimits=WZ;T0.ModelPermissions=QZ;T0.HostedToolPermissions=JZ;T0.Groups=Z2;T0.Roles=VZ;T0.DataRetention=zZ;T0.SpendAlerts=KZ;T0.Certificates=GZ;class qZ extends L{create($,Z,X){return this._client.post(q`/organization/users/${$}/roles`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{user_id:Y}=Z;return this._client.get(q`/organization/users/${Y}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/users/${$}/roles`,X0,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{user_id:Y}=Z;return this._client.delete(q`/organization/users/${Y}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class Y2 extends L{constructor(){super(...arguments);this.roles=new qZ(this._client)}retrieve($,Z){return this._client.get(q`/organization/users/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/users/${$}`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/users",d,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/users/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}Y2.Roles=qZ;class F0 extends L{constructor(){super(...arguments);this.auditLogs=new n4(this._client),this.adminAPIKeys=new a4(this._client),this.usage=new $Z(this._client),this.invites=new o4(this._client),this.users=new Y2(this._client),this.groups=new J1(this._client),this.roles=new t4(this._client),this.dataRetention=new s4(this._client),this.spendAlerts=new e4(this._client),this.certificates=new r4(this._client),this.projects=new T0(this._client)}}F0.AuditLogs=n4;F0.AdminAPIKeys=a4;F0.Usage=$Z;F0.Invites=o4;F0.Users=Y2;F0.Groups=J1;F0.Roles=t4;F0.DataRetention=s4;F0.SpendAlerts=e4;F0.Certificates=r4;F0.Projects=T0;class Q1 extends L{constructor(){super(...arguments);this.organization=new F0(this._client)}}Q1.Organization=F0;var Bz=Symbol("brand.privateNullableHeaders");function*gw($){if(!$)return;if(Bz in $){let{values:Y,nulls:G}=$;yield*Y.entries();for(let z of G)yield[z,null];return}let Z=!1,X;if($ instanceof Headers)X=$.entries();else if(Q5($))X=$;else Z=!0,X=Object.entries($??{});for(let Y of X){let G=Y[0];if(typeof G!=="string")throw TypeError("expected header name to be a string");let z=Q5(Y[1])?Y[1]:[Y[1]],J=!1;for(let Q of z){if(Q===void 0)continue;if(Z&&!J)J=!0,yield[G,null];yield[G,Q]}}}var E=($)=>{let Z=new Headers,X=new Set;for(let Y of $){let G=new Set;for(let[z,J]of gw(Y)){let Q=z.toLowerCase();if(!G.has(Q))Z.delete(z),G.add(Q);if(J===null)Z.delete(z),X.add(Q);else Z.append(z,J),X.delete(Q)}}return{[Bz]:!0,values:Z,nulls:X}};class TZ extends L{create($,Z){return this._client.post("/audio/speech",{body:$,...Z,headers:E([{Accept:"application/octet-stream"},Z?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class FZ extends L{create($,Z){return this._client.post("/audio/transcriptions",q0({body:$,...Z,stream:$.stream??!1,__metadata:{model:$.model},__security:{bearerAuth:!0}},this._client))}}class LZ extends L{create($,Z){return this._client.post("/audio/translations",q0({body:$,...Z,__metadata:{model:$.model},__security:{bearerAuth:!0}},this._client))}}class W$ extends L{constructor(){super(...arguments);this.transcriptions=new FZ(this._client),this.translations=new LZ(this._client),this.speech=new TZ(this._client)}}W$.Transcriptions=FZ;W$.Translations=LZ;W$.Speech=TZ;class G2 extends L{create($,Z){return this._client.post("/batches",{body:$,...Z,__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/batches/${$}`,{...Z,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/batches",y,{query:$,...Z,__security:{bearerAuth:!0}})}cancel($,Z){return this._client.post(q`/batches/${$}/cancel`,{...Z,__security:{bearerAuth:!0}})}}class wZ extends L{create($,Z){return this._client.post("/assistants",{body:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/assistants/${$}`,{...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/assistants/${$}`,{body:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/assistants",y,{query:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/assistants/${$}`,{...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}class MZ extends L{create($,Z){return this._client.post("/realtime/sessions",{body:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}class OZ extends L{create($,Z){return this._client.post("/realtime/transcription_sessions",{body:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}class W1 extends L{constructor(){super(...arguments);this.sessions=new MZ(this._client),this.transcriptionSessions=new OZ(this._client)}}W1.Sessions=MZ;W1.TranscriptionSessions=OZ;class NZ extends L{create($,Z){return this._client.post("/chatkit/sessions",{body:$,...Z,headers:E([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers]),__security:{bearerAuth:!0}})}cancel($,Z){return this._client.post(q`/chatkit/sessions/${$}/cancel`,{...Z,headers:E([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers]),__security:{bearerAuth:!0}})}}class _Z extends L{retrieve($,Z){return this._client.get(q`/chatkit/threads/${$}`,{...Z,headers:E([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers]),__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/chatkit/threads",d,{query:$,...Z,headers:E([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers]),__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/chatkit/threads/${$}`,{...Z,headers:E([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers]),__security:{bearerAuth:!0}})}listItems($,Z={},X){return this._client.getAPIList(q`/chatkit/threads/${$}/items`,d,{query:Z,...X,headers:E([{"OpenAI-Beta":"chatkit_beta=v1"},X?.headers]),__security:{bearerAuth:!0}})}}class V1 extends L{constructor(){super(...arguments);this.sessions=new NZ(this._client),this.threads=new _Z(this._client)}}V1.Sessions=NZ;V1.Threads=_Z;class PZ extends L{create($,Z,X){return this._client.post(q`/threads/${$}/messages`,{body:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}retrieve($,Z,X){let{thread_id:Y}=Z;return this._client.get(q`/threads/${Y}/messages/${$}`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}update($,Z,X){let{thread_id:Y,...G}=Z;return this._client.post(q`/threads/${Y}/messages/${$}`,{body:G,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/threads/${$}/messages`,y,{query:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}delete($,Z,X){let{thread_id:Y}=Z;return this._client.delete(q`/threads/${Y}/messages/${$}`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}}class DZ extends L{retrieve($,Z,X){let{thread_id:Y,run_id:G,...z}=Z;return this._client.get(q`/threads/${Y}/runs/${G}/steps/${$}`,{query:z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($,Z,X){let{thread_id:Y,...G}=Z;return this._client.getAPIList(q`/threads/${Y}/runs/${$}/steps`,y,{query:G,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}}var Uz=($)=>{if(typeof Buffer<"u"){let Z=Buffer.from($,"base64");return Array.from(new Float32Array(Z.buffer,Z.byteOffset,Z.length/Float32Array.BYTES_PER_ELEMENT))}else{let Z=atob($),X=Z.length,Y=new Uint8Array(X);for(let G=0;G<X;G++)Y[G]=Z.charCodeAt(G);return Array.from(new Float32Array(Y.buffer))}};var l0=($)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[$]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.($)?.trim()||void 0;return};var V0,K1,h5,p0,p8,v0,B1,z2,H1,n8,A0,i8,a8,AZ,EZ,RZ,qz,Tz,Fz,Lz,wz,Mz,Oz;class j$ extends G1{constructor(){super(...arguments);V0.add(this),h5.set(this,[]),p0.set(this,{}),p8.set(this,{}),v0.set(this,void 0),B1.set(this,void 0),z2.set(this,void 0),H1.set(this,void 0),n8.set(this,void 0),A0.set(this,void 0),i8.set(this,void 0),a8.set(this,void 0),AZ.set(this,void 0)}[(h5=new WeakMap,p0=new WeakMap,p8=new WeakMap,v0=new WeakMap,B1=new WeakMap,z2=new WeakMap,H1=new WeakMap,n8=new WeakMap,A0=new WeakMap,i8=new WeakMap,a8=new WeakMap,AZ=new WeakMap,V0=new WeakSet,Symbol.asyncIterator)](){let $=[],Z=[],X=!1;return this.on("event",(Y)=>{let G=Z.shift();if(G)G.resolve(Y);else $.push(Y)}),this.on("end",()=>{X=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),this.on("error",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(X)return{value:void 0,done:!0};return new Promise((G,z)=>Z.push({resolve:G,reject:z})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream($){let Z=new K1;return Z._run(()=>Z._fromReadableStream($)),Z}async _fromReadableStream($,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}this._connected();let Y=R0.fromReadableStream($,this.controller);for await(let G of Y)M(this,V0,"m",EZ).call(this,G);if(Y.controller.signal?.aborted)throw new $0;return this._addRun(M(this,V0,"m",RZ).call(this))}toReadableStream(){return new R0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream($,Z,X,Y){let G=new K1;return G._run(()=>G._runToolAssistantStream($,Z,X,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),G}async _createToolAssistantStream($,Z,X,Y){let G=Y?.signal;if(G){if(G.aborted)this.controller.abort();G.addEventListener("abort",()=>this.controller.abort())}let z={...X,stream:!0},J=await $.submitToolOutputs(Z,z,{...Y,signal:this.controller.signal});this._connected();for await(let Q of J)M(this,V0,"m",EZ).call(this,Q);if(J.controller.signal?.aborted)throw new $0;return this._addRun(M(this,V0,"m",RZ).call(this))}static createThreadAssistantStream($,Z,X){let Y=new K1;return Y._run(()=>Y._threadAssistantStream($,Z,{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}static createAssistantStream($,Z,X,Y){let G=new K1;return G._run(()=>G._runAssistantStream($,Z,X,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),G}currentEvent(){return M(this,i8,"f")}currentRun(){return M(this,a8,"f")}currentMessageSnapshot(){return M(this,v0,"f")}currentRunStepSnapshot(){return M(this,AZ,"f")}async finalRunSteps(){return await this.done(),Object.values(M(this,p0,"f"))}async finalMessages(){return await this.done(),Object.values(M(this,p8,"f"))}async finalRun(){if(await this.done(),!M(this,B1,"f"))throw Error("Final run was not received.");return M(this,B1,"f")}async _createThreadAssistantStream($,Z,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}let G={...Z,stream:!0},z=await $.createAndRun(G,{...X,signal:this.controller.signal});this._connected();for await(let J of z)M(this,V0,"m",EZ).call(this,J);if(z.controller.signal?.aborted)throw new $0;return this._addRun(M(this,V0,"m",RZ).call(this))}async _createAssistantStream($,Z,X,Y){let G=Y?.signal;if(G){if(G.aborted)this.controller.abort();G.addEventListener("abort",()=>this.controller.abort())}let z={...X,stream:!0},J=await $.create(Z,z,{...Y,signal:this.controller.signal});this._connected();for await(let Q of J)M(this,V0,"m",EZ).call(this,Q);if(J.controller.signal?.aborted)throw new $0;return this._addRun(M(this,V0,"m",RZ).call(this))}static accumulateDelta($,Z){for(let[X,Y]of Object.entries(Z)){if(!$.hasOwnProperty(X)){$[X]=Y;continue}let G=$[X];if(G===null||G===void 0){$[X]=Y;continue}if(X==="index"||X==="type"){$[X]=Y;continue}if(typeof G==="string"&&typeof Y==="string")G+=Y;else if(typeof G==="number"&&typeof Y==="number")G+=Y;else if(x4(G)&&x4(Y))G=this.accumulateDelta(G,Y);else if(Array.isArray(G)&&Array.isArray(Y)){if(G.every((z)=>typeof z==="string"||typeof z==="number")){G.push(...Y);continue}for(let z of Y){if(!x4(z))throw Error(`Expected array delta entry to be an object but got: ${z}`);let J=z.index;if(J==null)throw console.error(z),Error("Expected array delta entry to have an `index` property");if(typeof J!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${J}`);let Q=G[J];if(Q==null)G.push(z);else G[J]=this.accumulateDelta(Q,z)}continue}else throw Error(`Unhandled record type: ${X}, deltaValue: ${Y}, accValue: ${G}`);$[X]=G}return $}_addRun($){return $}async _threadAssistantStream($,Z,X){return await this._createThreadAssistantStream(Z,$,X)}async _runAssistantStream($,Z,X,Y){return await this._createAssistantStream(Z,$,X,Y)}async _runToolAssistantStream($,Z,X,Y){return await this._createToolAssistantStream(Z,$,X,Y)}}K1=j$,EZ=function(Z){if(this.ended)return;switch(x(this,i8,Z,"f"),M(this,V0,"m",Fz).call(this,Z),Z.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":M(this,V0,"m",Oz).call(this,Z);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":M(this,V0,"m",Tz).call(this,Z);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":M(this,V0,"m",qz).call(this,Z);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:ow(Z)}},RZ=function(){if(this.ended)throw new I("stream has ended, this shouldn't happen");if(!M(this,B1,"f"))throw Error("Final run has not been received");return M(this,B1,"f")},qz=function(Z){let[X,Y]=M(this,V0,"m",wz).call(this,Z,M(this,v0,"f"));x(this,v0,X,"f"),M(this,p8,"f")[X.id]=X;for(let G of Y){let z=X.content[G.index];if(z?.type=="text")this._emit("textCreated",z.text)}switch(Z.event){case"thread.message.created":this._emit("messageCreated",Z.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",Z.data.delta,X),Z.data.delta.content)for(let G of Z.data.delta.content){if(G.type=="text"&&G.text){let z=G.text,J=X.content[G.index];if(J&&J.type=="text")this._emit("textDelta",z,J.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(G.index!=M(this,z2,"f")){if(M(this,H1,"f"))switch(M(this,H1,"f").type){case"text":this._emit("textDone",M(this,H1,"f").text,M(this,v0,"f"));break;case"image_file":this._emit("imageFileDone",M(this,H1,"f").image_file,M(this,v0,"f"));break}x(this,z2,G.index,"f")}x(this,H1,X.content[G.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(M(this,z2,"f")!==void 0){let G=Z.data.content[M(this,z2,"f")];if(G)switch(G.type){case"image_file":this._emit("imageFileDone",G.image_file,M(this,v0,"f"));break;case"text":this._emit("textDone",G.text,M(this,v0,"f"));break}}if(M(this,v0,"f"))this._emit("messageDone",Z.data);x(this,v0,void 0,"f")}},Tz=function(Z){let X=M(this,V0,"m",Lz).call(this,Z);switch(x(this,AZ,X,"f"),Z.event){case"thread.run.step.created":this._emit("runStepCreated",Z.data);break;case"thread.run.step.delta":let Y=Z.data.delta;if(Y.step_details&&Y.step_details.type=="tool_calls"&&Y.step_details.tool_calls&&X.step_details.type=="tool_calls")for(let z of Y.step_details.tool_calls)if(z.index==M(this,n8,"f"))this._emit("toolCallDelta",z,X.step_details.tool_calls[z.index]);else{if(M(this,A0,"f"))this._emit("toolCallDone",M(this,A0,"f"));if(x(this,n8,z.index,"f"),x(this,A0,X.step_details.tool_calls[z.index],"f"),M(this,A0,"f"))this._emit("toolCallCreated",M(this,A0,"f"))}this._emit("runStepDelta",Z.data.delta,X);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(x(this,AZ,void 0,"f"),Z.data.step_details.type=="tool_calls"){if(M(this,A0,"f"))this._emit("toolCallDone",M(this,A0,"f")),x(this,A0,void 0,"f")}this._emit("runStepDone",Z.data,X);break;case"thread.run.step.in_progress":break}},Fz=function(Z){M(this,h5,"f").push(Z),this._emit("event",Z)},Lz=function(Z){switch(Z.event){case"thread.run.step.created":return M(this,p0,"f")[Z.data.id]=Z.data,Z.data;case"thread.run.step.delta":let X=M(this,p0,"f")[Z.data.id];if(!X)throw Error("Received a RunStepDelta before creation of a snapshot");let Y=Z.data;if(Y.delta){let G=K1.accumulateDelta(X,Y.delta);M(this,p0,"f")[Z.data.id]=G}return M(this,p0,"f")[Z.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":M(this,p0,"f")[Z.data.id]=Z.data;break}if(M(this,p0,"f")[Z.data.id])return M(this,p0,"f")[Z.data.id];throw Error("No snapshot available")},wz=function(Z,X){let Y=[];switch(Z.event){case"thread.message.created":return[Z.data,Y];case"thread.message.delta":if(!X)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let G=Z.data;if(G.delta.content)for(let z of G.delta.content)if(z.index in X.content){let J=X.content[z.index];X.content[z.index]=M(this,V0,"m",Mz).call(this,z,J)}else X.content[z.index]=z,Y.push(z);return[X,Y];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(X)return[X,Y];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Mz=function(Z,X){return K1.accumulateDelta(X,Z)},Oz=function(Z){switch(x(this,a8,Z.data,"f"),Z.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":if(x(this,B1,Z.data,"f"),M(this,A0,"f"))this._emit("toolCallDone",M(this,A0,"f")),x(this,A0,void 0,"f");break;case"thread.run.cancelling":break}};function ow($){}class J2 extends L{constructor(){super(...arguments);this.steps=new DZ(this._client)}create($,Z,X){let{include:Y,...G}=Z;return this._client.post(q`/threads/${$}/runs`,{query:{include:Y},body:G,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),stream:Z.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve($,Z,X){let{thread_id:Y}=Z;return this._client.get(q`/threads/${Y}/runs/${$}`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}update($,Z,X){let{thread_id:Y,...G}=Z;return this._client.post(q`/threads/${Y}/runs/${$}`,{body:G,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/threads/${$}/runs`,y,{query:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}cancel($,Z,X){let{thread_id:Y}=Z;return this._client.post(q`/threads/${Y}/runs/${$}/cancel`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}async createAndPoll($,Z,X){let Y=await this.create($,Z,X);return await this.poll(Y.id,{thread_id:$},X)}createAndStream($,Z,X){return j$.createAssistantStream($,this._client.beta.threads.runs,Z,X)}async poll($,Z,X){let Y=E([X?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":X?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:G,response:z}=await this.retrieve($,Z,{...X,headers:{...X?.headers,...Y}}).withResponse();switch(G.status){case"queued":case"in_progress":case"cancelling":let J=5000;if(X?.pollIntervalMs)J=X.pollIntervalMs;else{let Q=z.headers.get("openai-poll-after-ms");if(Q){let W=parseInt(Q);if(!isNaN(W))J=W}}await d0(J);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return G}}}stream($,Z,X){return j$.createAssistantStream($,this._client.beta.threads.runs,Z,X)}submitToolOutputs($,Z,X){let{thread_id:Y,...G}=Z;return this._client.post(q`/threads/${Y}/runs/${$}/submit_tool_outputs`,{body:G,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),stream:Z.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll($,Z,X){let Y=await this.submitToolOutputs($,Z,X);return await this.poll(Y.id,Z,X)}submitToolOutputsStream($,Z,X){return j$.createToolAssistantStream($,this._client.beta.threads.runs,Z,X)}}J2.Steps=DZ;class U1 extends L{constructor(){super(...arguments);this.runs=new J2(this._client),this.messages=new PZ(this._client)}create($={},Z){return this._client.post("/threads",{body:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/threads/${$}`,{...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/threads/${$}`,{body:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/threads/${$}`,{...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}createAndRun($,Z){return this._client.post("/threads/runs",{body:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),stream:$.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll($,Z){let X=await this.createAndRun($,Z);return await this.runs.poll(X.id,{thread_id:X.thread_id},Z)}createAndRunStream($,Z){return j$.createThreadAssistantStream($,this._client.beta.threads,Z)}}U1.Runs=J2;U1.Messages=PZ;class i0 extends L{constructor(){super(...arguments);this.realtime=new W1(this._client),this.chatkit=new V1(this._client),this.assistants=new wZ(this._client),this.threads=new U1(this._client)}}i0.Realtime=W1;i0.ChatKit=V1;i0.Assistants=wZ;i0.Threads=U1;class Q2 extends L{create($,Z){return this._client.post("/completions",{body:$,...Z,stream:$.stream??!1,__security:{bearerAuth:!0}})}}class SZ extends L{retrieve($,Z,X){let{container_id:Y}=Z;return this._client.get(q`/containers/${Y}/files/${$}/content`,{...X,headers:E([{Accept:"application/binary"},X?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class W2 extends L{constructor(){super(...arguments);this.content=new SZ(this._client)}create($,Z,X){return this._client.post(q`/containers/${$}/files`,A$({body:Z,...X,__security:{bearerAuth:!0}},this._client))}retrieve($,Z,X){let{container_id:Y}=Z;return this._client.get(q`/containers/${Y}/files/${$}`,{...X,__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/containers/${$}/files`,y,{query:Z,...X,__security:{bearerAuth:!0}})}delete($,Z,X){let{container_id:Y}=Z;return this._client.delete(q`/containers/${Y}/files/${$}`,{...X,headers:E([{Accept:"*/*"},X?.headers]),__security:{bearerAuth:!0}})}}W2.Content=SZ;class q1 extends L{constructor(){super(...arguments);this.files=new W2(this._client)}create($,Z){return this._client.post("/containers",{body:$,...Z,__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/containers/${$}`,{...Z,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/containers",y,{query:$,...Z,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/containers/${$}`,{...Z,headers:E([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}}q1.Files=W2;class CZ extends L{create($,Z,X){let{include:Y,...G}=Z;return this._client.post(q`/conversations/${$}/items`,{query:{include:Y},body:G,...X,__security:{bearerAuth:!0}})}retrieve($,Z,X){let{conversation_id:Y,...G}=Z;return this._client.get(q`/conversations/${Y}/items/${$}`,{query:G,...X,__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/conversations/${$}/items`,d,{query:Z,...X,__security:{bearerAuth:!0}})}delete($,Z,X){let{conversation_id:Y}=Z;return this._client.delete(q`/conversations/${Y}/items/${$}`,{...X,__security:{bearerAuth:!0}})}}class T1 extends L{constructor(){super(...arguments);this.items=new CZ(this._client)}create($={},Z){return this._client.post("/conversations",{body:$,...Z,__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/conversations/${$}`,{...Z,__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/conversations/${$}`,{body:Z,...X,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/conversations/${$}`,{...Z,__security:{bearerAuth:!0}})}}T1.Items=CZ;class V2 extends L{create($,Z){let X=!!$.encoding_format,Y=X?$.encoding_format:"base64";if(X)s(this._client).debug("embeddings/user defined encoding_format:",$.encoding_format);let G=this._client.post("/embeddings",{body:{...$,encoding_format:Y},...Z,__security:{bearerAuth:!0}});if(X)return G;return s(this._client).debug("embeddings/decoding base64 embeddings from base64"),G._thenUnwrap((z)=>{if(z&&z.data)z.data.forEach((J)=>{let Q=J.embedding;J.embedding=Uz(Q)});return z})}}class IZ extends L{retrieve($,Z,X){let{eval_id:Y,run_id:G}=Z;return this._client.get(q`/evals/${Y}/runs/${G}/output_items/${$}`,{...X,__security:{bearerAuth:!0}})}list($,Z,X){let{eval_id:Y,...G}=Z;return this._client.getAPIList(q`/evals/${Y}/runs/${$}/output_items`,y,{query:G,...X,__security:{bearerAuth:!0}})}}class H2 extends L{constructor(){super(...arguments);this.outputItems=new IZ(this._client)}create($,Z,X){return this._client.post(q`/evals/${$}/runs`,{body:Z,...X,__security:{bearerAuth:!0}})}retrieve($,Z,X){let{eval_id:Y}=Z;return this._client.get(q`/evals/${Y}/runs/${$}`,{...X,__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/evals/${$}/runs`,y,{query:Z,...X,__security:{bearerAuth:!0}})}delete($,Z,X){let{eval_id:Y}=Z;return this._client.delete(q`/evals/${Y}/runs/${$}`,{...X,__security:{bearerAuth:!0}})}cancel($,Z,X){let{eval_id:Y}=Z;return this._client.post(q`/evals/${Y}/runs/${$}`,{...X,__security:{bearerAuth:!0}})}}H2.OutputItems=IZ;class F1 extends L{constructor(){super(...arguments);this.runs=new H2(this._client)}create($,Z){return this._client.post("/evals",{body:$,...Z,__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/evals/${$}`,{...Z,__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/evals/${$}`,{body:Z,...X,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/evals",y,{query:$,...Z,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/evals/${$}`,{...Z,__security:{bearerAuth:!0}})}}F1.Runs=H2;class K2 extends L{create($,Z){return this._client.post("/files",q0({body:$,...Z,__security:{bearerAuth:!0}},this._client))}retrieve($,Z){return this._client.get(q`/files/${$}`,{...Z,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/files",y,{query:$,...Z,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/files/${$}`,{...Z,__security:{bearerAuth:!0}})}content($,Z){return this._client.get(q`/files/${$}/content`,{...Z,headers:E([{Accept:"application/binary"},Z?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing($,{pollInterval:Z=5000,maxWait:X=1800000}={}){let Y=new Set(["processed","error","deleted"]),G=Date.now(),z=await this.retrieve($);while(!z.status||!Y.has(z.status))if(await d0(Z),z=await this.retrieve($),Date.now()-G>X)throw new Z1({message:`Giving up on waiting for file ${$} to finish processing after ${X} milliseconds.`});return z}}class jZ extends L{}class xZ extends L{run($,Z){return this._client.post("/fine_tuning/alpha/graders/run",{body:$,...Z,__security:{bearerAuth:!0}})}validate($,Z){return this._client.post("/fine_tuning/alpha/graders/validate",{body:$,...Z,__security:{bearerAuth:!0}})}}class B2 extends L{constructor(){super(...arguments);this.graders=new xZ(this._client)}}B2.Graders=xZ;class kZ extends L{create($,Z,X){return this._client.getAPIList(q`/fine_tuning/checkpoints/${$}/permissions`,L0,{body:Z,method:"post",...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z={},X){return this._client.get(q`/fine_tuning/checkpoints/${$}/permissions`,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/fine_tuning/checkpoints/${$}/permissions`,d,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{fine_tuned_model_checkpoint:Y}=Z;return this._client.delete(q`/fine_tuning/checkpoints/${Y}/permissions/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class U2 extends L{constructor(){super(...arguments);this.permissions=new kZ(this._client)}}U2.Permissions=kZ;class bZ extends L{list($,Z={},X){return this._client.getAPIList(q`/fine_tuning/jobs/${$}/checkpoints`,y,{query:Z,...X,__security:{bearerAuth:!0}})}}class q2 extends L{constructor(){super(...arguments);this.checkpoints=new bZ(this._client)}create($,Z){return this._client.post("/fine_tuning/jobs",{body:$,...Z,__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/fine_tuning/jobs/${$}`,{...Z,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/fine_tuning/jobs",y,{query:$,...Z,__security:{bearerAuth:!0}})}cancel($,Z){return this._client.post(q`/fine_tuning/jobs/${$}/cancel`,{...Z,__security:{bearerAuth:!0}})}listEvents($,Z={},X){return this._client.getAPIList(q`/fine_tuning/jobs/${$}/events`,y,{query:Z,...X,__security:{bearerAuth:!0}})}pause($,Z){return this._client.post(q`/fine_tuning/jobs/${$}/pause`,{...Z,__security:{bearerAuth:!0}})}resume($,Z){return this._client.post(q`/fine_tuning/jobs/${$}/resume`,{...Z,__security:{bearerAuth:!0}})}}q2.Checkpoints=bZ;class a0 extends L{constructor(){super(...arguments);this.methods=new jZ(this._client),this.jobs=new q2(this._client),this.checkpoints=new U2(this._client),this.alpha=new B2(this._client)}}a0.Methods=jZ;a0.Jobs=q2;a0.Checkpoints=U2;a0.Alpha=B2;class fZ extends L{}class L1 extends L{constructor(){super(...arguments);this.graderModels=new fZ(this._client)}}L1.GraderModels=fZ;class T2 extends L{createVariation($,Z){return this._client.post("/images/variations",q0({body:$,...Z,__security:{bearerAuth:!0}},this._client))}edit($,Z){return this._client.post("/images/edits",q0({body:$,...Z,stream:$.stream??!1,__security:{bearerAuth:!0}},this._client))}generate($,Z){return this._client.post("/images/generations",{body:$,...Z,stream:$.stream??!1,__security:{bearerAuth:!0}})}}class F2 extends L{retrieve($,Z){return this._client.get(q`/models/${$}`,{...Z,__security:{bearerAuth:!0}})}list($){return this._client.getAPIList("/models",L0,{...$,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/models/${$}`,{...Z,__security:{bearerAuth:!0}})}}class L2 extends L{create($,Z){return this._client.post("/moderations",{body:$,...Z,__security:{bearerAuth:!0}})}}class yZ extends L{accept($,Z,X){return this._client.post(q`/realtime/calls/${$}/accept`,{body:Z,...X,headers:E([{Accept:"*/*"},X?.headers]),__security:{bearerAuth:!0}})}hangup($,Z){return this._client.post(q`/realtime/calls/${$}/hangup`,{...Z,headers:E([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}refer($,Z,X){return this._client.post(q`/realtime/calls/${$}/refer`,{body:Z,...X,headers:E([{Accept:"*/*"},X?.headers]),__security:{bearerAuth:!0}})}reject($,Z={},X){return this._client.post(q`/realtime/calls/${$}/reject`,{body:Z,...X,headers:E([{Accept:"*/*"},X?.headers]),__security:{bearerAuth:!0}})}}class vZ extends L{create($,Z){return this._client.post("/realtime/client_secrets",{body:$,...Z,__security:{bearerAuth:!0}})}}class x$ extends L{constructor(){super(...arguments);this.clientSecrets=new vZ(this._client),this.calls=new yZ(this._client)}}x$.ClientSecrets=vZ;x$.Calls=yZ;function Nz($,Z){if(!Z||!FM(Z))return{...$,output_parsed:null,output:$.output.map((X)=>{if(X.type==="function_call")return{...X,parsed_arguments:null};if(X.type==="message")return{...X,content:X.content.map((Y)=>({...Y,parsed:null}))};else return X})};return u5($,Z)}function u5($,Z){let X=$.output.map((G)=>{if(G.type==="function_call")return{...G,parsed_arguments:MM(Z,G)};if(G.type==="message"){let z=G.content.map((J)=>{if(J.type==="output_text")return{...J,parsed:TM(Z,J.text)};return J});return{...G,content:z}}return G}),Y=Object.assign({},$,{output:X});if(!Object.getOwnPropertyDescriptor($,"output_text"))r8(Y);return Object.defineProperty(Y,"output_parsed",{enumerable:!0,get(){for(let G of Y.output){if(G.type!=="message")continue;for(let z of G.content)if(z.type==="output_text"&&z.parsed!==null)return z.parsed}return null}}),Y}function TM($,Z){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(Z);return JSON.parse(Z)}function FM($){if(h4($.text?.format))return!0;return!1}function LM($){return $?.$brand==="auto-parseable-tool"}function wM($,Z){return $.find((X)=>X.type==="function"&&X.name===Z)}function MM($,Z){let X=wM($.tools??[],Z.name);return{...Z,...Z,parsed_arguments:LM(X)?X.$parseRaw(Z.arguments):X?.strict?JSON.parse(Z.arguments):null}}function r8($){let Z=[];for(let X of $.output){if(X.type!=="message")continue;for(let Y of X.content)if(Y.type==="output_text")Z.push(Y.text)}$.output_text=Z.join("")}var w2,s8,k$,o8,_z,Pz,Dz,Ez;class t8 extends G1{constructor($){super();w2.add(this),s8.set(this,void 0),k$.set(this,void 0),o8.set(this,void 0),x(this,s8,$,"f")}static createResponse($,Z,X){let Y=new t8(Z);return Y._run(()=>Y._createOrRetrieveResponse($,Z,{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}async _createOrRetrieveResponse($,Z,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}M(this,w2,"m",_z).call(this);let G,z=null;if("response_id"in Z)G=await $.responses.retrieve(Z.response_id,{stream:!0},{...X,signal:this.controller.signal,stream:!0}),z=Z.starting_after??null;else G=await $.responses.create({...Z,stream:!0},{...X,signal:this.controller.signal});this._connected();for await(let J of G)M(this,w2,"m",Pz).call(this,J,z);if(G.controller.signal?.aborted)throw new $0;return M(this,w2,"m",Dz).call(this)}[(s8=new WeakMap,k$=new WeakMap,o8=new WeakMap,w2=new WeakSet,_z=function(){if(this.ended)return;x(this,k$,void 0,"f")},Pz=function(Z,X){if(this.ended)return;let Y=(z,J)=>{if(X==null||J.sequence_number>X)this._emit(z,J)},G=M(this,w2,"m",Ez).call(this,Z);switch(Y("event",Z),Z.type){case"response.output_text.delta":{let z=G.output[Z.output_index];if(!z)throw new I(`missing output at index ${Z.output_index}`);if(z.type==="message"){let J=z.content[Z.content_index];if(!J)throw new I(`missing content at index ${Z.content_index}`);if(J.type!=="output_text")throw new I(`expected content to be 'output_text', got ${J.type}`);Y("response.output_text.delta",{...Z,snapshot:J.text})}break}case"response.function_call_arguments.delta":{let z=G.output[Z.output_index];if(!z)throw new I(`missing output at index ${Z.output_index}`);if(z.type==="function_call")Y("response.function_call_arguments.delta",{...Z,snapshot:z.arguments});break}default:Y(Z.type,Z);break}},Dz=function(){if(this.ended)throw new I("stream has ended, this shouldn't happen");let Z=M(this,k$,"f");if(!Z)throw new I("request ended without sending any events");x(this,k$,void 0,"f");let X=OM(Z,M(this,s8,"f"));return x(this,o8,X,"f"),X},Ez=function(Z){let X=M(this,k$,"f");if(!X){if(Z.type!=="response.created")throw new I(`When snapshot hasn't been set yet, expected 'response.created' event, got ${Z.type}`);return X=x(this,k$,Z.response,"f"),X}switch(Z.type){case"response.output_item.added":{X.output.push(Z.item);break}case"response.content_part.added":{let Y=X.output[Z.output_index];if(!Y)throw new I(`missing output at index ${Z.output_index}`);let G=Y.type,z=Z.part;if(G==="message"&&z.type!=="reasoning_text")Y.content.push(z);else if(G==="reasoning"&&z.type==="reasoning_text"){if(!Y.content)Y.content=[];Y.content.push(z)}break}case"response.output_text.delta":{let Y=X.output[Z.output_index];if(!Y)throw new I(`missing output at index ${Z.output_index}`);if(Y.type==="message"){let G=Y.content[Z.content_index];if(!G)throw new I(`missing content at index ${Z.content_index}`);if(G.type!=="output_text")throw new I(`expected content to be 'output_text', got ${G.type}`);G.text+=Z.delta}break}case"response.function_call_arguments.delta":{let Y=X.output[Z.output_index];if(!Y)throw new I(`missing output at index ${Z.output_index}`);if(Y.type==="function_call")Y.arguments+=Z.delta;break}case"response.reasoning_text.delta":{let Y=X.output[Z.output_index];if(!Y)throw new I(`missing output at index ${Z.output_index}`);if(Y.type==="reasoning"){let G=Y.content?.[Z.content_index];if(!G)throw new I(`missing content at index ${Z.content_index}`);if(G.type!=="reasoning_text")throw new I(`expected content to be 'reasoning_text', got ${G.type}`);G.text+=Z.delta}break}case"response.completed":{x(this,k$,Z.response,"f");break}}return X},Symbol.asyncIterator)](){let $=[],Z=[],X=!1;return this.on("event",(Y)=>{let G=Z.shift();if(G)G.resolve(Y);else $.push(Y)}),this.on("end",()=>{X=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),this.on("error",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(X)return{value:void 0,done:!0};return new Promise((G,z)=>Z.push({resolve:G,reject:z})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let $=M(this,o8,"f");if(!$)throw new I("stream ended without producing a ChatCompletion");return $}}function OM($,Z){return Nz($,Z)}class gZ extends L{list($,Z={},X){return this._client.getAPIList(q`/responses/${$}/input_items`,y,{query:Z,...X,__security:{bearerAuth:!0}})}}class hZ extends L{count($={},Z){return this._client.post("/responses/input_tokens",{body:$,...Z,__security:{bearerAuth:!0}})}}class b$ extends L{constructor(){super(...arguments);this.inputItems=new gZ(this._client),this.inputTokens=new hZ(this._client)}create($,Z){return this._client.post("/responses",{body:$,...Z,stream:$.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap((X)=>{if("object"in X&&X.object==="response")r8(X);return X})}retrieve($,Z={},X){return this._client.get(q`/responses/${$}`,{query:Z,...X,stream:Z?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap((Y)=>{if("object"in Y&&Y.object==="response")r8(Y);return Y})}delete($,Z){return this._client.delete(q`/responses/${$}`,{...Z,headers:E([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}parse($,Z){return this._client.responses.create($,Z)._thenUnwrap((X)=>u5(X,$))}stream($,Z){return t8.createResponse(this._client,$,Z)}cancel($,Z){return this._client.post(q`/responses/${$}/cancel`,{...Z,__security:{bearerAuth:!0}})}compact($,Z){return this._client.post("/responses/compact",{body:$,...Z,__security:{bearerAuth:!0}})}}b$.InputItems=gZ;b$.InputTokens=hZ;class uZ extends L{retrieve($,Z){return this._client.get(q`/skills/${$}/content`,{...Z,headers:E([{Accept:"application/binary"},Z?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class mZ extends L{retrieve($,Z,X){let{skill_id:Y}=Z;return this._client.get(q`/skills/${Y}/versions/${$}/content`,{...X,headers:E([{Accept:"application/binary"},X?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class M2 extends L{constructor(){super(...arguments);this.content=new mZ(this._client)}create($,Z={},X){return this._client.post(q`/skills/${$}/versions`,A$({body:Z,...X,__security:{bearerAuth:!0}},this._client))}retrieve($,Z,X){let{skill_id:Y}=Z;return this._client.get(q`/skills/${Y}/versions/${$}`,{...X,__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/skills/${$}/versions`,y,{query:Z,...X,__security:{bearerAuth:!0}})}delete($,Z,X){let{skill_id:Y}=Z;return this._client.delete(q`/skills/${Y}/versions/${$}`,{...X,__security:{bearerAuth:!0}})}}M2.Content=mZ;class f$ extends L{constructor(){super(...arguments);this.content=new uZ(this._client),this.versions=new M2(this._client)}create($={},Z){return this._client.post("/skills",A$({body:$,...Z,__security:{bearerAuth:!0}},this._client))}retrieve($,Z){return this._client.get(q`/skills/${$}`,{...Z,__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/skills/${$}`,{body:Z,...X,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/skills",y,{query:$,...Z,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/skills/${$}`,{...Z,__security:{bearerAuth:!0}})}}f$.Content=uZ;f$.Versions=M2;class dZ extends L{create($,Z,X){return this._client.post(q`/uploads/${$}/parts`,q0({body:Z,...X,__security:{bearerAuth:!0}},this._client))}}class w1 extends L{constructor(){super(...arguments);this.parts=new dZ(this._client)}create($,Z){return this._client.post("/uploads",{body:$,...Z,__security:{bearerAuth:!0}})}cancel($,Z){return this._client.post(q`/uploads/${$}/cancel`,{...Z,__security:{bearerAuth:!0}})}complete($,Z,X){return this._client.post(q`/uploads/${$}/complete`,{body:Z,...X,__security:{bearerAuth:!0}})}}w1.Parts=dZ;var Rz=async($)=>{let Z=await Promise.allSettled($),X=Z.filter((G)=>G.status==="rejected");if(X.length){for(let G of X)console.error(G.reason);throw Error(`${X.length} promise(s) failed - see the above errors`)}let Y=[];for(let G of Z)if(G.status==="fulfilled")Y.push(G.value);return Y};class cZ extends L{create($,Z,X){return this._client.post(q`/vector_stores/${$}/file_batches`,{body:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}retrieve($,Z,X){let{vector_store_id:Y}=Z;return this._client.get(q`/vector_stores/${Y}/file_batches/${$}`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}cancel($,Z,X){let{vector_store_id:Y}=Z;return this._client.post(q`/vector_stores/${Y}/file_batches/${$}/cancel`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}async createAndPoll($,Z,X){let Y=await this.create($,Z);return await this.poll($,Y.id,X)}listFiles($,Z,X){let{vector_store_id:Y,...G}=Z;return this._client.getAPIList(q`/vector_stores/${Y}/file_batches/${$}/files`,y,{query:G,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}async poll($,Z,X){let Y=E([X?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":X?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:G,response:z}=await this.retrieve(Z,{vector_store_id:$},{...X,headers:Y}).withResponse();switch(G.status){case"in_progress":let J=5000;if(X?.pollIntervalMs)J=X.pollIntervalMs;else{let Q=z.headers.get("openai-poll-after-ms");if(Q){let W=parseInt(Q);if(!isNaN(W))J=W}}await d0(J);break;case"failed":case"cancelled":case"completed":return G}}}async uploadAndPoll($,{files:Z,fileIds:X=[]},Y){if(Z==null||Z.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let G=Y?.maxConcurrency??5,z=Math.min(G,Z.length),J=this._client,Q=Z.values(),W=[...X];async function V(H){for(let B of H){let U=await J.files.create({file:B,purpose:"assistants"},Y);W.push(U.id)}}let K=Array(z).fill(Q).map(V);return await Rz(K),await this.createAndPoll($,{file_ids:W})}}class lZ extends L{create($,Z,X){return this._client.post(q`/vector_stores/${$}/files`,{body:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}retrieve($,Z,X){let{vector_store_id:Y}=Z;return this._client.get(q`/vector_stores/${Y}/files/${$}`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}update($,Z,X){let{vector_store_id:Y,...G}=Z;return this._client.post(q`/vector_stores/${Y}/files/${$}`,{body:G,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/vector_stores/${$}/files`,y,{query:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}delete($,Z,X){let{vector_store_id:Y}=Z;return this._client.delete(q`/vector_stores/${Y}/files/${$}`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}async createAndPoll($,Z,X){let Y=await this.create($,Z,X);return await this.poll($,Y.id,X)}async poll($,Z,X){let Y=E([X?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":X?.pollIntervalMs?.toString()??void 0}]);while(!0){let G=await this.retrieve(Z,{vector_store_id:$},{...X,headers:Y}).withResponse(),z=G.data;switch(z.status){case"in_progress":let J=5000;if(X?.pollIntervalMs)J=X.pollIntervalMs;else{let Q=G.response.headers.get("openai-poll-after-ms");if(Q){let W=parseInt(Q);if(!isNaN(W))J=W}}await d0(J);break;case"failed":case"completed":return z}}}async upload($,Z,X){let Y=await this._client.files.create({file:Z,purpose:"assistants"},X);return this.create($,{file_id:Y.id},X)}async uploadAndPoll($,Z,X){let Y=await this.upload($,Z,X);return await this.poll($,Y.id,X)}content($,Z,X){let{vector_store_id:Y}=Z;return this._client.getAPIList(q`/vector_stores/${Y}/files/${$}/content`,L0,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}}class y$ extends L{constructor(){super(...arguments);this.files=new lZ(this._client),this.fileBatches=new cZ(this._client)}create($,Z){return this._client.post("/vector_stores",{body:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/vector_stores/${$}`,{...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/vector_stores/${$}`,{body:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/vector_stores",y,{query:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/vector_stores/${$}`,{...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}search($,Z,X){return this._client.getAPIList(q`/vector_stores/${$}/search`,L0,{body:Z,method:"post",...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}}y$.Files=lZ;y$.FileBatches=cZ;class O2 extends L{create($,Z){return this._client.post("/videos",q0({body:$,...Z,__security:{bearerAuth:!0}},this._client))}retrieve($,Z){return this._client.get(q`/videos/${$}`,{...Z,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/videos",d,{query:$,...Z,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/videos/${$}`,{...Z,__security:{bearerAuth:!0}})}createCharacter($,Z){return this._client.post("/videos/characters",q0({body:$,...Z,__security:{bearerAuth:!0}},this._client))}downloadContent($,Z={},X){return this._client.get(q`/videos/${$}/content`,{query:Z,...X,headers:E([{Accept:"application/binary"},X?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit($,Z){return this._client.post("/videos/edits",q0({body:$,...Z,__security:{bearerAuth:!0}},this._client))}extend($,Z){return this._client.post("/videos/extensions",q0({body:$,...Z,__security:{bearerAuth:!0}},this._client))}getCharacter($,Z){return this._client.get(q`/videos/characters/${$}`,{...Z,__security:{bearerAuth:!0}})}remix($,Z,X){return this._client.post(q`/videos/${$}/remix`,A$({body:Z,...X,__security:{bearerAuth:!0}},this._client))}}var N2,Az,e8;class _2 extends L{constructor(){super(...arguments);N2.add(this)}async unwrap($,Z,X=this._client.webhookSecret,Y=300){return await this.verifySignature($,Z,X,Y),JSON.parse($)}async verifySignature($,Z,X=this._client.webhookSecret,Y=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");M(this,N2,"m",Az).call(this,X);let G=E([Z]).values,z=M(this,N2,"m",e8).call(this,G,"webhook-signature"),J=M(this,N2,"m",e8).call(this,G,"webhook-timestamp"),Q=M(this,N2,"m",e8).call(this,G,"webhook-id"),W=parseInt(J,10);if(isNaN(W))throw new G$("Invalid webhook timestamp format");let V=Math.floor(Date.now()/1000);if(V-W>Y)throw new G$("Webhook timestamp is too old");if(W>V+Y)throw new G$("Webhook timestamp is too new");let K=z.split(" ").map((F)=>F.startsWith("v1,")?F.substring(3):F),H=X.startsWith("whsec_")?Buffer.from(X.replace("whsec_",""),"base64"):Buffer.from(X,"utf-8"),B=Q?`${Q}.${J}.${$}`:`${J}.${$}`,U=await crypto.subtle.importKey("raw",H,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let F of K)try{let T=Buffer.from(F,"base64");if(await crypto.subtle.verify("HMAC",U,T,new TextEncoder().encode(B)))return}catch{continue}throw new G$("The given webhook signature does not match the expected signature")}}N2=new WeakSet,Az=function(Z){if(typeof Z!=="string"||Z.length===0)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},e8=function(Z,X){if(!Z)throw Error("Headers are required");let Y=Z.get(X);if(Y===null||Y===void 0)throw Error(`Missing required header: ${X}`);return Y};var m5,d5,$X,Sz,IM="workload-identity-auth";class f{constructor({baseURL:$=l0("OPENAI_BASE_URL"),apiKey:Z=l0("OPENAI_API_KEY")??null,adminAPIKey:X=l0("OPENAI_ADMIN_KEY")??null,organization:Y=l0("OPENAI_ORG_ID")??null,project:G=l0("OPENAI_PROJECT_ID")??null,webhookSecret:z=l0("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:J,...Q}={}){m5.add(this),$X.set(this,void 0),this.completions=new Q2(this),this.chat=new z1(this),this.embeddings=new V2(this),this.files=new K2(this),this.images=new T2(this),this.audio=new W$(this),this.moderations=new L2(this),this.models=new F2(this),this.fineTuning=new a0(this),this.graders=new L1(this),this.vectorStores=new y$(this),this.webhooks=new _2(this),this.beta=new i0(this),this.batches=new G2(this),this.uploads=new w1(this),this.admin=new Q1(this),this.responses=new b$(this),this.realtime=new x$(this),this.conversations=new T1(this),this.evals=new F1(this),this.containers=new q1(this),this.skills=new f$(this),this.videos=new O2(this);let W={apiKey:Z,adminAPIKey:X,organization:Y,project:G,webhookSecret:z,workloadIdentity:J,...Q,baseURL:$||"https://api.openai.com/v1"};if(Z&&J)throw new I("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!Z&&!X&&!J)throw new I("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!W.dangerouslyAllowBrowser&&SG())throw new I(`It looks like you're running in a browser-like environment.
|
|
255
|
+
${l8($)}`);return{...D,id:S,type:A,function:{...i,name:b,arguments:k}}})}};return{...B,message:{...O,content:T,role:N,refusal:V.refusal??null},finish_reason:K,index:H,logprobs:U}}),created:G,model:z,object:"chat.completion",...J?{system_fingerprint:J}:{}};return Zz(W,Z)}function l8($){return JSON.stringify($)}function Uz($){return}function Bz($){}class o1 extends S${static fromReadableStream($){let Z=new o1(null);return Z._run(()=>Z._fromReadableStream($)),Z}static runTools($,Z,X){let Y=new o1(Z),G={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runTools"}};return Y._run(()=>Y._runTools($,Z,G)),Y}}class C$ extends L{constructor(){super(...arguments);this.messages=new a1(this._client)}create($,Z){return this._client.post("/chat/completions",{body:$,...Z,stream:$.stream??!1,__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/chat/completions/${$}`,{...Z,__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/chat/completions/${$}`,{body:Z,...X,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/chat/completions",y,{query:$,...Z,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/chat/completions/${$}`,{...Z,__security:{bearerAuth:!0}})}parse($,Z){return Gz($.tools),this._client.chat.completions.create($,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((X)=>h4(X,$))}runTools($,Z){if($.stream)return o1.runTools(this._client,$,Z);return p4.runTools(this._client,$,Z)}stream($,Z){return S$.createChatCompletion(this._client,$,Z)}}C$.Messages=a1;class Z1 extends L{constructor(){super(...arguments);this.completions=new C$(this._client)}}Z1.Completions=C$;class i4 extends L{create($,Z){return this._client.post("/organization/admin_api_keys",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z){return this._client.get(q`/organization/admin_api_keys/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/admin_api_keys",y,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/admin_api_keys/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class a4 extends L{list($={},Z){return this._client.getAPIList("/organization/audit_logs",d,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}}class n4 extends L{create($,Z){return this._client.post("/organization/certificates",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z={},X){return this._client.get(q`/organization/certificates/${$}`,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/certificates/${$}`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/certificates",d,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/certificates/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}activate($,Z){return this._client.getAPIList("/organization/certificates/activate",F0,{body:$,method:"post",...Z,__security:{adminAPIKeyAuth:!0}})}deactivate($,Z){return this._client.getAPIList("/organization/certificates/deactivate",F0,{body:$,method:"post",...Z,__security:{adminAPIKeyAuth:!0}})}}class r4 extends L{retrieve($){return this._client.get("/organization/data_retention",{...$,__security:{adminAPIKeyAuth:!0}})}update($,Z){return this._client.post("/organization/data_retention",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}}class s4 extends L{create($,Z){return this._client.post("/organization/invites",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z){return this._client.get(q`/organization/invites/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/invites",d,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/invites/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class o4 extends L{create($,Z){return this._client.post("/organization/roles",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z){return this._client.get(q`/organization/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/roles/${$}`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/roles",Y0,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class t4 extends L{create($,Z){return this._client.post("/organization/spend_alerts",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/spend_alerts/${$}`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/spend_alerts",d,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/spend_alerts/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class e4 extends L{audioSpeeches($,Z){return this._client.get("/organization/usage/audio_speeches",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions($,Z){return this._client.get("/organization/usage/audio_transcriptions",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions($,Z){return this._client.get("/organization/usage/code_interpreter_sessions",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}completions($,Z){return this._client.get("/organization/usage/completions",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}costs($,Z){return this._client.get("/organization/costs",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}embeddings($,Z){return this._client.get("/organization/usage/embeddings",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls($,Z){return this._client.get("/organization/usage/file_search_calls",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}images($,Z){return this._client.get("/organization/usage/images",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}moderations($,Z){return this._client.get("/organization/usage/moderations",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}vectorStores($,Z){return this._client.get("/organization/usage/vector_stores",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}webSearchCalls($,Z){return this._client.get("/organization/usage/web_search_calls",{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}}class $6 extends L{create($,Z,X){return this._client.post(q`/organization/groups/${$}/roles`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{group_id:Y}=Z;return this._client.get(q`/organization/groups/${Y}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/groups/${$}/roles`,Y0,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{group_id:Y}=Z;return this._client.delete(q`/organization/groups/${Y}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class Z6 extends L{create($,Z,X){return this._client.post(q`/organization/groups/${$}/users`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{group_id:Y}=Z;return this._client.get(q`/organization/groups/${Y}/users/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/groups/${$}/users`,Y0,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{group_id:Y}=Z;return this._client.delete(q`/organization/groups/${Y}/users/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class X1 extends L{constructor(){super(...arguments);this.users=new Z6(this._client),this.roles=new $6(this._client)}create($,Z){return this._client.post("/organization/groups",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z){return this._client.get(q`/organization/groups/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/groups/${$}`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/groups",Y0,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/groups/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}X1.Users=Z6;X1.Roles=$6;class X6 extends L{retrieve($,Z,X){let{project_id:Y}=Z;return this._client.get(q`/organization/projects/${Y}/api_keys/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/projects/${$}/api_keys`,d,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y}=Z;return this._client.delete(q`/organization/projects/${Y}/api_keys/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class Y6 extends L{list($,Z={},X){return this._client.getAPIList(q`/organization/projects/${$}/certificates`,d,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}activate($,Z,X){return this._client.getAPIList(q`/organization/projects/${$}/certificates/activate`,F0,{body:Z,method:"post",...X,__security:{adminAPIKeyAuth:!0}})}deactivate($,Z,X){return this._client.getAPIList(q`/organization/projects/${$}/certificates/deactivate`,F0,{body:Z,method:"post",...X,__security:{adminAPIKeyAuth:!0}})}}class G6 extends L{retrieve($,Z){return this._client.get(q`/organization/projects/${$}/data_retention`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/projects/${$}/data_retention`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}}class z6 extends L{retrieve($,Z){return this._client.get(q`/organization/projects/${$}/hosted_tool_permissions`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/projects/${$}/hosted_tool_permissions`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}}class J6 extends L{retrieve($,Z){return this._client.get(q`/organization/projects/${$}/model_permissions`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/projects/${$}/model_permissions`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/projects/${$}/model_permissions`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class Q6 extends L{listRateLimits($,Z={},X){return this._client.getAPIList(q`/organization/projects/${$}/rate_limits`,d,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}updateRateLimit($,Z,X){let{project_id:Y,...G}=Z;return this._client.post(q`/organization/projects/${Y}/rate_limits/${$}`,{body:G,...X,__security:{adminAPIKeyAuth:!0}})}}class W6 extends L{create($,Z,X){return this._client.post(q`/projects/${$}/roles`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{project_id:Y}=Z;return this._client.get(q`/projects/${Y}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){let{project_id:Y,...G}=Z;return this._client.post(q`/projects/${Y}/roles/${$}`,{body:G,...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/projects/${$}/roles`,Y0,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y}=Z;return this._client.delete(q`/projects/${Y}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class V6 extends L{create($,Z,X){return this._client.post(q`/organization/projects/${$}/service_accounts`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{project_id:Y}=Z;return this._client.get(q`/organization/projects/${Y}/service_accounts/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){let{project_id:Y,...G}=Z;return this._client.post(q`/organization/projects/${Y}/service_accounts/${$}`,{body:G,...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/projects/${$}/service_accounts`,d,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y}=Z;return this._client.delete(q`/organization/projects/${Y}/service_accounts/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class H6 extends L{create($,Z,X){return this._client.post(q`/organization/projects/${$}/spend_alerts`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){let{project_id:Y,...G}=Z;return this._client.post(q`/organization/projects/${Y}/spend_alerts/${$}`,{body:G,...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/projects/${$}/spend_alerts`,d,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y}=Z;return this._client.delete(q`/organization/projects/${Y}/spend_alerts/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class K6 extends L{create($,Z,X){let{project_id:Y,...G}=Z;return this._client.post(q`/projects/${Y}/groups/${$}/roles`,{body:G,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{project_id:Y,group_id:G}=Z;return this._client.get(q`/projects/${Y}/groups/${G}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}list($,Z,X){let{project_id:Y,...G}=Z;return this._client.getAPIList(q`/projects/${Y}/groups/${$}/roles`,Y0,{query:G,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y,group_id:G}=Z;return this._client.delete(q`/projects/${Y}/groups/${G}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class t1 extends L{constructor(){super(...arguments);this.roles=new K6(this._client)}create($,Z,X){return this._client.post(q`/organization/projects/${$}/groups`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{project_id:Y,...G}=Z;return this._client.get(q`/organization/projects/${Y}/groups/${$}`,{query:G,...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/projects/${$}/groups`,Y0,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y}=Z;return this._client.delete(q`/organization/projects/${Y}/groups/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}t1.Roles=K6;class U6 extends L{create($,Z,X){let{project_id:Y,...G}=Z;return this._client.post(q`/projects/${Y}/users/${$}/roles`,{body:G,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{project_id:Y,user_id:G}=Z;return this._client.get(q`/projects/${Y}/users/${G}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}list($,Z,X){let{project_id:Y,...G}=Z;return this._client.getAPIList(q`/projects/${Y}/users/${$}/roles`,Y0,{query:G,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y,user_id:G}=Z;return this._client.delete(q`/projects/${Y}/users/${G}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class e1 extends L{constructor(){super(...arguments);this.roles=new U6(this._client)}create($,Z,X){return this._client.post(q`/organization/projects/${$}/users`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{project_id:Y}=Z;return this._client.get(q`/organization/projects/${Y}/users/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){let{project_id:Y,...G}=Z;return this._client.post(q`/organization/projects/${Y}/users/${$}`,{body:G,...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/projects/${$}/users`,d,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{project_id:Y}=Z;return this._client.delete(q`/organization/projects/${Y}/users/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}e1.Roles=U6;class q0 extends L{constructor(){super(...arguments);this.users=new e1(this._client),this.serviceAccounts=new V6(this._client),this.apiKeys=new X6(this._client),this.rateLimits=new Q6(this._client),this.modelPermissions=new J6(this._client),this.hostedToolPermissions=new z6(this._client),this.groups=new t1(this._client),this.roles=new W6(this._client),this.dataRetention=new G6(this._client),this.spendAlerts=new H6(this._client),this.certificates=new Y6(this._client)}create($,Z){return this._client.post("/organization/projects",{body:$,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z){return this._client.get(q`/organization/projects/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/projects/${$}`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/projects",d,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}archive($,Z){return this._client.post(q`/organization/projects/${$}/archive`,{...Z,__security:{adminAPIKeyAuth:!0}})}}q0.Users=e1;q0.ServiceAccounts=V6;q0.APIKeys=X6;q0.RateLimits=Q6;q0.ModelPermissions=J6;q0.HostedToolPermissions=z6;q0.Groups=t1;q0.Roles=W6;q0.DataRetention=G6;q0.SpendAlerts=H6;q0.Certificates=Y6;class B6 extends L{create($,Z,X){return this._client.post(q`/organization/users/${$}/roles`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z,X){let{user_id:Y}=Z;return this._client.get(q`/organization/users/${Y}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/organization/users/${$}/roles`,Y0,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{user_id:Y}=Z;return this._client.delete(q`/organization/users/${Y}/roles/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class $2 extends L{constructor(){super(...arguments);this.roles=new B6(this._client)}retrieve($,Z){return this._client.get(q`/organization/users/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Z,X){return this._client.post(q`/organization/users/${$}`,{body:Z,...X,__security:{adminAPIKeyAuth:!0}})}list($={},Z){return this._client.getAPIList("/organization/users",d,{query:$,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Z){return this._client.delete(q`/organization/users/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}$2.Roles=B6;class T0 extends L{constructor(){super(...arguments);this.auditLogs=new a4(this._client),this.adminAPIKeys=new i4(this._client),this.usage=new e4(this._client),this.invites=new s4(this._client),this.users=new $2(this._client),this.groups=new X1(this._client),this.roles=new o4(this._client),this.dataRetention=new r4(this._client),this.spendAlerts=new t4(this._client),this.certificates=new n4(this._client),this.projects=new q0(this._client)}}T0.AuditLogs=a4;T0.AdminAPIKeys=i4;T0.Usage=e4;T0.Invites=s4;T0.Users=$2;T0.Groups=X1;T0.Roles=o4;T0.DataRetention=r4;T0.SpendAlerts=t4;T0.Certificates=n4;T0.Projects=q0;class Y1 extends L{constructor(){super(...arguments);this.organization=new T0(this._client)}}Y1.Organization=T0;var qz=Symbol("brand.privateNullableHeaders");function*mM($){if(!$)return;if(qz in $){let{values:Y,nulls:G}=$;yield*Y.entries();for(let z of G)yield[z,null];return}let Z=!1,X;if($ instanceof Headers)X=$.entries();else if(Q5($))X=$;else Z=!0,X=Object.entries($??{});for(let Y of X){let G=Y[0];if(typeof G!=="string")throw TypeError("expected header name to be a string");let z=Q5(Y[1])?Y[1]:[Y[1]],J=!1;for(let Q of z){if(Q===void 0)continue;if(Z&&!J)J=!0,yield[G,null];yield[G,Q]}}}var E=($)=>{let Z=new Headers,X=new Set;for(let Y of $){let G=new Set;for(let[z,J]of mM(Y)){let Q=z.toLowerCase();if(!G.has(Q))Z.delete(z),G.add(Q);if(J===null)Z.delete(z),X.add(Q);else Z.append(z,J),X.delete(Q)}}return{[qz]:!0,values:Z,nulls:X}};class q6 extends L{create($,Z){return this._client.post("/audio/speech",{body:$,...Z,headers:E([{Accept:"application/octet-stream"},Z?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class T6 extends L{create($,Z){return this._client.post("/audio/transcriptions",B0({body:$,...Z,stream:$.stream??!1,__metadata:{model:$.model},__security:{bearerAuth:!0}},this._client))}}class F6 extends L{create($,Z){return this._client.post("/audio/translations",B0({body:$,...Z,__metadata:{model:$.model},__security:{bearerAuth:!0}},this._client))}}class Q$ extends L{constructor(){super(...arguments);this.transcriptions=new T6(this._client),this.translations=new F6(this._client),this.speech=new q6(this._client)}}Q$.Transcriptions=T6;Q$.Translations=F6;Q$.Speech=q6;class Z2 extends L{create($,Z){return this._client.post("/batches",{body:$,...Z,__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/batches/${$}`,{...Z,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/batches",y,{query:$,...Z,__security:{bearerAuth:!0}})}cancel($,Z){return this._client.post(q`/batches/${$}/cancel`,{...Z,__security:{bearerAuth:!0}})}}class L6 extends L{create($,Z){return this._client.post("/assistants",{body:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/assistants/${$}`,{...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/assistants/${$}`,{body:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/assistants",y,{query:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/assistants/${$}`,{...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}class M6 extends L{create($,Z){return this._client.post("/realtime/sessions",{body:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}class w6 extends L{create($,Z){return this._client.post("/realtime/transcription_sessions",{body:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}class G1 extends L{constructor(){super(...arguments);this.sessions=new M6(this._client),this.transcriptionSessions=new w6(this._client)}}G1.Sessions=M6;G1.TranscriptionSessions=w6;class O6 extends L{create($,Z){return this._client.post("/chatkit/sessions",{body:$,...Z,headers:E([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers]),__security:{bearerAuth:!0}})}cancel($,Z){return this._client.post(q`/chatkit/sessions/${$}/cancel`,{...Z,headers:E([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers]),__security:{bearerAuth:!0}})}}class N6 extends L{retrieve($,Z){return this._client.get(q`/chatkit/threads/${$}`,{...Z,headers:E([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers]),__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/chatkit/threads",d,{query:$,...Z,headers:E([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers]),__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/chatkit/threads/${$}`,{...Z,headers:E([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers]),__security:{bearerAuth:!0}})}listItems($,Z={},X){return this._client.getAPIList(q`/chatkit/threads/${$}/items`,d,{query:Z,...X,headers:E([{"OpenAI-Beta":"chatkit_beta=v1"},X?.headers]),__security:{bearerAuth:!0}})}}class z1 extends L{constructor(){super(...arguments);this.sessions=new O6(this._client),this.threads=new N6(this._client)}}z1.Sessions=O6;z1.Threads=N6;class _6 extends L{create($,Z,X){return this._client.post(q`/threads/${$}/messages`,{body:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}retrieve($,Z,X){let{thread_id:Y}=Z;return this._client.get(q`/threads/${Y}/messages/${$}`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}update($,Z,X){let{thread_id:Y,...G}=Z;return this._client.post(q`/threads/${Y}/messages/${$}`,{body:G,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/threads/${$}/messages`,y,{query:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}delete($,Z,X){let{thread_id:Y}=Z;return this._client.delete(q`/threads/${Y}/messages/${$}`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}}class P6 extends L{retrieve($,Z,X){let{thread_id:Y,run_id:G,...z}=Z;return this._client.get(q`/threads/${Y}/runs/${G}/steps/${$}`,{query:z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($,Z,X){let{thread_id:Y,...G}=Z;return this._client.getAPIList(q`/threads/${Y}/runs/${$}/steps`,y,{query:G,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}}var Tz=($)=>{if(typeof Buffer<"u"){let Z=Buffer.from($,"base64");return Array.from(new Float32Array(Z.buffer,Z.byteOffset,Z.length/Float32Array.BYTES_PER_ELEMENT))}else{let Z=atob($),X=Z.length,Y=new Uint8Array(X);for(let G=0;G<X;G++)Y[G]=Z.charCodeAt(G);return Array.from(new Float32Array(Y.buffer))}};var d0=($)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[$]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.($)?.trim()||void 0;return};var Q0,Q1,h5,c0,p8,f0,W1,X2,J1,n8,R0,i8,a8,R6,D6,E6,Fz,Lz,Mz,wz,Oz,Nz,_z;class I$ extends $1{constructor(){super(...arguments);Q0.add(this),h5.set(this,[]),c0.set(this,{}),p8.set(this,{}),f0.set(this,void 0),W1.set(this,void 0),X2.set(this,void 0),J1.set(this,void 0),n8.set(this,void 0),R0.set(this,void 0),i8.set(this,void 0),a8.set(this,void 0),R6.set(this,void 0)}[(h5=new WeakMap,c0=new WeakMap,p8=new WeakMap,f0=new WeakMap,W1=new WeakMap,X2=new WeakMap,J1=new WeakMap,n8=new WeakMap,R0=new WeakMap,i8=new WeakMap,a8=new WeakMap,R6=new WeakMap,Q0=new WeakSet,Symbol.asyncIterator)](){let $=[],Z=[],X=!1;return this.on("event",(Y)=>{let G=Z.shift();if(G)G.resolve(Y);else $.push(Y)}),this.on("end",()=>{X=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),this.on("error",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(X)return{value:void 0,done:!0};return new Promise((G,z)=>Z.push({resolve:G,reject:z})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream($){let Z=new Q1;return Z._run(()=>Z._fromReadableStream($)),Z}async _fromReadableStream($,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}this._connected();let Y=E0.fromReadableStream($,this.controller);for await(let G of Y)w(this,Q0,"m",D6).call(this,G);if(Y.controller.signal?.aborted)throw new Z0;return this._addRun(w(this,Q0,"m",E6).call(this))}toReadableStream(){return new E0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream($,Z,X,Y){let G=new Q1;return G._run(()=>G._runToolAssistantStream($,Z,X,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),G}async _createToolAssistantStream($,Z,X,Y){let G=Y?.signal;if(G){if(G.aborted)this.controller.abort();G.addEventListener("abort",()=>this.controller.abort())}let z={...X,stream:!0},J=await $.submitToolOutputs(Z,z,{...Y,signal:this.controller.signal});this._connected();for await(let Q of J)w(this,Q0,"m",D6).call(this,Q);if(J.controller.signal?.aborted)throw new Z0;return this._addRun(w(this,Q0,"m",E6).call(this))}static createThreadAssistantStream($,Z,X){let Y=new Q1;return Y._run(()=>Y._threadAssistantStream($,Z,{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}static createAssistantStream($,Z,X,Y){let G=new Q1;return G._run(()=>G._runAssistantStream($,Z,X,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),G}currentEvent(){return w(this,i8,"f")}currentRun(){return w(this,a8,"f")}currentMessageSnapshot(){return w(this,f0,"f")}currentRunStepSnapshot(){return w(this,R6,"f")}async finalRunSteps(){return await this.done(),Object.values(w(this,c0,"f"))}async finalMessages(){return await this.done(),Object.values(w(this,p8,"f"))}async finalRun(){if(await this.done(),!w(this,W1,"f"))throw Error("Final run was not received.");return w(this,W1,"f")}async _createThreadAssistantStream($,Z,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}let G={...Z,stream:!0},z=await $.createAndRun(G,{...X,signal:this.controller.signal});this._connected();for await(let J of z)w(this,Q0,"m",D6).call(this,J);if(z.controller.signal?.aborted)throw new Z0;return this._addRun(w(this,Q0,"m",E6).call(this))}async _createAssistantStream($,Z,X,Y){let G=Y?.signal;if(G){if(G.aborted)this.controller.abort();G.addEventListener("abort",()=>this.controller.abort())}let z={...X,stream:!0},J=await $.create(Z,z,{...Y,signal:this.controller.signal});this._connected();for await(let Q of J)w(this,Q0,"m",D6).call(this,Q);if(J.controller.signal?.aborted)throw new Z0;return this._addRun(w(this,Q0,"m",E6).call(this))}static accumulateDelta($,Z){for(let[X,Y]of Object.entries(Z)){if(!$.hasOwnProperty(X)){$[X]=Y;continue}let G=$[X];if(G===null||G===void 0){$[X]=Y;continue}if(X==="index"||X==="type"){$[X]=Y;continue}if(typeof G==="string"&&typeof Y==="string")G+=Y;else if(typeof G==="number"&&typeof Y==="number")G+=Y;else if(j4(G)&&j4(Y))G=this.accumulateDelta(G,Y);else if(Array.isArray(G)&&Array.isArray(Y)){if(G.every((z)=>typeof z==="string"||typeof z==="number")){G.push(...Y);continue}for(let z of Y){if(!j4(z))throw Error(`Expected array delta entry to be an object but got: ${z}`);let J=z.index;if(J==null)throw console.error(z),Error("Expected array delta entry to have an `index` property");if(typeof J!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${J}`);let Q=G[J];if(Q==null)G.push(z);else G[J]=this.accumulateDelta(Q,z)}continue}else throw Error(`Unhandled record type: ${X}, deltaValue: ${Y}, accValue: ${G}`);$[X]=G}return $}_addRun($){return $}async _threadAssistantStream($,Z,X){return await this._createThreadAssistantStream(Z,$,X)}async _runAssistantStream($,Z,X,Y){return await this._createAssistantStream(Z,$,X,Y)}async _runToolAssistantStream($,Z,X,Y){return await this._createToolAssistantStream(Z,$,X,Y)}}Q1=I$,D6=function(Z){if(this.ended)return;switch(x(this,i8,Z,"f"),w(this,Q0,"m",Mz).call(this,Z),Z.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":w(this,Q0,"m",_z).call(this,Z);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":w(this,Q0,"m",Lz).call(this,Z);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":w(this,Q0,"m",Fz).call(this,Z);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:$w(Z)}},E6=function(){if(this.ended)throw new I("stream has ended, this shouldn't happen");if(!w(this,W1,"f"))throw Error("Final run has not been received");return w(this,W1,"f")},Fz=function(Z){let[X,Y]=w(this,Q0,"m",Oz).call(this,Z,w(this,f0,"f"));x(this,f0,X,"f"),w(this,p8,"f")[X.id]=X;for(let G of Y){let z=X.content[G.index];if(z?.type=="text")this._emit("textCreated",z.text)}switch(Z.event){case"thread.message.created":this._emit("messageCreated",Z.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",Z.data.delta,X),Z.data.delta.content)for(let G of Z.data.delta.content){if(G.type=="text"&&G.text){let z=G.text,J=X.content[G.index];if(J&&J.type=="text")this._emit("textDelta",z,J.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(G.index!=w(this,X2,"f")){if(w(this,J1,"f"))switch(w(this,J1,"f").type){case"text":this._emit("textDone",w(this,J1,"f").text,w(this,f0,"f"));break;case"image_file":this._emit("imageFileDone",w(this,J1,"f").image_file,w(this,f0,"f"));break}x(this,X2,G.index,"f")}x(this,J1,X.content[G.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(w(this,X2,"f")!==void 0){let G=Z.data.content[w(this,X2,"f")];if(G)switch(G.type){case"image_file":this._emit("imageFileDone",G.image_file,w(this,f0,"f"));break;case"text":this._emit("textDone",G.text,w(this,f0,"f"));break}}if(w(this,f0,"f"))this._emit("messageDone",Z.data);x(this,f0,void 0,"f")}},Lz=function(Z){let X=w(this,Q0,"m",wz).call(this,Z);switch(x(this,R6,X,"f"),Z.event){case"thread.run.step.created":this._emit("runStepCreated",Z.data);break;case"thread.run.step.delta":let Y=Z.data.delta;if(Y.step_details&&Y.step_details.type=="tool_calls"&&Y.step_details.tool_calls&&X.step_details.type=="tool_calls")for(let z of Y.step_details.tool_calls)if(z.index==w(this,n8,"f"))this._emit("toolCallDelta",z,X.step_details.tool_calls[z.index]);else{if(w(this,R0,"f"))this._emit("toolCallDone",w(this,R0,"f"));if(x(this,n8,z.index,"f"),x(this,R0,X.step_details.tool_calls[z.index],"f"),w(this,R0,"f"))this._emit("toolCallCreated",w(this,R0,"f"))}this._emit("runStepDelta",Z.data.delta,X);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(x(this,R6,void 0,"f"),Z.data.step_details.type=="tool_calls"){if(w(this,R0,"f"))this._emit("toolCallDone",w(this,R0,"f")),x(this,R0,void 0,"f")}this._emit("runStepDone",Z.data,X);break;case"thread.run.step.in_progress":break}},Mz=function(Z){w(this,h5,"f").push(Z),this._emit("event",Z)},wz=function(Z){switch(Z.event){case"thread.run.step.created":return w(this,c0,"f")[Z.data.id]=Z.data,Z.data;case"thread.run.step.delta":let X=w(this,c0,"f")[Z.data.id];if(!X)throw Error("Received a RunStepDelta before creation of a snapshot");let Y=Z.data;if(Y.delta){let G=Q1.accumulateDelta(X,Y.delta);w(this,c0,"f")[Z.data.id]=G}return w(this,c0,"f")[Z.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":w(this,c0,"f")[Z.data.id]=Z.data;break}if(w(this,c0,"f")[Z.data.id])return w(this,c0,"f")[Z.data.id];throw Error("No snapshot available")},Oz=function(Z,X){let Y=[];switch(Z.event){case"thread.message.created":return[Z.data,Y];case"thread.message.delta":if(!X)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let G=Z.data;if(G.delta.content)for(let z of G.delta.content)if(z.index in X.content){let J=X.content[z.index];X.content[z.index]=w(this,Q0,"m",Nz).call(this,z,J)}else X.content[z.index]=z,Y.push(z);return[X,Y];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(X)return[X,Y];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Nz=function(Z,X){return Q1.accumulateDelta(X,Z)},_z=function(Z){switch(x(this,a8,Z.data,"f"),Z.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":if(x(this,W1,Z.data,"f"),w(this,R0,"f"))this._emit("toolCallDone",w(this,R0,"f")),x(this,R0,void 0,"f");break;case"thread.run.cancelling":break}};function $w($){}class Y2 extends L{constructor(){super(...arguments);this.steps=new P6(this._client)}create($,Z,X){let{include:Y,...G}=Z;return this._client.post(q`/threads/${$}/runs`,{query:{include:Y},body:G,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),stream:Z.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve($,Z,X){let{thread_id:Y}=Z;return this._client.get(q`/threads/${Y}/runs/${$}`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}update($,Z,X){let{thread_id:Y,...G}=Z;return this._client.post(q`/threads/${Y}/runs/${$}`,{body:G,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/threads/${$}/runs`,y,{query:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}cancel($,Z,X){let{thread_id:Y}=Z;return this._client.post(q`/threads/${Y}/runs/${$}/cancel`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}async createAndPoll($,Z,X){let Y=await this.create($,Z,X);return await this.poll(Y.id,{thread_id:$},X)}createAndStream($,Z,X){return I$.createAssistantStream($,this._client.beta.threads.runs,Z,X)}async poll($,Z,X){let Y=E([X?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":X?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:G,response:z}=await this.retrieve($,Z,{...X,headers:{...X?.headers,...Y}}).withResponse();switch(G.status){case"queued":case"in_progress":case"cancelling":let J=5000;if(X?.pollIntervalMs)J=X.pollIntervalMs;else{let Q=z.headers.get("openai-poll-after-ms");if(Q){let W=parseInt(Q);if(!isNaN(W))J=W}}await u0(J);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return G}}}stream($,Z,X){return I$.createAssistantStream($,this._client.beta.threads.runs,Z,X)}submitToolOutputs($,Z,X){let{thread_id:Y,...G}=Z;return this._client.post(q`/threads/${Y}/runs/${$}/submit_tool_outputs`,{body:G,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),stream:Z.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll($,Z,X){let Y=await this.submitToolOutputs($,Z,X);return await this.poll(Y.id,Z,X)}submitToolOutputsStream($,Z,X){return I$.createToolAssistantStream($,this._client.beta.threads.runs,Z,X)}}Y2.Steps=P6;class V1 extends L{constructor(){super(...arguments);this.runs=new Y2(this._client),this.messages=new _6(this._client)}create($={},Z){return this._client.post("/threads",{body:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/threads/${$}`,{...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/threads/${$}`,{body:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/threads/${$}`,{...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}createAndRun($,Z){return this._client.post("/threads/runs",{body:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),stream:$.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll($,Z){let X=await this.createAndRun($,Z);return await this.runs.poll(X.id,{thread_id:X.thread_id},Z)}createAndRunStream($,Z){return I$.createThreadAssistantStream($,this._client.beta.threads,Z)}}V1.Runs=Y2;V1.Messages=_6;class l0 extends L{constructor(){super(...arguments);this.realtime=new G1(this._client),this.chatkit=new z1(this._client),this.assistants=new L6(this._client),this.threads=new V1(this._client)}}l0.Realtime=G1;l0.ChatKit=z1;l0.Assistants=L6;l0.Threads=V1;class G2 extends L{create($,Z){return this._client.post("/completions",{body:$,...Z,stream:$.stream??!1,__security:{bearerAuth:!0}})}}class A6 extends L{retrieve($,Z,X){let{container_id:Y}=Z;return this._client.get(q`/containers/${Y}/files/${$}/content`,{...X,headers:E([{Accept:"application/binary"},X?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class z2 extends L{constructor(){super(...arguments);this.content=new A6(this._client)}create($,Z,X){return this._client.post(q`/containers/${$}/files`,R$({body:Z,...X,__security:{bearerAuth:!0}},this._client))}retrieve($,Z,X){let{container_id:Y}=Z;return this._client.get(q`/containers/${Y}/files/${$}`,{...X,__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/containers/${$}/files`,y,{query:Z,...X,__security:{bearerAuth:!0}})}delete($,Z,X){let{container_id:Y}=Z;return this._client.delete(q`/containers/${Y}/files/${$}`,{...X,headers:E([{Accept:"*/*"},X?.headers]),__security:{bearerAuth:!0}})}}z2.Content=A6;class H1 extends L{constructor(){super(...arguments);this.files=new z2(this._client)}create($,Z){return this._client.post("/containers",{body:$,...Z,__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/containers/${$}`,{...Z,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/containers",y,{query:$,...Z,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/containers/${$}`,{...Z,headers:E([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}}H1.Files=z2;class S6 extends L{create($,Z,X){let{include:Y,...G}=Z;return this._client.post(q`/conversations/${$}/items`,{query:{include:Y},body:G,...X,__security:{bearerAuth:!0}})}retrieve($,Z,X){let{conversation_id:Y,...G}=Z;return this._client.get(q`/conversations/${Y}/items/${$}`,{query:G,...X,__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/conversations/${$}/items`,d,{query:Z,...X,__security:{bearerAuth:!0}})}delete($,Z,X){let{conversation_id:Y}=Z;return this._client.delete(q`/conversations/${Y}/items/${$}`,{...X,__security:{bearerAuth:!0}})}}class K1 extends L{constructor(){super(...arguments);this.items=new S6(this._client)}create($={},Z){return this._client.post("/conversations",{body:$,...Z,__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/conversations/${$}`,{...Z,__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/conversations/${$}`,{body:Z,...X,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/conversations/${$}`,{...Z,__security:{bearerAuth:!0}})}}K1.Items=S6;class J2 extends L{create($,Z){let X=!!$.encoding_format,Y=X?$.encoding_format:"base64";if(X)s(this._client).debug("embeddings/user defined encoding_format:",$.encoding_format);let G=this._client.post("/embeddings",{body:{...$,encoding_format:Y},...Z,__security:{bearerAuth:!0}});if(X)return G;return s(this._client).debug("embeddings/decoding base64 embeddings from base64"),G._thenUnwrap((z)=>{if(z&&z.data)z.data.forEach((J)=>{let Q=J.embedding;J.embedding=Tz(Q)});return z})}}class C6 extends L{retrieve($,Z,X){let{eval_id:Y,run_id:G}=Z;return this._client.get(q`/evals/${Y}/runs/${G}/output_items/${$}`,{...X,__security:{bearerAuth:!0}})}list($,Z,X){let{eval_id:Y,...G}=Z;return this._client.getAPIList(q`/evals/${Y}/runs/${$}/output_items`,y,{query:G,...X,__security:{bearerAuth:!0}})}}class Q2 extends L{constructor(){super(...arguments);this.outputItems=new C6(this._client)}create($,Z,X){return this._client.post(q`/evals/${$}/runs`,{body:Z,...X,__security:{bearerAuth:!0}})}retrieve($,Z,X){let{eval_id:Y}=Z;return this._client.get(q`/evals/${Y}/runs/${$}`,{...X,__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/evals/${$}/runs`,y,{query:Z,...X,__security:{bearerAuth:!0}})}delete($,Z,X){let{eval_id:Y}=Z;return this._client.delete(q`/evals/${Y}/runs/${$}`,{...X,__security:{bearerAuth:!0}})}cancel($,Z,X){let{eval_id:Y}=Z;return this._client.post(q`/evals/${Y}/runs/${$}`,{...X,__security:{bearerAuth:!0}})}}Q2.OutputItems=C6;class U1 extends L{constructor(){super(...arguments);this.runs=new Q2(this._client)}create($,Z){return this._client.post("/evals",{body:$,...Z,__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/evals/${$}`,{...Z,__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/evals/${$}`,{body:Z,...X,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/evals",y,{query:$,...Z,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/evals/${$}`,{...Z,__security:{bearerAuth:!0}})}}U1.Runs=Q2;class W2 extends L{create($,Z){return this._client.post("/files",B0({body:$,...Z,__security:{bearerAuth:!0}},this._client))}retrieve($,Z){return this._client.get(q`/files/${$}`,{...Z,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/files",y,{query:$,...Z,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/files/${$}`,{...Z,__security:{bearerAuth:!0}})}content($,Z){return this._client.get(q`/files/${$}/content`,{...Z,headers:E([{Accept:"application/binary"},Z?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing($,{pollInterval:Z=5000,maxWait:X=1800000}={}){let Y=new Set(["processed","error","deleted"]),G=Date.now(),z=await this.retrieve($);while(!z.status||!Y.has(z.status))if(await u0(Z),z=await this.retrieve($),Date.now()-G>X)throw new o$({message:`Giving up on waiting for file ${$} to finish processing after ${X} milliseconds.`});return z}}class I6 extends L{}class j6 extends L{run($,Z){return this._client.post("/fine_tuning/alpha/graders/run",{body:$,...Z,__security:{bearerAuth:!0}})}validate($,Z){return this._client.post("/fine_tuning/alpha/graders/validate",{body:$,...Z,__security:{bearerAuth:!0}})}}class V2 extends L{constructor(){super(...arguments);this.graders=new j6(this._client)}}V2.Graders=j6;class x6 extends L{create($,Z,X){return this._client.getAPIList(q`/fine_tuning/checkpoints/${$}/permissions`,F0,{body:Z,method:"post",...X,__security:{adminAPIKeyAuth:!0}})}retrieve($,Z={},X){return this._client.get(q`/fine_tuning/checkpoints/${$}/permissions`,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/fine_tuning/checkpoints/${$}/permissions`,d,{query:Z,...X,__security:{adminAPIKeyAuth:!0}})}delete($,Z,X){let{fine_tuned_model_checkpoint:Y}=Z;return this._client.delete(q`/fine_tuning/checkpoints/${Y}/permissions/${$}`,{...X,__security:{adminAPIKeyAuth:!0}})}}class H2 extends L{constructor(){super(...arguments);this.permissions=new x6(this._client)}}H2.Permissions=x6;class k6 extends L{list($,Z={},X){return this._client.getAPIList(q`/fine_tuning/jobs/${$}/checkpoints`,y,{query:Z,...X,__security:{bearerAuth:!0}})}}class K2 extends L{constructor(){super(...arguments);this.checkpoints=new k6(this._client)}create($,Z){return this._client.post("/fine_tuning/jobs",{body:$,...Z,__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/fine_tuning/jobs/${$}`,{...Z,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/fine_tuning/jobs",y,{query:$,...Z,__security:{bearerAuth:!0}})}cancel($,Z){return this._client.post(q`/fine_tuning/jobs/${$}/cancel`,{...Z,__security:{bearerAuth:!0}})}listEvents($,Z={},X){return this._client.getAPIList(q`/fine_tuning/jobs/${$}/events`,y,{query:Z,...X,__security:{bearerAuth:!0}})}pause($,Z){return this._client.post(q`/fine_tuning/jobs/${$}/pause`,{...Z,__security:{bearerAuth:!0}})}resume($,Z){return this._client.post(q`/fine_tuning/jobs/${$}/resume`,{...Z,__security:{bearerAuth:!0}})}}K2.Checkpoints=k6;class p0 extends L{constructor(){super(...arguments);this.methods=new I6(this._client),this.jobs=new K2(this._client),this.checkpoints=new H2(this._client),this.alpha=new V2(this._client)}}p0.Methods=I6;p0.Jobs=K2;p0.Checkpoints=H2;p0.Alpha=V2;class b6 extends L{}class B1 extends L{constructor(){super(...arguments);this.graderModels=new b6(this._client)}}B1.GraderModels=b6;class U2 extends L{createVariation($,Z){return this._client.post("/images/variations",B0({body:$,...Z,__security:{bearerAuth:!0}},this._client))}edit($,Z){return this._client.post("/images/edits",B0({body:$,...Z,stream:$.stream??!1,__security:{bearerAuth:!0}},this._client))}generate($,Z){return this._client.post("/images/generations",{body:$,...Z,stream:$.stream??!1,__security:{bearerAuth:!0}})}}class B2 extends L{retrieve($,Z){return this._client.get(q`/models/${$}`,{...Z,__security:{bearerAuth:!0}})}list($){return this._client.getAPIList("/models",F0,{...$,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/models/${$}`,{...Z,__security:{bearerAuth:!0}})}}class q2 extends L{create($,Z){return this._client.post("/moderations",{body:$,...Z,__security:{bearerAuth:!0}})}}class f6 extends L{accept($,Z,X){return this._client.post(q`/realtime/calls/${$}/accept`,{body:Z,...X,headers:E([{Accept:"*/*"},X?.headers]),__security:{bearerAuth:!0}})}hangup($,Z){return this._client.post(q`/realtime/calls/${$}/hangup`,{...Z,headers:E([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}refer($,Z,X){return this._client.post(q`/realtime/calls/${$}/refer`,{body:Z,...X,headers:E([{Accept:"*/*"},X?.headers]),__security:{bearerAuth:!0}})}reject($,Z={},X){return this._client.post(q`/realtime/calls/${$}/reject`,{body:Z,...X,headers:E([{Accept:"*/*"},X?.headers]),__security:{bearerAuth:!0}})}}class y6 extends L{create($,Z){return this._client.post("/realtime/client_secrets",{body:$,...Z,__security:{bearerAuth:!0}})}}class j$ extends L{constructor(){super(...arguments);this.clientSecrets=new y6(this._client),this.calls=new f6(this._client)}}j$.ClientSecrets=y6;j$.Calls=f6;function Pz($,Z){if(!Z||!ww(Z))return{...$,output_parsed:null,output:$.output.map((X)=>{if(X.type==="function_call")return{...X,parsed_arguments:null};if(X.type==="message")return{...X,content:X.content.map((Y)=>({...Y,parsed:null}))};else return X})};return u5($,Z)}function u5($,Z){let X=$.output.map((G)=>{if(G.type==="function_call")return{...G,parsed_arguments:_w(Z,G)};if(G.type==="message"){let z=G.content.map((J)=>{if(J.type==="output_text")return{...J,parsed:Mw(Z,J.text)};return J});return{...G,content:z}}return G}),Y=Object.assign({},$,{output:X});if(!Object.getOwnPropertyDescriptor($,"output_text"))r8(Y);return Object.defineProperty(Y,"output_parsed",{enumerable:!0,get(){for(let G of Y.output){if(G.type!=="message")continue;for(let z of G.content)if(z.type==="output_text"&&z.parsed!==null)return z.parsed}return null}}),Y}function Mw($,Z){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(Z);return JSON.parse(Z)}function ww($){if(g4($.text?.format))return!0;return!1}function Ow($){return $?.$brand==="auto-parseable-tool"}function Nw($,Z){return $.find((X)=>X.type==="function"&&X.name===Z)}function _w($,Z){let X=Nw($.tools??[],Z.name);return{...Z,...Z,parsed_arguments:Ow(X)?X.$parseRaw(Z.arguments):X?.strict?JSON.parse(Z.arguments):null}}function r8($){let Z=[];for(let X of $.output){if(X.type!=="message")continue;for(let Y of X.content)if(Y.type==="output_text")Z.push(Y.text)}$.output_text=Z.join("")}var T2,s8,x$,o8,Dz,Ez,Rz,Az;class t8 extends $1{constructor($){super();T2.add(this),s8.set(this,void 0),x$.set(this,void 0),o8.set(this,void 0),x(this,s8,$,"f")}static createResponse($,Z,X){let Y=new t8(Z);return Y._run(()=>Y._createOrRetrieveResponse($,Z,{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}async _createOrRetrieveResponse($,Z,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}w(this,T2,"m",Dz).call(this);let G,z=null;if("response_id"in Z)G=await $.responses.retrieve(Z.response_id,{stream:!0},{...X,signal:this.controller.signal,stream:!0}),z=Z.starting_after??null;else G=await $.responses.create({...Z,stream:!0},{...X,signal:this.controller.signal});this._connected();for await(let J of G)w(this,T2,"m",Ez).call(this,J,z);if(G.controller.signal?.aborted)throw new Z0;return w(this,T2,"m",Rz).call(this)}[(s8=new WeakMap,x$=new WeakMap,o8=new WeakMap,T2=new WeakSet,Dz=function(){if(this.ended)return;x(this,x$,void 0,"f")},Ez=function(Z,X){if(this.ended)return;let Y=(z,J)=>{if(X==null||J.sequence_number>X)this._emit(z,J)},G=w(this,T2,"m",Az).call(this,Z);switch(Y("event",Z),Z.type){case"response.output_text.delta":{let z=G.output[Z.output_index];if(!z)throw new I(`missing output at index ${Z.output_index}`);if(z.type==="message"){let J=z.content[Z.content_index];if(!J)throw new I(`missing content at index ${Z.content_index}`);if(J.type!=="output_text")throw new I(`expected content to be 'output_text', got ${J.type}`);Y("response.output_text.delta",{...Z,snapshot:J.text})}break}case"response.function_call_arguments.delta":{let z=G.output[Z.output_index];if(!z)throw new I(`missing output at index ${Z.output_index}`);if(z.type==="function_call")Y("response.function_call_arguments.delta",{...Z,snapshot:z.arguments});break}default:Y(Z.type,Z);break}},Rz=function(){if(this.ended)throw new I("stream has ended, this shouldn't happen");let Z=w(this,x$,"f");if(!Z)throw new I("request ended without sending any events");x(this,x$,void 0,"f");let X=Pw(Z,w(this,s8,"f"));return x(this,o8,X,"f"),X},Az=function(Z){let X=w(this,x$,"f");if(!X){if(Z.type!=="response.created")throw new I(`When snapshot hasn't been set yet, expected 'response.created' event, got ${Z.type}`);return X=x(this,x$,Z.response,"f"),X}switch(Z.type){case"response.output_item.added":{X.output.push(Z.item);break}case"response.content_part.added":{let Y=X.output[Z.output_index];if(!Y)throw new I(`missing output at index ${Z.output_index}`);let G=Y.type,z=Z.part;if(G==="message"&&z.type!=="reasoning_text")Y.content.push(z);else if(G==="reasoning"&&z.type==="reasoning_text"){if(!Y.content)Y.content=[];Y.content.push(z)}break}case"response.output_text.delta":{let Y=X.output[Z.output_index];if(!Y)throw new I(`missing output at index ${Z.output_index}`);if(Y.type==="message"){let G=Y.content[Z.content_index];if(!G)throw new I(`missing content at index ${Z.content_index}`);if(G.type!=="output_text")throw new I(`expected content to be 'output_text', got ${G.type}`);G.text+=Z.delta}break}case"response.function_call_arguments.delta":{let Y=X.output[Z.output_index];if(!Y)throw new I(`missing output at index ${Z.output_index}`);if(Y.type==="function_call")Y.arguments+=Z.delta;break}case"response.reasoning_text.delta":{let Y=X.output[Z.output_index];if(!Y)throw new I(`missing output at index ${Z.output_index}`);if(Y.type==="reasoning"){let G=Y.content?.[Z.content_index];if(!G)throw new I(`missing content at index ${Z.content_index}`);if(G.type!=="reasoning_text")throw new I(`expected content to be 'reasoning_text', got ${G.type}`);G.text+=Z.delta}break}case"response.completed":{x(this,x$,Z.response,"f");break}}return X},Symbol.asyncIterator)](){let $=[],Z=[],X=!1;return this.on("event",(Y)=>{let G=Z.shift();if(G)G.resolve(Y);else $.push(Y)}),this.on("end",()=>{X=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),this.on("error",(Y)=>{X=!0;for(let G of Z)G.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(X)return{value:void 0,done:!0};return new Promise((G,z)=>Z.push({resolve:G,reject:z})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let $=w(this,o8,"f");if(!$)throw new I("stream ended without producing a ChatCompletion");return $}}function Pw($,Z){return Pz($,Z)}class v6 extends L{list($,Z={},X){return this._client.getAPIList(q`/responses/${$}/input_items`,y,{query:Z,...X,__security:{bearerAuth:!0}})}}class g6 extends L{count($={},Z){return this._client.post("/responses/input_tokens",{body:$,...Z,__security:{bearerAuth:!0}})}}class k$ extends L{constructor(){super(...arguments);this.inputItems=new v6(this._client),this.inputTokens=new g6(this._client)}create($,Z){return this._client.post("/responses",{body:$,...Z,stream:$.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap((X)=>{if("object"in X&&X.object==="response")r8(X);return X})}retrieve($,Z={},X){return this._client.get(q`/responses/${$}`,{query:Z,...X,stream:Z?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap((Y)=>{if("object"in Y&&Y.object==="response")r8(Y);return Y})}delete($,Z){return this._client.delete(q`/responses/${$}`,{...Z,headers:E([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}parse($,Z){return this._client.responses.create($,Z)._thenUnwrap((X)=>u5(X,$))}stream($,Z){return t8.createResponse(this._client,$,Z)}cancel($,Z){return this._client.post(q`/responses/${$}/cancel`,{...Z,__security:{bearerAuth:!0}})}compact($,Z){return this._client.post("/responses/compact",{body:$,...Z,__security:{bearerAuth:!0}})}}k$.InputItems=v6;k$.InputTokens=g6;class h6 extends L{retrieve($,Z){return this._client.get(q`/skills/${$}/content`,{...Z,headers:E([{Accept:"application/binary"},Z?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class u6 extends L{retrieve($,Z,X){let{skill_id:Y}=Z;return this._client.get(q`/skills/${Y}/versions/${$}/content`,{...X,headers:E([{Accept:"application/binary"},X?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class F2 extends L{constructor(){super(...arguments);this.content=new u6(this._client)}create($,Z={},X){return this._client.post(q`/skills/${$}/versions`,R$({body:Z,...X,__security:{bearerAuth:!0}},this._client))}retrieve($,Z,X){let{skill_id:Y}=Z;return this._client.get(q`/skills/${Y}/versions/${$}`,{...X,__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/skills/${$}/versions`,y,{query:Z,...X,__security:{bearerAuth:!0}})}delete($,Z,X){let{skill_id:Y}=Z;return this._client.delete(q`/skills/${Y}/versions/${$}`,{...X,__security:{bearerAuth:!0}})}}F2.Content=u6;class b$ extends L{constructor(){super(...arguments);this.content=new h6(this._client),this.versions=new F2(this._client)}create($={},Z){return this._client.post("/skills",R$({body:$,...Z,__security:{bearerAuth:!0}},this._client))}retrieve($,Z){return this._client.get(q`/skills/${$}`,{...Z,__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/skills/${$}`,{body:Z,...X,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/skills",y,{query:$,...Z,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/skills/${$}`,{...Z,__security:{bearerAuth:!0}})}}b$.Content=h6;b$.Versions=F2;class m6 extends L{create($,Z,X){return this._client.post(q`/uploads/${$}/parts`,B0({body:Z,...X,__security:{bearerAuth:!0}},this._client))}}class q1 extends L{constructor(){super(...arguments);this.parts=new m6(this._client)}create($,Z){return this._client.post("/uploads",{body:$,...Z,__security:{bearerAuth:!0}})}cancel($,Z){return this._client.post(q`/uploads/${$}/cancel`,{...Z,__security:{bearerAuth:!0}})}complete($,Z,X){return this._client.post(q`/uploads/${$}/complete`,{body:Z,...X,__security:{bearerAuth:!0}})}}q1.Parts=m6;var Sz=async($)=>{let Z=await Promise.allSettled($),X=Z.filter((G)=>G.status==="rejected");if(X.length){for(let G of X)console.error(G.reason);throw Error(`${X.length} promise(s) failed - see the above errors`)}let Y=[];for(let G of Z)if(G.status==="fulfilled")Y.push(G.value);return Y};class d6 extends L{create($,Z,X){return this._client.post(q`/vector_stores/${$}/file_batches`,{body:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}retrieve($,Z,X){let{vector_store_id:Y}=Z;return this._client.get(q`/vector_stores/${Y}/file_batches/${$}`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}cancel($,Z,X){let{vector_store_id:Y}=Z;return this._client.post(q`/vector_stores/${Y}/file_batches/${$}/cancel`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}async createAndPoll($,Z,X){let Y=await this.create($,Z);return await this.poll($,Y.id,X)}listFiles($,Z,X){let{vector_store_id:Y,...G}=Z;return this._client.getAPIList(q`/vector_stores/${Y}/file_batches/${$}/files`,y,{query:G,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}async poll($,Z,X){let Y=E([X?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":X?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:G,response:z}=await this.retrieve(Z,{vector_store_id:$},{...X,headers:Y}).withResponse();switch(G.status){case"in_progress":let J=5000;if(X?.pollIntervalMs)J=X.pollIntervalMs;else{let Q=z.headers.get("openai-poll-after-ms");if(Q){let W=parseInt(Q);if(!isNaN(W))J=W}}await u0(J);break;case"failed":case"cancelled":case"completed":return G}}}async uploadAndPoll($,{files:Z,fileIds:X=[]},Y){if(Z==null||Z.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let G=Y?.maxConcurrency??5,z=Math.min(G,Z.length),J=this._client,Q=Z.values(),W=[...X];async function V(H){for(let U of H){let B=await J.files.create({file:U,purpose:"assistants"},Y);W.push(B.id)}}let K=Array(z).fill(Q).map(V);return await Sz(K),await this.createAndPoll($,{file_ids:W})}}class c6 extends L{create($,Z,X){return this._client.post(q`/vector_stores/${$}/files`,{body:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}retrieve($,Z,X){let{vector_store_id:Y}=Z;return this._client.get(q`/vector_stores/${Y}/files/${$}`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}update($,Z,X){let{vector_store_id:Y,...G}=Z;return this._client.post(q`/vector_stores/${Y}/files/${$}`,{body:G,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/vector_stores/${$}/files`,y,{query:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}delete($,Z,X){let{vector_store_id:Y}=Z;return this._client.delete(q`/vector_stores/${Y}/files/${$}`,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}async createAndPoll($,Z,X){let Y=await this.create($,Z,X);return await this.poll($,Y.id,X)}async poll($,Z,X){let Y=E([X?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":X?.pollIntervalMs?.toString()??void 0}]);while(!0){let G=await this.retrieve(Z,{vector_store_id:$},{...X,headers:Y}).withResponse(),z=G.data;switch(z.status){case"in_progress":let J=5000;if(X?.pollIntervalMs)J=X.pollIntervalMs;else{let Q=G.response.headers.get("openai-poll-after-ms");if(Q){let W=parseInt(Q);if(!isNaN(W))J=W}}await u0(J);break;case"failed":case"completed":return z}}}async upload($,Z,X){let Y=await this._client.files.create({file:Z,purpose:"assistants"},X);return this.create($,{file_id:Y.id},X)}async uploadAndPoll($,Z,X){let Y=await this.upload($,Z,X);return await this.poll($,Y.id,X)}content($,Z,X){let{vector_store_id:Y}=Z;return this._client.getAPIList(q`/vector_stores/${Y}/files/${$}/content`,F0,{...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}}class f$ extends L{constructor(){super(...arguments);this.files=new c6(this._client),this.fileBatches=new d6(this._client)}create($,Z){return this._client.post("/vector_stores",{body:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/vector_stores/${$}`,{...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/vector_stores/${$}`,{body:Z,...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/vector_stores",y,{query:$,...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/vector_stores/${$}`,{...Z,headers:E([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}search($,Z,X){return this._client.getAPIList(q`/vector_stores/${$}/search`,F0,{body:Z,method:"post",...X,headers:E([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}}f$.Files=c6;f$.FileBatches=d6;class L2 extends L{create($,Z){return this._client.post("/videos",B0({body:$,...Z,__security:{bearerAuth:!0}},this._client))}retrieve($,Z){return this._client.get(q`/videos/${$}`,{...Z,__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/videos",d,{query:$,...Z,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/videos/${$}`,{...Z,__security:{bearerAuth:!0}})}createCharacter($,Z){return this._client.post("/videos/characters",B0({body:$,...Z,__security:{bearerAuth:!0}},this._client))}downloadContent($,Z={},X){return this._client.get(q`/videos/${$}/content`,{query:Z,...X,headers:E([{Accept:"application/binary"},X?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit($,Z){return this._client.post("/videos/edits",B0({body:$,...Z,__security:{bearerAuth:!0}},this._client))}extend($,Z){return this._client.post("/videos/extensions",B0({body:$,...Z,__security:{bearerAuth:!0}},this._client))}getCharacter($,Z){return this._client.get(q`/videos/characters/${$}`,{...Z,__security:{bearerAuth:!0}})}remix($,Z,X){return this._client.post(q`/videos/${$}/remix`,R$({body:Z,...X,__security:{bearerAuth:!0}},this._client))}}var M2,Cz,e8;class w2 extends L{constructor(){super(...arguments);M2.add(this)}async unwrap($,Z,X=this._client.webhookSecret,Y=300){return await this.verifySignature($,Z,X,Y),JSON.parse($)}async verifySignature($,Z,X=this._client.webhookSecret,Y=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");w(this,M2,"m",Cz).call(this,X);let G=E([Z]).values,z=w(this,M2,"m",e8).call(this,G,"webhook-signature"),J=w(this,M2,"m",e8).call(this,G,"webhook-timestamp"),Q=w(this,M2,"m",e8).call(this,G,"webhook-id"),W=parseInt(J,10);if(isNaN(W))throw new Y$("Invalid webhook timestamp format");let V=Math.floor(Date.now()/1000);if(V-W>Y)throw new Y$("Webhook timestamp is too old");if(W>V+Y)throw new Y$("Webhook timestamp is too new");let K=z.split(" ").map((T)=>T.startsWith("v1,")?T.substring(3):T),H=X.startsWith("whsec_")?Buffer.from(X.replace("whsec_",""),"base64"):Buffer.from(X,"utf-8"),U=Q?`${Q}.${J}.${$}`:`${J}.${$}`,B=await crypto.subtle.importKey("raw",H,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let T of K)try{let F=Buffer.from(T,"base64");if(await crypto.subtle.verify("HMAC",B,F,new TextEncoder().encode(U)))return}catch{continue}throw new Y$("The given webhook signature does not match the expected signature")}}M2=new WeakSet,Cz=function(Z){if(typeof Z!=="string"||Z.length===0)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},e8=function(Z,X){if(!Z)throw Error("Headers are required");let Y=Z.get(X);if(Y===null||Y===void 0)throw Error(`Missing required header: ${X}`);return Y};var m5,d5,$9,Iz,kw="workload-identity-auth";class f{constructor({baseURL:$=d0("OPENAI_BASE_URL"),apiKey:Z=d0("OPENAI_API_KEY")??null,adminAPIKey:X=d0("OPENAI_ADMIN_KEY")??null,organization:Y=d0("OPENAI_ORG_ID")??null,project:G=d0("OPENAI_PROJECT_ID")??null,webhookSecret:z=d0("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:J,...Q}={}){m5.add(this),$9.set(this,void 0),this.completions=new G2(this),this.chat=new Z1(this),this.embeddings=new J2(this),this.files=new W2(this),this.images=new U2(this),this.audio=new Q$(this),this.moderations=new q2(this),this.models=new B2(this),this.fineTuning=new p0(this),this.graders=new B1(this),this.vectorStores=new f$(this),this.webhooks=new w2(this),this.beta=new l0(this),this.batches=new Z2(this),this.uploads=new q1(this),this.admin=new Y1(this),this.responses=new k$(this),this.realtime=new j$(this),this.conversations=new K1(this),this.evals=new U1(this),this.containers=new H1(this),this.skills=new b$(this),this.videos=new L2(this);let W={apiKey:Z,adminAPIKey:X,organization:Y,project:G,webhookSecret:z,workloadIdentity:J,...Q,baseURL:$||"https://api.openai.com/v1"};if(Z&&J)throw new I("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!Z&&!X&&!J)throw new I("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!W.dangerouslyAllowBrowser&&IG())throw new I(`It looks like you're running in a browser-like environment.
|
|
255
256
|
|
|
256
257
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
257
258
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -260,23 +261,23 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
260
261
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
261
262
|
|
|
262
263
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
263
|
-
`);this.baseURL=W.baseURL,this.timeout=W.timeout??d5.DEFAULT_TIMEOUT,this.logger=W.logger??console;let V="warn";this.logLevel=V,this.logLevel=
|
|
264
|
-
`)){let U=B.indexOf(":");if(U>=0)H[B.substring(0,U).trim()]=B.substring(U+1).trim()}W.defaultHeaders=E([H,W.defaultHeaders])}if(this._options=W,J)this._workloadIdentityAuth=new N5(J,this.fetch);this.apiKey=typeof Z==="string"?Z:null,this.adminAPIKey=X,this.organization=Y,this.project=G,this.webhookSecret=z}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:Z},X={bearerAuth:!0,adminAPIKeyAuth:!0}){if($.get("authorization")||$.get("api-key"))return;if(Z.has("authorization")||Z.has("api-key"))return;if(this._workloadIdentityAuth&&X.bearerAuth)return;throw Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders($,Z={bearerAuth:!0,adminAPIKeyAuth:!0}){return E([Z.bearerAuth?await this.bearerAuth($):null,Z.adminAPIKeyAuth?await this.adminAPIKeyAuth($):null])}async bearerAuth($){if(this._workloadIdentityAuth)return E([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey==null)return;return E([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth($){if(this.adminAPIKey==null)return;return E([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery($){return uG($)}getUserAgent(){return`${this.constructor.name}/JS ${R$}`}defaultIdempotencyKey(){return`stainless-node-retry-${J5()}`}makeStatusError($,Z,X,Y){return r.generate($,Z,X,Y)}async _callApiKey(){let $=this._options.apiKey;if(typeof $!=="function")return!1;let Z;try{Z=await $()}catch(X){if(X instanceof I)throw X;throw new I(`Failed to get token from 'apiKey' function: ${X.message}`,{cause:X})}if(typeof Z!=="string"||!Z)throw new I(`Expected 'apiKey' function argument to return a string but it returned ${Z}`);return this.apiKey=Z,!0}buildURL($,Z,X){let Y=!M(this,m5,"m",Sz).call(this)&&X||this.baseURL,G=NG($)?new URL($):new URL(Y+(Y.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),z=this.defaultQuery(),J=Object.fromEntries(G.searchParams);if(!W5(z)||!W5(J))Z={...J,...z,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))G.search=this.stringifyQuery(Z);return G.toString()}async prepareOptions($){if(($.__security??{bearerAuth:!0}).bearerAuth)await this._callApiKey()}async prepareRequest($,{url:Z,options:X}){}get($,Z){return this.methodRequest("get",$,Z)}post($,Z){return this.methodRequest("post",$,Z)}patch($,Z){return this.methodRequest("patch",$,Z)}put($,Z){return this.methodRequest("put",$,Z)}delete($,Z){return this.methodRequest("delete",$,Z)}methodRequest($,Z,X){return this.request(Promise.resolve(X).then((Y)=>{return{method:$,path:Z,...Y}}))}request($,Z=null){return new X1(this,this.makeRequest($,Z,void 0))}async makeRequest($,Z,X){let Y=await $,G=Y.maxRetries??this.maxRetries;if(Z==null)Z=G;await this.prepareOptions(Y);let{req:z,url:J,timeout:Q}=await this.buildRequest(Y,{retryCount:G-Z});await this.prepareRequest(z,{url:J,options:Y});let W="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),V=X===void 0?"":`, retryOf: ${X}`,K=Date.now();if(s(this).debug(`[${W}] sending request`,z$({retryOfRequestLogID:X,method:Y.method,url:J,options:Y,headers:z.headers})),Y.signal?.aborted)throw new $0;let H=Y.__security??{bearerAuth:!0},B=new AbortController,U=await this.fetchWithAuth(J,z,Q,B,H).catch(N4),F=Date.now();if(U instanceof globalThis.Error){let O=`retrying, ${Z} attempts remaining`;if(Y.signal?.aborted)throw new $0;let N=O4(U)||/timed? ?out/i.test(String(U)+("cause"in U?String(U.cause):""));if(Z)return s(this).info(`[${W}] connection ${N?"timed out":"failed"} - ${O}`),s(this).debug(`[${W}] connection ${N?"timed out":"failed"} (${O})`,z$({retryOfRequestLogID:X,url:J,durationMs:F-K,message:U.message})),this.retryRequest(Y,Z,X??W);if(s(this).info(`[${W}] connection ${N?"timed out":"failed"} - error; no more retries left`),s(this).debug(`[${W}] connection ${N?"timed out":"failed"} (error; no more retries left)`,z$({retryOfRequestLogID:X,url:J,durationMs:F-K,message:U.message})),U instanceof i1||U instanceof D8)throw U;if(N)throw new Z1;throw new $1({cause:U})}let T=[...U.headers.entries()].filter(([O])=>O==="x-request-id").map(([O,N])=>", "+O+": "+JSON.stringify(N)).join(""),w=`[${W}${V}${T}] ${z.method} ${J} ${U.ok?"succeeded":"failed"} with status ${U.status} in ${F-K}ms`;if(!U.ok){if(U.status===401&&this._workloadIdentityAuth&&H.bearerAuth&&!Y.__metadata?.hasStreamingBody&&!Y.__metadata?.workloadIdentityTokenRefreshed)return await K5(U.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...Y,__metadata:{...Y.__metadata,workloadIdentityTokenRefreshed:!0}},Z,X??W);let O=await this.shouldRetry(U);if(Z&&O){let S=`retrying, ${Z} attempts remaining`;return await K5(U.body),s(this).info(`${w} - ${S}`),s(this).debug(`[${W}] response error (${S})`,z$({retryOfRequestLogID:X,url:U.url,status:U.status,headers:U.headers,durationMs:F-K})),this.retryRequest(Y,Z,X??W,U.headers)}let N=O?"error; no more retries left":"error; not retryable";s(this).info(`${w} - ${N}`);let _=await U.text().catch((S)=>N4(S).message),P=DG(_),R=P?void 0:_;throw s(this).debug(`[${W}] response error (${N})`,z$({retryOfRequestLogID:X,url:U.url,status:U.status,headers:U.headers,message:R,durationMs:Date.now()-K})),this.makeStatusError(U.status,P,R,U.headers)}return s(this).info(w),s(this).debug(`[${W}] response start`,z$({retryOfRequestLogID:X,url:U.url,status:U.status,headers:U.headers,durationMs:F-K})),{response:U,options:Y,controller:B,requestLogID:W,retryOfRequestLogID:X,startTime:K}}getAPIList($,Z,X){return this.requestAPIList(Z,X&&"then"in X?X.then((Y)=>({method:"get",path:$,...Y})):{method:"get",path:$,...X})}requestAPIList($,Z){let X=this.makeRequest(Z,null,void 0);return new k8(this,X,$)}async fetchWithAuth($,Z,X,Y,G={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&G.bearerAuth){let J=Z.headers,Q=J.get("Authorization");if(!Q||Q===`Bearer ${IM}`){let W=await this._workloadIdentityAuth.getToken();J.set("Authorization",`Bearer ${W}`)}}return await this.fetchWithTimeout($,Z,X,Y)}async fetchWithTimeout($,Z,X,Y){let{signal:G,method:z,...J}=Z||{},Q=this._makeAbort(Y);if(G)G.addEventListener("abort",Q,{once:!0});let W=setTimeout(Q,X),V=globalThis.ReadableStream&&J.body instanceof globalThis.ReadableStream||typeof J.body==="object"&&J.body!==null&&Symbol.asyncIterator in J.body,K={signal:Y.signal,...V?{duplex:"half"}:{},method:"GET",...J};if(z)K.method=z.toUpperCase();try{return await this.fetch.call(void 0,$,K)}finally{clearTimeout(W)}}async shouldRetry($){let Z=$.headers.get("x-should-retry");if(Z==="true")return!0;if(Z==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,X,Y){let G,z=Y?.get("retry-after-ms");if(z){let Q=parseFloat(z);if(!Number.isNaN(Q))G=Q}let J=Y?.get("retry-after");if(J&&!G){let Q=parseFloat(J);if(!Number.isNaN(Q))G=Q*1000;else G=Date.parse(J)-Date.now()}if(G===void 0){let Q=$.maxRetries??this.maxRetries;G=this.calculateDefaultRetryTimeoutMillis(Z,Q)}return await d0(G),this.makeRequest($,Z-1,X)}calculateDefaultRetryTimeoutMillis($,Z){let G=Z-$,z=Math.min(0.5*Math.pow(2,G),8),J=1-Math.random()*0.25;return z*J*1000}async buildRequest($,{retryCount:Z=0}={}){let X={...$},{method:Y,path:G,query:z,defaultBaseURL:J}=X,Q=this.buildURL(G,z,J);if("timeout"in X)PG("timeout",X.timeout);X.timeout=X.timeout??this.timeout;let{bodyHeaders:W,body:V,isStreamingBody:K}=this.buildBody({options:X});if(K)$.__metadata={...$.__metadata,hasStreamingBody:!0};let H=await this.buildHeaders({options:$,method:Y,bodyHeaders:W,retryCount:Z});return{req:{method:Y,headers:H,...X.signal&&{signal:X.signal},...globalThis.ReadableStream&&V instanceof globalThis.ReadableStream&&{duplex:"half"},...V&&{body:V},...this.fetchOptions??{},...X.fetchOptions??{}},url:Q,timeout:X.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:X,retryCount:Y}){let G={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();G[this.idempotencyHeader]=$.idempotencyKey}let z=E([G,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Y),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...CG(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders($,$.__security??{bearerAuth:!0}),this._options.defaultHeaders,X,$.headers]);return this.validateHeaders(z,$.__security??{bearerAuth:!0}),z.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:Z}}){if(!$)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let X=E([Z]),Y=typeof globalThis.ReadableStream<"u"&&$ instanceof globalThis.ReadableStream,G=!Y&&(typeof $==="string"||$ instanceof ArrayBuffer||ArrayBuffer.isView($)||typeof globalThis.Blob<"u"&&$ instanceof globalThis.Blob||$ instanceof URLSearchParams||$ instanceof FormData);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&X.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||Y)return{bodyHeaders:void 0,body:$,isStreamingBody:!G};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:A8($),isStreamingBody:!0};else if(typeof $==="object"&&X.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery($),isStreamingBody:!1};else return{...M(this,$X,"f").call(this,{body:$,headers:X}),isStreamingBody:!1}}}d5=f,$X=new WeakMap,m5=new WeakSet,Sz=function(){return this.baseURL!=="https://api.openai.com/v1"};f.OpenAI=d5;f.DEFAULT_TIMEOUT=600000;f.OpenAIError=I;f.APIError=r;f.APIConnectionError=$1;f.APIConnectionTimeoutError=Z1;f.APIUserAbortError=$0;f.NotFoundError=E4;f.ConflictError=R4;f.RateLimitError=S4;f.BadRequestError=_4;f.AuthenticationError=P4;f.InternalServerError=C4;f.PermissionDeniedError=D4;f.UnprocessableEntityError=A4;f.InvalidWebhookSignatureError=G$;f.toFile=f8;f.Completions=Q2;f.Chat=z1;f.Embeddings=V2;f.Files=K2;f.Images=T2;f.Audio=W$;f.Moderations=L2;f.Models=F2;f.FineTuning=a0;f.Graders=L1;f.VectorStores=y$;f.Webhooks=_2;f.Beta=i0;f.Batches=G2;f.Uploads=w1;f.Admin=Q1;f.Responses=b$;f.Realtime=x$;f.Conversations=T1;f.Evals=F1;f.Containers=q1;f.Skills=f$;f.Videos=O2;class c5{category="api";provider="openai";name;config;clientFactory;constructor($,Z,X){this.name=$,this.config=Z,this.clientFactory=X??(()=>new f)}async run($,Z){let{tool:X,docs:Y,requiredSources:G,discovery:z,webTools:J,mcpTools:Q}=Z;if(!this.config.model)throw Error(`API target "${this.name}" missing 'model'. API targets must declare an explicit model.`);let W=z?p1(X,z.sourceHint):E$(X,Y,G),V=this.clientFactory(),K=[];if(J?.search)K.push({type:"web_search"});if(Q?.servers)for(let[w,O]of Object.entries(Q.servers))K.push(jM(w,O));let H=K.length>0?K:void 0,B=await V.responses.create({model:this.config.model,instructions:W,input:$,temperature:this.config.temperature??0,max_output_tokens:this.config.maxTokens??4096,...H?{tools:H}:{}}),U=typeof B.output_text==="string"?B.output_text:"",F=xM(B.output);return{response:U,allResponses:U?[{type:"final",text:U}]:[],toolsUsed:F,sources:[],metadata:{model:this.config.model,category:this.category,provider:this.provider,target:this.name}}}}function jM($,Z){if(!Z.url)throw Error(`MCP server "${$}" has no url; the OpenAI hosted-MCP tool requires server_url. Stdio MCP transports are not reachable from the OpenAI API.`);let X={type:"mcp",server_label:$,server_url:Z.url,require_approval:"never"};if(Z.headers&&Object.keys(Z.headers).length>0)X.headers=Z.headers;return X}function xM($){if(!Array.isArray($))return[];let Z=new Set;for(let X of $)if(X?.type==="web_search_call")Z.add("web_search");else if(X?.type==="mcp_call"&&typeof X.server_label==="string"&&typeof X.name==="string")Z.add(`mcp__${X.server_label}__${X.name}`);return Array.from(Z)}import{query as kM}from"@anthropic-ai/claude-agent-sdk";class l5{category="cli";provider="claude-code";name;config;constructor($,Z){this.name=$,this.config=Z}async run($,Z){let{tool:X,cwd:Y,context:G,docs:z,requiredSources:J,discovery:Q,restrictBuiltinTools:W}=Z,V=[],K=[],H=Q?p1(X,Q.sourceHint):E$(X,z,J),B={cwd:Y,model:this.config.model??"sonnet",systemPrompt:H,allowedTools:G?.allowedTools??this.config.allowedTools??MX,disallowedTools:G?.disallowedTools??this.config.disallowedTools??OX,permissionMode:this.config.permissionMode??"acceptEdits",maxTurns:this.config.maxTurns??10,maxThinkingTokens:this.config.maxThinkingTokens,maxBudgetUsd:this.config.maxBudgetUsd,mcpServers:G?.mcpServers??this.config.mcpServers,settingSources:[]};if(W!==void 0)B.tools=W;let U=[],F="",T="";for await(let w of kM({prompt:$,options:B})){if(w.type==="assistant"){let O=w.message?.content;if(Array.isArray(O)){let N="";for(let _ of O){if(_.type==="text")N+=_.text;if(_.type==="tool_use"){let P=_;if(!V.includes(P.name))V.push(P.name)}}if(N){let _=U.length===0?"initial":"intermediate";U.push({type:_,text:N}),F=N}}}if(w.type==="result"){let O=w;if(O.result)T=O.result}}if(U.length>0)U[U.length-1].type="final";return{response:T||F,allResponses:U,toolsUsed:V,sources:K,metadata:{model:this.config.model??"sonnet",category:this.category,provider:this.provider,target:this.name}}}}import{randomUUID as bM}from"crypto";import{rm as fM}from"fs/promises";import{tmpdir as yM}from"os";import{join as vM}from"path";var gM="codex";class p5{category="cli";provider="codex-cli";name;config;spawnFn;readFileFn;binary;constructor($,Z,X={}){this.name=$,this.config=Z,this.spawnFn=X.spawn??dM,this.readFileFn=X.readFile??cM,this.binary=X.binary??gM}async run($,Z){let{tool:X,cwd:Y,docs:G,requiredSources:z}=Z,J=this.config.model;if(!J)throw Error(`CodexCliTarget "${this.name}" requires an explicit model. Validation should have caught this at config load.`);let W=`${E$(X,G,z)}
|
|
264
|
+
`);this.baseURL=W.baseURL,this.timeout=W.timeout??d5.DEFAULT_TIMEOUT,this.logger=W.logger??console;let V="warn";this.logLevel=V,this.logLevel=w5(W.logLevel,"ClientOptions.logLevel",this)??w5(d0("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??V,this.fetchOptions=W.fetchOptions,this.maxRetries=W.maxRetries??2,this.fetch=W.fetch??R8(),x(this,$9,kG,"f");let K=d0("OPENAI_CUSTOM_HEADERS");if(K){let H={};for(let U of K.split(`
|
|
265
|
+
`)){let B=U.indexOf(":");if(B>=0)H[U.substring(0,B).trim()]=U.substring(B+1).trim()}W.defaultHeaders=E([H,W.defaultHeaders])}if(this._options=W,J)this._workloadIdentityAuth=new N5(J,this.fetch);this.apiKey=typeof Z==="string"?Z:null,this.adminAPIKey=X,this.organization=Y,this.project=G,this.webhookSecret=z}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:Z},X={bearerAuth:!0,adminAPIKeyAuth:!0}){if($.get("authorization")||$.get("api-key"))return;if(Z.has("authorization")||Z.has("api-key"))return;if(this._workloadIdentityAuth&&X.bearerAuth)return;throw Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders($,Z={bearerAuth:!0,adminAPIKeyAuth:!0}){return E([Z.bearerAuth?await this.bearerAuth($):null,Z.adminAPIKeyAuth?await this.adminAPIKeyAuth($):null])}async bearerAuth($){if(this._workloadIdentityAuth)return E([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey==null)return;return E([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth($){if(this.adminAPIKey==null)return;return E([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery($){return dG($)}getUserAgent(){return`${this.constructor.name}/JS ${E$}`}defaultIdempotencyKey(){return`stainless-node-retry-${J5()}`}makeStatusError($,Z,X,Y){return r.generate($,Z,X,Y)}async _callApiKey(){let $=this._options.apiKey;if(typeof $!=="function")return!1;let Z;try{Z=await $()}catch(X){if(X instanceof I)throw X;throw new I(`Failed to get token from 'apiKey' function: ${X.message}`,{cause:X})}if(typeof Z!=="string"||!Z)throw new I(`Expected 'apiKey' function argument to return a string but it returned ${Z}`);return this.apiKey=Z,!0}buildURL($,Z,X){let Y=!w(this,m5,"m",Iz).call(this)&&X||this.baseURL,G=PG($)?new URL($):new URL(Y+(Y.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),z=this.defaultQuery(),J=Object.fromEntries(G.searchParams);if(!W5(z)||!W5(J))Z={...J,...z,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))G.search=this.stringifyQuery(Z);return G.toString()}async prepareOptions($){if(($.__security??{bearerAuth:!0}).bearerAuth)await this._callApiKey()}async prepareRequest($,{url:Z,options:X}){}get($,Z){return this.methodRequest("get",$,Z)}post($,Z){return this.methodRequest("post",$,Z)}patch($,Z){return this.methodRequest("patch",$,Z)}put($,Z){return this.methodRequest("put",$,Z)}delete($,Z){return this.methodRequest("delete",$,Z)}methodRequest($,Z,X){return this.request(Promise.resolve(X).then((Y)=>{return{method:$,path:Z,...Y}}))}request($,Z=null){return new t$(this,this.makeRequest($,Z,void 0))}async makeRequest($,Z,X){let Y=await $,G=Y.maxRetries??this.maxRetries;if(Z==null)Z=G;await this.prepareOptions(Y);let{req:z,url:J,timeout:Q}=await this.buildRequest(Y,{retryCount:G-Z});await this.prepareRequest(z,{url:J,options:Y});let W="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),V=X===void 0?"":`, retryOf: ${X}`,K=Date.now();if(s(this).debug(`[${W}] sending request`,G$({retryOfRequestLogID:X,method:Y.method,url:J,options:Y,headers:z.headers})),Y.signal?.aborted)throw new Z0;let H=Y.__security??{bearerAuth:!0},U=new AbortController,B=await this.fetchWithAuth(J,z,Q,U,H).catch(O4),T=Date.now();if(B instanceof globalThis.Error){let O=`retrying, ${Z} attempts remaining`;if(Y.signal?.aborted)throw new Z0;let N=w4(B)||/timed? ?out/i.test(String(B)+("cause"in B?String(B.cause):""));if(Z)return s(this).info(`[${W}] connection ${N?"timed out":"failed"} - ${O}`),s(this).debug(`[${W}] connection ${N?"timed out":"failed"} (${O})`,G$({retryOfRequestLogID:X,url:J,durationMs:T-K,message:B.message})),this.retryRequest(Y,Z,X??W);if(s(this).info(`[${W}] connection ${N?"timed out":"failed"} - error; no more retries left`),s(this).debug(`[${W}] connection ${N?"timed out":"failed"} (error; no more retries left)`,G$({retryOfRequestLogID:X,url:J,durationMs:T-K,message:B.message})),B instanceof c1||B instanceof D8)throw B;if(N)throw new o$;throw new s$({cause:B})}let F=[...B.headers.entries()].filter(([O])=>O==="x-request-id").map(([O,N])=>", "+O+": "+JSON.stringify(N)).join(""),M=`[${W}${V}${F}] ${z.method} ${J} ${B.ok?"succeeded":"failed"} with status ${B.status} in ${T-K}ms`;if(!B.ok){if(B.status===401&&this._workloadIdentityAuth&&H.bearerAuth&&!Y.__metadata?.hasStreamingBody&&!Y.__metadata?.workloadIdentityTokenRefreshed)return await K5(B.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...Y,__metadata:{...Y.__metadata,workloadIdentityTokenRefreshed:!0}},Z,X??W);let O=await this.shouldRetry(B);if(Z&&O){let S=`retrying, ${Z} attempts remaining`;return await K5(B.body),s(this).info(`${M} - ${S}`),s(this).debug(`[${W}] response error (${S})`,G$({retryOfRequestLogID:X,url:B.url,status:B.status,headers:B.headers,durationMs:T-K})),this.retryRequest(Y,Z,X??W,B.headers)}let N=O?"error; no more retries left":"error; not retryable";s(this).info(`${M} - ${N}`);let _=await B.text().catch((S)=>O4(S).message),P=RG(_),R=P?void 0:_;throw s(this).debug(`[${W}] response error (${N})`,G$({retryOfRequestLogID:X,url:B.url,status:B.status,headers:B.headers,message:R,durationMs:Date.now()-K})),this.makeStatusError(B.status,P,R,B.headers)}return s(this).info(M),s(this).debug(`[${W}] response start`,G$({retryOfRequestLogID:X,url:B.url,status:B.status,headers:B.headers,durationMs:T-K})),{response:B,options:Y,controller:U,requestLogID:W,retryOfRequestLogID:X,startTime:K}}getAPIList($,Z,X){return this.requestAPIList(Z,X&&"then"in X?X.then((Y)=>({method:"get",path:$,...Y})):{method:"get",path:$,...X})}requestAPIList($,Z){let X=this.makeRequest(Z,null,void 0);return new k8(this,X,$)}async fetchWithAuth($,Z,X,Y,G={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&G.bearerAuth){let J=Z.headers,Q=J.get("Authorization");if(!Q||Q===`Bearer ${kw}`){let W=await this._workloadIdentityAuth.getToken();J.set("Authorization",`Bearer ${W}`)}}return await this.fetchWithTimeout($,Z,X,Y)}async fetchWithTimeout($,Z,X,Y){let{signal:G,method:z,...J}=Z||{},Q=this._makeAbort(Y);if(G)G.addEventListener("abort",Q,{once:!0});let W=setTimeout(Q,X),V=globalThis.ReadableStream&&J.body instanceof globalThis.ReadableStream||typeof J.body==="object"&&J.body!==null&&Symbol.asyncIterator in J.body,K={signal:Y.signal,...V?{duplex:"half"}:{},method:"GET",...J};if(z)K.method=z.toUpperCase();try{return await this.fetch.call(void 0,$,K)}finally{clearTimeout(W)}}async shouldRetry($){let Z=$.headers.get("x-should-retry");if(Z==="true")return!0;if(Z==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,X,Y){let G,z=Y?.get("retry-after-ms");if(z){let Q=parseFloat(z);if(!Number.isNaN(Q))G=Q}let J=Y?.get("retry-after");if(J&&!G){let Q=parseFloat(J);if(!Number.isNaN(Q))G=Q*1000;else G=Date.parse(J)-Date.now()}if(G===void 0){let Q=$.maxRetries??this.maxRetries;G=this.calculateDefaultRetryTimeoutMillis(Z,Q)}return await u0(G),this.makeRequest($,Z-1,X)}calculateDefaultRetryTimeoutMillis($,Z){let G=Z-$,z=Math.min(0.5*Math.pow(2,G),8),J=1-Math.random()*0.25;return z*J*1000}async buildRequest($,{retryCount:Z=0}={}){let X={...$},{method:Y,path:G,query:z,defaultBaseURL:J}=X,Q=this.buildURL(G,z,J);if("timeout"in X)EG("timeout",X.timeout);X.timeout=X.timeout??this.timeout;let{bodyHeaders:W,body:V,isStreamingBody:K}=this.buildBody({options:X});if(K)$.__metadata={...$.__metadata,hasStreamingBody:!0};let H=await this.buildHeaders({options:$,method:Y,bodyHeaders:W,retryCount:Z});return{req:{method:Y,headers:H,...X.signal&&{signal:X.signal},...globalThis.ReadableStream&&V instanceof globalThis.ReadableStream&&{duplex:"half"},...V&&{body:V},...this.fetchOptions??{},...X.fetchOptions??{}},url:Q,timeout:X.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:X,retryCount:Y}){let G={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();G[this.idempotencyHeader]=$.idempotencyKey}let z=E([G,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Y),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...jG(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders($,$.__security??{bearerAuth:!0}),this._options.defaultHeaders,X,$.headers]);return this.validateHeaders(z,$.__security??{bearerAuth:!0}),z.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:Z}}){if(!$)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let X=E([Z]),Y=typeof globalThis.ReadableStream<"u"&&$ instanceof globalThis.ReadableStream,G=!Y&&(typeof $==="string"||$ instanceof ArrayBuffer||ArrayBuffer.isView($)||typeof globalThis.Blob<"u"&&$ instanceof globalThis.Blob||$ instanceof URLSearchParams||$ instanceof FormData);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&X.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||Y)return{bodyHeaders:void 0,body:$,isStreamingBody:!G};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:A8($),isStreamingBody:!0};else if(typeof $==="object"&&X.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery($),isStreamingBody:!1};else return{...w(this,$9,"f").call(this,{body:$,headers:X}),isStreamingBody:!1}}}d5=f,$9=new WeakMap,m5=new WeakSet,Iz=function(){return this.baseURL!=="https://api.openai.com/v1"};f.OpenAI=d5;f.DEFAULT_TIMEOUT=600000;f.OpenAIError=I;f.APIError=r;f.APIConnectionError=s$;f.APIConnectionTimeoutError=o$;f.APIUserAbortError=Z0;f.NotFoundError=D4;f.ConflictError=E4;f.RateLimitError=A4;f.BadRequestError=N4;f.AuthenticationError=_4;f.InternalServerError=S4;f.PermissionDeniedError=P4;f.UnprocessableEntityError=R4;f.InvalidWebhookSignatureError=Y$;f.toFile=f8;f.Completions=G2;f.Chat=Z1;f.Embeddings=J2;f.Files=W2;f.Images=U2;f.Audio=Q$;f.Moderations=q2;f.Models=B2;f.FineTuning=p0;f.Graders=B1;f.VectorStores=f$;f.Webhooks=w2;f.Beta=l0;f.Batches=Z2;f.Uploads=q1;f.Admin=Y1;f.Responses=k$;f.Realtime=j$;f.Conversations=K1;f.Evals=U1;f.Containers=H1;f.Skills=b$;f.Videos=L2;class c5{category="api";provider="openai";name;config;clientFactory;constructor($,Z,X){this.name=$,this.config=Z,this.clientFactory=X??(()=>new f)}async run($,Z){let{tool:X,docs:Y,requiredSources:G,discovery:z,webTools:J,mcpTools:Q}=Z;if(!this.config.model)throw Error(`API target "${this.name}" missing 'model'. API targets must declare an explicit model.`);let W=z?d1(X,z.sourceHint):D$(X,Y,G),V=this.clientFactory(),K=[];if(J?.search)K.push({type:"web_search"});if(Q?.servers)for(let[M,O]of Object.entries(Q.servers))K.push(bw(M,O));let H=K.length>0?K:void 0,U=await V.responses.create({model:this.config.model,instructions:W,input:$,temperature:this.config.temperature??0,max_output_tokens:this.config.maxTokens??4096,...H?{tools:H}:{}}),B=typeof U.output_text==="string"?U.output_text:"",T=fw(U.output);return{response:B,allResponses:B?[{type:"final",text:B}]:[],toolsUsed:T,sources:[],metadata:{model:this.config.model,category:this.category,provider:this.provider,target:this.name}}}}function bw($,Z){if(!Z.url)throw Error(`MCP server "${$}" has no url; the OpenAI hosted-MCP tool requires server_url. Stdio MCP transports are not reachable from the OpenAI API.`);let X={type:"mcp",server_label:$,server_url:Z.url,require_approval:"never"};if(Z.headers&&Object.keys(Z.headers).length>0)X.headers=Z.headers;return X}function fw($){if(!Array.isArray($))return[];let Z=new Set;for(let X of $)if(X?.type==="web_search_call")Z.add("web_search");else if(X?.type==="mcp_call"&&typeof X.server_label==="string"&&typeof X.name==="string")Z.add(`mcp__${X.server_label}__${X.name}`);return Array.from(Z)}import{query as yw}from"@anthropic-ai/claude-agent-sdk";class l5{category="cli";provider="claude-code";name;config;constructor($,Z){this.name=$,this.config=Z}async run($,Z){let{tool:X,cwd:Y,context:G,docs:z,requiredSources:J,discovery:Q,restrictBuiltinTools:W}=Z,V=[],K=[],H=Q?d1(X,Q.sourceHint):D$(X,z,J),U={cwd:Y,model:this.config.model??"sonnet",systemPrompt:H,allowedTools:G?.allowedTools??this.config.allowedTools??w9,disallowedTools:G?.disallowedTools??this.config.disallowedTools??O9,permissionMode:this.config.permissionMode??"acceptEdits",maxTurns:this.config.maxTurns??10,maxThinkingTokens:this.config.maxThinkingTokens,maxBudgetUsd:this.config.maxBudgetUsd,mcpServers:G?.mcpServers??this.config.mcpServers,settingSources:[]};if(W!==void 0)U.tools=W;let B=[],T="",F="";for await(let M of yw({prompt:$,options:U})){if(M.type==="assistant"){let O=M.message?.content;if(Array.isArray(O)){let N="";for(let _ of O){if(_.type==="text")N+=_.text;if(_.type==="tool_use"){let P=_;if(!V.includes(P.name))V.push(P.name)}}if(N){let _=B.length===0?"initial":"intermediate";B.push({type:_,text:N}),T=N}}}if(M.type==="result"){let O=M;if(O.result)F=O.result}}if(B.length>0)B[B.length-1].type="final";return{response:F||T,allResponses:B,toolsUsed:V,sources:K,metadata:{model:this.config.model??"sonnet",category:this.category,provider:this.provider,target:this.name}}}}import{randomUUID as vw}from"crypto";import{rm as gw}from"fs/promises";import{tmpdir as hw}from"os";import{join as uw}from"path";var mw="codex";class p5{category="cli";provider="codex-cli";name;config;spawnFn;readFileFn;binary;constructor($,Z,X={}){this.name=$,this.config=Z,this.spawnFn=X.spawn??pw,this.readFileFn=X.readFile??iw,this.binary=X.binary??mw}async run($,Z){let{tool:X,cwd:Y,docs:G,requiredSources:z}=Z,J=this.config.model;if(!J)throw Error(`CodexCliTarget "${this.name}" requires an explicit model. Validation should have caught this at config load.`);let W=`${D$(X,G,z)}
|
|
265
266
|
|
|
266
267
|
---
|
|
267
268
|
|
|
268
|
-
${$}`,V=
|
|
269
|
-
`)){let G=Y.trim();if(!G)continue;let z;try{z=JSON.parse(G)}catch{continue}let J=uM(z);if(J){let W=Z.length===0?"initial":"intermediate";Z.push({type:W,text:J})}let Q=mM(z);if(Q&&!X.includes(Q))X.push(Q)}return{allResponses:Z,toolsUsed:X}}function uM($){if(!$||typeof $!=="object")return null;let Z=$;if(typeof Z.message==="string")return Z.message;if(typeof Z.content==="string")return Z.content;if(typeof Z.type==="string"&&(Z.type==="assistant_message"||Z.type==="agent_message")&&typeof Z.text==="string")return Z.text;if(Z.type==="message"&&typeof Z.text==="string")return Z.text;return null}function mM($){if(!$||typeof $!=="object")return null;let Z=$;if(typeof Z.tool==="string")return Z.tool;if(typeof Z.type==="string"&&(Z.type==="tool_call"||Z.type==="function_call")&&typeof Z.name==="string")return Z.name;return null}var dM=async($,Z,X)=>{let Y=Bun.spawn([$,...Z],{cwd:X.cwd,stdin:"pipe",stdout:"pipe",stderr:"pipe"});Y.stdin.write(X.stdin),await Y.stdin.end();let[G,z,J]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text(),Y.exited]);return{exitCode:J,stdout:G,stderr:z}},cM=async($)=>{let Z=Bun.file($);if(!await Z.exists())throw Error(`Last-message file not found: ${$}`);return Z.text()};function ZX($,Z){let X=Z??h0;switch(X.category){case"cli":return lM($,X);case"api":return pM($,X);case"ide":throw Error("IDE targets not yet implemented. Coming soon!");default:throw Error(`Unknown target category: ${X.category}`)}}function lM($,Z){switch(Z.provider){case"claude-code":return new l5($,Z);case"codex-cli":return new p5($,Z);case"amazon-q":throw Error("Amazon Q target not yet implemented. Coming soon!");default:throw Error(`Unknown CLI provider: ${Z.provider}`)}}function pM($,Z){switch(Z.provider){case"anthropic":return new z5($,Z);case"openai":return new c5($,Z);case"google":throw Error("Google API target not yet implemented. Coming soon!");default:throw Error(`Unknown API provider: ${Z.provider}`)}}var P2="default";function XX($,Z){if(!$||$===P2)return{name:P2,config:h0};if(Z?.[$])return{name:$,config:Z[$]};return console.warn(`Target "${$}" not found, using default`),{name:P2,config:h0}}function i5($,Z){if(!$||$===P2)return{name:P2,config:{}};if(Z?.[$])return{name:$,config:Z[$]};return console.warn(`Context "${$}" not found, using default`),{name:P2,config:{}}}var YX="__matrix__";function iM($){let Z=[],X=$.matrix?.target??["default"],Y=$.matrix?.context??["default"];for(let G of $.scenarios){let z=G.context?[G.context]:Y;if(G.matrix){for(let Q of z)Z.push({scenario:G,targetName:YX,contextName:Q});continue}let J=G.target?[G.target]:X;for(let Q of J)for(let W of z)Z.push({scenario:G,targetName:Q,contextName:W})}return Z}function aM($,Z,X){let Y=[];for(let{scenario:G,targetName:z,contextName:J}of $)if(G.matrix&&z===YX){let Q=G.matrix,W=G.target??"default",V=Q.interfaces??[W],K=Q.sources??[null],H=Q.toolsets??["none"];for(let B of V){if(X.interface&&X.interface!==B)continue;for(let U of K){if(X.source!==void 0&&X.source!==(U??""))continue;for(let F of H){if(X.toolset&&X.toolset!==F)continue;Y.push({scenario:G.name,kind:"matrix",interface:B,source:U,toolset:F})}}}}else Y.push({scenario:G.name,kind:"single",target:z,context:J});return Y}function a5($){if($.kind==="matrix")return`m:${$.scenario}\x01${$.interface}\x01${$.source??""}\x01${$.toolset}`;return`s:${$.scenario}\x01${$.target}\x01${$.context}`}function nM($){let{tool:Z,docs:X,expandedCells:Y,selectedCells:G,seed:z}=$;return{tool:{name:Z.name,description:Z.description,path:Z.path},docs:X,scenarios:[],summary:{total:0,answered:0,unanswered:0,score:0},plan:{expandedCells:Y,selectedCells:G.length,seed:z,cells:G.map((J)=>J.kind==="matrix"?{scenario:J.scenario,interface:J.interface,source:J.source,toolset:J.toolset}:{scenario:J.scenario,target:J.target,context:J.context})}}}async function n5($,Z,X={}){let{onProgress:Y}=X,G=[];if(Z.scenarios.length===0)throw Error("No scenarios defined in config");let z=Z.docs?.sources??{},J=[];if(Object.keys(z).length>0){Y?.("Loading sources..."),J=await Z4(z,$.path);for(let w of J)Y?.(` [${w.id}] ${w.name}`);Y?.("")}let Q=J.map((w)=>w.id),W=iM(Z);if(X.scenarioFilter&&X.scenarioFilter.length>0){let w=new Set(X.scenarioFilter);if(W=W.filter((O)=>w.has(O.scenario.name)),W.length===0)throw Error(`No scenarios matched filter: ${[...w].join(", ")}. Declared scenarios: ${Z.scenarios.map((O)=>O.name).join(", ")}`)}let V=X.cellFilter??{},K=aM(W,Z,V),H=K,B;if(X.sample!==void 0){let w=X.seed??"default",O=K.filter((P)=>P.kind==="matrix"),N=dY(O,X.sample,w),_=new Set(N.map(a5));H=K.filter((P)=>P.kind!=="matrix"||_.has(a5(P))),B=w}if(X.maxCells!==void 0&&H.length>X.maxCells)throw Error(`Matrix expands to ${H.length} cells, exceeding --max-cells ${X.maxCells}. Add --interface/--source/--toolset/--scenario filters, or pass --sample N to sample per scenario.`);if(X.plan)return nM({tool:$,docs:J,expandedCells:K.length,selectedCells:H,seed:B});let U=X.sample!==void 0?new Set(H.filter((w)=>w.kind==="matrix").map(a5)):void 0,F="";for(let{scenario:w,targetName:O,contextName:N}of W){let _=rM(O,N);if(w.name!==F){if(F)Y?.("");Y?.(`"${w.name}"`),F=w.name}try{let P=await sM(w,O,N,$,Z,J,Q,X,U);G.push(P);let R=_?_.padEnd(18):"";if(P.cells){Y?.(` ${R} (matrix mode)`);for(let A of P.cells){let S=e0(A),k=` [${[A.cell.interface,A.cell.source??"-",A.cell.toolset].join(" \xB7 ")}]`.padEnd(40);Y?.(`${k} ${S.icon} ${S.label} (${S.confidence}%)`)}}else if(P.surfaces){Y?.(` ${R} (compare-surfaces mode)`);for(let A of P.surfaces){let S=e0(A),D=` [${A.active.join(",")}]`.padEnd(22);Y?.(`${D} ${S.icon} ${S.label} (${S.confidence}%)`)}}else{let A=e0({answerable:P.answerable??"NO",confidence:P.confidence??0,traps:P.traps??{fired:[],avoided:[]},error:P.error});Y?.(` ${R} ${A.icon} ${A.label} (${A.confidence}%)`)}}catch(P){let R=O==="default"?h0:Z.targets?.[O]??h0,A=w.requiredSources??[],S={scenario:w,answerable:"NO",confidence:0,response:"",reason:"Error during run",citations:{cited:[],required:A,missing:A,unknown:[]},traps:{fired:[],avoided:(w.traps??[]).map((k)=>k.id)},error:P instanceof Error?P.message:String(P),target:{target:O===YX?"matrix":O,category:R.category,provider:R.provider,model:R.model??"unknown"},context:{name:N}};G.push(S);let D=_?_.padEnd(18):"";Y?.(` ${D} \u2717 Error`)}}Y?.("");let T=oM($,J,G);return T.plan={expandedCells:K.length,selectedCells:H.length,seed:B},T}function rM($,Z){if($==="default"&&Z==="default")return"";if(Z==="default")return`[${$}]`;return`[${$}/${Z}]`}async function sM($,Z,X,Y,G,z,J,Q,W){if($.matrix&&Z===YX)return tM($,X,Y,G,z,Q,W);let{config:V}=XX(Z,G.targets),{config:K}=i5(X,G.contexts),H=Q.targetFactory?Q.targetFactory(Z,V):ZX(Z,V);if($.compareSurfaces&&$.compareSurfaces.length>0){let R=[],A;for(let S of $.compareSurfaces){let D=new Set(S),k=z.filter((V$)=>D.has(V$.id)),i=($.requiredSources??[]).filter((V$)=>D.has(V$)),c=await H.run($.prompt,{tool:Y,cwd:Y.path,context:K,docs:k,requiredSources:i,onProgress:Q.onProgress}),M0=b1({response:c.response,requiredSources:i,registeredIds:S}),v$=O$({response:c.response,traps:$.traps??[]}),N0=v$.fired.length>0,aZ=N0?"NO":M0.answerable,WX=N0?0:M0.confidence,nZ=N0?`Trap fired: ${v$.fired.map((V$)=>`"${V$.id}" (${V$.reason})`).join("; ")}`:M0.reason;R.push({active:S,answerable:aZ,confidence:WX,response:c.response,reason:nZ,citations:M0.citations,traps:v$,allResponses:c.allResponses}),A=c.metadata??A}return{scenario:$,answerable:null,confidence:null,response:null,reason:null,citations:null,traps:null,surfaces:R,target:A,context:{name:X}}}let B=$.requiredSources??[],U=await H.run($.prompt,{tool:Y,cwd:Y.path,context:K,docs:z,requiredSources:B,onProgress:Q.onProgress}),F=O$({response:U.response,traps:$.traps??[]}),T=F.fired.length>0,w=$.requiredSources!==void 0?b1({response:U.response,requiredSources:B,registeredIds:J}):null,O=$.expected!==void 0?n6({response:U.response,expected:$.expected}):null,N,_,P;if(T)N="NO",_=0,P=`Trap fired: ${F.fired.map((R)=>`"${R.id}" (${R.reason})`).join("; ")}`;else{let R=[],A=[];if(w)R.push({answerable:w.answerable,confidence:w.confidence}),A.push(w.reason);if(O){let S=O.total===0?100:Math.round(O.satisfied/O.total*100),D=S===100?"YES":S===0?"NO":"PARTIAL";R.push({answerable:D,confidence:S})}if(R.length===0)N="YES",_=100,P="No traps fired; no other contract declared";else{let S={YES:0,PARTIAL:1,NO:2};N=R.reduce((k,b)=>S[b.answerable]>S[k.answerable]?b:k).answerable,_=Math.round(R.reduce((k,b)=>k+b.confidence,0)/R.length),P=A.filter((k)=>k.length>0).join(" | ")}}return{scenario:$,answerable:N,confidence:_,response:U.response,reason:P,citations:w?w.citations:{cited:[],required:B,missing:[],unknown:[]},traps:F,target:U.metadata,context:{name:X},toolsUsed:U.toolsUsed,sources:U.sources,allResponses:U.allResponses}}function oM($,Z,X){let Y=[];for(let Q of X){if(Q.surfaces){for(let W of Q.surfaces)Y.push({answerable:W.answerable,confidence:W.confidence});continue}if(Q.cells){for(let W of Q.cells)Y.push({answerable:W.answerable,confidence:W.confidence});continue}if(Q.answerable!==null&&Q.confidence!==null)Y.push({answerable:Q.answerable,confidence:Q.confidence})}let G=Y.length,z=Y.filter((Q)=>Q.answerable==="YES"||Q.answerable==="PARTIAL").length,J=G>0?Math.round(Y.reduce((Q,W)=>{if(W.answerable==="YES")return Q+W.confidence;if(W.answerable==="PARTIAL")return Q+W.confidence*0.5;return Q},0)/G):0;return{tool:{name:$.name,description:$.description,path:$.path},docs:Z,scenarios:X,summary:{total:G,answered:z,unanswered:G-z,score:J}}}async function tM($,Z,X,Y,G,z,J){let{config:Q}=i5(Z,Y.contexts),W=$.matrix??{},V=$.target??"default",K=W.interfaces??[V],H=W.sources??[null],B=W.toolsets??["none"],U=z.cellFilter??{},F=[],T;for(let O of K){if(U.interface&&U.interface!==O)continue;for(let N of H){if(U.source!==void 0&&U.source!==(N??""))continue;for(let _ of B){if(U.toolset&&U.toolset!==_)continue;if(J!==void 0){let g=`m:${$.name}\x01${O}\x01${N??""}\x01${_}`;if(!J.has(g))continue}let P=_==="none"?null:Y.toolsets?.[_]??null,R=_!=="none"&&(P?.webSearch===!0||P?.webFetch===!0),A=_!=="none"&&P?.mcpServers?Object.keys(P.mcpServers):[],S=A.length>0,{config:D}=XX(O,Y.targets);if(_!=="none"){if(R&&S)throw Error(`Toolset "${_}" mixes webSearch/webFetch with mcpServers; declare separate toolsets per shape so provenance can be attributed to one tool path.`);if(!R&&!S)throw Error(`Toolset "${_}" is declared but defines no runtime shape. Supported today: "none", web (webSearch/webFetch flags), MCP (mcpServers map). Other adapters (Firecrawl, native API search) land per release.`);if(S&&D.provider!=="claude-code"&&D.provider!=="openai")throw Error(`Toolset "${_}" (MCP) is implemented on claude-code and openai interfaces today. Interface "${O}" uses provider "${D.provider}"; rerun with a supported interface or use toolset "none".`);if(R&&D.provider!=="claude-code"&&D.provider!=="anthropic"&&D.provider!=="openai")throw Error(`Toolset "${_}" (web) is implemented on claude-code, anthropic, and openai interfaces today. Interface "${O}" uses provider "${D.provider}"; rerun with a supported interface or use toolset "none".`);if(R&&(D.provider==="anthropic"||D.provider==="openai")&&!P?.webSearch)throw Error(`Toolset "${_}" on ${D.provider} provider requires webSearch: true. The ${D.provider} API exposes a single server-side web tool; declare webSearch to enable it, or split web/fetch behaviour across separate toolsets.`)}let k=[],b=[],i=[],c=D.provider==="anthropic"||D.provider==="openai";if(R)if(c)i.push((g)=>g==="web_search");else{if(P?.webSearch)k.push("WebSearch"),b.push("WebSearch"),i.push((g)=>g==="WebSearch");if(P?.webFetch)k.push("WebFetch"),b.push("WebFetch"),i.push((g)=>g==="WebFetch")}if(S)for(let g of A)k.push(`mcp__${g}__*`),i.push((z0)=>z0.startsWith(`mcp__${g}__`));let M0=_==="none"||c?D:{...D,allowedTools:k,disallowedTools:[],mcpServers:S?P?.mcpServers:void 0,maxTurns:Math.max(D.maxTurns??0,15)},v$=z.targetFactory?z.targetFactory(O,M0):ZX(O,M0),N0=_==="none",aZ=N==="none",WX=aZ||!N0?[]:N===null?G:G.filter((g)=>g.id===N),nZ=aZ||!N0?[]:N===null?G.map((g)=>g.id):[N],V$=$.requiredSources??[],G3=N0?V$.filter((g)=>nZ.includes(g)):[],sz=$O($.prompt,N,G,N0),oz=N0?void 0:{sourceHint:ZO(N,G)},n0;try{let g=_==="none"?Q:void 0;n0=await v$.run(sz,{tool:X,cwd:X.path,context:g,docs:WX,requiredSources:G3,discovery:oz,restrictBuiltinTools:_==="none"?void 0:b,webTools:R&&c?{search:P?.webSearch===!0}:void 0,mcpTools:S&&D.provider==="openai"&&P?.mcpServers?{servers:P.mcpServers}:void 0,onProgress:z.onProgress})}catch(g){F.push({cell:{interface:O,source:N,toolset:_},answerable:"NO",confidence:0,response:"",reason:`Error in cell: ${g instanceof Error?g.message:String(g)}`,citations:null,traps:{fired:[],avoided:($.traps??[]).map((z0)=>z0.id)},error:g instanceof Error?g.message:String(g)});continue}let VX=O$({response:n0.response,traps:$.traps??[]}),tz=VX.fired.length>0,H$=$.requiredSources!==void 0&&N0?b1({response:n0.response,requiredSources:G3,registeredIds:nZ}):null,G0=$.expected!==void 0?n6({response:n0.response,expected:$.expected}):null,R2=_!=="none"&&i.length>0?{expected:k,used:(n0.toolsUsed??[]).filter((g)=>i.some((z0)=>z0(g)))}:null,ez=R2!==null&&R2.used.length===0,$J=()=>{let g=[];if(H$)g.push(H$.reason);if(G0){let z0=G0.includes.filter((Q0)=>!Q0.satisfied).map((Q0)=>`"${Q0.value}"`),S0=G0.excludes.filter((Q0)=>!Q0.satisfied).map((Q0)=>`"${Q0.value}"`),g$=[];if(z0.length>0)g$.push(`missing includes: ${z0.join(", ")}`);if(S0.length>0)g$.push(`hit excludes: ${S0.join(", ")}`);g.push(g$.length>0?g$.join("; "):`expected checks satisfied (${G0.satisfied}/${G0.total})`)}return g.filter((z0)=>z0.length>0)},A2,S2,C2;if(tz)A2="NO",S2=0,C2=`Trap fired: ${VX.fired.map((g)=>`"${g.id}" (${g.reason})`).join("; ")}`;else if(ez){let g=R2;A2="NO",S2=0;let z0=`Provenance failed: toolset "${_}" configured but none of [${g.expected.join(", ")}] were used (answer rests on model prior knowledge)`,S0=$J();C2=S0.length>0?`${z0} | ${S0.join(" | ")}`:z0}else{let g=[],z0=[];if(H$)g.push({answerable:H$.answerable,confidence:H$.confidence}),z0.push(H$.reason);if(G0){let S0=G0.total===0?100:Math.round(G0.satisfied/G0.total*100),g$=S0===100?"YES":S0===0?"NO":"PARTIAL";g.push({answerable:g$,confidence:S0});let Q0=G0.includes.filter((u$)=>!u$.satisfied).map((u$)=>`"${u$.value}"`),h$=G0.excludes.filter((u$)=>!u$.satisfied).map((u$)=>`"${u$.value}"`),rZ=[];if(Q0.length>0)rZ.push(`missing includes: ${Q0.join(", ")}`);if(h$.length>0)rZ.push(`hit excludes: ${h$.join(", ")}`);z0.push(rZ.length>0?rZ.join("; "):`expected checks satisfied (${G0.satisfied}/${G0.total})`)}if(R2)z0.push(`tool use verified (${R2.used.join(", ")})`);if(g.length===0)A2="YES",S2=100,C2="No traps fired; no other contract declared";else{let S0={YES:0,PARTIAL:1,NO:2};A2=g.reduce((Q0,h$)=>S0[h$.answerable]>S0[Q0.answerable]?h$:Q0).answerable,S2=Math.round(g.reduce((Q0,h$)=>Q0+h$.confidence,0)/g.length),C2=z0.filter((Q0)=>Q0.length>0).join(" | ")}}F.push({cell:{interface:O,source:N,toolset:_},answerable:A2,confidence:S2,response:n0.response,reason:C2,citations:H$?H$.citations:null,traps:VX,expected:G0?{includes:G0.includes,excludes:G0.excludes,satisfied:G0.satisfied,total:G0.total}:void 0,toolsUsed:n0.toolsUsed,allResponses:n0.allResponses}),T=n0.metadata??T}}}let w=eM($,G);return{scenario:$,answerable:null,confidence:null,response:null,reason:null,citations:null,traps:null,cells:F,verifierSamples:w,target:T,context:{name:Z}}}function eM($,Z){let X=$.verifiers?.sources;if(!X||X.length===0)return;let Y=new Map(Z.map((z)=>[z.id,z])),G=[];for(let z of X){let J=Y.get(z);if(!J)continue;G.push({id:J.id,name:J.name,content:J.content})}return G.length>0?G:void 0}function $O($,Z,X,Y){if(Y)return $;if(Z===null||Z==="none")return $;let G=X.find((J)=>J.id===Z);if(!G)return $;let z=G.type==="url"?`The canonical source for this question is the documentation at ${G.source}. Use your available tools to research it.`:`The canonical source for this question is "${G.name}" (registered locally as ${G.id}). Use your available tools to research from authoritative sources.`;return`${$}
|
|
269
|
+
${$}`,V=uw(hw(),`pickled-codex-${vw()}.txt`),K=["--ask-for-approval","never","exec","--json","--sandbox","read-only","--ignore-user-config","--ignore-rules","--ephemeral","--skip-git-repo-check","--cd",Y,"--model",J,"--output-last-message",V,"-"];try{let H=await this.spawnFn(this.binary,K,{cwd:Y,stdin:W}),{allResponses:U,toolsUsed:B}=dw(H.stdout);if(H.exitCode!==0)throw Error(`codex exec failed (exit ${H.exitCode}): ${H.stderr.trim()||"no stderr output"}`);let T="";try{T=(await this.readFileFn(V)).trim()}catch{T=U.length>0?U[U.length-1].text:""}if(U.length>0)U[U.length-1].type="final";return{response:T,allResponses:U,toolsUsed:B,sources:[],metadata:{model:J,category:this.category,provider:this.provider,target:this.name}}}finally{await gw(V,{force:!0})}}}function dw($){let Z=[],X=[];for(let Y of $.split(`
|
|
270
|
+
`)){let G=Y.trim();if(!G)continue;let z;try{z=JSON.parse(G)}catch{continue}let J=cw(z);if(J){let W=Z.length===0?"initial":"intermediate";Z.push({type:W,text:J})}let Q=lw(z);if(Q&&!X.includes(Q))X.push(Q)}return{allResponses:Z,toolsUsed:X}}function cw($){if(!$||typeof $!=="object")return null;let Z=$;if(typeof Z.message==="string")return Z.message;if(typeof Z.content==="string")return Z.content;if(typeof Z.type==="string"&&(Z.type==="assistant_message"||Z.type==="agent_message")&&typeof Z.text==="string")return Z.text;if(Z.type==="message"&&typeof Z.text==="string")return Z.text;return null}function lw($){if(!$||typeof $!=="object")return null;let Z=$;if(typeof Z.tool==="string")return Z.tool;if(typeof Z.type==="string"&&(Z.type==="tool_call"||Z.type==="function_call")&&typeof Z.name==="string")return Z.name;return null}var pw=async($,Z,X)=>{let Y=Bun.spawn([$,...Z],{cwd:X.cwd,stdin:"pipe",stdout:"pipe",stderr:"pipe"});Y.stdin.write(X.stdin),await Y.stdin.end();let[G,z,J]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text(),Y.exited]);return{exitCode:J,stdout:G,stderr:z}},iw=async($)=>{let Z=Bun.file($);if(!await Z.exists())throw Error(`Last-message file not found: ${$}`);return Z.text()};function Z9($,Z){let X=Z??v0;switch(X.category){case"cli":return aw($,X);case"api":return nw($,X);case"ide":throw Error("IDE targets not yet implemented. Coming soon!");default:throw Error(`Unknown target category: ${X.category}`)}}function aw($,Z){switch(Z.provider){case"claude-code":return new l5($,Z);case"codex-cli":return new p5($,Z);case"amazon-q":throw Error("Amazon Q target not yet implemented. Coming soon!");default:throw Error(`Unknown CLI provider: ${Z.provider}`)}}function nw($,Z){switch(Z.provider){case"anthropic":return new z5($,Z);case"openai":return new c5($,Z);case"google":throw Error("Google API target not yet implemented. Coming soon!");default:throw Error(`Unknown API provider: ${Z.provider}`)}}var O2="default";function X9($,Z){if(!$||$===O2)return{name:O2,config:v0};if(Z?.[$])return{name:$,config:Z[$]};return console.warn(`Target "${$}" not found, using default`),{name:O2,config:v0}}function i5($,Z){if(!$||$===O2)return{name:O2,config:{}};if(Z?.[$])return{name:$,config:Z[$]};return console.warn(`Context "${$}" not found, using default`),{name:O2,config:{}}}var Y9="__matrix__";function rw($){let Z=[],X=$.matrix?.target??["default"],Y=$.matrix?.context??["default"];for(let G of $.scenarios){let z=G.context?[G.context]:Y;if(G.matrix){for(let Q of z)Z.push({scenario:G,targetName:Y9,contextName:Q});continue}let J=G.target?[G.target]:X;for(let Q of J)for(let W of z)Z.push({scenario:G,targetName:Q,contextName:W})}return Z}function sw($,Z,X){let Y=[];for(let{scenario:G,targetName:z,contextName:J}of $)if(G.matrix&&z===Y9){let Q=G.matrix,W=G.target??"default",V=Q.interfaces??[W],K=Q.sources??[null],H=Q.toolsets??["none"];for(let U of V){if(X.interface&&X.interface!==U)continue;for(let B of K){if(X.source!==void 0&&X.source!==(B??""))continue;for(let T of H){if(X.toolset&&X.toolset!==T)continue;Y.push({scenario:G.name,kind:"matrix",interface:U,source:B,toolset:T})}}}}else Y.push({scenario:G.name,kind:"single",target:z,context:J});return Y}function a5($){if($.kind==="matrix")return`m:${$.scenario}\x01${$.interface}\x01${$.source??""}\x01${$.toolset}`;return`s:${$.scenario}\x01${$.target}\x01${$.context}`}function ow($){let{tool:Z,docs:X,expandedCells:Y,selectedCells:G,seed:z}=$;return{tool:{name:Z.name,description:Z.description,path:Z.path},docs:X,scenarios:[],summary:{total:0,answered:0,unanswered:0,score:0},plan:{expandedCells:Y,selectedCells:G.length,seed:z,cells:G.map((J)=>J.kind==="matrix"?{scenario:J.scenario,interface:J.interface,source:J.source,toolset:J.toolset}:{scenario:J.scenario,target:J.target,context:J.context})}}}async function n5($,Z,X={}){let{onProgress:Y}=X,G=[];if(Z.scenarios.length===0)throw Error("No scenarios defined in config");let z=Z.docs?.sources??{},J=[];if(Object.keys(z).length>0){Y?.("Loading sources..."),J=await t2(z,$.path);for(let M of J)Y?.(` [${M.id}] ${M.name}`);Y?.("")}let Q=J.map((M)=>M.id),W=rw(Z);if(X.scenarioFilter&&X.scenarioFilter.length>0){let M=new Set(X.scenarioFilter);if(W=W.filter((O)=>M.has(O.scenario.name)),W.length===0)throw Error(`No scenarios matched filter: ${[...M].join(", ")}. Declared scenarios: ${Z.scenarios.map((O)=>O.name).join(", ")}`)}let V=X.cellFilter??{},K=sw(W,Z,V),H=K,U;if(X.sample!==void 0){let M=X.seed??"default",O=K.filter((P)=>P.kind==="matrix"),N=lY(O,X.sample,M),_=new Set(N.map(a5));H=K.filter((P)=>P.kind!=="matrix"||_.has(a5(P))),U=M}if(X.maxCells!==void 0&&H.length>X.maxCells)throw Error(`Matrix expands to ${H.length} cells, exceeding --max-cells ${X.maxCells}. Add --interface/--source/--toolset/--scenario filters, or pass --sample N to sample per scenario.`);if(X.plan)return ow({tool:$,docs:J,expandedCells:K.length,selectedCells:H,seed:U});let B=X.sample!==void 0?new Set(H.filter((M)=>M.kind==="matrix").map(a5)):void 0,T="";for(let{scenario:M,targetName:O,contextName:N}of W){let _=tw(O,N);if(M.name!==T){if(T)Y?.("");Y?.(`"${M.name}"`),T=M.name}try{let P=await ew(M,O,N,$,Z,J,Q,X,B);G.push(P);let R=_?_.padEnd(18):"";if(P.cells){Y?.(` ${R} (matrix mode)`);for(let A of P.cells){let S=t0(A),k=` [${[A.cell.interface,A.cell.source??"-",A.cell.toolset].join(" \xB7 ")}]`.padEnd(40);Y?.(`${k} ${S.icon} ${S.label} (${S.confidence}%)`)}}else if(P.surfaces){Y?.(` ${R} (compare-surfaces mode)`);for(let A of P.surfaces){let S=t0(A),D=` [${A.active.join(",")}]`.padEnd(22);Y?.(`${D} ${S.icon} ${S.label} (${S.confidence}%)`)}}else{let A=t0({answerable:P.answerable??"NO",confidence:P.confidence??0,traps:P.traps??{fired:[],avoided:[]},error:P.error});Y?.(` ${R} ${A.icon} ${A.label} (${A.confidence}%)`)}}catch(P){let R=O==="default"?v0:Z.targets?.[O]??v0,A=M.requiredSources??[],S={scenario:M,answerable:"NO",confidence:0,response:"",reason:"Error during run",citations:{cited:[],required:A,missing:A,unknown:[]},traps:{fired:[],avoided:(M.traps??[]).map((k)=>k.id)},error:P instanceof Error?P.message:String(P),target:{target:O===Y9?"matrix":O,category:R.category,provider:R.provider,model:R.model??"unknown"},context:{name:N}};G.push(S);let D=_?_.padEnd(18):"";Y?.(` ${D} \u2717 Error`)}}Y?.("");let F=$O($,J,G);return F.plan={expandedCells:K.length,selectedCells:H.length,seed:U},F}function tw($,Z){if($==="default"&&Z==="default")return"";if(Z==="default")return`[${$}]`;return`[${$}/${Z}]`}async function ew($,Z,X,Y,G,z,J,Q,W){if($.matrix&&Z===Y9)return ZO($,X,Y,G,z,Q,W);let{config:V}=X9(Z,G.targets),{config:K}=i5(X,G.contexts),H=Q.targetFactory?Q.targetFactory(Z,V):Z9(Z,V);if($.compareSurfaces&&$.compareSurfaces.length>0){let R=[],A;for(let S of $.compareSurfaces){let D=new Set(S),k=z.filter((W$)=>D.has(W$.id)),i=($.requiredSources??[]).filter((W$)=>D.has(W$)),c=await H.run($.prompt,{tool:Y,cwd:Y.path,context:K,docs:k,requiredSources:i,onProgress:Q.onProgress}),M0=j1({response:c.response,requiredSources:i,registeredIds:S}),y$=w$({response:c.response,traps:$.traps??[]}),O0=y$.fired.length>0,i6=O0?"NO":M0.answerable,W9=O0?0:M0.confidence,a6=O0?`Trap fired: ${y$.fired.map((W$)=>`"${W$.id}" (${W$.reason})`).join("; ")}`:M0.reason;R.push({active:S,answerable:i6,confidence:W9,response:c.response,reason:a6,citations:M0.citations,traps:y$,allResponses:c.allResponses}),A=c.metadata??A}return{scenario:$,answerable:null,confidence:null,response:null,reason:null,citations:null,traps:null,surfaces:R,target:A,context:{name:X}}}let U=$.requiredSources??[],B=await H.run($.prompt,{tool:Y,cwd:Y.path,context:K,docs:z,requiredSources:U,onProgress:Q.onProgress}),T=w$({response:B.response,traps:$.traps??[]}),F=T.fired.length>0,M=$.requiredSources!==void 0?j1({response:B.response,requiredSources:U,registeredIds:J}):null,O=$.expected!==void 0?nZ({response:B.response,expected:$.expected}):null;if(O)aZ(O,z);let N,_,P;if(F)N="NO",_=0,P=`Trap fired: ${T.fired.map((R)=>`"${R.id}" (${R.reason})`).join("; ")}`;else{let R=[],A=[];if(M)R.push({answerable:M.answerable,confidence:M.confidence}),A.push(M.reason);if(O){let S=O.total===0?100:Math.round(O.satisfied/O.total*100),D=S===100?"YES":S===0?"NO":"PARTIAL";R.push({answerable:D,confidence:S}),A.push(...$4(O)),A.push(...e2(O))}if(R.length===0)N="YES",_=100,P="No traps fired; no other contract declared";else{let S={YES:0,PARTIAL:1,NO:2};N=R.reduce((k,b)=>S[b.answerable]>S[k.answerable]?b:k).answerable,_=Math.round(R.reduce((k,b)=>k+b.confidence,0)/R.length),P=A.filter((k)=>k.length>0).join(" | ")}}return{scenario:$,answerable:N,confidence:_,response:B.response,reason:P,citations:M?M.citations:{cited:[],required:U,missing:[],unknown:[]},traps:T,expected:O?{includes:O.includes,excludes:O.excludes,symbols:O.symbols,paths:O.paths,options:O.options,constraints:O.constraints,satisfied:O.satisfied,total:O.total}:void 0,target:B.metadata,context:{name:X},toolsUsed:B.toolsUsed,sources:B.sources,allResponses:B.allResponses}}function $O($,Z,X){let Y=[];for(let Q of X){if(Q.surfaces){for(let W of Q.surfaces)Y.push({answerable:W.answerable,confidence:W.confidence});continue}if(Q.cells){for(let W of Q.cells)Y.push({answerable:W.answerable,confidence:W.confidence});continue}if(Q.answerable!==null&&Q.confidence!==null)Y.push({answerable:Q.answerable,confidence:Q.confidence})}let G=Y.length,z=Y.filter((Q)=>Q.answerable==="YES"||Q.answerable==="PARTIAL").length,J=G>0?Math.round(Y.reduce((Q,W)=>{if(W.answerable==="YES")return Q+W.confidence;if(W.answerable==="PARTIAL")return Q+W.confidence*0.5;return Q},0)/G):0;return{tool:{name:$.name,description:$.description,path:$.path},docs:Z,scenarios:X,summary:{total:G,answered:z,unanswered:G-z,score:J}}}async function ZO($,Z,X,Y,G,z,J){let{config:Q}=i5(Z,Y.contexts),W=$.matrix??{},V=$.target??"default",K=W.interfaces??[V],H=W.sources??[null],U=W.toolsets??["none"],B=z.cellFilter??{},T=[],F;for(let O of K){if(B.interface&&B.interface!==O)continue;for(let N of H){if(B.source!==void 0&&B.source!==(N??""))continue;for(let _ of U){if(B.toolset&&B.toolset!==_)continue;if(J!==void 0){let g=`m:${$.name}\x01${O}\x01${N??""}\x01${_}`;if(!J.has(g))continue}let P=_==="none"?null:Y.toolsets?.[_]??null,R=_!=="none"&&(P?.webSearch===!0||P?.webFetch===!0),A=_!=="none"&&P?.mcpServers?Object.keys(P.mcpServers):[],S=A.length>0,{config:D}=X9(O,Y.targets);if(_!=="none"){if(R&&S)throw Error(`Toolset "${_}" mixes webSearch/webFetch with mcpServers; declare separate toolsets per shape so provenance can be attributed to one tool path.`);if(!R&&!S)throw Error(`Toolset "${_}" is declared but defines no runtime shape. Supported today: "none", web (webSearch/webFetch flags), MCP (mcpServers map). Other adapters (Firecrawl, native API search) land per release.`);if(S&&D.provider!=="claude-code"&&D.provider!=="openai")throw Error(`Toolset "${_}" (MCP) is implemented on claude-code and openai interfaces today. Interface "${O}" uses provider "${D.provider}"; rerun with a supported interface or use toolset "none".`);if(R&&D.provider!=="claude-code"&&D.provider!=="anthropic"&&D.provider!=="openai")throw Error(`Toolset "${_}" (web) is implemented on claude-code, anthropic, and openai interfaces today. Interface "${O}" uses provider "${D.provider}"; rerun with a supported interface or use toolset "none".`);if(R&&(D.provider==="anthropic"||D.provider==="openai")&&!P?.webSearch)throw Error(`Toolset "${_}" on ${D.provider} provider requires webSearch: true. The ${D.provider} API exposes a single server-side web tool; declare webSearch to enable it, or split web/fetch behaviour across separate toolsets.`)}let k=[],b=[],i=[],c=D.provider==="anthropic"||D.provider==="openai";if(R)if(c)i.push((g)=>g==="web_search");else{if(P?.webSearch)k.push("WebSearch"),b.push("WebSearch"),i.push((g)=>g==="WebSearch");if(P?.webFetch)k.push("WebFetch"),b.push("WebFetch"),i.push((g)=>g==="WebFetch")}if(S)for(let g of A)k.push(`mcp__${g}__*`),i.push((W0)=>W0.startsWith(`mcp__${g}__`));let M0=_==="none"||c?D:{...D,allowedTools:k,disallowedTools:[],mcpServers:S?P?.mcpServers:void 0,maxTurns:Math.max(D.maxTurns??0,15)},y$=z.targetFactory?z.targetFactory(O,M0):Z9(O,M0),O0=_==="none",i6=N==="none",W9=i6||!O0?[]:N===null?G:G.filter((g)=>g.id===N),a6=i6||!O0?[]:N===null?G.map((g)=>g.id):[N],W$=$.requiredSources??[],G3=O0?W$.filter((g)=>a6.includes(g)):[],tz=YO($.prompt,N,G,O0),ez=O0?void 0:{sourceHint:GO(N,G)},i0;try{let g=_==="none"?Q:void 0;i0=await y$.run(tz,{tool:X,cwd:X.path,context:g,docs:W9,requiredSources:G3,discovery:ez,restrictBuiltinTools:_==="none"?void 0:b,webTools:R&&c?{search:P?.webSearch===!0}:void 0,mcpTools:S&&D.provider==="openai"&&P?.mcpServers?{servers:P.mcpServers}:void 0,onProgress:z.onProgress})}catch(g){T.push({cell:{interface:O,source:N,toolset:_},answerable:"NO",confidence:0,response:"",reason:`Error in cell: ${g instanceof Error?g.message:String(g)}`,citations:null,traps:{fired:[],avoided:($.traps??[]).map((W0)=>W0.id)},error:g instanceof Error?g.message:String(g)});continue}let V9=w$({response:i0.response,traps:$.traps??[]}),$J=V9.fired.length>0,V$=$.requiredSources!==void 0&&O0?j1({response:i0.response,requiredSources:G3,registeredIds:a6}):null,o=$.expected!==void 0?nZ({response:i0.response,expected:$.expected}):null;if(o)aZ(o,G);let P2=_!=="none"&&i.length>0?{expected:k,used:(i0.toolsUsed??[]).filter((g)=>i.some((W0)=>W0(g)))}:null,ZJ=P2!==null&&P2.used.length===0,XJ=()=>{let g=[];if(V$)g.push(V$.reason);if(o)g.push(...$4(o)),g.push(...e2(o));return g.filter((W0)=>W0.length>0)},D2,E2,R2;if($J)D2="NO",E2=0,R2=`Trap fired: ${V9.fired.map((g)=>`"${g.id}" (${g.reason})`).join("; ")}`;else if(ZJ){let g=P2;D2="NO",E2=0;let W0=`Provenance failed: toolset "${_}" configured but none of [${g.expected.join(", ")}] were used (answer rests on model prior knowledge)`,a0=XJ();R2=a0.length>0?`${W0} | ${a0.join(" | ")}`:W0}else{let g=[],W0=[];if(V$)g.push({answerable:V$.answerable,confidence:V$.confidence}),W0.push(V$.reason);if(o){let a0=o.total===0?100:Math.round(o.satisfied/o.total*100),z3=a0===100?"YES":a0===0?"NO":"PARTIAL";g.push({answerable:z3,confidence:a0}),W0.push(...$4(o)),W0.push(...e2(o))}if(P2)W0.push(`tool use verified (${P2.used.join(", ")})`);if(g.length===0)D2="YES",E2=100,R2="No traps fired; no other contract declared";else{let a0={YES:0,PARTIAL:1,NO:2};D2=g.reduce((T1,n6)=>a0[n6.answerable]>a0[T1.answerable]?n6:T1).answerable,E2=Math.round(g.reduce((T1,n6)=>T1+n6.confidence,0)/g.length),R2=W0.filter((T1)=>T1.length>0).join(" | ")}}T.push({cell:{interface:O,source:N,toolset:_},answerable:D2,confidence:E2,response:i0.response,reason:R2,citations:V$?V$.citations:null,traps:V9,expected:o?{includes:o.includes,excludes:o.excludes,symbols:o.symbols,paths:o.paths,options:o.options,constraints:o.constraints,satisfied:o.satisfied,total:o.total}:void 0,toolsUsed:i0.toolsUsed,allResponses:i0.allResponses}),F=i0.metadata??F}}}let M=XO($,G);return{scenario:$,answerable:null,confidence:null,response:null,reason:null,citations:null,traps:null,cells:T,verifierSamples:M,target:F,context:{name:Z}}}function XO($,Z){let X=$.verifiers?.sources;if(!X||X.length===0)return;let Y=new Map(Z.map((z)=>[z.id,z])),G=[];for(let z of X){let J=Y.get(z);if(!J)continue;G.push({id:J.id,name:J.name,content:J.content})}return G.length>0?G:void 0}function YO($,Z,X,Y){if(Y)return $;if(Z===null||Z==="none")return $;let G=X.find((J)=>J.id===Z);if(!G)return $;let z=G.type==="url"?`The canonical source for this question is the documentation at ${G.source}. Use your available tools to research it.`:`The canonical source for this question is "${G.name}" (registered locally as ${G.id}). Use your available tools to research from authoritative sources.`;return`${$}
|
|
270
271
|
|
|
271
|
-
${z}`}function
|
|
272
|
+
${z}`}function GO($,Z){if($===null||$==="none")return null;let X=Z.find((Y)=>Y.id===$);if(!X)return null;if(X.type==="url")return X.source;return X.name}var jz=($=0)=>(Z)=>`\x1B[${Z+$}m`,xz=($=0)=>(Z)=>`\x1B[${38+$};5;${Z}m`,kz=($=0)=>(Z,X,Y)=>`\x1B[${38+$};2;${Z};${X};${Y}m`,a={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},Nf=Object.keys(a.modifier),zO=Object.keys(a.color),JO=Object.keys(a.bgColor),_f=[...zO,...JO];function QO(){let $=new Map;for(let[Z,X]of Object.entries(a)){for(let[Y,G]of Object.entries(X))a[Y]={open:`\x1B[${G[0]}m`,close:`\x1B[${G[1]}m`},X[Y]=a[Y],$.set(G[0],G[1]);Object.defineProperty(a,Z,{value:X,enumerable:!1})}return Object.defineProperty(a,"codes",{value:$,enumerable:!1}),a.color.close="\x1B[39m",a.bgColor.close="\x1B[49m",a.color.ansi=jz(),a.color.ansi256=xz(),a.color.ansi16m=kz(),a.bgColor.ansi=jz(10),a.bgColor.ansi256=xz(10),a.bgColor.ansi16m=kz(10),Object.defineProperties(a,{rgbToAnsi256:{value(Z,X,Y){if(Z===X&&X===Y){if(Z<8)return 16;if(Z>248)return 231;return Math.round((Z-8)/247*24)+232}return 16+36*Math.round(Z/255*5)+6*Math.round(X/255*5)+Math.round(Y/255*5)},enumerable:!1},hexToRgb:{value(Z){let X=/[a-f\d]{6}|[a-f\d]{3}/i.exec(Z.toString(16));if(!X)return[0,0,0];let[Y]=X;if(Y.length===3)Y=[...Y].map((z)=>z+z).join("");let G=Number.parseInt(Y,16);return[G>>16&255,G>>8&255,G&255]},enumerable:!1},hexToAnsi256:{value:(Z)=>a.rgbToAnsi256(...a.hexToRgb(Z)),enumerable:!1},ansi256ToAnsi:{value(Z){if(Z<8)return 30+Z;if(Z<16)return 90+(Z-8);let X,Y,G;if(Z>=232)X=((Z-232)*10+8)/255,Y=X,G=X;else{Z-=16;let Q=Z%36;X=Math.floor(Z/36)/5,Y=Math.floor(Q/6)/5,G=Q%6/5}let z=Math.max(X,Y,G)*2;if(z===0)return 30;let J=30+(Math.round(G)<<2|Math.round(Y)<<1|Math.round(X));if(z===2)J+=60;return J},enumerable:!1},rgbToAnsi:{value:(Z,X,Y)=>a.ansi256ToAnsi(a.rgbToAnsi256(Z,X,Y)),enumerable:!1},hexToAnsi:{value:(Z)=>a.ansi256ToAnsi(a.hexToAnsi256(Z)),enumerable:!1}}),a}var WO=QO(),y0=WO;import r5 from"process";import VO from"os";import bz from"tty";function x0($,Z=globalThis.Deno?globalThis.Deno.args:r5.argv){let X=$.startsWith("-")?"":$.length===1?"-":"--",Y=Z.indexOf(X+$),G=Z.indexOf("--");return Y!==-1&&(G===-1||Y<G)}var{env:n}=r5,G9;if(x0("no-color")||x0("no-colors")||x0("color=false")||x0("color=never"))G9=0;else if(x0("color")||x0("colors")||x0("color=true")||x0("color=always"))G9=1;function HO(){if("FORCE_COLOR"in n){if(n.FORCE_COLOR==="true")return 1;if(n.FORCE_COLOR==="false")return 0;return n.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(n.FORCE_COLOR,10),3)}}function KO($){if($===0)return!1;return{level:$,hasBasic:!0,has256:$>=2,has16m:$>=3}}function UO($,{streamIsTTY:Z,sniffFlags:X=!0}={}){let Y=HO();if(Y!==void 0)G9=Y;let G=X?G9:Y;if(G===0)return 0;if(X){if(x0("color=16m")||x0("color=full")||x0("color=truecolor"))return 3;if(x0("color=256"))return 2}if("TF_BUILD"in n&&"AGENT_NAME"in n)return 1;if($&&!Z&&G===void 0)return 0;let z=G||0;if(n.TERM==="dumb")return z;if(r5.platform==="win32"){let J=VO.release().split(".");if(Number(J[0])>=10&&Number(J[2])>=10586)return Number(J[2])>=14931?3:2;return 1}if("CI"in n){if(["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some((J)=>(J in n)))return 3;if(["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((J)=>(J in n))||n.CI_NAME==="codeship")return 1;return z}if("TEAMCITY_VERSION"in n)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(n.TEAMCITY_VERSION)?1:0;if(n.COLORTERM==="truecolor")return 3;if(n.TERM==="xterm-kitty")return 3;if(n.TERM==="xterm-ghostty")return 3;if(n.TERM==="wezterm")return 3;if("TERM_PROGRAM"in n){let J=Number.parseInt((n.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(n.TERM_PROGRAM){case"iTerm.app":return J>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(n.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(n.TERM))return 1;if("COLORTERM"in n)return 1;return z}function fz($,Z={}){let X=UO($,{streamIsTTY:$&&$.isTTY,...Z});return KO(X)}var BO={stdout:fz({isTTY:bz.isatty(1)}),stderr:fz({isTTY:bz.isatty(2)})},yz=BO;function vz($,Z,X){let Y=$.indexOf(Z);if(Y===-1)return $;let G=Z.length,z=0,J="";do J+=$.slice(z,Y)+Z+X,z=Y+G,Y=$.indexOf(Z,z);while(Y!==-1);return J+=$.slice(z),J}function gz($,Z,X,Y){let G=0,z="";do{let J=$[Y-1]==="\r";z+=$.slice(G,J?Y-1:Y)+Z+(J?`\r
|
|
272
273
|
`:`
|
|
273
274
|
`)+X,G=Y+1,Y=$.indexOf(`
|
|
274
|
-
`,G)}while(Y!==-1);return z+=$.slice(G),z}var{stdout:
|
|
275
|
-
`);if(z!==-1)Z=
|
|
276
|
-
`)}if(
|
|
277
|
-
`)}function Y3($,Z={}){console.log(
|
|
278
|
-
`);let Q=z.findings.filter((H)=>H.severity==="error").length,W=z.findings.filter((H)=>H.severity==="warning").length;if(Y!=="json"&&!X)if(console.log(),Q===0&&W===0)console.log(j.green("Audit clean. No issues found."));else{let H=Q>0?j.red:j.yellow;console.log(H(`Audit found ${Q} error(s), ${W} warning(s).`))}if((Z.failOn??"error")==="warning"?Q+W>0:Q>0)process.exit(1)}function
|
|
279
|
-
`);else Y3(
|
|
275
|
+
`,G)}while(Y!==-1);return z+=$.slice(G),z}var{stdout:hz,stderr:uz}=yz,s5=Symbol("GENERATOR"),N2=Symbol("STYLER"),l6=Symbol("IS_EMPTY"),mz=["ansi","ansi","ansi256","ansi16m"],_2=Object.create(null),qO=($,Z={})=>{if(Z.level&&!(Number.isInteger(Z.level)&&Z.level>=0&&Z.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let X=hz?hz.level:0;$.level=Z.level===void 0?X:Z.level};var TO=($)=>{let Z=(...X)=>X.join(" ");return qO(Z,$),Object.setPrototypeOf(Z,p6.prototype),Z};function p6($){return TO($)}Object.setPrototypeOf(p6.prototype,Function.prototype);for(let[$,Z]of Object.entries(y0))_2[$]={get(){let X=z9(this,t5(Z.open,Z.close,this[N2]),this[l6]);return Object.defineProperty(this,$,{value:X}),X}};_2.visible={get(){let $=z9(this,this[N2],!0);return Object.defineProperty(this,"visible",{value:$}),$}};var o5=($,Z,X,...Y)=>{if($==="rgb"){if(Z==="ansi16m")return y0[X].ansi16m(...Y);if(Z==="ansi256")return y0[X].ansi256(y0.rgbToAnsi256(...Y));return y0[X].ansi(y0.rgbToAnsi(...Y))}if($==="hex")return o5("rgb",Z,X,...y0.hexToRgb(...Y));return y0[X][$](...Y)},FO=["rgb","hex","ansi256"];for(let $ of FO){_2[$]={get(){let{level:X}=this;return function(...Y){let G=t5(o5($,mz[X],"color",...Y),y0.color.close,this[N2]);return z9(this,G,this[l6])}}};let Z="bg"+$[0].toUpperCase()+$.slice(1);_2[Z]={get(){let{level:X}=this;return function(...Y){let G=t5(o5($,mz[X],"bgColor",...Y),y0.bgColor.close,this[N2]);return z9(this,G,this[l6])}}}}var LO=Object.defineProperties(()=>{},{..._2,level:{enumerable:!0,get(){return this[s5].level},set($){this[s5].level=$}}}),t5=($,Z,X)=>{let Y,G;if(X===void 0)Y=$,G=Z;else Y=X.openAll+$,G=Z+X.closeAll;return{open:$,close:Z,openAll:Y,closeAll:G,parent:X}},z9=($,Z,X)=>{let Y=(...G)=>MO(Y,G.length===1?""+G[0]:G.join(" "));return Object.setPrototypeOf(Y,LO),Y[s5]=$,Y[N2]=Z,Y[l6]=X,Y},MO=($,Z)=>{if($.level<=0||!Z)return $[l6]?"":Z;let X=$[N2];if(X===void 0)return Z;let{openAll:Y,closeAll:G}=X;if(Z.includes("\x1B"))while(X!==void 0)Z=vz(Z,X.close,X.open),X=X.parent;let z=Z.indexOf(`
|
|
276
|
+
`);if(z!==-1)Z=gz(Z,G,Y,z);return Y+Z+G};Object.defineProperties(p6.prototype,_2);var wO=p6(),xf=p6({level:uz?uz.level:0});var j=wO;var e5="\u2500".repeat(55);function $3($){if($==="success")return j.green;if($==="warning")return j.yellow;return j.red}function OO($){if($>=70)return j.green;if($>=50)return j.yellow;return j.red}function Z3($){if($.label==="Error")return $.label;return`${$.label} (${$.confidence}%)`}function NO($){let Z=t0({answerable:$.answerable??"NO",confidence:$.confidence??0,traps:$.traps??{fired:[],avoided:[]},error:$.error}),X=$3(Z.tone);return{icon:X(Z.icon),status:Z3(Z),color:X}}function _O($){let Z=$.target?.target??"default",X=$.context?.name??"default";if(Z==="default"&&X==="default")return"";if(X==="default")return j.dim(`[${Z}]`);return j.dim(`[${Z}/${X}]`)}function PO($){let Z=$.map((X)=>X.scenario.name);return new Set(Z).size!==Z.length}function J9($){return $.map((Z)=>`[${Z}]`).join(", ")}function X3($,Z){let X=[];if($.error)return X.push(j.dim(`${Z}error: ${$.error}`)),X;if($.traps.fired.length>0)for(let Y of $.traps.fired)X.push(j.red(`${Z}trap: ${Y.id}`)),X.push(j.dim(`${Z}reason: ${Y.reason}`)),X.push(j.dim(`${Z}match: "${Y.matched}"`));else if($.reason&&$.answerable!=="YES")X.push(j.dim(`${Z}reason: ${$.reason}`));if($.citations.cited.length>0)X.push(j.dim(`${Z}cited: ${J9($.citations.cited)}`));if($.citations.missing.length>0)X.push(j.dim(`${Z}missing: ${J9($.citations.missing)}`));if($.citations.unknown.length>0)X.push(j.dim(`${Z}unknown: ${J9($.citations.unknown)}`));return X}function dz($,Z){if(!$.traps||!$.citations)return[];return X3({error:$.error,traps:$.traps,reason:$.reason??"",answerable:$.answerable??"NO",citations:$.citations},Z)}function cz($){let{icon:Z,status:X,color:Y}=NO($),G=_O($),z=`${Z} ${X}`;return G?`${G} ${Y(z)}`:Y(z)}function lz($,Z){if(!$.cells)return[];let X=[];X.push(`${Z}${j.dim("Matrix cells (interface \xB7 source \xB7 toolset)")}`);for(let Y of $.cells){let G=t0(Y),z=$3(G.tone),J=`[${Y.cell.interface} \xB7 ${Y.cell.source??"-"} \xB7 ${Y.cell.toolset}]`,Q=j.dim(J),W=`${z(G.icon)} ${z(Z3(G))}`;if(X.push(`${Z}${Q} ${W}`),X.push(...X3({traps:Y.traps,reason:Y.reason,answerable:Y.answerable,citations:Y.citations??{cited:[],required:[],missing:[],unknown:[]}},`${Z} `)),Y.expected){let V=Y.expected.includes.filter((H)=>!H.satisfied).map((H)=>`"${H.value}"`),K=Y.expected.excludes.filter((H)=>!H.satisfied).map((H)=>`"${H.value}"`);if(V.length>0)X.push(j.dim(`${Z} expected.includes missing: ${V.join(", ")}`));if(K.length>0)X.push(j.dim(`${Z} expected.excludes hit: ${K.join(", ")}`))}if(Y.toolsUsed&&Y.toolsUsed.length>0)X.push(j.dim(`${Z} tools: ${Y.toolsUsed.join(", ")}`))}if($.verifierSamples&&$.verifierSamples.length>0){X.push(`${Z}${j.dim("Verifier samples (human review; never LLM-judged)")}`);for(let Y of $.verifierSamples){let G=Y.content.slice(0,200).replace(/\s+/g," ").trim(),z=Y.content.length>200?"...":"";X.push(j.dim(`${Z} [${Y.id}] ${Y.name}`)),X.push(j.dim(`${Z} ${G}${z}`))}}return X}function pz($,Z){if(!$.surfaces)return[];let X=[];X.push(`${Z}${j.dim("Citations scoped to active surface (compare mode)")}`);for(let Y of $.surfaces){let G=t0(Y),z=$3(G.tone),J=j.dim(`[${Y.active.join(",")}]`),Q=`${z(G.icon)} ${z(Z3(G))}`;X.push(`${Z}${J} ${Q}`),X.push(...X3({traps:Y.traps,reason:Y.reason,answerable:Y.answerable,citations:Y.citations},`${Z} `))}return X}function DO($){let Z=0,X=0,Y=0;for(let G of $){if(G.surfaces){for(let z of G.surfaces)Z+=z.traps.fired.length,X+=z.citations.missing.length,Y+=z.citations.unknown.length;continue}if(G.traps)Z+=G.traps.fired.length;if(G.citations)X+=G.citations.missing.length,Y+=G.citations.unknown.length}if(Z>0&&X+Y>0)return"Review fired traps and citation gaps.";if(Z>0)return"Review fired traps before trusting this surface.";if(X+Y>0)return"Review missing and unknown citations.";return"Citations hold. No declared traps fired."}function EO($,Z){let X=$.summary.score,G=`Overall: ${OO(X)(`${X}`)} / 100`;if(Z===void 0||Z<=0)return G;let J=X>=Z?j.green("run passes"):j.red("run fails");return`${G} \xB7 threshold ${Z} \xB7 ${J}`}function iz($,Z={}){let{tool:X,scenarios:Y,summary:G}=$,z=Y,J=[];if(J.push(j.bold("pickled check")),J.push(e5),J.push(`Tool: ${j.cyan(X.name)}`),$.docs.length>0)J.push(`Sources: ${j.dim(J9($.docs.map((Q)=>Q.id)))}`);else J.push(`Sources: ${j.dim("none registered")}`);if(J.push(`Scenarios: ${j.dim(String(G.total))}`),$.plan){let{expandedCells:Q,selectedCells:W,seed:V}=$.plan,H=W<Q?`Cells: ${j.dim(`${W} of ${Q} (sampled${V?`, seed=${V}`:""})`)}`:`Cells: ${j.dim(String(Q))}`;J.push(H)}if(J.push(""),$.plan?.cells&&z.length===0){if(J.push(j.bold(`Planned cells (${$.plan.selectedCells} of ${$.plan.expandedCells})`)),$.plan.cells.length===0)J.push(j.dim(" (no cells after filters)"));let Q="";for(let W of $.plan.cells){if(W.scenario!==Q)Q=W.scenario,J.push(` ${W.scenario}`);let V=W.interface!==void 0?`[${W.interface} \xB7 ${W.source??"-"} \xB7 ${W.toolset}]`:`[${W.target}${W.context&&W.context!=="default"?`/${W.context}`:""}]`;J.push(` ${j.dim(V)}`)}return J.push(""),J.push(e5),J.push(j.dim("Dry-run: no model calls. Re-run without --plan to execute these cells.")),J.join(`
|
|
277
|
+
`)}if(PO(z)){let Q=new Map;for(let W of z){let V=W.scenario.name;if(!Q.has(V))Q.set(V,[]);Q.get(V)?.push(W)}for(let[W,V]of Q){J.push(`Scenario: ${W}`);for(let K of V)if(K.cells)J.push(...lz(K," "));else if(K.surfaces)J.push(...pz(K," "));else J.push(` ${cz(K)}`),J.push(...dz(K," "));J.push("")}}else for(let Q of z){if(J.push(`Scenario: ${Q.scenario.name}`),Q.cells)J.push(...lz(Q," "));else if(Q.surfaces)J.push(...pz(Q," "));else J.push(` ${cz(Q)}`),J.push(...dz(Q," "));J.push("")}return J.push(e5),J.push(EO($,Z.threshold)),J.push(j.dim(DO(Y))),J.join(`
|
|
278
|
+
`)}function Y3($,Z={}){console.log(iz($,Z)),console.log()}function Q9($,Z={}){if(Z.verbose)return JSON.stringify($,null,2);let X={...$,docs:$.docs.map((Y)=>({...Y,content:""})),scenarios:$.scenarios.map((Y)=>{let{allResponses:G,verifierSamples:z,cells:J,surfaces:Q,...W}=Y;return{...W,verifierSamples:z?.map((V)=>({...V,content:""})),cells:J?.map((V)=>{let{allResponses:K,...H}=V;return H}),surfaces:Q?.map((V)=>{let{allResponses:K,...H}=V;return H})}})};return JSON.stringify(X,null,2)}function AO($){if($.format&&$.format!=="terminal")return $.format;if($.json)return"json";return $.format??"terminal"}async function az($,Z){let{output:X}=Z,Y=AO(Z),G=RO.resolve($),z;try{z=await iZ({targetRepo:G})}catch(H){console.error(j.red(H instanceof Error?H.message:H)),process.exit(1)}let J;if(Y==="json")J=hZ(z);else if(Y==="markdown")J=gZ(z);else J=uZ(z);if(X)await Bun.write(X,J);else await SO(`${J}
|
|
279
|
+
`);let Q=z.findings.filter((H)=>H.severity==="error").length,W=z.findings.filter((H)=>H.severity==="warning").length;if(Y!=="json"&&!X)if(console.log(),Q===0&&W===0)console.log(j.green("Audit clean. No issues found."));else{let H=Q>0?j.red:j.yellow;console.log(H(`Audit found ${Q} error(s), ${W} warning(s).`))}if((Z.failOn??"error")==="warning"?Q+W>0:Q>0)process.exit(1)}function SO($){return new Promise((Z,X)=>{process.stdout.write($,(Y)=>{if(Y)X(Y);else Z()})})}import CO from"path";async function sz($,Z){let{json:X,output:Y,verbose:G}=Z,z=(O)=>!X&&console.log(O),J=CO.resolve($),Q;try{Q=await S1(J)}catch(O){console.error(j.red(O instanceof Error?O.message:O)),console.error(),console.error(j.dim("Run `pickled init` to create a config file")),process.exit(1)}if(Z.target){let O=Q.scenarios.length;try{Q=kX(Q,Z.target)}catch(_){console.error(j.red(_ instanceof Error?_.message:String(_))),process.exit(1)}let N=O-Q.scenarios.length;if(N>0&&!X)z(j.dim(`Skipping ${N} scenario(s) with explicit target != "${Z.target}"`))}let W={name:Q.tool.name,description:Q.tool.description,path:J};if(G){z(j.bold("pickled check")),z(""),z(j.dim(` Tool: ${W.name}`)),z(j.dim(` Scenarios: ${Q.scenarios.length}`));for(let O of Q.scenarios)z(j.dim(` - ${O.name}`))}let V;try{V=jO(Z.threshold,Q.threshold)}catch(O){console.error(j.red(O instanceof Error?O.message:O)),process.exit(1)}let K=Z.interface??Z.target,H=K||Z.source||Z.toolset?{interface:K,source:Z.source,toolset:Z.toolset}:void 0,U=Z.scenario?[Z.scenario]:void 0,B;if(Z.sample!==void 0){if(B=nz(Z.sample,"--sample"),B===null)process.exit(1)}let T;if(Z.maxCells!==void 0){if(T=nz(Z.maxCells,"--max-cells"),T===null)process.exit(1)}let F;try{F=await n5(W,Q,{onProgress:G?(O)=>{if(!X)z(j.dim(` ${O}`))}:void 0,cellFilter:H,scenarioFilter:U,plan:Z.plan,maxCells:T,sample:B,seed:Z.seed})}catch(O){console.error(j.red(O instanceof Error?O.message:O)),process.exit(1)}let M=IO({plan:Z.plan===!0,threshold:V,score:F.summary.score});if(Y)await Bun.write(Y,Q9(F,{verbose:G}));else if(X)await xO(`${Q9(F,{verbose:G})}
|
|
280
|
+
`);else Y3(F,{threshold:V});if(M){if(X||Y)console.error(j.red(`Overall: ${F.summary.score} / 100 \xB7 threshold ${V} \xB7 run fails`)),console.error(j.dim("Review failed scenarios before trusting this surface."));process.exit(1)}}function IO($){if($.plan)return!1;return $.threshold>0&&$.score<$.threshold}function jO($,Z){if($===void 0){if(Z===void 0)return 0;return rz(Z,"pickled.yml threshold")}return rz($,"--threshold")}function nz($,Z){if(!/^\d+$/.test($))return console.error(j.red(`Invalid ${Z} "${$}". Expected a non-negative integer.`)),null;return Number($)}function rz($,Z){if(typeof $==="number"){if(Number.isInteger($)&&$>=0&&$<=100)return $;throw Error(`Invalid ${Z} "${$}". Expected an integer from 0 to 100.`)}if(typeof $==="string"&&/^\d+$/.test($)){let X=Number($);if(X<=100)return X}if(typeof $==="string")throw Error(`Invalid ${Z} "${$}". Expected an integer from 0 to 100.`);throw Error(`Invalid ${Z}. Expected an integer from 0 to 100.`)}function xO($){return new Promise((Z,X)=>{process.stdout.write($,(Y)=>{if(Y)X(Y);else Z()})})}import kO from"path";var bO=`# pickled.yml - Agent legibility check for your product
|
|
280
281
|
|
|
281
282
|
tool:
|
|
282
283
|
name: "your-product"
|
|
@@ -298,4 +299,4 @@ scenarios:
|
|
|
298
299
|
|
|
299
300
|
# Optional: fail CI if score falls below threshold
|
|
300
301
|
# threshold: 80
|
|
301
|
-
`;async function
|
|
302
|
+
`;async function oz($){let X=`${kO.resolve($)}/pickled.yml`;if(await Bun.file(X).exists())console.error(j.red("pickled.yml already exists")),process.exit(1);await Bun.write(X,bO),console.log(j.green("Created pickled.yml")),console.log(),console.log(j.dim("Next steps:")),console.log(j.dim(" 1. Edit pickled.yml: list your sources and scenarios")),console.log(j.dim(" 2. Run: pickled check")),console.log()}F1.name("pickled").description("Test what agents actually understand about your product").version(E3.version);F1.command("init").description("Create a pickled.yml config file").argument("[path]","Path to your project (default: current directory)",".").action(oz);F1.command("audit").description("Static scan of agent-context files (CLAUDE.md, AGENTS.md, llms.txt). No LLM calls.").argument("[path]","Path to your project (default: current directory)",".").addOption(new M9("--format <name>","Output format").choices(["terminal","markdown","json"]).default("terminal")).option("--json","Shorthand for --format json").option("-o, --output <file>","Save report to file").addOption(new M9("--fail-on <level>","Exit non-zero on this severity or higher").choices(["error","warning"]).default("error")).action(az);F1.command("check").description("Run agent scenarios against registered sources").argument("[path]","Path to your project (default: current directory)",".").option("--json","Output as JSON").option("-o, --output <file>","Save report to file").option("-v, --verbose","Show detailed progress").option("-t, --threshold <percent>","Minimum score % to pass (overrides config)").option("--target <name>","Restrict to the named target. Overrides matrix.target for non-matrix scenarios; for matrix scenarios, also filters cells by interface unless --interface is explicitly set.").option("--scenario <name>","Run only the named scenario (for CI matrix one-job-per-cell usage)").option("--interface <name>","Matrix cell filter: run only cells with this interface. Takes precedence over --target for matrix cells.").option("--source <name>","Matrix cell filter: run only cells with this source id").option("--toolset <name>","Matrix cell filter: run only cells with this toolset name").option("--plan","Dry-run: expand the matrix, apply filters and sampling, print the cell list, exit. Makes zero model calls.").option("--max-cells <n>","Hard cap on the number of cells (after filters and sampling). Exits non-zero before any model call if exceeded.").option("--sample <n>","Deterministic per-scenario sample. Picks N cells per matrix scenario; single-cell scenarios always run.").option("--seed <value>",'Seed for --sample. Defaults to "default" so reruns without --seed are reproducible.').action(sz);await F1.parseAsync();
|