@pickled-dev/cli 0.22.0 → 0.24.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/README.md +12 -0
- package/dist/index.js +124 -123
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,101 +1,101 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
`)}displayWidth($){return
|
|
3
|
+
var ZJ=Object.create;var{getPrototypeOf:XJ,defineProperty:z3,getOwnPropertyNames:YJ}=Object;var GJ=Object.prototype.hasOwnProperty;function zJ($){return this[$]}var JJ,QJ,J3=($,Z,X)=>{var Y=$!=null&&typeof $==="object";if(Y){var G=Z?JJ??=new WeakMap:QJ??=new WeakMap,z=G.get($);if(z)return z}X=$!=null?ZJ(XJ($)):{};let J=Z||!$||!$.__esModule?z3(X,"default",{value:$,enumerable:!0}):X;for(let Q of YJ($))if(!GJ.call(J,Q))z3(J,Q,{get:zJ.bind($,Q),enumerable:!0});if(Y)G.set($,J);return J};var C=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var r0=import.meta.require;var I2=C((WJ)=>{class HX 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 Q3 extends HX{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}WJ.CommanderError=HX;WJ.InvalidArgumentError=Q3});var sZ=C((UJ)=>{var{InvalidArgumentError:KJ}=I2();class W3{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 KJ(`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 BJ($){let Z=$.name()+($.variadic===!0?"...":"");return $.required?"<"+Z+">":"["+Z+"]"}UJ.Argument=W3;UJ.humanReadableArgName=BJ});var KX=C((LJ)=>{var{humanReadableArgName:FJ}=sZ();class V3{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)=>FJ(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 B=K.map((U)=>{return G(Z.styleOptionTerm(Z.optionTerm(U)),Z.styleOptionDescription(Z.optionDescription(U)))});z=z.concat(this.formatItemList(H,B,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 B=K.map((U)=>{return G(Z.styleSubcommandTerm(Z.subcommandTerm(U)),Z.styleSubcommandDescription(Z.subcommandDescription(U)))});z=z.concat(this.formatItemList(H,B,Z))}),z.join(`
|
|
4
|
+
`)}displayWidth($){return H3($).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 H3($){let Z=/\x1b\[\d*(;\d*)*m/g;return $.replace(Z,"")}LJ.Help=V3;LJ.stripColor=H3});var BX=C((_J)=>{var{InvalidArgumentError:OJ}=I2();class B3{constructor($,Z){this.flags=$,this.description=Z||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let X=NJ($);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 OJ(`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 K3(this.name().replace(/^no-/,""));return K3(this.name())}helpGroup($){return this.helpGroupHeading=$,this}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class U3{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 K3($){return $.split("-").reduce((Z,X)=>{return Z+X[0].toUpperCase()+X.slice(1)})}function NJ($){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}}_J.Option=B3;_J.DualOptions=U3});var q3=C((AJ)=>{function EJ($,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 RJ($,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=EJ($,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""}AJ.suggestSimilar=RJ});var w3=C((fJ)=>{var CJ=r0("events").EventEmitter,UX=r0("child_process"),s0=r0("path"),oZ=r0("fs"),l=r0("process"),{Argument:IJ,humanReadableArgName:jJ}=sZ(),{CommanderError:qX}=I2(),{Help:xJ,stripColor:kJ}=KX(),{Option:T3,DualOptions:bJ}=BX(),{suggestSimilar:F3}=q3();class FX extends CJ{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:()=>TX()??(l.stdout.isTTY&&l.stdout.hasColors?.()),getErrHasColors:()=>TX()??(l.stderr.isTTY&&l.stderr.hasColors?.()),stripColor:(Z)=>kJ(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 FX($)}createHelp(){return Object.assign(new xJ,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 IJ($,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 qX($,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 T3($,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 T3)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(oZ.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=s0.resolve(V,K);if(
|
|
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=s0.resolve(V,K);if(oZ.existsSync(H))return H;if(Y.includes(s0.extname(K)))return;let B=Y.find((U)=>oZ.existsSync(`${H}${U}`));if(B)return`${H}${B}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let z=$._executableFile||`${this._name}-${$._name}`,J=this._executableDir||"";if(this._scriptPath){let V;try{V=oZ.realpathSync(this._scriptPath)}catch{V=this._scriptPath}J=s0.resolve(s0.dirname(V),J)}if(J){let V=G(J,z);if(!V&&!$._executableFile&&this._scriptPath){let K=s0.basename(this._scriptPath,s0.extname(this._scriptPath));if(K!==this._name)V=G(J,`${K}-${$._name}`)}z=V||z}X=Y.includes(s0.extname(z));let Q;if(l.platform!=="win32")if(X)Z.unshift(z),Z=L3(l.execArgv).concat(Z),Q=UX.spawn(l.argv[0],Z,{stdio:"inherit"});else Q=UX.spawn(z,Z,{stdio:"inherit"});else this._checkForMissingExecutable(z,J,$._name),Z.unshift(z),Z=L3(l.execArgv).concat(Z),Q=UX.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 qX(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 qX(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
|
|
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 bJ(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=F3($,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=F3($,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 jJ(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=s0.basename($,s0.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
|
-
`)}}C0.defaultYaml={explicit:!1,version:"1.2"};C0.defaultTags={"!!":"tag:yaml.org,2002:"};
|
|
30
|
-
`)?
|
|
28
|
+
`)}),this}_outputHelpIfRequested($){let Z=this._getHelpOption();if(Z&&$.find((Y)=>Z.is(Y)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function L3($){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 TX(){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}fJ.Command=FX;fJ.useColor=TX});var _3=C((uJ)=>{var{Argument:M3}=sZ(),{Command:LX}=w3(),{CommanderError:gJ,InvalidArgumentError:O3}=I2(),{Help:hJ}=KX(),{Option:N3}=BX();uJ.program=new LX;uJ.createCommand=($)=>new LX($);uJ.createOption=($,Z)=>new N3($,Z);uJ.createArgument=($,Z)=>new M3($,Z);uJ.Command=LX;uJ.Option=N3;uJ.Argument=M3;uJ.Help=hJ;uJ.CommanderError=gJ;uJ.InvalidArgumentError=O3;uJ.InvalidOptionArgumentError=O3});var m=C((JQ)=>{var NX=Symbol.for("yaml.alias"),E3=Symbol.for("yaml.document"),tZ=Symbol.for("yaml.map"),R3=Symbol.for("yaml.pair"),_X=Symbol.for("yaml.scalar"),eZ=Symbol.for("yaml.seq"),o0=Symbol.for("yaml.node.type"),eJ=($)=>!!$&&typeof $==="object"&&$[o0]===NX,$Q=($)=>!!$&&typeof $==="object"&&$[o0]===E3,ZQ=($)=>!!$&&typeof $==="object"&&$[o0]===tZ,XQ=($)=>!!$&&typeof $==="object"&&$[o0]===R3,A3=($)=>!!$&&typeof $==="object"&&$[o0]===_X,YQ=($)=>!!$&&typeof $==="object"&&$[o0]===eZ;function S3($){if($&&typeof $==="object")switch($[o0]){case tZ:case eZ:return!0}return!1}function GQ($){if($&&typeof $==="object")switch($[o0]){case NX:case tZ:case _X:case eZ:return!0}return!1}var zQ=($)=>(A3($)||S3($))&&!!$.anchor;JQ.ALIAS=NX;JQ.DOC=E3;JQ.MAP=tZ;JQ.NODE_TYPE=o0;JQ.PAIR=R3;JQ.SCALAR=_X;JQ.SEQ=eZ;JQ.hasAnchor=zQ;JQ.isAlias=eJ;JQ.isCollection=S3;JQ.isDocument=$Q;JQ.isMap=ZQ;JQ.isNode=GQ;JQ.isPair=XQ;JQ.isScalar=A3;JQ.isSeq=YQ});var j2=C((PQ)=>{var t=m(),O0=Symbol("break visit"),C3=Symbol("skip children"),u0=Symbol("remove node");function $6($,Z){let X=I3(Z);if(t.isDocument($)){if(O1(null,$.contents,X,Object.freeze([$]))===u0)$.contents=null}else O1(null,$,X,Object.freeze([]))}$6.BREAK=O0;$6.SKIP=C3;$6.REMOVE=u0;function O1($,Z,X,Y){let G=j3($,Z,X,Y);if(t.isNode(G)||t.isPair(G))return x3($,Y,G),O1($,G,X,Y);if(typeof G!=="symbol"){if(t.isCollection(Z)){Y=Object.freeze(Y.concat(Z));for(let z=0;z<Z.items.length;++z){let J=O1(z,Z.items[z],X,Y);if(typeof J==="number")z=J-1;else if(J===O0)return O0;else if(J===u0)Z.items.splice(z,1),z-=1}}else if(t.isPair(Z)){Y=Object.freeze(Y.concat(Z));let z=O1("key",Z.key,X,Y);if(z===O0)return O0;else if(z===u0)Z.key=null;let J=O1("value",Z.value,X,Y);if(J===O0)return O0;else if(J===u0)Z.value=null}}return G}async function Z6($,Z){let X=I3(Z);if(t.isDocument($)){if(await N1(null,$.contents,X,Object.freeze([$]))===u0)$.contents=null}else await N1(null,$,X,Object.freeze([]))}Z6.BREAK=O0;Z6.SKIP=C3;Z6.REMOVE=u0;async function N1($,Z,X,Y){let G=await j3($,Z,X,Y);if(t.isNode(G)||t.isPair(G))return x3($,Y,G),N1($,G,X,Y);if(typeof G!=="symbol"){if(t.isCollection(Z)){Y=Object.freeze(Y.concat(Z));for(let z=0;z<Z.items.length;++z){let J=await N1(z,Z.items[z],X,Y);if(typeof J==="number")z=J-1;else if(J===O0)return O0;else if(J===u0)Z.items.splice(z,1),z-=1}}else if(t.isPair(Z)){Y=Object.freeze(Y.concat(Z));let z=await N1("key",Z.key,X,Y);if(z===O0)return O0;else if(z===u0)Z.key=null;let J=await N1("value",Z.value,X,Y);if(J===O0)return O0;else if(J===u0)Z.value=null}}return G}function I3($){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 j3($,Z,X,Y){if(typeof X==="function")return X($,Z,Y);if(t.isMap(Z))return X.Map?.($,Z,Y);if(t.isSeq(Z))return X.Seq?.($,Z,Y);if(t.isPair(Z))return X.Pair?.($,Z,Y);if(t.isScalar(Z))return X.Scalar?.($,Z,Y);if(t.isAlias(Z))return X.Alias?.($,Z,Y);return}function x3($,Z,X){let Y=Z[Z.length-1];if(t.isCollection(Y))Y.items[$]=X;else if(t.isPair(Y))if($==="key")Y.key=X;else Y.value=X;else if(t.isDocument(Y))Y.contents=X;else{let G=t.isAlias(Y)?"alias":"scalar";throw Error(`Cannot replace node with ${G} parent`)}}PQ.visit=$6;PQ.visitAsync=Z6});var PX=C((CQ)=>{var k3=m(),RQ=j2(),AQ={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},SQ=($)=>$.replace(/[!,[\]{}]/g,(Z)=>AQ[Z]);class C0{constructor($,Z){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},C0.defaultYaml,$),this.tags=Object.assign({},C0.defaultTags,Z)}clone(){let $=new C0(this.yaml,this.tags);return $.docStart=this.docStart,$}atDocument(){let $=new C0(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:C0.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},C0.defaultTags);break}return $}add($,Z){if(this.atNextDocument)this.yaml={explicit:C0.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},C0.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+SQ($.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&&k3.isNode($.contents)){let G={};RQ.visit($.contents,(z,J)=>{if(k3.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
|
+
`)}}C0.defaultYaml={explicit:!1,version:"1.2"};C0.defaultTags={"!!":"tag:yaml.org,2002:"};CQ.Directives=C0});var X6=C((bQ)=>{var b3=m(),jQ=j2();function xQ($){if(/[\x00-\x19\s,[\]{}]/.test($)){let X=`Anchor must not contain whitespace or control characters: ${JSON.stringify($)}`;throw Error(X)}return!0}function f3($){let Z=new Set;return jQ.visit($,{Value(X,Y){if(Y.anchor)Z.add(Y.anchor)}}),Z}function y3($,Z){for(let X=1;;++X){let Y=`${$}${X}`;if(!Z.has(Y))return Y}}function kQ($,Z){let X=[],Y=new Map,G=null;return{onAnchor:(z)=>{X.push(z),G??(G=f3($));let J=y3(Z,G);return G.add(J),J},setAnchors:()=>{for(let z of X){let J=Y.get(z);if(typeof J==="object"&&J.anchor&&(b3.isScalar(J.node)||b3.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}}bQ.anchorIsValid=xQ;bQ.anchorNames=f3;bQ.createNodeAnchors=kQ;bQ.findNewAnchor=y3});var DX=C((hQ)=>{function x2($,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=x2($,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=x2($,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=x2($,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=x2($,Y,G,z);if(J===void 0)delete Y[G];else if(J!==z)Y[G]=J}return $.call(Z,X,Y)}hQ.applyReviver=x2});var K$=C((dQ)=>{var mQ=m();function v3($,Z,X){if(Array.isArray($))return $.map((Y,G)=>v3(Y,String(G),X));if($&&typeof $.toJSON==="function"){if(!X||!mQ.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 $}dQ.toJS=v3});var Y6=C((iQ)=>{var lQ=DX(),g3=m(),pQ=K$();class h3{constructor($){Object.defineProperty(this,g3.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(!g3.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=pQ.toJS(this,"",z);if(typeof Y==="function")for(let{count:Q,res:W}of z.anchors.values())Y(W,Q);return typeof G==="function"?lQ.applyReviver(G,{"":J},"",J):J}}iQ.NodeBase=h3});var k2=C((tQ)=>{var nQ=X6(),rQ=j2(),_1=m(),sQ=Y6(),oQ=K$();class u3 extends sQ.NodeBase{constructor($){super(_1.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=[],rQ.visit($,{Node:(G,z)=>{if(_1.isAlias(z)||_1.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)oQ.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=G6(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(nQ.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 G6($,Z,X){if(_1.isAlias(Z)){let Y=Z.resolve($),G=X&&Y&&X.get(Y);return G?G.count*G.aliasCount:0}else if(_1.isCollection(Z)){let Y=0;for(let G of Z.items){let z=G6($,G,X);if(z>Y)Y=z}return Y}else if(_1.isPair(Z)){let Y=G6($,Z.key,X),G=G6($,Z.value,X);return Math.max(Y,G)}return 1}tQ.Alias=u3});var o=C((GW)=>{var $W=m(),ZW=Y6(),XW=K$(),YW=($)=>!$||typeof $!=="function"&&typeof $!=="object";class m$ extends ZW.NodeBase{constructor($){super($W.SCALAR);this.value=$}toJSON($,Z){return Z?.keep?this.value:XW.toJS(this.value,$,Z)}toString(){return String(this.value)}}m$.BLOCK_FOLDED="BLOCK_FOLDED";m$.BLOCK_LITERAL="BLOCK_LITERAL";m$.PLAIN="PLAIN";m$.QUOTE_DOUBLE="QUOTE_DOUBLE";m$.QUOTE_SINGLE="QUOTE_SINGLE";GW.Scalar=m$;GW.isScalarValue=YW});var b2=C((KW)=>{var QW=k2(),d$=m(),m3=o(),WW="tag:yaml.org,2002:";function VW($,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 HW($,Z,X){if(d$.isDocument($))$=$.contents;if(d$.isNode($))return $;if(d$.isPair($)){let H=X.schema[d$.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 QW.Alias(W.anchor);else W={anchor:null,node:null},Q.set($,W);if(Z?.startsWith("!!"))Z=WW+Z.slice(2);let V=VW($,Z,J.tags);if(!V){if($&&typeof $.toJSON==="function")$=$.toJSON();if(!$||typeof $!=="object"){let H=new m3.Scalar($);if(W)W.node=H;return H}V=$ instanceof Map?J[d$.MAP]:(Symbol.iterator in Object($))?J[d$.SEQ]:J[d$.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 m3.Scalar($);if(Z)K.tag=Z;else if(!V.default)K.tag=V.tag;if(W)W.node=K;return K}KW.createNode=HW});var z6=C((TW)=>{var UW=b2(),m0=m(),qW=Y6();function EX($,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 UW.createNode(Y,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:$,sourceObjects:new Map})}var d3=($)=>$==null||typeof $==="object"&&!!$[Symbol.iterator]().next().done;class c3 extends qW.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)=>m0.isNode(X)||m0.isPair(X)?X.clone($):X),this.range)Z.range=this.range.slice();return Z}addIn($,Z){if(d3($))this.add(Z);else{let[X,...Y]=$,G=this.get(X,!0);if(m0.isCollection(G))G.addIn(Y,Z);else if(G===void 0&&this.schema)this.set(X,EX(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(m0.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&&m0.isScalar(G)?G.value:G;else return m0.isCollection(G)?G.getIn(Y,Z):void 0}hasAllNullValues($){return this.items.every((Z)=>{if(!m0.isPair(Z))return!1;let X=Z.value;return X==null||$&&m0.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 m0.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(m0.isCollection(G))G.setIn(Y,Z);else if(G===void 0&&this.schema)this.set(X,EX(this.schema,Y,Z));else throw Error(`Expected YAML collection at ${X}. Remaining path: ${Y}`)}}}TW.Collection=c3;TW.collectionFromPath=EX;TW.isEmptyPath=d3});var f2=C((NW)=>{var MW=($)=>$.replace(/^(?!$)(?: $)?/gm,"#");function RX($,Z){if(/^\n+$/.test($))return $.substring(1);return Z?$.replace(/^(?! *$)/gm,Z):$}var OW=($,Z,X)=>$.endsWith(`
|
|
30
|
+
`)?RX(X,Z):X.includes(`
|
|
31
31
|
`)?`
|
|
32
|
-
`+
|
|
33
|
-
`){if(X==="block")T=
|
|
34
|
-
`&&U!=="\t"){let
|
|
35
|
-
`&&
|
|
36
|
-
${Z}${$.slice(0,
|
|
37
|
-
${Z}${$.slice(
|
|
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 y2($,Z){let X=JSON.stringify($);if(Z.options.doubleQuotedAsJSON)return X;let{implicitKey:Y}=Z,G=Z.options.doubleQuotedMinMultiLineLength,z=Z.indent||(
|
|
32
|
+
`+RX(X,Z):($.endsWith(" ")?"":" ")+X;NW.indentComment=RX;NW.lineComment=OW;NW.stringifyComment=MW});var p3=C((RW)=>{function EW($,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 B=void 0,U=void 0,F=!1,T=-1,w=-1,O=-1;if(X==="block"){if(T=l3($,T,Z.length),T!==-1)H=T+W}for(let _;_=$[T+=1];){if(X==="quoted"&&_==="\\"){switch(w=T,$[T+1]){case"x":T+=3;break;case"u":T+=5;break;case"U":T+=9;break;default:T+=1}O=T}if(_===`
|
|
33
|
+
`){if(X==="block")T=l3($,T,Z.length);H=T+Z.length+W,B=void 0}else{if(_===" "&&U&&U!==" "&&U!==`
|
|
34
|
+
`&&U!=="\t"){let P=$[T+1];if(P&&P!==" "&&P!==`
|
|
35
|
+
`&&P!=="\t")B=T}if(T>=H)if(B)V.push(B),H=B+W,B=void 0;else if(X==="quoted"){while(U===" "||U==="\t")U=_,_=$[T+=1],F=!0;let P=T>O+1?T-2:w-1;if(K[P])return $;V.push(P),K[P]=!0,H=P+W,B=void 0}else F=!0}U=_}if(F&&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
|
+
${Z}${$.slice(0,R)}`;else{if(X==="quoted"&&K[P])N+=`${$[P]}\\`;N+=`
|
|
37
|
+
${Z}${$.slice(P+1,R)}`}}return N}function l3($,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}RW.FOLD_BLOCK="block";RW.FOLD_FLOW="flow";RW.FOLD_QUOTED="quoted";RW.foldFlowLines=EW});var v2=C((bW)=>{var f0=o(),B$=p3(),Q6=($,Z)=>({indentAtStart:Z?$.indent.length:$.indentAtStart,lineWidth:$.options.lineWidth,minContentWidth:$.options.minContentWidth}),W6=($)=>/^(%|---|\.\.\.)/m.test($);function jW($,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 y2($,Z){let X=JSON.stringify($);if(Z.options.doubleQuotedAsJSON)return X;let{implicitKey:Y}=Z,G=Z.options.doubleQuotedMinMultiLineLength,z=Z.indent||(W6($)?" ":""),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:B$.foldFlowLines(J,z,B$.FOLD_QUOTED,
|
|
43
|
-
`)||/[ \t]\n|\n[ \t]/.test($))return y2($,Z);let X=Z.indent||(
|
|
44
|
-
${X}`)+"'";return Z.implicitKey?Y:B$.foldFlowLines(Y,X,B$.FOLD_FLOW,
|
|
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:B$.foldFlowLines(J,z,B$.FOLD_QUOTED,Q6(Z,!1))}function AX($,Z){if(Z.options.singleQuote===!1||Z.implicitKey&&$.includes(`
|
|
43
|
+
`)||/[ \t]\n|\n[ \t]/.test($))return y2($,Z);let X=Z.indent||(W6($)?" ":""),Y="'"+$.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
44
|
+
${X}`)+"'";return Z.implicitKey?Y:B$.foldFlowLines(Y,X,B$.FOLD_FLOW,Q6(Z,!1))}function P1($,Z){let{singleQuote:X}=Z.options,Y;if(X===!1)Y=y2;else{let G=$.includes('"'),z=$.includes("'");if(G&&!z)Y=AX;else if(z&&!G)Y=y2;else Y=X?AX:y2}return Y($,Z)}var SX;try{SX=new RegExp(`(^|(?<!
|
|
45
45
|
))
|
|
46
46
|
+(?!
|
|
47
|
-
|$)`,"g")}catch{
|
|
47
|
+
|$)`,"g")}catch{SX=/\n+(?!\n|$)/g}function J6({comment:$,type:Z,value:X},Y,G,z){let{blockQuote:J,commentString:Q,lineWidth:W}=Y.options;if(!J||/\n[\t ]+$/.test(X))return P1(X,Y);let V=Y.indent||(Y.forceBlockIndent||W6(X)?" ":""),K=J==="literal"?!0:J==="folded"||Z===f0.Scalar.BLOCK_FOLDED?!1:Z===f0.Scalar.BLOCK_LITERAL?!0:!jW(X,W,V.length);if(!X)return K?`|
|
|
48
48
|
`:`>
|
|
49
|
-
`;let H,B;for(B=X.length;B>0;--B){let
|
|
50
|
-
`&&
|
|
49
|
+
`;let H,B;for(B=X.length;B>0;--B){let R=X[B-1];if(R!==`
|
|
50
|
+
`&&R!=="\t"&&R!==" ")break}let U=X.substring(B),F=U.indexOf(`
|
|
51
51
|
`);if(F===-1)H="-";else if(X===U||F!==U.length-1){if(H="+",z)z()}else H="";if(U){if(X=X.slice(0,-U.length),U[U.length-1]===`
|
|
52
|
-
`)U=U.slice(0,-1);U=U.replace(
|
|
53
|
-
`)O=w;else break}let N=X.substring(0,O<w?O+1:w);if(N)X=X.substring(N.length),N=N.replace(/\n+/g,`$&${V}`);let
|
|
54
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${V}`),A=!1,
|
|
55
|
-
${V}${D}`}return X=X.replace(/\n+/g,`$&${V}`),`|${
|
|
56
|
-
${V}${N}${X}${U}`}function
|
|
52
|
+
`)U=U.slice(0,-1);U=U.replace(SX,`$&${V}`)}let T=!1,w,O=-1;for(w=0;w<X.length;++w){let R=X[w];if(R===" ")T=!0;else if(R===`
|
|
53
|
+
`)O=w;else break}let N=X.substring(0,O<w?O+1:w);if(N)X=X.substring(N.length),N=N.replace(/\n+/g,`$&${V}`);let P=(T?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=Q6(Y,!0);if(J!=="folded"&&Z!==f0.Scalar.BLOCK_FOLDED)S.onOverflow=()=>{A=!0};let D=B$.foldFlowLines(`${N}${R}${U}`,V,B$.FOLD_BLOCK,S);if(!A)return`>${P}
|
|
55
|
+
${V}${D}`}return X=X.replace(/\n+/g,`$&${V}`),`|${P}
|
|
56
|
+
${V}${N}${X}${U}`}function xW($,Z,X,Y){let{type:G,value:z}=$,{actualString:J,implicitKey:Q,indent:W,indentStep:V,inFlow:K}=Z;if(Q&&z.includes(`
|
|
57
57
|
`)||K&&/[[\]{},]/.test(z))return P1(z,Z);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(z))return Q||K||!z.includes(`
|
|
58
|
-
`)?P1(z,Z):
|
|
59
|
-
`))return
|
|
60
|
-
${W}`);if(J){let B=(T)=>T.default&&T.tag!=="tag:yaml.org,2002:str"&&T.test?.test(H),{compat:U,tags:F}=Z.doc.schema;if(F.some(B)||U?.some(B))return P1(z,Z)}return Q?H:B$.foldFlowLines(H,W,B$.FOLD_FLOW,
|
|
61
|
-
${Z.indent}${Q}`}
|
|
62
|
-
${Q}:`}else if(w=`${w}:`,B)w+=h2.lineComment(w,X.indent,V(B));let O,N,
|
|
63
|
-
`:"",N){let
|
|
64
|
-
${h2.indentComment(
|
|
65
|
-
`&&
|
|
58
|
+
`)?P1(z,Z):J6($,Z,X,Y);if(!Q&&!K&&G!==f0.Scalar.PLAIN&&z.includes(`
|
|
59
|
+
`))return J6($,Z,X,Y);if(W6(z)){if(W==="")return Z.forceBlockIndent=!0,J6($,Z,X,Y);else if(Q&&W===V)return P1(z,Z)}let H=z.replace(/\n+/g,`$&
|
|
60
|
+
${W}`);if(J){let B=(T)=>T.default&&T.tag!=="tag:yaml.org,2002:str"&&T.test?.test(H),{compat:U,tags:F}=Z.doc.schema;if(F.some(B)||U?.some(B))return P1(z,Z)}return Q?H:B$.foldFlowLines(H,W,B$.FOLD_FLOW,Q6(Z,!1))}function kW($,Z,X,Y){let{implicitKey:G,inFlow:z}=Z,J=typeof $.value==="string"?$:Object.assign({},$,{value:String($.value)}),{type:Q}=$;if(Q!==f0.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(J.value))Q=f0.Scalar.QUOTE_DOUBLE}let W=(K)=>{switch(K){case f0.Scalar.BLOCK_FOLDED:case f0.Scalar.BLOCK_LITERAL:return G||z?P1(J.value,Z):J6(J,Z,X,Y);case f0.Scalar.QUOTE_DOUBLE:return y2(J.value,Z);case f0.Scalar.QUOTE_SINGLE:return AX(J.value,Z);case f0.Scalar.PLAIN:return xW(J,Z,X,Y);default:return null}},V=W(Q);if(V===null){let{defaultKeyType:K,defaultStringType:H}=Z.options,B=G&&K||H;if(V=W(B),V===null)throw Error(`Unsupported default string type ${B}`)}return V}bW.stringifyString=kW});var g2=C((cW)=>{var yW=X6(),U$=m(),vW=f2(),gW=v2();function hW($,Z){let X=Object.assign({blockQuote:!0,commentString:vW.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 uW($,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 mW($,Z,{anchors:X,doc:Y}){if(!Y.directives)return"";let G=[],z=(U$.isScalar($)||U$.isCollection($))&&$.anchor;if(z&&yW.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 dW($,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=uW(Z.doc.schema.tags,z));let J=mW(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)?gW.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}`}cW.createStringifyContext=hW;cW.stringify=dW});var n3=C((aW)=>{var t0=m(),i3=o(),a3=g2(),h2=f2();function iW({key:$,value:Z},X,Y,G){let{allNullValues:z,doc:J,indent:Q,indentStep:W,options:{commentString:V,indentSeq:K,simpleKeys:H}}=X,B=t0.isNode($)&&$.comment||null;if(H){if(B)throw Error("With simple keys, key nodes cannot have comments");if(t0.isCollection($)||!t0.isNode($)&&typeof $==="object")throw Error("With simple keys, collection cannot be used as a key value")}let U=!H&&(!$||B&&Z==null&&!X.inFlow||t0.isCollection($)||(t0.isScalar($)?$.type===i3.Scalar.BLOCK_FOLDED||$.type===i3.Scalar.BLOCK_LITERAL:typeof $==="object"));X=Object.assign({},X,{allNullValues:!1,implicitKey:!U&&(H||!z),indent:Q+W});let F=!1,T=!1,w=a3.stringify($,X,()=>F=!0,()=>T=!0);if(!U&&!X.inFlow&&w.length>1024){if(H)throw Error("With simple keys, single line scalar must not span more than 1024 characters");U=!0}if(X.inFlow){if(z||Z==null){if(F&&Y)Y();return w===""?"?":U?`? ${w}`:w}}else if(z&&!H||Z==null&&U){if(w=`? ${w}`,B&&!F)w+=h2.lineComment(w,X.indent,V(B));else if(T&&G)G();return w}if(F)B=null;if(U){if(B)w+=h2.lineComment(w,X.indent,V(B));w=`? ${w}
|
|
62
|
+
${Q}:`}else if(w=`${w}:`,B)w+=h2.lineComment(w,X.indent,V(B));let O,N,_;if(t0.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,!U&&!B&&t0.isScalar(Z))X.indentAtStart=w.length+1;if(T=!1,!K&&W.length>=2&&!X.inFlow&&!U&&t0.isSeq(Z)&&!Z.flow&&!Z.tag&&!Z.anchor)X.indent=X.indent.substring(2);let P=!1,R=a3.stringify(Z,X,()=>P=!0,()=>T=!0),A=" ";if(B||O||N){if(A=O?`
|
|
63
|
+
`:"",N){let S=V(N);A+=`
|
|
64
|
+
${h2.indentComment(S,X.indent)}`}if(R===""&&!X.inFlow){if(A===`
|
|
65
|
+
`&&_)A=`
|
|
66
66
|
|
|
67
67
|
`}else A+=`
|
|
68
|
-
${X.indent}`}else if(!U&&t0.isCollection(Z)){let
|
|
69
|
-
`),
|
|
70
|
-
${X.indent}`}}else if(
|
|
71
|
-
`)A="";if(w+=A+
|
|
68
|
+
${X.indent}`}else if(!U&&t0.isCollection(Z)){let S=R[0],D=R.indexOf(`
|
|
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
|
+
${X.indent}`}}else if(R===""||R[0]===`
|
|
71
|
+
`)A="";if(w+=A+R,X.inFlow){if(P&&Y)Y()}else if(_&&!P)w+=h2.lineComment(w,X.indent,V(_));else if(T&&G)G();return w}aW.stringifyPair=iW});var CX=C((oW)=>{var r3=r0("process");function rW($,...Z){if($==="debug")console.log(...Z)}function sW($,Z){if($==="debug"||$==="warn")if(typeof r3.emitWarning==="function")r3.emitWarning(Z);else console.warn(Z)}oW.debug=rW;oW.warn=sW});var K6=C((ZV)=>{var u2=m(),s3=o(),V6="<<",H6={identify:($)=>$===V6||typeof $==="symbol"&&$.description===V6,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new s3.Scalar(Symbol(V6)),{addToJSMap:o3}),stringify:()=>V6},$V=($,Z)=>(H6.identify(Z)||u2.isScalar(Z)&&(!Z.type||Z.type===s3.Scalar.PLAIN)&&H6.identify(Z.value))&&$?.doc.schema.tags.some((X)=>X.tag===H6.tag&&X.default);function o3($,Z,X){if(X=$&&u2.isAlias(X)?X.resolve($.doc):X,u2.isSeq(X))for(let Y of X.items)IX($,Z,Y);else if(Array.isArray(X))for(let Y of X)IX($,Z,Y);else IX($,Z,X)}function IX($,Z,X){let Y=$&&u2.isAlias(X)?X.resolve($.doc):X;if(!u2.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}ZV.addMergeToJSMap=o3;ZV.isMergeKey=$V;ZV.merge=H6});var xX=C((VV)=>{var zV=CX(),t3=K6(),JV=g2(),e3=m(),jX=K$();function QV($,Z,{key:X,value:Y}){if(e3.isNode(X)&&X.addToJSMap)X.addToJSMap($,Z,Y);else if(t3.isMergeKey($,X))t3.addMergeToJSMap($,Z,Y);else{let G=jX.toJS(X,"",$);if(Z instanceof Map)Z.set(G,jX.toJS(Y,G,$));else if(Z instanceof Set)Z.add(G);else{let z=WV(X,G,$),J=jX.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 WV($,Z,X){if(Z===null)return"";if(typeof Z!=="object")return String(Z);if(e3.isNode($)&&X?.doc){let Y=JV.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)+'..."';zV.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)}VV.addPairToJSMap=QV});var q$=C((qV)=>{var $7=b2(),KV=n3(),BV=xX(),B6=m();function UV($,Z,X){let Y=$7.createNode($,void 0,X),G=$7.createNode(Z,void 0,X);return new U6(Y,G)}class U6{constructor($,Z=null){Object.defineProperty(this,B6.NODE_TYPE,{value:B6.PAIR}),this.key=$,this.value=Z}clone($){let{key:Z,value:X}=this;if(B6.isNode(Z))Z=Z.clone($);if(B6.isNode(X))X=X.clone($);return new U6(Z,X)}toJSON($,Z){let X=Z?.mapAsMap?new Map:{};return BV.addPairToJSMap(Z,X,this)}toString($,Z,X){return $?.doc?KV.stringifyPair(this,$,Z,X):JSON.stringify(this)}}qV.Pair=U6;qV.createPair=UV});var kX=C((OV)=>{var c$=m(),Z7=g2(),q6=f2();function LV($,Z,X){return(Z.inFlow??$.flow?MV:wV)($,Z,X)}function wV({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,B=[];for(let F=0;F<Z.length;++F){let T=Z[F],w=null;if(c$.isNode(T)){if(!H&&T.spaceBefore)B.push("");if(T6(X,B,T.commentBefore,H),T.comment)w=T.comment}else if(c$.isPair(T)){let N=c$.isNode(T.key)?T.key:null;if(N){if(!H&&N.spaceBefore)B.push("");T6(X,B,N.commentBefore,H)}}H=!1;let O=Z7.stringify(T,K,()=>w=null,()=>H=!0);if(w)O+=q6.lineComment(O,z,V(w));if(H&&w)H=!1;B.push(Y+O)}let U;if(B.length===0)U=G.start+G.end;else{U=B[0];for(let F=1;F<B.length;++F){let T=B[F];U+=T?`
|
|
72
72
|
${W}${T}`:`
|
|
73
73
|
`}}if($){if(U+=`
|
|
74
|
-
`+
|
|
74
|
+
`+q6.indentComment(V($),W),Q)Q()}else if(H&&J)J();return U}function MV({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 F=0;F<$.length;++F){let T=$[F],w=null;if(c$.isNode(T)){if(T.spaceBefore)H.push("");if(T6(Z,H,T.commentBefore,!1),T.comment)w=T.comment}else if(c$.isPair(T)){let N=c$.isNode(T.key)?T.key:null;if(N){if(N.spaceBefore)H.push("");if(T6(Z,H,N.commentBefore,!1),N.comment)V=!0}let _=c$.isNode(T.value)?T.value:null;if(_){if(_.comment)w=_.comment;if(_.commentBefore)V=!0}else if(T.value==null&&N?.comment)w=N.comment}if(w)V=!0;let O=Z7.stringify(T,W,()=>w=null);if(F<$.length-1)O+=",";if(w)O+=q6.lineComment(O,Y,Q(w));if(!V&&(H.length>K||O.includes(`
|
|
75
75
|
`)))V=!0;H.push(O),K=H.length}let{start:B,end:U}=X;if(H.length===0)return B+U;else{if(!V){let F=H.reduce((T,w)=>T+w.length+2,2);V=Z.options.lineWidth>0&&F>Z.options.lineWidth}if(V){let F=B;for(let T of H)F+=T?`
|
|
76
76
|
${z}${G}${T}`:`
|
|
77
77
|
`;return`${F}
|
|
78
|
-
${G}${U}`}else return`${B}${J}${H.join(" ")}${J}${U}`}}function
|
|
79
|
-
`:" ")}return
|
|
78
|
+
${G}${U}`}else return`${B}${J}${H.join(" ")}${J}${U}`}}function T6({indent:$,options:{commentString:Z}},X,Y,G){if(Y&&G)Y=Y.replace(/^\n+/,"");if(Y){let z=q6.indentComment(Z(Y),$);X.push(z.trimStart())}}OV.stringifyCollection=LV});var F$=C((RV)=>{var _V=kX(),PV=xX(),DV=z6(),T$=m(),F6=q$(),EV=o();function m2($,Z){let X=T$.isScalar(Z)?Z.value:Z;for(let Y of $)if(T$.isPair(Y)){if(Y.key===Z||Y.key===X)return Y;if(T$.isScalar(Y.key)&&Y.key.value===X)return Y}return}class X7 extends DV.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor($){super(T$.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(F6.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(T$.isPair($))X=$;else if(!$||typeof $!=="object"||!("key"in $))X=new F6.Pair($,$?.value);else X=new F6.Pair($.key,$.value);let Y=m2(this.items,X.key),G=this.schema?.sortMapEntries;if(Y){if(!Z)throw Error(`Key ${X.key} already set`);if(T$.isScalar(Y.value)&&EV.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=m2(this.items,$);if(!Z)return!1;return this.items.splice(this.items.indexOf(Z),1).length>0}get($,Z){let Y=m2(this.items,$)?.value;return(!Z&&T$.isScalar(Y)?Y.value:Y)??void 0}has($){return!!m2(this.items,$)}set($,Z){this.add(new F6.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)PV.addPairToJSMap(Z,Y,G);return Y}toString($,Z,X){if(!$)return JSON.stringify(this);for(let Y of this.items)if(!T$.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 _V.stringifyCollection(this,$,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:$.indent||"",onChompKeep:X,onComment:Z})}}RV.YAMLMap=X7;RV.findPair=m2});var D1=C((jV)=>{var CV=m(),Y7=F$(),IV={collection:"map",default:!0,nodeClass:Y7.YAMLMap,tag:"tag:yaml.org,2002:map",resolve($,Z){if(!CV.isMap($))Z("Expected a mapping for this tag");return $},createNode:($,Z,X)=>Y7.YAMLMap.from($,Z,X)};jV.map=IV});var L$=C((gV)=>{var kV=b2(),bV=kX(),fV=z6(),w6=m(),yV=o(),vV=K$();class G7 extends fV.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor($){super(w6.SEQ,$);this.items=[]}add($){this.items.push($)}delete($){let Z=L6($);if(typeof Z!=="number")return!1;return this.items.splice(Z,1).length>0}get($,Z){let X=L6($);if(typeof X!=="number")return;let Y=this.items[X];return!Z&&w6.isScalar(Y)?Y.value:Y}has($){let Z=L6($);return typeof Z==="number"&&Z<this.items.length}set($,Z){let X=L6($);if(typeof X!=="number")throw Error(`Expected a valid index, not ${$}.`);let Y=this.items[X];if(w6.isScalar(Y)&&yV.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(vV.toJS(G,String(Y++),Z));return X}toString($,Z,X){if(!$)return JSON.stringify(this);return bV.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(kV.createNode(J,void 0,X))}}return G}}function L6($){let Z=w6.isScalar($)?$.value:$;if(Z&&typeof Z==="string")Z=Number(Z);return typeof Z==="number"&&Number.isInteger(Z)&&Z>=0?Z:null}gV.YAMLSeq=G7});var E1=C((dV)=>{var uV=m(),z7=L$(),mV={collection:"seq",default:!0,nodeClass:z7.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve($,Z){if(!uV.isSeq($))Z("Expected a sequence for this tag");return $},createNode:($,Z,X)=>z7.YAMLSeq.from($,Z,X)};dV.seq=mV});var d2=C((iV)=>{var lV=v2(),pV={identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify($,Z,X,Y){return Z=Object.assign({actualString:!0},Z),lV.stringifyString($,Z,X,Y)}};iV.string=pV});var M6=C((nV)=>{var J7=o(),Q7={identify:($)=>$==null,createNode:()=>new J7.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new J7.Scalar(null),stringify:({source:$},Z)=>typeof $==="string"&&Q7.test.test($)?$:Z.options.nullStr};nV.nullTag=Q7});var bX=C((oV)=>{var sV=o(),W7={identify:($)=>typeof $==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:($)=>new sV.Scalar($[0]==="t"||$[0]==="T"),stringify({source:$,value:Z},X){if($&&W7.test.test($)){let Y=$[0]==="t"||$[0]==="T";if(Z===Y)return $}return Z?X.options.trueStr:X.options.falseStr}};oV.boolTag=W7});var R1=C(($H)=>{function eV({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}$H.stringifyNumber=eV});var yX=C((JH)=>{var XH=o(),fX=R1(),YH={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:fX.stringifyNumber},GH={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():fX.stringifyNumber($)}},zH={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve($){let Z=new XH.Scalar(parseFloat($)),X=$.indexOf(".");if(X!==-1&&$[$.length-1]==="0")Z.minFractionDigits=$.length-X-1;return Z},stringify:fX.stringifyNumber};JH.float=zH;JH.floatExp=GH;JH.floatNaN=YH});var gX=C((UH)=>{var V7=R1(),O6=($)=>typeof $==="bigint"||Number.isInteger($),vX=($,Z,X,{intAsBigInt:Y})=>Y?BigInt($):parseInt($.substring(Z),X);function H7($,Z,X){let{value:Y}=$;if(O6(Y)&&Y>=0)return X+Y.toString(Z);return V7.stringifyNumber($)}var HH={identify:($)=>O6($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:($,Z,X)=>vX($,2,8,X),stringify:($)=>H7($,8,"0o")},KH={identify:O6,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:($,Z,X)=>vX($,0,10,X),stringify:V7.stringifyNumber},BH={identify:($)=>O6($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:($,Z,X)=>vX($,2,16,X),stringify:($)=>H7($,16,"0x")};UH.int=KH;UH.intHex=BH;UH.intOct=HH});var K7=C((PH)=>{var LH=D1(),wH=M6(),MH=E1(),OH=d2(),NH=bX(),hX=yX(),uX=gX(),_H=[LH.map,MH.seq,OH.string,wH.nullTag,NH.boolTag,uX.intOct,uX.int,uX.intHex,hX.floatNaN,hX.floatExp,hX.float];PH.schema=_H});var U7=C((jH)=>{var EH=o(),RH=D1(),AH=E1();function B7($){return typeof $==="bigint"||Number.isInteger($)}var N6=({value:$})=>JSON.stringify($),SH=[{identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify:N6},{identify:($)=>$==null,createNode:()=>new EH.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:N6},{identify:($)=>typeof $==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:($)=>$==="true",stringify:N6},{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:N6}],CH={default:!0,tag:"",test:/^/,resolve($,Z){return Z(`Unresolved plain scalar ${JSON.stringify($)}`),$}},IH=[RH.map,AH.seq].concat(SH,CH);jH.schema=IH});var dX=C((fH)=>{var c2=r0("buffer"),mX=o(),kH=v2(),bH={identify:($)=>$ instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve($,Z){if(typeof c2.Buffer==="function")return c2.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 c2.Buffer==="function")Q=J instanceof c2.Buffer?J.toString("base64"):c2.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=mX.Scalar.BLOCK_LITERAL),Z!==mX.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,B=0;H<V;++H,B+=W)K[H]=Q.substr(B,W);Q=K.join(Z===mX.Scalar.BLOCK_LITERAL?`
|
|
79
|
+
`:" ")}return kH.stringifyString({comment:$,type:Z,value:Q},Y,G,z)}};fH.binary=bH});var P6=C((uH)=>{var _6=m(),cX=q$(),vH=o(),gH=L$();function q7($,Z){if(_6.isSeq($))for(let X=0;X<$.items.length;++X){let Y=$.items[X];if(_6.isPair(Y))continue;else if(_6.isMap(Y)){if(Y.items.length>1)Z("Each pair must have its own sequence indicator");let G=Y.items[0]||new cX.Pair(new vH.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]=O6.isPair(Y)?Y:new mX.Pair(Y)}else Z("Expected a sequence for this tag");return $}function B7($,Z,X){let{replacer:Y}=X,G=new bH.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(mX.createPair(Q,W,X))}return G}var fH={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:K7,createNode:B7};yH.createPairs=B7;yH.pairs=fH;yH.resolvePairs=K7});var cX=R((dH)=>{var U7=m(),dX=K$(),l2=F$(),uH=L$(),q7=_6();class l$ extends uH.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(U7.isPair(Y))G=dX.toJS(Y.key,"",Z),z=dX.toJS(Y.value,G,Z);else G=dX.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=q7.createPairs($,Z,X),G=new this;return G.items=Y.items,G}}l$.tag="tag:yaml.org,2002:omap";var mH={collection:"seq",identify:($)=>$ instanceof Map,nodeClass:l$,default:!1,tag:"tag:yaml.org,2002:omap",resolve($,Z){let X=q7.resolvePairs($,Z),Y=[];for(let{key:G}of X.items)if(U7.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)};dH.YAMLOMap=l$;dH.omap=mH});var M7=R((pH)=>{var T7=o();function F7({value:$,source:Z},X){if(Z&&($?L7:w7).test.test(Z))return Z;return $?X.options.trueStr:X.options.falseStr}var L7={identify:($)=>$===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new T7.Scalar(!0),stringify:F7},w7={identify:($)=>$===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new T7.Scalar(!1),stringify:F7};pH.falseTag=w7;pH.trueTag=L7});var N7=R((tH)=>{var nH=o(),lX=R1(),rH={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:lX.stringifyNumber},sH={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():lX.stringifyNumber($)}},oH={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve($){let Z=new nH.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:lX.stringifyNumber};tH.float=oH;tH.floatExp=sH;tH.floatNaN=rH});var _7=R((JK)=>{var O7=R1(),p2=($)=>typeof $==="bigint"||Number.isInteger($);function P6($,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 pX($,Z,X){let{value:Y}=$;if(p2(Y)){let G=Y.toString(Z);return Y<0?"-"+X+G.substr(1):X+G}return O7.stringifyNumber($)}var XK={identify:p2,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:($,Z,X)=>P6($,2,2,X),stringify:($)=>pX($,2,"0b")},YK={identify:p2,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:($,Z,X)=>P6($,1,8,X),stringify:($)=>pX($,8,"0")},GK={identify:p2,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:($,Z,X)=>P6($,0,10,X),stringify:O7.stringifyNumber},zK={identify:p2,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:($,Z,X)=>P6($,2,16,X),stringify:($)=>pX($,16,"0x")};JK.int=GK;JK.intBin=XK;JK.intHex=zK;JK.intOct=YK});var iX=R((BK)=>{var R6=m(),D6=q$(),E6=F$();class p$ extends E6.YAMLMap{constructor($){super($);this.tag=p$.tag}add($){let Z;if(R6.isPair($))Z=$;else if($&&typeof $==="object"&&"key"in $&&"value"in $&&$.value===null)Z=new D6.Pair($.key,null);else Z=new D6.Pair($,null);if(!E6.findPair(this.items,Z.key))this.items.push(Z)}get($,Z){let X=E6.findPair(this.items,$);return!Z&&R6.isPair(X)?R6.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=E6.findPair(this.items,$);if(X&&!Z)this.items.splice(this.items.indexOf(X),1);else if(!X&&Z)this.items.push(new D6.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(D6.createPair(z,null,X))}return G}}p$.tag="tag:yaml.org,2002:set";var KK={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(R6.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 $}};BK.YAMLSet=p$;BK.set=KK});var nX=R((wK)=>{var TK=R1();function aX($,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 P7($){let{value:Z}=$,X=(J)=>J;if(typeof Z==="bigint")X=(J)=>BigInt(J);else if(isNaN(Z)||!isFinite(Z))return TK.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 FK={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})=>aX($,X),stringify:P7},LK={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:($)=>aX($,!1),stringify:P7},D7={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(D7.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=aX(K,!1);if(Math.abs(H)<30)H*=60;V-=60000*H}return new Date(V)},stringify:({value:$})=>$?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};wK.floatTime=LK;wK.intTime=FK;wK.timestamp=D7});var R7=R((xK)=>{var _K=D1(),PK=w6(),DK=E1(),EK=d2(),RK=uX(),E7=M7(),rX=N7(),A6=_7(),AK=H6(),SK=cX(),CK=_6(),IK=iX(),sX=nX(),jK=[_K.map,DK.seq,EK.string,PK.nullTag,E7.trueTag,E7.falseTag,A6.intBin,A6.intOct,A6.int,A6.intHex,rX.floatNaN,rX.floatExp,rX.float,RK.binary,AK.merge,SK.omap,CK.pairs,IK.set,sX.intTime,sX.floatTime,sX.timestamp];xK.schema=jK});var y7=R((mK)=>{var I7=D1(),bK=w6(),j7=E1(),fK=d2(),yK=xX(),oX=bX(),tX=yX(),gK=W7(),vK=H7(),x7=uX(),i2=H6(),k7=cX(),b7=_6(),A7=R7(),f7=iX(),S6=nX(),S7=new Map([["core",gK.schema],["failsafe",[I7.map,j7.seq,fK.string]],["json",vK.schema],["yaml11",A7.schema],["yaml-1.1",A7.schema]]),C7={binary:x7.binary,bool:yK.boolTag,float:oX.float,floatExp:oX.floatExp,floatNaN:oX.floatNaN,floatTime:S6.floatTime,int:tX.int,intHex:tX.intHex,intOct:tX.intOct,intTime:S6.intTime,map:I7.map,merge:i2.merge,null:bK.nullTag,omap:k7.omap,pairs:b7.pairs,seq:j7.seq,set:f7.set,timestamp:S6.timestamp},hK={"tag:yaml.org,2002:binary":x7.binary,"tag:yaml.org,2002:merge":i2.merge,"tag:yaml.org,2002:omap":k7.omap,"tag:yaml.org,2002:pairs":b7.pairs,"tag:yaml.org,2002:set":f7.set,"tag:yaml.org,2002:timestamp":S6.timestamp};function uK($,Z,X){let Y=S7.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(S7.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"?C7[J]:J;if(!Q){let W=JSON.stringify(J),V=Object.keys(C7).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},[])}mK.coreKnownTags=hK;mK.getTags=uK});var Z9=R((nK)=>{var eX=m(),lK=D1(),pK=E1(),iK=d2(),C6=y7(),aK=($,Z)=>$.key<Z.key?-1:$.key>Z.key?1:0;class $9{constructor({compat:$,customTags:Z,merge:X,resolveKnownTags:Y,schema:G,sortMapEntries:z,toStringDefaults:J}){this.compat=Array.isArray($)?C6.getTags($,"compat"):$?C6.getTags(null,$):null,this.name=typeof G==="string"&&G||"core",this.knownTags=Y?C6.coreKnownTags:{},this.tags=C6.getTags(Z,this.name,X),this.toStringOptions=J??null,Object.defineProperty(this,eX.MAP,{value:lK.map}),Object.defineProperty(this,eX.SCALAR,{value:iK.string}),Object.defineProperty(this,eX.SEQ,{value:pK.seq}),this.sortMapEntries=typeof z==="function"?z:z===!0?aK:null}clone(){let $=Object.create($9.prototype,Object.getOwnPropertyDescriptors(this));return $.tags=this.tags.slice(),$}}nK.Schema=$9});var g7=R((tK)=>{var sK=m(),X9=v2(),a2=f2();function oK($,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=X9.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(sK.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=X9.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(X9.stringify($.contents,G));if($.directives?.docEnd)if($.comment){let W=z($.comment);if(W.includes(`
|
|
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
82
|
`))X.push("..."),X.push(a2.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(a2.indentComment(z(W),""))}}return X.join(`
|
|
83
83
|
`)+`
|
|
84
|
-
`}
|
|
84
|
+
`}XB.stringifyDocument=ZB});var n2=C((KB)=>{var GB=k2(),A1=z6(),I0=m(),zB=q$(),JB=K$(),QB=Y9(),WB=u7(),z9=X6(),VB=DX(),HB=b2(),J9=PX();class Q9{constructor($,Z,X){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,I0.NODE_TYPE,{value:I0.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 J9.Directives({version:z});this.setSchema(z,X),this.contents=$===void 0?null:this.createNode($,Y,X)}clone(){let $=Object.create(Q9.prototype,{[I0.NODE_TYPE]:{value:I0.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=I0.isNode(this.contents)?this.contents.clone($.schema):this.contents,this.range)$.range=this.range.slice();return $}add($){if(S1(this.contents))this.contents.add($)}addIn($,Z){if(S1(this.contents))this.contents.addIn($,Z)}createAlias($,Z){if(!$.anchor){let X=z9.anchorNames(this);$.anchor=!Z||X.has(Z)?z9.findNewAnchor(Z||"a",X):Z}return new GB.Alias($.anchor)}createNode($,Z,X){let Y=void 0;if(typeof Z==="function")$=Z.call({"":$},"",$),Y=Z;else if(Array.isArray(Z)){let T=(O)=>typeof O==="number"||O instanceof String||O instanceof Number,w=Z.filter(T).map(String);if(w.length>0)Z=Z.concat(w);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:B}=z9.createNodeAnchors(this,z||"a"),U={aliasDuplicateObjects:G??!0,keepUndefined:Q??!1,onAnchor:K,onTagObj:W,replacer:Y,schema:this.schema,sourceObjects:B},F=HB.createNode($,V,U);if(J&&I0.isCollection(F))F.flow=!0;return H(),F}createPair($,Z,X={}){let Y=this.createNode($,null,X),G=this.createNode(Z,null,X);return new zB.Pair(Y,G)}delete($){return S1(this.contents)?this.contents.delete($):!1}deleteIn($){if(A1.isEmptyPath($)){if(this.contents==null)return!1;return this.contents=null,!0}return S1(this.contents)?this.contents.deleteIn($):!1}get($,Z){return I0.isCollection(this.contents)?this.contents.get($,Z):void 0}getIn($,Z){if(A1.isEmptyPath($))return!Z&&I0.isScalar(this.contents)?this.contents.value:this.contents;return I0.isCollection(this.contents)?this.contents.getIn($,Z):void 0}has($){return I0.isCollection(this.contents)?this.contents.has($):!1}hasIn($){if(A1.isEmptyPath($))return this.contents!==void 0;return I0.isCollection(this.contents)?this.contents.hasIn($):!1}set($,Z){if(this.contents==null)this.contents=A1.collectionFromPath(this.schema,[$],Z);else if(S1(this.contents))this.contents.set($,Z)}setIn($,Z){if(A1.isEmptyPath($))this.contents=Z;else if(this.contents==null)this.contents=A1.collectionFromPath(this.schema,Array.from($),Z);else if(S1(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 J9.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 J9.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 QB.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=JB.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"?VB.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 WB.stringifyDocument(this,$)}}function S1($){if(I0.isCollection($))return!0;throw Error("Expected a YAML collection as document contents")}KB.Document=Q9});var r2=C((qB)=>{class j6 extends Error{constructor($,Z,X,Y){super();this.name=$,this.code=X,this.message=Y,this.pos=Z}}class m7 extends j6{constructor($,Z,X){super("YAMLParseError",$,Z,X)}}class d7 extends j6{constructor($,Z,X){super("YAMLWarning",$,Z,X)}}var UB=($,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
|
-
`+T.comment;else Q.comment=T.comment;continue}if(T.newlineAfterProp||
|
|
92
|
-
`+
|
|
93
|
-
`+A.comment;else V.comment=A.comment;H=A.end;continue}if(!J&&X.options.strict&&
|
|
94
|
-
`+
|
|
95
|
-
`+
|
|
96
|
-
`+w.comment;else V.comment=w.comment;V.range=[Y.offset,T,w.offset]}else V.range=[Y.offset,T,T];return V}
|
|
89
|
+
`}};qB.YAMLError=j6;qB.YAMLParseError=m7;qB.YAMLWarning=d7;qB.prettifyError=UB});var s2=C((OB)=>{function MB($,{flow:Z,indicator:X,next:Y,offset:G,onError:z,parentIndent:J,startOnNewline:Q}){let W=!1,V=Q,K=Q,H="",B="",U=!1,F=!1,T=null,w=null,O=null,N=null,_=null,P=null,R=null;for(let D of $){if(F){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");F=!1}if(T){if(V&&D.type!=="comment"&&D.type!=="newline")z(T,"TAB_AS_INDENT","Tabs are not allowed as indentation");T=null}switch(D.type){case"space":if(!Z&&(X!=="doc-start"||Y?.type!=="flow-collection")&&D.source.includes("\t"))T=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+=B+k;B="",V=!1;break}case"newline":if(V){if(H)H+=D.source;else if(!P||X!=="seq-item-ind")W=!0}else B+=D.source;if(V=!0,U=!0,w||O)N=D;K=!0;break;case"anchor":if(w)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);w=D,R??(R=D.offset),V=!1,K=!1,F=!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,F=!0;break}case X:if(w||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(F&&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(T&&(V&&T.indent<=J||Y?.type==="block-map"||Y?.type==="block-seq"))z(T,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:_,found:P,spaceBefore:W,comment:H,hasNewline:U,anchor:w,tag:O,newlineAfterProp:N,end:S,start:R??S}}OB.resolveProps=MB});var x6=C((_B)=>{function W9($){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(W9(Z.key)||W9(Z.value))return!0}return!1;default:return!0}}_B.containsNewline=W9});var V9=C((RB)=>{var DB=x6();function EB($,Z,X){if(Z?.type==="flow-collection"){let Y=Z.end[0];if(Y.indent===$&&(Y.source==="]"||Y.source==="}")&&DB.containsNewline(Z))X(Y,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}RB.flowIndentCheck=EB});var H9=C((CB)=>{var c7=m();function SB($,Z,X){let{uniqueKeys:Y}=$.options;if(Y===!1)return!1;let G=typeof Y==="function"?Y:(z,J)=>z===J||c7.isScalar(z)&&c7.isScalar(J)&&z.value===J.value;return Z.some((z)=>G(z.key,X))}CB.mapIncludes=SB});var n7=C((fB)=>{var l7=q$(),jB=F$(),p7=s2(),xB=x6(),i7=V9(),kB=H9(),a7="All mapping items must start at the same column";function bB({composeNode:$,composeEmptyNode:Z},X,Y,G,z){let Q=new(z?.nodeClass??jB.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:B,sep:U,value:F}=K,T=p7.resolveProps(H,{indicator:"explicit-key-ind",next:B??U?.[0],offset:W,onError:G,parentIndent:Y.indent,startOnNewline:!0}),w=!T.found;if(w){if(B){if(B.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 B&&B.indent!==Y.indent)G(W,"BAD_INDENT",a7)}if(!T.anchor&&!T.tag&&!U){if(V=T.end,T.comment)if(Q.comment)Q.comment+=`
|
|
91
|
+
`+T.comment;else Q.comment=T.comment;continue}if(T.newlineAfterProp||xB.containsNewline(B))G(B??H[H.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(T.found?.indent!==Y.indent)G(W,"BAD_INDENT",a7);X.atKey=!0;let O=T.end,N=B?$(X,B,T,G):Z(X,O,H,null,T,G);if(X.schema.compat)i7.flowIndentCheck(Y.indent,B,G);if(X.atKey=!1,kB.mapIncludes(X,Q.items,N))G(O,"DUPLICATE_KEY","Map keys must be unique");let _=p7.resolveProps(U??[],{indicator:"map-value-ind",next:F,offset:N.range[2],onError:G,parentIndent:Y.indent,startOnNewline:!B||B.type==="block-scalar"});if(W=_.end,_.found){if(w){if(F?.type==="block-map"&&!_.hasNewline)G(W,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(X.options.strict&&T.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=F?$(X,F,_,G):Z(X,W,U,null,_,G);if(X.schema.compat)i7.flowIndentCheck(Y.indent,F,G);W=P.range[2];let R=new l7.Pair(N,P);if(X.options.keepSourceTokens)R.srcToken=K;Q.items.push(R)}else{if(w)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 l7.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}fB.resolveBlockMap=bB});var r7=C((mB)=>{var vB=L$(),gB=s2(),hB=V9();function uB({composeNode:$,composeEmptyNode:Z},X,Y,G,z){let Q=new(z?.nodeClass??vB.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 B=gB.resolveProps(K,{indicator:"seq-item-ind",next:H,offset:W,onError:G,parentIndent:Y.indent,startOnNewline:!0});if(!B.found)if(B.anchor||B.tag||H)if(H?.type==="block-seq")G(B.end,"BAD_INDENT","All sequence items must start at the same column");else G(W,"MISSING_CHAR","Sequence item without - indicator");else{if(V=B.end,B.comment)Q.comment=B.comment;continue}let U=H?$(X,H,B,G):Z(X,B.end,K,null,B,G);if(X.schema.compat)hB.flowIndentCheck(Y.indent,H,G);W=U.range[2],Q.items.push(U)}return Q.range=[Y.offset,W,V??W],Q}mB.resolveBlockSeq=uB});var C1=C((lB)=>{function cB($,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}}lB.resolveEnd=cB});var t7=C((eB)=>{var iB=m(),aB=q$(),s7=F$(),nB=L$(),rB=C1(),o7=s2(),sB=x6(),oB=H9(),K9="Block collections are not allowed within flow collections",B9=($)=>$&&($.type==="block-map"||$.type==="block-seq");function tB({composeNode:$,composeEmptyNode:Z},X,Y,G,z){let J=Y.start.source==="{",Q=J?"flow map":"flow sequence",V=new(z?.nodeClass??(J?s7.YAMLMap:nB.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 w=0;w<Y.items.length;++w){let O=Y.items[w],{start:N,key:_,sep:P,value:R}=O,A=o7.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(w===0&&A.comma)G(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${Q}`);else if(w<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&&sB.containsNewline(_))G(_,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(w===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(iB.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],B9(R))G(S.range,"BLOCK_IN_FLOW",K9)}else{X.atKey=!0;let S=A.end,D=_?$(X,_,A,G):Z(X,S,N,null,A,G);if(B9(_))G(D.range,"BLOCK_IN_FLOW",K9);X.atKey=!1;let k=o7.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(B9(R))G(b.range,"BLOCK_IN_FLOW",K9)}else if(k.comment)if(D.comment)D.comment+=`
|
|
95
|
+
`+k.comment;else D.comment=k.comment;let i=new aB.Pair(D,b);if(X.options.keepSourceTokens)i.srcToken=O;if(J){let c=V;if(oB.mapIncludes(X,c.items,D))G(S,"DUPLICATE_KEY","Map keys must be unique");c.items.push(i)}else{let c=new s7.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 B=J?"}":"]",[U,...F]=Y.end,T=H;if(U?.source===B)T=U.offset+U.source.length;else{let w=Q[0].toUpperCase()+Q.substring(1),O=K?`${w} must end with a ${B}`:`${w} in block collection must be sufficiently indented and end with a ${B}`;if(G(H,K?"MISSING_CHAR":"BAD_INDENT",O),U&&U.source.length!==1)F.unshift(U)}if(F.length>0){let w=rB.resolveEnd(F,T,X.options.strict,G);if(w.comment)if(V.comment)V.comment+=`
|
|
96
|
+
`+w.comment;else V.comment=w.comment;V.range=[Y.offset,T,w.offset]}else V.range=[Y.offset,T,T];return V}eB.resolveFlowCollection=tB});var e7=C((VU)=>{var ZU=m(),XU=o(),YU=F$(),GU=L$(),zU=n7(),JU=r7(),QU=t7();function U9($,Z,X,Y,G,z){let J=X.type==="block-map"?zU.resolveBlockMap($,Z,X,Y,z):X.type==="block-seq"?JU.resolveBlockSeq($,Z,X,Y,z):QU.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 WU($,Z,X,Y,G){let z=Y.tag,J=!z?null:Z.directives.tagName(z.source,(B)=>G(z,"TAG_RESOLVE_FAILED",B));if(X.type==="block-seq"){let{anchor:B,newlineAfterProp:U}=Y,F=B&&z?B.offset>z.offset?B:z:B??z;if(F&&(!U||U.offset<F.offset))G(F,"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===YU.YAMLMap.tagName&&Q==="map"||J===GU.YAMLSeq.tagName&&Q==="seq")return U9($,Z,X,G,J);let W=Z.schema.tags.find((B)=>B.tag===J&&B.collection===Q);if(!W){let B=Z.schema.knownTags[J];if(B?.collection===Q)Z.schema.tags.push(Object.assign({},B,{default:!1})),W=B;else{if(B)G(z,"BAD_COLLECTION_TYPE",`${B.tag} used for ${Q} collection, but expects ${B.collection??"scalar"}`,!0);else G(z,"TAG_RESOLVE_FAILED",`Unresolved tag: ${J}`,!0);return U9($,Z,X,G,J)}}let V=U9($,Z,X,G,J,W),K=W.resolve?.(V,(B)=>G(z,"TAG_RESOLVE_FAILED",B),Z.options)??V,H=ZU.isNode(K)?K:new XU.Scalar(K);if(H.range=V.range,H.tag=J,W?.format)H.format=W.format;return H}VU.composeCollection=WU});var T9=C((qU)=>{var q9=o();function KU($,Z,X){let Y=Z.offset,G=BU(Z,$.options.strict,X);if(!G)return{value:"",type:null,comment:"",range:[Y,Y,Y]};let z=G.mode===">"?q9.Scalar.BLOCK_FOLDED:q9.Scalar.BLOCK_LITERAL,J=Z.source?UU(Z.source):[],Q=J.length;for(let T=J.length-1;T>=0;--T){let w=J[T][1];if(w===""||w==="\r")Q=T;else break}if(Q===0){let T=G.chomp==="+"&&J.length>0?`
|
|
97
97
|
`.repeat(Math.max(1,J.length-1)):"",w=Y+G.length;if(Z.source)w+=Z.source.length;return{value:T,type:z,comment:G.comment,range:[Y,w,w]}}let W=Z.indent+G.indent,V=Z.offset+G.length,K=0;for(let T=0;T<Q;++T){let[w,O]=J[T];if(O===""||O==="\r"){if(G.indent===0&&w.length>W)W=w.length}else{if(w.length<W)X(V+w.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(G.indent===0)W=w.length;if(K=T,W===0&&!$.atRoot)X(V,"BAD_INDENT","Block scalar values in collections must be indented");break}V+=w.length+O.length+1}for(let T=J.length-1;T>=Q;--T)if(J[T][0].length>W)Q=T+1;let H="",B="",U=!1;for(let T=0;T<K;++T)H+=J[T][0].slice(W)+`
|
|
98
|
-
`;for(let T=K;T<Q;++T){let[w,O]=J[T];V+=w.length+O.length+1;let N=O[O.length-1]==="\r";if(N)O=O.slice(0,-1);if(O&&w.length<W){let
|
|
98
|
+
`;for(let T=K;T<Q;++T){let[w,O]=J[T];V+=w.length+O.length+1;let N=O[O.length-1]==="\r";if(N)O=O.slice(0,-1);if(O&&w.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),w=""}if(z===q9.Scalar.BLOCK_LITERAL)H+=B+w.slice(W)+O,B=`
|
|
99
99
|
`;else if(w.length>W||O[0]==="\t"){if(B===" ")B=`
|
|
100
100
|
`;else if(!U&&B===`
|
|
101
101
|
`)B=`
|
|
@@ -108,66 +108,66 @@ ${V}
|
|
|
108
108
|
`+J[T][0].slice(W);if(H[H.length-1]!==`
|
|
109
109
|
`)H+=`
|
|
110
110
|
`;break;default:H+=`
|
|
111
|
-
`}let F=Y+G.length+Z.source.length;return{value:H,type:z,comment:G.comment,range:[Y,F,F]}}function
|
|
111
|
+
`}let F=Y+G.length+Z.source.length;return{value:H,type:z,comment:G.comment,range:[Y,F,F]}}function BU({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 B=1;B<G.length;++B){let U=G[B];if(!Q&&(U==="-"||U==="+"))Q=U;else{let F=Number(U);if(!J&&F)J=F;else if(W===-1)W=$+B}}if(W!==-1)Y(W,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${G}`);let V=!1,K="",H=G.length;for(let B=1;B<Z.length;++B){let U=Z[B];switch(U.type){case"space":V=!0;case"newline":H+=U.source.length;break;case"comment":if(X&&!V)Y(U,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");H+=U.source.length,K=U.source.substring(1);break;case"error":Y(U,"UNEXPECTED_TOKEN",U.message),H+=U.source.length;break;default:{let F=`Unexpected token in block scalar header: ${U.type}`;Y(U,"UNEXPECTED_TOKEN",F);let T=U.source;if(T&&typeof T==="string")H+=T.length}}}return{mode:z,indent:J,chomp:Q,comment:K,length:H}}function UU($){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}qU.resolveBlockScalar=KU});var L9=C((DU)=>{var F9=o(),FU=C1();function LU($,Z,X){let{offset:Y,type:G,source:z,end:J}=$,Q,W,V=(B,U,F)=>X(Y+B,U,F);switch(G){case"scalar":Q=F9.Scalar.PLAIN,W=wU(z,V);break;case"single-quoted-scalar":Q=F9.Scalar.QUOTE_SINGLE,W=MU(z,V);break;case"double-quoted-scalar":Q=F9.Scalar.QUOTE_DOUBLE,W=OU(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=FU.resolveEnd(J,K,Z,X);return{value:W,type:Q,comment:H.comment,range:[Y,K,H.offset]}}function wU($,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 $Y($)}function MU($,Z){if($[$.length-1]!=="'"||$.length===1)Z($.length,"MISSING_CHAR","Missing closing 'quote");return $Y($.slice(1,-1)).replace(/''/g,"'")}function $Y($){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 OU($,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}=NU($,Y);X+=z,Y=J}else if(G==="\\"){let z=$[++Y],J=_U[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+=PU($,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 NU($,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 _U={"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 PU($,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)}DU.resolveFlowScalar=LU});var XY=C((jU)=>{var i$=m(),ZY=o(),RU=T9(),AU=L9();function SU($,Z,X,Y){let{value:G,type:z,comment:J,range:Q}=Z.type==="block-scalar"?RU.resolveBlockScalar($,Z,Y):AU.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[i$.SCALAR];else if(W)V=CU($.schema,G,W,X,Y);else if(Z.type==="scalar")V=IU($,G,Z,Y);else V=$.schema[i$.SCALAR];let K;try{let H=V.resolve(G,(B)=>Y(X??Z,"TAG_RESOLVE_FAILED",B),$.options);K=i$.isScalar(H)?H:new ZY.Scalar(H)}catch(H){let B=H instanceof Error?H.message:String(H);Y(X??Z,"TAG_RESOLVE_FAILED",B),K=new ZY.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 CU($,Z,X,Y,G){if(X==="!")return $[i$.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"),$[i$.SCALAR]}function IU({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[i$.SCALAR];if(X.compat){let Q=X.compat.find((W)=>W.default&&W.test?.test(Y))??X[i$.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}jU.composeScalar=SU});var YY=C((bU)=>{function kU($,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 $}bU.emptyScalarPosition=kU});var JY=C((cU)=>{var yU=k2(),vU=m(),gU=e7(),GY=XY(),hU=C1(),uU=YY(),mU={composeNode:zY,composeEmptyNode:w9};function zY($,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=dU($,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=GY.composeScalar($,Z,W,Y),Q)V.anchor=Q.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":if(V=gU.composeCollection(mU,$,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=w9($,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&&(!vU.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 w9($,Z,X,Y,{spaceBefore:G,comment:z,anchor:J,tag:Q,end:W},V){let K={type:"scalar",offset:uU.emptyScalarPosition(Z,X,Y),indent:-1,source:""},H=GY.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 dU({options:$},{offset:Z,source:X,end:Y},G){let z=new yU.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=hU.resolveEnd(Y,J,$.strict,G);if(z.range=[Z,J,Q.offset],Q.comment)z.comment=Q.comment;return z}cU.composeEmptyNode=w9;cU.composeNode=zY});var WY=C((sU)=>{var iU=n2(),QY=JY(),aU=C1(),nU=s2();function rU($,Z,{offset:X,start:Y,value:G,end:z},J){let Q=Object.assign({_directives:Z},$),W=new iU.Document(void 0,Q),V={atKey:!1,atRoot:!0,directives:W.directives,options:W.options,schema:W.schema},K=nU.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?QY.composeNode(V,G,K,J):QY.composeEmptyNode(V,K.end,Y,null,K,J);let H=W.contents.range[2],B=aU.resolveEnd(z,H,!1,J);if(B.comment)W.comment=B.comment;return W.range=[X,H,B.offset],W}sU.composeDoc=rU});var M9=C((Yq)=>{var tU=r0("process"),eU=PX(),$q=n2(),o2=r2(),VY=m(),Zq=WY(),Xq=C1();function t2($){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 HY($){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 KY{constructor($={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(Z,X,Y,G)=>{let z=t2(Z);if(G)this.warnings.push(new o2.YAMLWarning(z,X,Y));else this.errors.push(new o2.YAMLParseError(z,X,Y))},this.directives=new eU.Directives({version:$.version||"1.2"}),this.options=$}decorate($,Z){let{comment:X,afterEmptyLine:Y}=HY(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(VY.isCollection(G)&&!G.flow&&G.items.length>0){let z=G.items[0];if(VY.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 o2.YAMLParseError(t2($),"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
|
|
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:HY(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(tU.env.LOG_STREAM)console.dir($,{depth:null});switch($.type){case"directive":this.directives.add($.source,(Z,X,Y)=>{let G=t2($);G[0]+=Z,this.onError(G,"BAD_DIRECTIVE",X,Y)}),this.prelude.push($.source),this.atDirectives=!0;break;case"document":{let Z=Zq.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 o2.YAMLParseError(t2($),"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 o2.YAMLParseError(t2($),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let Z=Xq.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 o2.YAMLParseError(t2($),"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 $q.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}}}Yq.Composer=KY});var qY=C((Bq)=>{var zq=T9(),Jq=L9(),Qq=r2(),BY=v2();function Wq($,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 Qq.YAMLParseError([Q,Q+1],z,J)};switch($.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Jq.resolveFlowScalar($,Z,Y);case"block-scalar":return zq.resolveBlockScalar({options:{strict:Z}},$,Y)}}return null}function Vq($,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
|
-
`,B=[{type:"block-scalar-header",offset:z,indent:Y,source:K}];if(!
|
|
137
|
-
`});return{type:"block-scalar",offset:z,indent:Y,props:B,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
|
|
136
|
+
`,B=[{type:"block-scalar-header",offset:z,indent:Y,source:K}];if(!UY(B,W))B.push({type:"newline",offset:-1,indent:Y,source:`
|
|
137
|
+
`});return{type:"block-scalar",offset:z,indent:Y,props:B,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 Hq($,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">":Kq($,W);break;case'"':O9($,W,"double-quoted-scalar");break;case"'":O9($,W,"single-quoted-scalar");break;default:O9($,W,"scalar")}}function Kq($,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(!UY(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 UY($,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 O9($,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})}}}Bq.createScalarToken=Vq;Bq.resolveAsScalar=Wq;Bq.setScalarValue=Hq});var TY=C((Lq)=>{var Fq=($)=>("type"in $)?b6($):k6($);function b6($){switch($.type){case"block-scalar":{let Z="";for(let X of $.props)Z+=b6(X);return Z+$.source}case"block-map":case"block-seq":{let Z="";for(let X of $.items)Z+=k6(X);return Z}case"flow-collection":{let Z=$.start.source;for(let X of $.items)Z+=k6(X);for(let X of $.end)Z+=X.source;return Z}case"document":{let Z=k6($);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 k6({start:$,key:Z,sep:X,value:Y}){let G="";for(let z of $)G+=z.source;if(Z)G+=b6(Z);if(X)for(let z of X)G+=z.source;if(Y)G+=b6(Y);return G}Lq.stringify=Fq});var wY=C((Oq)=>{var N9=Symbol("break visit"),Mq=Symbol("skip children"),FY=Symbol("remove item");function a$($,Z){if("type"in $&&$.type==="document")$={start:$.start,value:$.value};LY(Object.freeze([]),$,Z)}a$.BREAK=N9;a$.SKIP=Mq;a$.REMOVE=FY;a$.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};a$.parentCollection=($,Z)=>{let X=a$.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 LY($,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=LY(Object.freeze($.concat([[G,J]])),z.items[J],X);if(typeof Q==="number")J=Q-1;else if(Q===N9)return N9;else if(Q===FY)z.items.splice(J,1),J-=1}if(typeof Y==="function"&&G==="key")Y=Y(Z,$)}}return typeof Y==="function"?Y(Z,$):Y}Oq.visit=a$});var f6=C((Sq)=>{var _9=qY(),_q=TY(),Pq=wY(),P9="\uFEFF",D9="\x02",E9="\x18",R9="\x1F",Dq=($)=>!!$&&("items"in $),Eq=($)=>!!$&&($.type==="scalar"||$.type==="single-quoted-scalar"||$.type==="double-quoted-scalar"||$.type==="block-scalar");function Rq($){switch($){case P9:return"<BOM>";case D9:return"<DOC>";case E9:return"<FLOW_END>";case R9:return"<SCALAR>";default:return JSON.stringify($)}}function Aq($){switch($){case P9:return"byte-order-mark";case D9:return"doc-mode";case E9:return"flow-error-end";case R9: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}Sq.createScalarToken=_9.createScalarToken;Sq.resolveAsScalar=_9.resolveAsScalar;Sq.setScalarValue=_9.setScalarValue;Sq.stringify=_q.stringify;Sq.visit=Pq.visit;Sq.BOM=P9;Sq.DOCUMENT=D9;Sq.FLOW_END=E9;Sq.SCALAR=R9;Sq.isCollection=Dq;Sq.isScalar=Eq;Sq.prettyToken=Rq;Sq.tokenType=Aq});var S9=C((lq)=>{var e2=f6();function y0($){switch($){case void 0:case" ":case`
|
|
144
|
+
`:case"\r":case"\t":return!0;default:return!1}}var MY=new Set("0123456789ABCDEFabcdef"),dq=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),y6=new Set(",[]{}"),cq=new Set(` ,[]{}
|
|
145
|
+
\r `),A9=($)=>!$||cq.has($);class OY{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
149
|
`||X>=this.indentNext||!Z&&!this.atEnd?$+X:-1}if(Z==="-"||Z==="."){let X=this.buffer.substr($,3);if((X==="---"||X==="...")&&y0(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]===e2.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 e2.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==="...")&&y0(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&&!y0(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(($==="-"||$==="?"||$===":")&&y0(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(
|
|
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]===e2.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 e2.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==="...")&&y0(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&&!y0(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(($==="-"||$==="?"||$===":")&&y0(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(A9),"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("..."))&&y0(Y[3])){if(!(X===this.indentNext-1&&this.flowLevel===1&&(Y[0]==="]"||Y[0]==="}")))return this.flowLevel=0,yield e2.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(A9),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let z=this.charAt(1);if(this.flowKey||y0(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
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)=>y0(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 e2.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(y0(G)||$&&
|
|
157
|
+
`&&G>=this.pos&&G+1+Z>J)$=G;else break}while(!0);return yield e2.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(y0(G)||$&&y6.has(G))break;Z=X}else if(y0(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==="#"||$&&y6.has(G))break;if(Y===`
|
|
160
|
+
`){let z=this.continueScalar(X+1);if(z===-1)break;X=Math.max(X,z-2)}}else{if($&&y6.has(Y))break;Z=X}if(!Y&&!this.atEnd)return this.setNext("plain-scalar");return yield e2.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(A9))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let $=this.flowLevel>0,Z=this.charAt(1);if(y0(Z)||$&&y6.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(!y0(Z)&&Z!==">")Z=this.buffer[++$];return yield*this.pushToIndex(Z===">"?$+1:$,!1)}else{let $=this.pos+1,Z=this.buffer[$];while(Z)if(dq.has(Z))Z=this.buffer[++$];else if(Z==="%"&&MY.has(this.buffer[$+1])&&MY.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)}}lq.Lexer=OY});var C9=C((iq)=>{class NY{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}}}}iq.LineCounter=NY});var I9=C((sq)=>{var nq=r0("process"),_Y=f6(),rq=S9();function w$($,Z){for(let X=0;X<$.length;++X)if($[X].type===Z)return!0;return!1}function PY($){for(let Z=0;Z<$.length;++Z)switch($[Z].type){case"space":case"comment":case"newline":break;default:return Z}return-1}function EY($){switch($?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function v6($){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 I1($){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 DY($){if($.start.type==="flow-seq-start"){for(let Z of $.items)if(Z.sep&&!Z.value&&!w$(Z.start,"explicit-key-ind")&&!w$(Z.sep,"map-value-ind")){if(Z.key)Z.value=Z.key;if(delete Z.key,EY(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 RY{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 rq.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=$,nq.env.LOG_TOKENS)console.log("|",_Y.prettyToken($));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=$.length;return}let Z=_Y.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")DY(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&&PY(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(PY($.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=v6(this.peek(2)),X=I1(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(w$(Z.start,"newline"))Object.assign(Z,{key:null,sep:[this.sourceToken]});else{let z=I1(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(w$(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(
|
|
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(w$(Z.start,"newline"))Object.assign(Z,{key:null,sep:[this.sourceToken]});else{let z=I1(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(w$(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(EY(Z.key)&&!w$(Z.sep,"newline")){let z=I1(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(w$(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&&!w$(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||w$(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=v6(X),G=I1(Y);DY($);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=y6($),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=y6($),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()}}}iq.Parser=PY});var SY=R((ZT)=>{var DY=L9(),nq=n2(),$4=r2(),rq=AX(),sq=m(),oq=A9(),EY=S9();function RY($){let Z=$.prettyErrors!==!1;return{lineCounter:$.lineCounter||Z&&new oq.LineCounter||null,prettyErrors:Z}}function tq($,Z={}){let{lineCounter:X,prettyErrors:Y}=RY(Z),G=new EY.Parser(X?.addNewLine),z=new DY.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 AY($,Z={}){let{lineCounter:X,prettyErrors:Y}=RY(Z),G=new EY.Parser(X?.addNewLine),z=new DY.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 eq($,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=AY($,X);if(!G)return null;if(G.warnings.forEach((z)=>rq.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 $T($,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(sq.isDocument($)&&!Y)return $.toString(X);return new nq.Document($,Y,X).toString(X)}ZT.parse=eq;ZT.parseAllDocuments=tq;ZT.parseDocument=AY;ZT.stringify=$T});var IY=R((wT)=>{var JT=L9(),QT=n2(),WT=Z9(),C9=r2(),VT=k2(),M$=m(),HT=q$(),KT=o(),BT=F$(),UT=L$(),qT=b6(),TT=R9(),FT=A9(),LT=S9(),g6=SY(),CY=j2();wT.Composer=JT.Composer;wT.Document=QT.Document;wT.Schema=WT.Schema;wT.YAMLError=C9.YAMLError;wT.YAMLParseError=C9.YAMLParseError;wT.YAMLWarning=C9.YAMLWarning;wT.Alias=VT.Alias;wT.isAlias=M$.isAlias;wT.isCollection=M$.isCollection;wT.isDocument=M$.isDocument;wT.isMap=M$.isMap;wT.isNode=M$.isNode;wT.isPair=M$.isPair;wT.isScalar=M$.isScalar;wT.isSeq=M$.isSeq;wT.Pair=HT.Pair;wT.Scalar=KT.Scalar;wT.YAMLMap=BT.YAMLMap;wT.YAMLSeq=UT.YAMLSeq;wT.CST=qT;wT.Lexer=TT.Lexer;wT.LineCounter=FT.LineCounter;wT.Parser=LT.Parser;wT.parse=g6.parse;wT.parseAllDocuments=g6.parseAllDocuments;wT.parseDocument=g6.parseDocument;wT.stringify=g6.stringify;wT.visit=CY.visit;wT.visitAsync=CY.visitAsync});var N3=Y3(M3(),1),{program:M1,createCommand:CN,createArgument:IN,createOption:jN,CommanderError:xN,InvalidArgumentError:kN,InvalidOptionArgumentError:bN,Command:fN,Argument:yN,Option:FX,Help:gN}=N3.default;var O3={name:"@pickled-dev/cli",version:"0.21.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 UN from"path";var h0={category:"cli",provider:"claude-code",model:"sonnet"},LX=["Read","Glob","Grep","Bash"],wX=["Edit","MultiEdit","Write","NotebookEdit"];var jY=Y3(IY(),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=jY.default.parse(G)}catch(G){throw Error(`Failed to parse pickled.yml: ${G}`)}return Y=I9(Y),rT(Y),Y}var nT=/\$\{([A-Z_][A-Z0-9_]*)\}/g;function I9($){if(typeof $==="string")return $.replace(nT,(Z,X)=>process.env[X]??"");if(Array.isArray($))return $.map(I9);if($!==null&&typeof $==="object"){let Z={};for(let[X,Y]of Object.entries($))Z[X]=I9(Y);return Z}return $}function rT($){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.');XF(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)"}`)}zF(X.name,X.traps),ZF(X.name,X.compareSurfaces,Z),oT(X.name,X.matrix,Z,new Set(Object.keys($.targets??{})),new Set(Object.keys($.toolsets??{none:{}}))),tT(X.name,X.expected),eT(X.name,X.verifiers,Z),$F(X)}sT($)}function sT($){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 oT($,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 tT($,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 eT($,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 $F($){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 XF($,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 YF=new Set(["g","y"]),GF=new Set(["i","m","s","u","v"]);function zF($,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(YF.has(Q))throw Error(`pickled.yml: scenario "${$}" trap "${Y.id}" uses forbidden regex flag "${Q}" (g and y are not allowed)`);if(!GF.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 j9($,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 x9($){if(typeof $==="string")return{path:$,auditTraps:!0};return{path:$.path,auditTraps:$.audit?.traps??!0}}function v6($){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=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:hO,createArgument:uO,createOption:mO,CommanderError:dO,InvalidArgumentError:cO,InvalidOptionArgumentError:lO,Command:pO,Argument:iO,Option:wX,Help:aO}=P3.default;var D3={name:"@pickled-dev/cli",version:"0.23.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 _O 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
|
|
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,U)=>U.lineCount-B.lineCount);for(let B of H){let U=!B.relPath.includes("/"),F=
|
|
170
|
+
`);else{z.push("| File | Lines | Kind | Notes |"),z.push("|---|---|---|---|");let H=[...X].sort((B,U)=>U.lineCount-B.lineCount);for(let B of H){let U=!B.relPath.includes("/"),F=fY(B.lineCount,U,Z),T=B.isSymlink?`symlink \u2192 ${B.symlinkTarget?.replace(`${Z.targetRepo}/`,"")??"?"}`:"file";z.push(`| \`${B.relPath}\` | ${B.lineCount} | ${T} | ${F} |`)}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.
|
|
@@ -182,31 +182,31 @@ ${Z.comment}`:Z.comment}this.doc.range[2]=Z.offset;break}default:this.errors.pus
|
|
|
182
182
|
`),z.push("| Section | Lines |"),z.push("|---|---|");for(let B of H.sections.slice(0,10))z.push(`| ${B.header} | ${B.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
|
|
185
|
+
`)}function u6($){return JSON.stringify($,null,2)}function m6($){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((U,F)=>F.lineCount-U.lineCount),B=Math.max(...H.map((U)=>U.relPath.length));for(let U of H){let F=!U.relPath.includes("/"),T=fY(U.lineCount,F,Z),w=U.isSymlink?`symlink \u2192 ${U.symlinkTarget?.replace(`${Z.targetRepo}/`,"")??"?"}`:"file",O=`${U.lineCount}`.padStart(4),N=U.relPath.padEnd(B),_=T?` (${T})`:"";z.push(` ${N} ${O} lines ${w}${_}`)}}if(z.push(""),z.push("AGENTS.md / CLAUDE.md pairs"),Y.length===0)z.push(" none");else for(let H of Y){let B=H.dir||"(root)";z.push(` ${B}: ${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 B of H.brokenPathRefs)z.push(` path: ${B}`);for(let B of H.brokenImports)z.push(` @-import: ${B}`)}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 B of H.unresolvedCommands)z.push(` ${B}`)}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 B of H.sections.slice(0,10))z.push(` ${B.header.padEnd(40)} ${B.lines} lines`)}if(z.push(""),z.push("Registered-source trap matches"),$.sourceTrapMatches.length===0)z.push(" none");else for(let H of $.sourceTrapMatches){let B=H.severity==="error"?"error":"warning";z.push(` [${B}] ${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 fY($,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 k1,lstatSync as mY,readFileSync as p6,readlinkSync as _F,statSync as PF}from"fs";import{dirname as i6,isAbsolute as DF,join as f9,relative as EF,resolve as y9}from"path";var{Glob:uY}=globalThis.Bun;var d6=["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/**"],x1={targetRepo:".",budgets:{rootLines:120,nestedWarnLines:200},ignore:d6,intentionalDifferentPairs:[],knownCommands:[]};function c6($){if(!$)return x1;return{targetRepo:$.targetRepo??x1.targetRepo,budgets:{rootLines:$.budgets?.rootLines??x1.budgets.rootLines,nestedWarnLines:$.budgets?.nestedWarnLines??x1.budgets.nestedWarnLines},ignore:$.ignore??d6,intentionalDifferentPairs:$.intentionalDifferentPairs??[],knownCommands:$.knownCommands??[]}}import{existsSync as LF}from"fs";import{join as wF,resolve as MF}from"path";function O$($){let Z=[],X=[];for(let Y of $.traps){let G=HF($.response,Y);if(G)Z.push(G);else X.push(Y.id)}return{fired:Z,avoided:X}}function HF($,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:yY($,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:yY($,Y.index,Y[0].length),index:Y.index}}return null}function yY($,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 l6 from"path";var{Glob:vY}=globalThis.Bun;var KF=262144,BF=4194304;function UF($){return $.startsWith("http://")||$.startsWith("https://")}async function qF($,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 TF($,Z,X,Y){let G=l6.isAbsolute(Z)?Z:l6.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:l6.basename(G),type:"file",auditTraps:Y}}async function FF($,Z,X,Y,G){let z=new vY(Z.path),J=(Z.exclude??[]).map((U)=>new vY(U)),Q=[];for await(let U of z.scan({cwd:X,onlyFiles:!0,followSymlinks:!1})){if(J.some((F)=>F.match(U)))continue;Q.push(U)}Q.sort();let W=Z.maxBytes??KF,V=Math.max(W,BF),K=[],H=0;for(let U of Q){let F=l6.resolve(X,U),T=await Bun.file(F).text(),w=`// === ${U} ===
|
|
187
187
|
`;if(K.push(w,T),!T.endsWith(`
|
|
188
188
|
`))K.push(`
|
|
189
|
-
`);if(H+=w.length+T.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 B=K.join("");return{id:$,source:Z.path,content:B,name:`${Q.length} file${Q.length===1?"":"s"} in ${Z.path}`,type:"codebase",auditTraps:Y,matchedFiles:Q}}async function
|
|
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 kF($){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 bF($){return $.replace(/```[\s\S]*?```/g,"")}function fF($,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=p6(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=l6(V.absPath,"utf8"),T=l6(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 yF($,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 f9($){let Z=gF($);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 gF($){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=f9($.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 a6($){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 hY=!1,r$=void 0,y9=void 0,vF=void 0,hF=void 0,uF=void 0,uY=void 0,mF=void 0,n6=void 0,g9=void 0,mY=void 0,v9=void 0,r6=void 0,dY=void 0;function cY($,Z={auto:!1}){if(hY)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$}'\``);hY=Z.auto,r$=$.kind,y9=$.fetch,vF=$.Request,hF=$.Response,uF=$.Headers,uY=$.FormData,mF=$.Blob,n6=$.File,g9=$.ReadableStream,mY=$.getMultipartRequestOptions,v9=$.getDefaultAgent,r6=$.fileFromPath,dY=$.isFsReadStream}class h9{constructor($){this.body=$}get[Symbol.toStringTag](){return"MultipartBody"}}function lY({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 h9(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 cF}from"fs";function pY(){let $=lY();function Z(X){return X instanceof cF}return{...$,isFsReadStream:Z}}var u9=()=>{if(!r$)cY(pY(),{auto:!0})};u9();class y extends Error{}class e extends y{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:G8(Z)});let G=Z;if($===400)return new s6($,G,X,Y);if($===401)return new o6($,G,X,Y);if($===403)return new t6($,G,X,Y);if($===404)return new e6($,G,X,Y);if($===409)return new $8($,G,X,Y);if($===422)return new Z8($,G,X,Y);if($===429)return new X8($,G,X,Y);if($>=500)return new Y8($,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 s6 extends e{}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{}var z8=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($)},N0;class O${constructor(){N0.set(this,void 0),this.buffer=new Uint8Array,z8(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=pF(this.buffer,o$(this,N0,"f")))!=null){if(G.carriage&&o$(this,N0,"f")==null){z8(this,N0,G.index,"f");continue}if(o$(this,N0,"f")!=null&&(G.index!==o$(this,N0,"f")+1||G.carriage)){Y.push(this.decodeText(this.buffer.slice(0,o$(this,N0,"f")-1))),this.buffer=this.buffer.slice(o$(this,N0,"f")),z8(this,N0,null,"f");continue}let z=o$(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),z8(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 y(`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 y(`Unexpected: received non-Uint8Array/ArrayBuffer (${$.constructor.name}) in a web platform. Please report this error.`)}throw new y("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length)return[];return this.decode(`
|
|
193
|
-
`)}}
|
|
194
|
-
`,"\r"]);
|
|
195
|
-
`);Y.enqueue(J)}catch(G){Y.error(G)}},async cancel(){await Z.return?.()}})}}async function*
|
|
196
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],G}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,X,Y]=nF($,":");if(Y.startsWith(" "))Y=Y.substring(1);if(Z==="event")this.event=Y;else if(Z==="data")this.data.push(Y);return null}}function nF($,Z){let X=$.indexOf(Z);if(X!==-1)return[$.substring(0,X),Z,$.substring(X+Z.length)];return[$,"",""]}var rF=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function",sF=($)=>$!=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 nY($,Z,X){if($=await $,sF($))return $;if(rF($)){let G=await $.blob();Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()??"unknown_file");let z=G4(G)?[await G.arrayBuffer()]:[G];return new n6(z,Z,X)}let Y=await oF($);if(Z||(Z=eF($)??"unknown_file"),!X?.type){let G=Y[0]?.type;if(typeof G==="string")X={...X,type:G}}return new n6(Y,Z,X)}async function oF($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(G4($))Z.push(await $.arrayBuffer());else if($L($))for await(let X of $)Z.push(X);else throw Error(`Unexpected data type: ${typeof $}; constructor: ${$?.constructor?.name}; props: ${tF($)}`);return Z}function tF($){return`[${Object.getOwnPropertyNames($).map((X)=>`"${X}"`).join(", ")}]`}function eF($){return d9($.name)||d9($.filename)||d9($.path)?.split(/[\\/]/).pop()}var d9=($)=>{if(typeof $==="string")return $;if(typeof Buffer<"u"&&$ instanceof Buffer)return String($);return},$L=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function",c9=($)=>$&&typeof $==="object"&&$.body&&$[Symbol.toStringTag]==="MultipartBody";var XL=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},YL=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($)},J8;u9();async function eY($){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 O0.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),$G(J,Z)}let z=await Z.text();return f1("response",Z.status,Z.url,Z.headers,z),z}function $G($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}class W8 extends Promise{constructor($,Z=eY){super((X)=>{X(null)});this.responsePromise=$,this.parseResponse=Z}_thenUnwrap($){return new W8(this.responsePromise,async(Z)=>$G($(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 p9{constructor({baseURL:$,maxRetries:Z=2,timeout:X=600000,httpAgent:Y,fetch:G}){this.baseURL=$,this.maxRetries=l9("maxRetries",Z),this.timeout=l9("timeout",X),this.httpAgent=Y,this.fetch=G??y9}authHeaders($){return{}}defaultHeaders($){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...QL(),...this.authHeaders($)}}validateHeaders($,Z){}defaultIdempotencyKey(){return`stainless-node-retry-${BL()}`}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:c9(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)l9("timeout",X.timeout);X.timeout=X.timeout??this.timeout;let K=X.httpAgent??this.httpAgent??v9(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(tY(G,z),tY(G,Z),c9($.body)&&r$!=="node")delete G["content-type"];if(Q8(z,"x-stainless-retry-count")===void 0&&Q8(Z,"x-stainless-retry-count")===void 0)G["x-stainless-retry-count"]=String(Y);if(Q8(z,"x-stainless-timeout")===void 0&&Q8(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 y("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 W8(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(G8);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=m9(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)=>G8(T).message),H=WL(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=HL($)?new URL($):new URL(this.baseURL+(this.baseURL.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Y=this.defaultQuery();if(!XG(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 y(`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 KL(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 i9{constructor($,Z,X,Y){J8.set(this,void 0),XL(this,J8,$,"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 y("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 YL(this,J8,"f").requestAPIList(this.constructor,Z)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(J8=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class ZG extends W8{constructor($,Z,X){super(Z,async(Y)=>new X($,Y.response,await eY(Y),Y.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}var m9=($)=>{return new Proxy(Object.fromEntries($.entries()),{get(Z,X){let Y=X.toString();return Z[Y.toLowerCase()]||Z[Y]}})},GL={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&&!XG($)&&Object.keys($).every((Z)=>YG(GL,Z))},zL=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n$,"X-Stainless-OS":sY(Deno.build.os),"X-Stainless-Arch":rY(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":sY(process.platform),"X-Stainless-Arch":rY(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let $=JL();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 JL(){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 rY=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},sY=($)=>{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"},oY,QL=()=>{return oY??(oY=zL())},WL=($)=>{try{return JSON.parse($)}catch(Z){return}},VL=/^[a-z][a-z0-9+.-]*:/i,HL=($)=>{return VL.test($)},KL=($)=>new Promise((Z)=>setTimeout(Z,$)),l9=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new y(`${$} must be an integer`);if(Z<0)throw new y(`${$} must be a positive integer`);return Z},G8=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null)try{return Error(JSON.stringify($))}catch{}return Error(String($))};var V8=($)=>{if(typeof process<"u")return process.env?.[$]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.($)?.trim();return};function XG($){if(!$)return!0;for(let Z in $)return!1;return!0}function YG($,Z){return Object.prototype.hasOwnProperty.call($,Z)}function tY($,Z){for(let X in Z){if(!YG(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 BL=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,($)=>{let Z=Math.random()*16|0;return($==="x"?Z:Z&3|8).toString(16)})},GG=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},UL=($)=>{return typeof $?.get==="function"};var Q8=($,Z)=>{let X=Z.toLowerCase();if(UL($)){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 i9{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 g1{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 y("Attempted to iterate over a response with no body");return new g1(Y4($.body),Z)}}class v1 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 y(`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)=>g1.fromResponse(J.response,J.controller))}}class J4 extends $${}v1.BetaMessageBatchesPage=J4;var LL=($)=>{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 $},wL=($)=>{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 $},ML=($)=>{let Z="";return $.map((X)=>{switch(X.type){case"string":Z+='"'+X.value+'"';break;default:Z+=X.value;break}}),Z},H8=($)=>JSON.parse(ML(wL(h1(LL($)))));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,K8,W4,V4,B8,H4,Z$,K4,U8,q8,u1,T8,F8,a9,zG,n9,r9,s9,o9,JG,QG="__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),K8.set(this,()=>{}),W4.set(this,()=>{}),V4.set(this,void 0),B8.set(this,()=>{}),H4.set(this,()=>{}),Z$.set(this,{}),K4.set(this,!1),U8.set(this,!1),q8.set(this,!1),u1.set(this,!1),T8.set(this,void 0),F8.set(this,void 0),n9.set(this,($)=>{if(K0(this,U8,!0,"f"),$ instanceof Error&&$.name==="AbortError")$=new H0;if($ instanceof H0)return K0(this,q8,!0,"f"),this._emit("abort",$);if($ instanceof y)return this._emit("error",$);if($ instanceof Error){let Z=new y($.message);return Z.cause=$,this._emit("error",Z)}return this._emit("error",new y(String($)))}),K0(this,Q4,new Promise(($,Z)=>{K0(this,K8,$,"f"),K0(this,W4,Z,"f")}),"f"),K0(this,V4,new Promise(($,Z)=>{K0(this,B8,$,"f"),K0(this,H4,Z,"f")}),"f"),h(this,Q4,"f").catch(()=>{}),h(this,V4,"f").catch(()=>{})}get response(){return h(this,T8,"f")}get request_id(){return h(this,F8,"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,n9,"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",r9).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",s9).call(this,J);if(z.controller.signal?.aborted)throw new H0;h(this,x0,"m",o9).call(this)}_connected($){if(this.ended)return;K0(this,T8,$,"f"),K0(this,F8,$?.headers.get("request-id"),"f"),h(this,K8,"f").call(this,$),this._emit("connect")}get ended(){return h(this,K4,"f")}get errored(){return h(this,U8,"f")}get aborted(){return h(this,q8,"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",a9).call(this)}async finalText(){return await this.done(),h(this,x0,"m",zG).call(this)}_emit($,...Z){if(h(this,K4,"f"))return;if($==="end")K0(this,K4,!0,"f"),h(this,B8,"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",a9).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",r9).call(this),this._connected(null);let Y=O0.fromReadableStream($,this.controller);for await(let G of Y)h(this,x0,"m",s9).call(this,G);if(Y.controller.signal?.aborted)throw new H0;h(this,x0,"m",o9).call(this)}[(_$=new WeakMap,Q4=new WeakMap,K8=new WeakMap,W4=new WeakMap,V4=new WeakMap,B8=new WeakMap,H4=new WeakMap,Z$=new WeakMap,K4=new WeakMap,U8=new WeakMap,q8=new WeakMap,u1=new WeakMap,T8=new WeakMap,F8=new WeakMap,n9=new WeakMap,x0=new WeakSet,a9=function(){if(this.receivedMessages.length===0)throw new y("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},zG=function(){if(this.receivedMessages.length===0)throw new y("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 y("stream ended without producing a content block with type=text");return Z.join(" ")},r9=function(){if(this.ended)return;K0(this,_$,void 0,"f")},s9=function(Z){if(this.ended)return;let X=h(this,x0,"m",JG).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}},o9=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let Z=h(this,_$,"f");if(!Z)throw new y("request ended without sending any chunks");return K0(this,_$,void 0,"f"),Z},JG=function(Z){let X=h(this,_$,"f");if(Z.type==="message_start"){if(X)throw new y(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!X)throw new y(`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[QG]||"";if(G+=Z.delta.partial_json,Object.defineProperty(Y,QG,{value:G,enumerable:!1,writable:!0}),G)Y.input=H8(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 O0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function WG($){}var VG={"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 v1(this._client)}create($,Z){let{betas:X,...Y}=$;if(Y.model in VG)console.warn(`The model '${Y.model}' is deprecated and will reach end-of-life on ${VG[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=v1;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 y(`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)=>g1.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,L8,T4,F4,w8,L4,Y$,w4,M8,N8,c1,O8,_8,t9,HG,e9,$5,Z5,X5,KG,BG="__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),L8.set(this,()=>{}),T4.set(this,()=>{}),F4.set(this,void 0),w8.set(this,()=>{}),L4.set(this,()=>{}),Y$.set(this,{}),w4.set(this,!1),M8.set(this,!1),N8.set(this,!1),c1.set(this,!1),O8.set(this,void 0),_8.set(this,void 0),e9.set(this,($)=>{if(B0(this,M8,!0,"f"),$ instanceof Error&&$.name==="AbortError")$=new H0;if($ instanceof H0)return B0(this,N8,!0,"f"),this._emit("abort",$);if($ instanceof y)return this._emit("error",$);if($ instanceof Error){let Z=new y($.message);return Z.cause=$,this._emit("error",Z)}return this._emit("error",new y(String($)))}),B0(this,q4,new Promise(($,Z)=>{B0(this,L8,$,"f"),B0(this,T4,Z,"f")}),"f"),B0(this,F4,new Promise(($,Z)=>{B0(this,w8,$,"f"),B0(this,L4,Z,"f")}),"f"),u(this,q4,"f").catch(()=>{}),u(this,F4,"f").catch(()=>{})}get response(){return u(this,O8,"f")}get request_id(){return u(this,_8,"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,e9,"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",$5).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",Z5).call(this,J);if(z.controller.signal?.aborted)throw new H0;u(this,k0,"m",X5).call(this)}_connected($){if(this.ended)return;B0(this,O8,$,"f"),B0(this,_8,$?.headers.get("request-id"),"f"),u(this,L8,"f").call(this,$),this._emit("connect")}get ended(){return u(this,w4,"f")}get errored(){return u(this,M8,"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",t9).call(this)}async finalText(){return await this.done(),u(this,k0,"m",HG).call(this)}_emit($,...Z){if(u(this,w4,"f"))return;if($==="end")B0(this,w4,!0,"f"),u(this,w8,"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",t9).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",$5).call(this),this._connected(null);let Y=O0.fromReadableStream($,this.controller);for await(let G of Y)u(this,k0,"m",Z5).call(this,G);if(Y.controller.signal?.aborted)throw new H0;u(this,k0,"m",X5).call(this)}[(P$=new WeakMap,q4=new WeakMap,L8=new WeakMap,T4=new WeakMap,F4=new WeakMap,w8=new WeakMap,L4=new WeakMap,Y$=new WeakMap,w4=new WeakMap,M8=new WeakMap,N8=new WeakMap,c1=new WeakMap,O8=new WeakMap,_8=new WeakMap,e9=new WeakMap,k0=new WeakSet,t9=function(){if(this.receivedMessages.length===0)throw new y("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},HG=function(){if(this.receivedMessages.length===0)throw new y("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 y("stream ended without producing a content block with type=text");return Z.join(" ")},$5=function(){if(this.ended)return;B0(this,P$,void 0,"f")},Z5=function(Z){if(this.ended)return;let X=u(this,k0,"m",KG).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:UG(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}},X5=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let Z=u(this,P$,"f");if(!Z)throw new y("request ended without sending any chunks");return B0(this,P$,void 0,"f"),Z},KG=function(Z){let X=u(this,P$,"f");if(Z.type==="message_start"){if(X)throw new y(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!X)throw new y(`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=H8(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:UG(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 O0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function UG($){}class D$ extends W0{constructor(){super(...arguments);this.batches=new d1(this._client)}create($,Z){if($.model in qG)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${qG[$.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
|
|
189
|
+
`);if(H+=w.length+T.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 B=K.join("");return{id:$,source:Z.path,content:B,name:`${Q.length} file${Q.length===1?"":"s"} in ${Z.path}`,type:"codebase",auditTraps:Y,matchedFiles:Q}}async function gY($,Z,X,Y){let{path:G,auditTraps:z}=b9(Z);if(typeof Z!=="string"&&Z.type==="codebase")return FF($,Z,X,z,Y);if(UF(G))return qF($,G,z);return TF($,G,X,z)}async function Z4($,Z,X){let Y=Object.entries($);return await Promise.all(Y.map(([z,J])=>gY(z,J,Z,X)))}async function hY($){if(!LF(wF($,"pickled.yml")))return{matches:[],findings:[]};let Z=await j1($),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 Z4(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,B=V.type==="codebase"&&V.matchedFiles?await OF(V.matchedFiles,$,V.source):[{path:V.source,content:V.content}];for(let U of B)for(let F of G){if(H?.has(F.id))continue;let{fired:T}=O$({response:U.content,traps:[F]}),w=T[0];if(!w)continue;let O=NF(U.content,w.index),N=z.get(F)??"warning";Q.push({sourceId:V.id,sourcePath:U.path,trapId:w.id,trapReason:w.reason,matched:w.matched,snippet:w.snippet,line:O,severity:N}),W.push({severity:N,category:"trap-source-match",file:U.path,message:`source [${V.id}] matches trap '${w.id}' ("${w.matched}") in ${U.path}. ${w.reason} Fix: remove the stale claim from the source, retire the trap if no longer relevant, set audit.traps: ['${w.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 OF($,Z,X){let Y=[];for(let G of $)try{let z=await Bun.file(MF(Z,G)).text();Y.push({path:G,content:z})}catch{}return Y}function NF($,Z){let X=1,Y=Math.min(Z,$.length);for(let G=0;G<Y;G++)if($[G]===`
|
|
190
|
+
`)X++;return X}var RF=["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 a6($){let Z=c6($),X=y9(Z.targetRepo);if(!k1(X))throw Error(`targetRepo does not exist: ${X}`);let Y=new Set;for(let V of RF){let K=new uY(V);for await(let H of K.scan({cwd:X,dot:!0,onlyFiles:!1,followSymlinks:!1})){if(Z.ignore.some((F)=>new uY(F).match(H)))continue;let B=f9(X,H),U=mY(B);if(U.isFile()){Y.add(H);continue}if(U.isSymbolicLink())try{if(PF(B).isFile())Y.add(H)}catch{}}}let G=[];for(let V of[...Y].sort())G.push(await AF(X,V,f9(X,V),Z));let z=hF(G,Z),J=uF(G,z,Z),{matches:Q,findings:W}=await hY(X);return{config:Z,files:G,pairs:z,findings:[...J,...W],sourceTrapMatches:Q}}async function AF($,Z,X,Y){let z=mY(X).isSymbolicLink(),J=null,Q=Z;if(z){let B=_F(X),U=DF(B)?B:y9(i6(X),B);if(J=U,k1(U))Q=EF($,U)}let W=z&&J&&k1(J)?J:X,V=p6(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:CF(V,$,Z),brokenImports:jF(V,i6(X)),unresolvedCommands:fF(V,$,Y.knownCommands),sections:yF(V)}}function SF($){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 CF($,Z,X){let Y=gF($),G=i6(X),z=SF(X),J=new Set,Q=/`([^`\n]{2,200})`/g,W;W=Q.exec(Y);while(W!==null){let V=W[1].trim().replace(/[#?].*$/,"");if(vF(V)&&!IF(Z,V,G,z).found)J.add(V);W=Q.exec(Y)}return[...J].sort()}function IF($,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(k1(`${$}/${J}`))return{found:!0,resolvedAs:J}}return{found:!1}}function jF($,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:y9(Z,z);if(!k1(J))X.add(z);G=Y.exec($)}return[...X].sort()}var xF=["bun","pnpm","npm","yarn"],kF=new Set(["install","add","remove","update","i","audit","list","ls","why","outdated","exec","run","create","init","x"]),bF={bun:new Set(["build","test","link","unlink","upgrade"])};function fF($,Z,X){let Y=new Set,G=f9(Z,"package.json"),z=new Set;if(k1(G))try{let Q=JSON.parse(p6(G,"utf8"));z=new Set(Object.keys(Q.scripts??{}))}catch{}let J=new Set(X.map((Q)=>Q.trim()));for(let Q of xF){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}`)&&!kF.has(K)&&!bF[Q]?.has(K))Y.add(`${Q} ${K}`);V=W.exec($)}}return[...Y].sort()}function yF($){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 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
|
+
`)}}_0=new WeakMap;N$.NEWLINE_CHARS=new Set([`
|
|
194
|
+
`,"\r"]);N$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function oF($,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 sY($){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 Y4($){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 P0{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 tF($,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 e.generate(void 0,`SSE Error: ${z.data}`,z.data,c9($.headers))}G=!0}catch(z){if(z instanceof Error&&z.name==="AbortError")return;throw z}finally{if(!G)Z.abort()}}return new P0(Y,Z)}static fromReadableStream($,Z){let X=!1;async function*Y(){let z=new N$,J=Y4($);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 P0(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 P0(()=>Y($),this.controller),new P0(()=>Y(Z),this.controller)]}toReadableStream(){let $=this,Z,X=new TextEncoder;return new h9({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)+`
|
|
195
|
+
`);Y.enqueue(J)}catch(G){Y.error(G)}},async cancel(){await Z.return?.()}})}}async function*tF($,Z){if(!$.body)throw Z.abort(),new v("Attempted to iterate over a response with no body");let X=new oY,Y=new N$,G=Y4($.body);for await(let z of eF(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*eF($){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=sY(Z))!==-1)yield Z.slice(0,z),Z=Z.slice(z)}if(Z.length>0)yield Z}class oY{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(`
|
|
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.
|
|
199
199
|
|
|
200
200
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
201
201
|
If you understand the risks and have appropriate mitigations in place,
|
|
202
202
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
203
203
|
|
|
204
204
|
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 m1(this),this.messages=new D$(this),this.models=new e$(this),this.beta=new X$(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}`}}}
|
|
205
|
+
`);super({baseURL:G.baseURL,timeout:G.timeout??600000,httpAgent:G.httpAgent,maxRetries:G.maxRetries,fetch:G.fetch});this.completions=new m1(this),this.messages=new D$(this),this.models=new e$(this),this.beta=new X$(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}`}}}MG=p;p.Anthropic=MG;p.HUMAN_PROMPT=`
|
|
206
206
|
|
|
207
207
|
Human:`;p.AI_PROMPT=`
|
|
208
208
|
|
|
209
|
-
Assistant:`;p.DEFAULT_TIMEOUT=600000;p.AnthropicError=
|
|
209
|
+
Assistant:`;p.DEFAULT_TIMEOUT=600000;p.AnthropicError=v;p.APIError=e;p.APIConnectionError=s$;p.APIConnectionTimeoutError=X4;p.APIUserAbortError=H0;p.NotFoundError=$8;p.ConflictError=Z8;p.RateLimitError=Y8;p.BadRequestError=o6;p.AuthenticationError=t6;p.InternalServerError=G8;p.PermissionDeniedError=e6;p.UnprocessableEntityError=X8;p.toFile=tY;p.fileFromPath=s6;p.Completions=m1;p.Messages=D$;p.Models=e$;p.ModelInfosPage=l1;p.Beta=X$;var OG=p;function E$($,Z,X){let Y=Z.length>0?Z.map((J)=>`- ${J.id}: ${J.name} (${J.source})`).join(`
|
|
210
210
|
`):"(no sources provided)",G=Z.map((J)=>`<source id="${J.id}">
|
|
211
211
|
${J.content.trimEnd()}
|
|
212
212
|
</source>`).join(`
|
|
@@ -238,20 +238,20 @@ Research the answer using authoritative sources you can reach with your tools.`;
|
|
|
238
238
|
|
|
239
239
|
Use the tools available to you to research the answer. Be specific and accurate; do not invent facts.${X}
|
|
240
240
|
|
|
241
|
-
If you cannot find the answer with the available tools, say so explicitly rather than guessing.`}class Y5{category="api";provider="anthropic";name;config;clientFactory;constructor($,Z,X){this.name=$,this.config=Z,this.clientFactory=X??(()=>new FG)}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=PL(K.content),B=DL(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 PL($){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 DL($){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 G5=function(){let{crypto:$}=globalThis;if($?.randomUUID)return G5=$.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 N4($){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 S extends Error{}class r extends S{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:O4(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 S{constructor(){super("Could not parse response content as the length limit was reached")}}class j4 extends S{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 P8 extends S{constructor($,Z,X){super($);this.provider=Z,this.cause=X}}var RL=/^[a-z][a-z0-9+.-]*:/i,LG=($)=>{return RL.test($)},U0=($)=>(U0=Array.isArray,U0($)),z5=U0;function D8($){if(typeof $!=="object")return{};return $??{}}function J5($){if(!$)return!0;for(let Z in $)return!1;return!0}function wG($,Z){return Object.prototype.hasOwnProperty.call($,Z)}function x4($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var MG=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new S(`${$} must be an integer`);if(Z<0)throw new S(`${$} must be a positive integer`);return Z};var NG=($)=>{try{return JSON.parse($)}catch(Z){return}};var d0=($)=>new Promise((Z)=>setTimeout(Z,$));var R$="6.39.0";var DG=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function AL(){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 SL=()=>{let $=AL();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":R$,"X-Stainless-OS":_G(Deno.build.os),"X-Stainless-Arch":OG(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":_G(globalThis.process.platform??"unknown"),"X-Stainless-Arch":OG(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=CL();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 CL(){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 OG=($)=>{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"},PG,EG=()=>{return PG??(PG=SL())};function E8(){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 Q5(...$){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 R8($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return Q5({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 W5($){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 V5($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),X=Z.cancel();Z.releaseLock(),await X}var AG=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};var H5="RFC3986",K5=($)=>String($),B5={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:K5},SG="RFC1738";var A8=($,Z)=>(A8=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),A8($,Z)),c0=(()=>{let $=[];for(let Z=0;Z<256;++Z)$.push("%"+((Z<16?"0":"")+Z.toString(16)).toUpperCase());return $})();var U5=1024,CG=($,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+=U5){let W=z.length>=U5?z.slice(Q,Q+U5):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===SG&&(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 IG($){if(!$||typeof $!=="object")return!1;return!!($.constructor&&$.constructor.isBuffer&&$.constructor.isBuffer($))}function q5($,Z){if(U0($)){let X=[];for(let Y=0;Y<$.length;Y+=1)X.push(Z($[Y]));return X}return Z($)}var xG={brackets($){return String($)+"[]"},comma:"comma",indices($,Z){return String($)+"["+Z+"]"},repeat($){return String($)}},kG=function($,Z){Array.prototype.push.apply($,U0(Z)?Z:[Z])},jG,Z0={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:CG,encodeValuesOnly:!1,format:H5,formatter:K5,indices:!1,serializeDate($){return(jG??(jG=Function.prototype.call.bind(Date.prototype.toISOString)))($)},skipNulls:!1,strictNullHandling:!1};function jL($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}var T5={};function bG($,Z,X,Y,G,z,J,Q,W,V,K,H,B,U,F,T,w,O){let N=$,P=O,E=0,I=!1;while((P=P.get(T5))!==void 0&&!I){let k=P.get($);if(E+=1,typeof k<"u")if(k===E)throw RangeError("Cyclic object value");else I=!0;if(typeof P.get(T5)>"u")E=0}if(typeof V==="function")N=V(Z,N);else if(N instanceof Date)N=B?.(N);else if(X==="comma"&&U0(N))N=q5(N,function(k){if(k instanceof Date)return B?.(k);return k});if(N===null){if(z)return W&&!T?W(Z,Z0.encoder,w,"key",U):Z;N=""}if(jL(N)||IG(N)){if(W){let k=T?Z:W(Z,Z0.encoder,w,"key",U);return[F?.(k)+"="+F?.(W(N,Z0.encoder,w,"value",U))]}return[F?.(Z)+"="+F?.(String(N))]}let A=[];if(typeof N>"u")return A;let C;if(X==="comma"&&U0(N)){if(T&&W)N=q5(N,W);C=[{value:N.length>0?N.join(",")||null:void 0}]}else if(U0(V))C=V;else{let k=Object.keys(N);C=K?k.sort(K):k}let D=Q?String(Z).replace(/\./g,"%2E"):String(Z),v=Y&&U0(N)&&N.length===1?D+"[]":D;if(G&&U0(N)&&N.length===0)return v+"[]";for(let k=0;k<C.length;++k){let i=C[k],l=typeof i==="object"&&typeof i.value<"u"?i.value:N[i];if(J&&l===null)continue;let R0=H&&Q?i.replace(/\./g,"%2E"):i,A0=U0(N)?typeof X==="function"?X(v,R0):v:v+(H?"."+R0:"["+R0+"]");O.set($,E);let g$=new WeakMap;g$.set(T5,O),kG(A,bG(l,A0,X,Y,G,z,J,Q,X==="comma"&&T&&U0(N)?null:W,V,K,H,B,U,F,T,w,g$))}return A}function xL($=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=H5;if(typeof $.format<"u"){if(!A8(B5,$.format))throw TypeError("Unknown format option provided.");X=$.format}let Y=B5[X],G=Z0.filter;if(typeof $.filter==="function"||U0($.filter))G=$.filter;let z;if($.arrayFormat&&$.arrayFormat in xG)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 fG($,Z={}){let X=$,Y=xL(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=xG[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;kG(J,bG(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 yG($){return fG($,{arrayFormat:"brackets"})}function hG($){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 gG;function a1($){let Z;return(gG??(Z=new globalThis.TextEncoder,gG=Z.encode.bind(Z)))($)}var vG;function F5($){let Z;return(vG??(Z=new globalThis.TextDecoder,vG=Z.decode.bind(Z)))($)}var _0,P0;class n1{constructor(){_0.set(this,void 0),P0.set(this,void 0),x(this,_0,new Uint8Array,"f"),x(this,P0,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?a1($):$;x(this,_0,hG([M(this,_0,"f"),Z]),"f");let X=[],Y;while((Y=bL(M(this,_0,"f"),M(this,P0,"f")))!=null){if(Y.carriage&&M(this,P0,"f")==null){x(this,P0,Y.index,"f");continue}if(M(this,P0,"f")!=null&&(Y.index!==M(this,P0,"f")+1||Y.carriage)){X.push(F5(M(this,_0,"f").subarray(0,M(this,P0,"f")-1))),x(this,_0,M(this,_0,"f").subarray(M(this,P0,"f")),"f"),x(this,P0,null,"f");continue}let G=M(this,P0,"f")!==null?Y.preceding-1:Y.preceding,z=F5(M(this,_0,"f").subarray(0,G));X.push(z),x(this,_0,M(this,_0,"f").subarray(Y.index),"f"),x(this,P0,null,"f")}return X}flush(){if(!M(this,_0,"f").length)return[];return this.decode(`
|
|
242
|
-
`)}}
|
|
243
|
-
`,"\r"]);n1.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function
|
|
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]=vL($,":");if(Y.startsWith(" "))Y=Y.substring(1);if(Z==="event")this.event=Y;else if(Z==="data")this.data.push(Y);return null}}function vL($,Z){let X=$.indexOf(Z);if(X!==-1)return[$.substring(0,X),Z,$.substring(X+Z.length)];return[$,"",""]}async function I8($,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 D0.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 w5(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 w5($,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=I8){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)=>w5($(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 j8;class y4{constructor($,Z,X,Y){j8.set(this,void 0),x(this,j8,$,"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 S("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await M(this,j8,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(j8=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class x8 extends X1{constructor($,Z,X){super($,Z,async(Y,G)=>new X(Y,G.response,await I8(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 f 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:{...D8(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:{...D8(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:{...D8(this.options.query),after:$}}}}var uL={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},mL="urn:ietf:params:oauth:grant-type:token-exchange";class M5{constructor($,Z){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=$,this.fetch=Z??E8()}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:mL,subject_token:$,subject_token_type:uL[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 _5=()=>{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 _5(),new File($,Z??"unknown_file",X)}function g4($){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 k8=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function",A$=async($,Z)=>{if(!N5($.body))return $;return{...$,body:await lG($.body,Z)}},q0=async($,Z)=>{return{...$,body:await lG($.body,Z)}},cG=new WeakMap;function dL($){let Z=typeof $==="function"?$:$.fetch,X=cG.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 cG.set(Z,Y),Y}var lG=async($,Z)=>{if(!await dL(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])=>O5(X,Y,G))),X},pG=($)=>$ instanceof Blob&&("name"in $),cL=($)=>typeof $==="object"&&$!==null&&($ instanceof Response||k8($)||pG($)),N5=($)=>{if(cL($))return!0;if(Array.isArray($))return $.some(N5);if($&&typeof $==="object"){for(let Z in $)if(N5($[Z]))return!0}return!1},O5=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()],g4(X)));else if(k8(X))$.append(Z,r1([await new Response(R8(X)).blob()],g4(X)));else if(pG(X))$.append(Z,X,g4(X));else if(Array.isArray(X))await Promise.all(X.map((Y)=>O5($,Z+"[]",Y)));else if(typeof X==="object")await Promise.all(Object.entries(X).map(([Y,G])=>O5($,`${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 iG=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",lL=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&iG($),pL=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function b8($,Z,X){if(_5(),$=await $,lL($)){if($ instanceof File)return $;return r1([await $.arrayBuffer()],$.name)}if(pL($)){let G=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),r1(await P5(G),Z,X)}let Y=await P5($);if(Z||(Z=g4($)),!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 P5($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(iG($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(k8($))for await(let X of $)Z.push(...await P5(X));else{let X=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${X?`; constructor: ${X}`:""}${iL($)}`)}return Z}function iL($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((X)=>`"${X}"`).join(", ")}]`}class L{constructor($){this._client=$}}function nG($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var aG=Object.freeze(Object.create(null)),nL=($=nG)=>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??aG)??aG)?.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 S(`Path parameters result in path with invalid segments:
|
|
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
|
+
`)}}D0=new WeakMap,E0=new WeakMap;n1.NEWLINE_CHARS=new Set([`
|
|
243
|
+
`,"\r"]);n1.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function uL($,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 lG($){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},M5=($,Z,X)=>{if(!$)return;if(_G(I8,$))return $;s(X).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(I8))}`);return};function k4(){}function C8($,Z,X){if(!Z||I8[$]>I8[X])return k4;else return Z[$].bind(Z)}var mL={error:k4,warn:k4,info:k4,debug:k4},pG=new WeakMap;function s($){let Z=$.logger,X=$.logLevel??"off";if(!Z)return mL;let Y=pG.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 pG.set(Z,[X,G]),G}var z$=($)=>{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 b4;class R0{constructor($,Z,X){this.iterator=$,b4.set(this,void 0),this.controller=Z,x(this,b4,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 dL($,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(O4(W))return;throw W}finally{if(!Q)Z.abort()}}return new R0(J,Z,X)}static fromReadableStream($,Z,X){let Y=!1;async function*G(){let J=new n1,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(O4(Q))return;throw Q}finally{if(!J)Z.abort()}}return new R0(z,Z,X)}[(b4=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 R0(()=>Y($),this.controller,M(this,b4,"f")),new R0(()=>Y(Z),this.controller,M(this,b4,"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=a1(JSON.stringify(Y)+`
|
|
244
|
+
`);X.enqueue(z)}catch(Y){X.error(Y)}},async cancel(){await Z.return?.()}})}}async function*dL($,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 iG,Y=new n1,G=H5($.body);for await(let z of cL(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*cL($){let Z=new Uint8Array;for await(let X of $){if(X==null)continue;let Y=X instanceof ArrayBuffer?new Uint8Array(X):typeof X==="string"?a1(X):X,G=new Uint8Array(Z.length+Y.length);G.set(Z),G.set(Y,Z.length),Z=G;let z;while((z=lG(Z))!==-1)yield Z.slice(0,z),Z=Z.slice(z)}if(Z.length>0)yield Z}class iG{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(`
|
|
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
246
|
${z.map((B)=>B.error).join(`
|
|
247
247
|
`)}
|
|
248
248
|
${J}
|
|
249
|
-
${H}`)}return J},q=nL(nG);class s1 extends L{list($,Z={},X){return this._client.getAPIList(q`/chat/completions/${$}/messages`,f,{query:Z,...X,__security:{bearerAuth:!0}})}}function v4($){return $!==void 0&&"function"in $&&$.function!==void 0}function h4($){return $?.$brand==="auto-parseable-response-format"}function Y1($){return $?.$brand==="auto-parseable-tool"}function rG($,Z){if(!Z||!D5(Z))return{...$,choices:$.choices.map((X)=>{return oG(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 oG(Y.message.tool_calls),{...Y,message:{...Y.message,...Y.message.tool_calls?{tool_calls:Y.message.tool_calls?.map((G)=>tL(Z,G))??void 0}:void 0,parsed:Y.message.content&&!Y.message.refusal?oL(Z,Y.message.content):null}}});return{...$,choices:X}}function oL($,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 tL($,Z){let X=$.tools?.find((Y)=>v4(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 sG($,Z){if(!$||!("tools"in $)||!$.tools)return!1;let X=$.tools?.find((Y)=>v4(Y)&&Y.function?.name===Z.function.name);return v4(X)&&(Y1(X)||X?.function.strict||!1)}function D5($){if(h4($.response_format))return!0;return $.tools?.some((Z)=>Y1(Z)||Z.type==="function"&&Z.function.strict===!0)??!1}function oG($){for(let Z of $||[])if(Z.type!=="function")throw new S(`Currently only \`function\` tool calls are supported; Received \`${Z.type}\``)}function tG($){for(let Z of $??[]){if(Z.type!=="function")throw new S(`Currently only \`function\` tool types support auto-parsing; Received \`${Z.type}\``);if(Z.function.strict!==!0)throw new S(`The \`${Z.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var o1=($)=>{return $?.role==="assistant"},E5=($)=>{return $?.role==="tool"};var R5,f8,y8,m4,d4,g8,c4,J$,l4,v8,h8,t1,eG;class G1{constructor(){R5.add(this),this.controller=new AbortController,f8.set(this,void 0),y8.set(this,()=>{}),m4.set(this,()=>{}),d4.set(this,void 0),g8.set(this,()=>{}),c4.set(this,()=>{}),J$.set(this,{}),l4.set(this,!1),v8.set(this,!1),h8.set(this,!1),t1.set(this,!1),x(this,f8,new Promise(($,Z)=>{x(this,y8,$,"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,f8,"f").catch(()=>{}),M(this,d4,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},M(this,R5,"m",eG).bind(this))},0)}_connected(){if(this.ended)return;M(this,y8,"f").call(this),this._emit("connect")}get ended(){return M(this,l4,"f")}get errored(){return M(this,v8,"f")}get aborted(){return M(this,h8,"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(){}}f8=new WeakMap,y8=new WeakMap,m4=new WeakMap,d4=new WeakMap,g8=new WeakMap,c4=new WeakMap,J$=new WeakMap,l4=new WeakMap,v8=new WeakMap,h8=new WeakMap,t1=new WeakMap,R5=new WeakSet,eG=function(Z){if(x(this,v8,!0,"f"),Z instanceof Error&&Z.name==="AbortError")Z=new $0;if(Z instanceof $0)return x(this,h8,!0,"f"),this._emit("abort",Z);if(Z instanceof S)return this._emit("error",Z);if(Z instanceof Error){let X=new S(Z.message);return X.cause=Z,this._emit("error",X)}return this._emit("error",new S(String(Z)))};function $z($){return typeof $.parse==="function"}var w0,A5,u8,S5,C5,I5,Zz,Xz,eL=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",$),E5($)&&$.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 S("stream ended without producing a ChatCompletion");return $}async finalContent(){return await this.done(),M(this,w0,"m",A5).call(this)}async finalMessage(){return await this.done(),M(this,w0,"m",u8).call(this)}async finalFunctionToolCall(){return await this.done(),M(this,w0,"m",S5).call(this)}async finalFunctionToolCallResult(){return await this.done(),M(this,w0,"m",C5).call(this)}async totalUsage(){return await this.done(),M(this,w0,"m",I5).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let $=this._chatCompletions[this._chatCompletions.length-1];if($)this._emit("finalChatCompletion",$);let Z=M(this,w0,"m",u8).call(this);if(Z)this._emit("finalMessage",Z);let X=M(this,w0,"m",A5).call(this);if(X)this._emit("finalContent",X);let Y=M(this,w0,"m",S5).call(this);if(Y)this._emit("finalFunctionToolCall",Y);let G=M(this,w0,"m",C5).call(this);if(G!=null)this._emit("finalFunctionToolCallResult",G);if(this._chatCompletions.some((z)=>z.usage))this._emit("totalUsage",M(this,w0,"m",I5).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=eL}=X||{},V=Z.tools.map((B)=>{if(Y1(B)){if(!B.$callback)throw new S("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 S("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,P=K[O];if(!P){let C=`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:C});continue}else if(Q&&Q!==O){let C=`Invalid tool_call: ${JSON.stringify(O)}. ${JSON.stringify(Q)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:w,content:C});continue}let E;try{E=$z(P)?await P.parse(N):N}catch(C){let D=C instanceof Error?C.message:String(C);this._addMessage({role:"tool",tool_call_id:w,content:D});continue}let I=await P.function(E,this),A=M(this,w0,"m",Xz).call(this,I);if(this._addMessage({role:"tool",tool_call_id:w,content:A}),Q)return}}return}}w0=new WeakSet,A5=function(){return M(this,w0,"m",u8).call(this).content??null},u8=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 S("stream ended without producing a ChatCompletionMessage with role=assistant")},S5=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},C5=function(){for(let Z=this.messages.length-1;Z>=0;Z--){let X=this.messages[Z];if(E5(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},I5=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 S("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Xz=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 Yz extends Error{}class Gz extends Error{}function $w($,Z=J0.ALL){if(typeof $!=="string")throw TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw Error(`${$} is empty`);return Zw($.trim(),Z)}var Zw=($,Z)=>{let X=$.length,Y=0,G=(B)=>{throw new Yz(`${B} at position ${Y}`)},z=(B)=>{throw new Gz(`${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()},
|
|
251
|
-
${
|
|
252
|
-
${
|
|
253
|
-
${
|
|
254
|
-
${c8($)}`);return{...D,id:C,type:A,function:{...i,name:k,arguments:v}}})}};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 rG(W,Z)}function c8($){return JSON.stringify($)}function Jz($){return}function Qz($){}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",f,{query:$,...Z,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/chat/completions/${$}`,{...Z,__security:{bearerAuth:!0}})}parse($,Z){return tG($.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",f,{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 Wz=Symbol("brand.privateNullableHeaders");function*xw($){if(!$)return;if(Wz 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(z5($))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=z5(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 _=($)=>{let Z=new Headers,X=new Set;for(let Y of $){let G=new Set;for(let[z,J]of xw(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{[Wz]:!0,values:Z,nulls:X}};class TZ extends L{create($,Z){return this._client.post("/audio/speech",{body:$,...Z,headers:_([{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",f,{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:_([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/assistants/${$}`,{...Z,headers:_([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/assistants/${$}`,{body:Z,...X,headers:_([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/assistants",f,{query:$,...Z,headers:_([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/assistants/${$}`,{...Z,headers:_([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}class MZ extends L{create($,Z){return this._client.post("/realtime/sessions",{body:$,...Z,headers:_([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}class NZ extends L{create($,Z){return this._client.post("/realtime/transcription_sessions",{body:$,...Z,headers:_([{"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 NZ(this._client)}}W1.Sessions=MZ;W1.TranscriptionSessions=NZ;class OZ extends L{create($,Z){return this._client.post("/chatkit/sessions",{body:$,...Z,headers:_([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers]),__security:{bearerAuth:!0}})}cancel($,Z){return this._client.post(q`/chatkit/sessions/${$}/cancel`,{...Z,headers:_([{"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:_([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers]),__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/chatkit/threads",d,{query:$,...Z,headers:_([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers]),__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/chatkit/threads/${$}`,{...Z,headers:_([{"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:_([{"OpenAI-Beta":"chatkit_beta=v1"},X?.headers]),__security:{bearerAuth:!0}})}}class V1 extends L{constructor(){super(...arguments);this.sessions=new OZ(this._client),this.threads=new _Z(this._client)}}V1.Sessions=OZ;V1.Threads=_Z;class PZ extends L{create($,Z,X){return this._client.post(q`/threads/${$}/messages`,{body:Z,...X,headers:_([{"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:_([{"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:_([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/threads/${$}/messages`,f,{query:Z,...X,headers:_([{"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:_([{"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:_([{"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`,f,{query:G,...X,headers:_([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}}var Vz=($)=>{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,g5,p0,l8,g0,B1,z2,H1,a8,E0,p8,i8,AZ,EZ,RZ,Hz,Kz,Bz,Uz,qz,Tz,Fz;class j$ extends G1{constructor(){super(...arguments);V0.add(this),g5.set(this,[]),p0.set(this,{}),l8.set(this,{}),g0.set(this,void 0),B1.set(this,void 0),z2.set(this,void 0),H1.set(this,void 0),a8.set(this,void 0),E0.set(this,void 0),p8.set(this,void 0),i8.set(this,void 0),AZ.set(this,void 0)}[(g5=new WeakMap,p0=new WeakMap,l8=new WeakMap,g0=new WeakMap,B1=new WeakMap,z2=new WeakMap,H1=new WeakMap,a8=new WeakMap,E0=new WeakMap,p8=new WeakMap,i8=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=D0.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 D0(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,p8,"f")}currentRun(){return M(this,i8,"f")}currentMessageSnapshot(){return M(this,g0,"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,l8,"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,p8,Z,"f"),M(this,V0,"m",Bz).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",Fz).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",Kz).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",Hz).call(this,Z);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:pw(Z)}},RZ=function(){if(this.ended)throw new S("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")},Hz=function(Z){let[X,Y]=M(this,V0,"m",qz).call(this,Z,M(this,g0,"f"));x(this,g0,X,"f"),M(this,l8,"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,g0,"f"));break;case"image_file":this._emit("imageFileDone",M(this,H1,"f").image_file,M(this,g0,"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,g0,"f"));break;case"text":this._emit("textDone",G.text,M(this,g0,"f"));break}}if(M(this,g0,"f"))this._emit("messageDone",Z.data);x(this,g0,void 0,"f")}},Kz=function(Z){let X=M(this,V0,"m",Uz).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,a8,"f"))this._emit("toolCallDelta",z,X.step_details.tool_calls[z.index]);else{if(M(this,E0,"f"))this._emit("toolCallDone",M(this,E0,"f"));if(x(this,a8,z.index,"f"),x(this,E0,X.step_details.tool_calls[z.index],"f"),M(this,E0,"f"))this._emit("toolCallCreated",M(this,E0,"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,E0,"f"))this._emit("toolCallDone",M(this,E0,"f")),x(this,E0,void 0,"f")}this._emit("runStepDone",Z.data,X);break;case"thread.run.step.in_progress":break}},Bz=function(Z){M(this,g5,"f").push(Z),this._emit("event",Z)},Uz=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")},qz=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",Tz).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")},Tz=function(Z,X){return K1.accumulateDelta(X,Z)},Fz=function(Z){switch(x(this,i8,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,E0,"f"))this._emit("toolCallDone",M(this,E0,"f")),x(this,E0,void 0,"f");break;case"thread.run.cancelling":break}};function pw($){}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:_([{"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:_([{"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:_([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/threads/${$}/runs`,f,{query:Z,...X,headers:_([{"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:_([{"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=_([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:_([{"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:_([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/threads/${$}`,{...Z,headers:_([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/threads/${$}`,{body:Z,...X,headers:_([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/threads/${$}`,{...Z,headers:_([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}createAndRun($,Z){return this._client.post("/threads/runs",{body:$,...Z,headers:_([{"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:_([{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`,f,{query:Z,...X,__security:{bearerAuth:!0}})}delete($,Z,X){let{container_id:Y}=Z;return this._client.delete(q`/containers/${Y}/files/${$}`,{...X,headers:_([{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",f,{query:$,...Z,__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/containers/${$}`,{...Z,headers:_([{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=Vz(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`,f,{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`,f,{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",f,{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",f,{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:_([{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`,f,{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",f,{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`,f,{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:_([{Accept:"*/*"},X?.headers]),__security:{bearerAuth:!0}})}hangup($,Z){return this._client.post(q`/realtime/calls/${$}/hangup`,{...Z,headers:_([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}refer($,Z,X){return this._client.post(q`/realtime/calls/${$}/refer`,{body:Z,...X,headers:_([{Accept:"*/*"},X?.headers]),__security:{bearerAuth:!0}})}reject($,Z={},X){return this._client.post(q`/realtime/calls/${$}/reject`,{body:Z,...X,headers:_([{Accept:"*/*"},X?.headers]),__security:{bearerAuth:!0}})}}class gZ 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 gZ(this._client),this.calls=new yZ(this._client)}}x$.ClientSecrets=gZ;x$.Calls=yZ;function Lz($,Z){if(!Z||!HM(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 v5($,Z)}function v5($,Z){let X=$.output.map((G)=>{if(G.type==="function_call")return{...G,parsed_arguments:UM(Z,G)};if(G.type==="message"){let z=G.content.map((J)=>{if(J.type==="output_text")return{...J,parsed:VM(Z,J.text)};return J});return{...G,content:z}}return G}),Y=Object.assign({},$,{output:X});if(!Object.getOwnPropertyDescriptor($,"output_text"))n8(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 VM($,Z){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(Z);return JSON.parse(Z)}function HM($){if(h4($.text?.format))return!0;return!1}function KM($){return $?.$brand==="auto-parseable-tool"}function BM($,Z){return $.find((X)=>X.type==="function"&&X.name===Z)}function UM($,Z){let X=BM($.tools??[],Z.name);return{...Z,...Z,parsed_arguments:KM(X)?X.$parseRaw(Z.arguments):X?.strict?JSON.parse(Z.arguments):null}}function n8($){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,r8,k$,s8,wz,Mz,Nz,Oz;class o8 extends G1{constructor($){super();w2.add(this),r8.set(this,void 0),k$.set(this,void 0),s8.set(this,void 0),x(this,r8,$,"f")}static createResponse($,Z,X){let Y=new o8(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",wz).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",Mz).call(this,J,z);if(G.controller.signal?.aborted)throw new $0;return M(this,w2,"m",Nz).call(this)}[(r8=new WeakMap,k$=new WeakMap,s8=new WeakMap,w2=new WeakSet,wz=function(){if(this.ended)return;x(this,k$,void 0,"f")},Mz=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",Oz).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 S(`missing output at index ${Z.output_index}`);if(z.type==="message"){let J=z.content[Z.content_index];if(!J)throw new S(`missing content at index ${Z.content_index}`);if(J.type!=="output_text")throw new S(`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 S(`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}},Nz=function(){if(this.ended)throw new S("stream has ended, this shouldn't happen");let Z=M(this,k$,"f");if(!Z)throw new S("request ended without sending any events");x(this,k$,void 0,"f");let X=qM(Z,M(this,r8,"f"));return x(this,s8,X,"f"),X},Oz=function(Z){let X=M(this,k$,"f");if(!X){if(Z.type!=="response.created")throw new S(`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 S(`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 S(`missing output at index ${Z.output_index}`);if(Y.type==="message"){let G=Y.content[Z.content_index];if(!G)throw new S(`missing content at index ${Z.content_index}`);if(G.type!=="output_text")throw new S(`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 S(`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 S(`missing output at index ${Z.output_index}`);if(Y.type==="reasoning"){let G=Y.content?.[Z.content_index];if(!G)throw new S(`missing content at index ${Z.content_index}`);if(G.type!=="reasoning_text")throw new S(`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,s8,"f");if(!$)throw new S("stream ended without producing a ChatCompletion");return $}}function qM($,Z){return Lz($,Z)}class vZ extends L{list($,Z={},X){return this._client.getAPIList(q`/responses/${$}/input_items`,f,{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 vZ(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")n8(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")n8(Y);return Y})}delete($,Z){return this._client.delete(q`/responses/${$}`,{...Z,headers:_([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}parse($,Z){return this._client.responses.create($,Z)._thenUnwrap((X)=>v5(X,$))}stream($,Z){return o8.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=vZ;b$.InputTokens=hZ;class uZ extends L{retrieve($,Z){return this._client.get(q`/skills/${$}/content`,{...Z,headers:_([{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:_([{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`,f,{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",f,{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 _z=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:_([{"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:_([{"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:_([{"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`,f,{query:G,...X,headers:_([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}async poll($,Z,X){let Y=_([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 _z(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:_([{"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:_([{"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:_([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($,Z={},X){return this._client.getAPIList(q`/vector_stores/${$}/files`,f,{query:Z,...X,headers:_([{"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:_([{"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=_([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:_([{"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:_([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}retrieve($,Z){return this._client.get(q`/vector_stores/${$}`,{...Z,headers:_([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}update($,Z,X){return this._client.post(q`/vector_stores/${$}`,{body:Z,...X,headers:_([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}list($={},Z){return this._client.getAPIList("/vector_stores",f,{query:$,...Z,headers:_([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}delete($,Z){return this._client.delete(q`/vector_stores/${$}`,{...Z,headers:_([{"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:_([{"OpenAI-Beta":"assistants=v2"},X?.headers]),__security:{bearerAuth:!0}})}}y$.Files=lZ;y$.FileBatches=cZ;class N2 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:_([{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 O2,Pz,t8;class _2 extends L{constructor(){super(...arguments);O2.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,O2,"m",Pz).call(this,X);let G=_([Z]).values,z=M(this,O2,"m",t8).call(this,G,"webhook-signature"),J=M(this,O2,"m",t8).call(this,G,"webhook-timestamp"),Q=M(this,O2,"m",t8).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")}}O2=new WeakSet,Pz=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")},t8=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 h5,u5,e8,Dz,DM="workload-identity-auth";class b{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}={}){h5.add(this),e8.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 N2(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 S("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!Z&&!X&&!J)throw new S("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!W.dangerouslyAllowBrowser&&DG())throw new S(`It looks like you're running in a browser-like environment.
|
|
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=($)=>Jw($,J0.ALL^J0.NUM);var Y0,Q$,e1,S$,b5,d8,f5,y5,v5,c8,g5,Vz;class C$ extends p4{constructor($){super();Y0.add(this),Q$.set(this,void 0),e1.set(this,void 0),S$.set(this,void 0),x(this,Q$,$,"f"),x(this,e1,[],"f")}get currentChatCompletionSnapshot(){return M(this,S$,"f")}static fromReadableStream($){let Z=new C$(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createChatCompletion($,Z,X){let Y=new C$(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())}M(this,Y0,"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)M(this,Y0,"m",f5).call(this,z);if(G.controller.signal?.aborted)throw new $0;return this._addChatCompletion(M(this,Y0,"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())}M(this,Y0,"m",b5).call(this),this._connected();let Y=R0.fromReadableStream($,this.controller),G;for await(let z of Y){if(G&&G!==z.id)this._addChatCompletion(M(this,Y0,"m",c8).call(this));M(this,Y0,"m",f5).call(this,z),G=z.id}if(Y.controller.signal?.aborted)throw new $0;return this._addChatCompletion(M(this,Y0,"m",c8).call(this))}[(Q$=new WeakMap,e1=new WeakMap,S$=new WeakMap,Y0=new WeakSet,b5=function(){if(this.ended)return;x(this,S$,void 0,"f")},d8=function(Z){let X=M(this,e1,"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},M(this,e1,"f")[Z.index]=X,X},f5=function(Z){if(this.ended)return;let X=M(this,Y0,"m",Vz).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=M(this,Y0,"m",d8).call(this,G);if(G.finish_reason){if(M(this,Y0,"m",v5).call(this,G),z.current_tool_call_index!=null)M(this,Y0,"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(M(this,Y0,"m",v5).call(this,G),z.current_tool_call_index!=null)M(this,Y0,"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 Kz(Q?.type)}}},y5=function(Z,X){if(M(this,Y0,"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=M(this,Q$,"f")?.tools?.find((J)=>g4(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:Y1(z)?z.$parseRaw(G.function.arguments):z?.function.strict?JSON.parse(G.function.arguments):null})}else Kz(G.type)},v5=function(Z){let X=M(this,Y0,"m",d8).call(this,Z);if(Z.message.content&&!X.content_done){X.content_done=!0;let Y=M(this,Y0,"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=M(this,S$,"f");if(!Z)throw new I("request ended without sending any chunks");return x(this,S$,void 0,"f"),x(this,e1,[],"f"),Ww(Z,M(this,Q$,"f"))},g5=function(){let Z=M(this,Q$,"f")?.response_format;if(h4(Z))return Z;return null},Vz=function(Z){var X,Y,G,z;let J=M(this,S$,"f"),{choices:Q,...W}=Z;if(!J)J=x(this,S$,{...W,choices:[]},"f");else Object.assign(J,W);for(let{delta:V,finish_reason:K,index:H,logprobs:B=null,...U}of Z.choices){let F=J.choices[H];if(!F)F=J.choices[H]={finish_reason:K,index:H,message:{},logprobs:B,...U};if(B)if(!F.logprobs)F.logprobs=Object.assign({},B);else{let{content:R,refusal:A,...S}=B;if(Hz(S),Object.assign(F.logprobs,S),R)(X=F.logprobs).content??(X.content=[]),F.logprobs.content.push(...R);if(A)(Y=F.logprobs).refusal??(Y.refusal=[]),F.logprobs.refusal.push(...A)}if(K){if(F.finish_reason=K,M(this,Q$,"f")&&R5(M(this,Q$,"f"))){if(K==="length")throw new I4;if(K==="content_filter")throw new j4}}if(Object.assign(F,U),!V)continue;let{content:T,refusal:w,function_call:O,role:N,tool_calls:_,...P}=V;if(Hz(P),Object.assign(F.message,P),w)F.message.refusal=(F.message.refusal||"")+w;if(N)F.message.role=N;if(O)if(!F.message.function_call)F.message.function_call=O;else{if(O.name)F.message.function_call.name=O.name;if(O.arguments)(G=F.message.function_call).arguments??(G.arguments=""),F.message.function_call.arguments+=O.arguments}if(T){if(F.message.content=(F.message.content||"")+T,!F.message.refusal&&M(this,Y0,"m",g5).call(this))F.message.parsed=k5(F.message.content)}if(_){if(!F.message.tool_calls)F.message.tool_calls=[];for(let{index:R,id:A,type:S,function:D,...k}of _){let b=(z=F.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,$z(M(this,Q$,"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 R0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Ww($,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:B,...U})=>{if(!K)throw new I(`missing finish_reason for choice ${H}`);let{content:F=null,function_call:T,tool_calls:w,...O}=V,N=V.role;if(!N)throw new I(`missing role for choice ${H}`);if(T){let{arguments:_,name:P}=T;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{...U,message:{content:F,function_call:{arguments:_,name:P},role:N,refusal:V.refusal??null},finish_reason:K,index:H,logprobs:B}}if(w)return{...U,index:H,finish_reason:K,logprobs:B,message:{...O,role:N,content:F,refusal:V.refusal??null,tool_calls:w.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
|
+
${l8($)}`);if(A==null)throw new I(`missing choices[${H}].tool_calls[${P}].type
|
|
252
|
+
${l8($)}`);if(b==null)throw new I(`missing choices[${H}].tool_calls[${P}].function.name
|
|
253
|
+
${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
255
|
|
|
256
256
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
257
257
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -260,22 +260,23 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
260
260
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
261
261
|
|
|
262
262
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
263
|
-
`);this.baseURL=W.baseURL,this.timeout=W.timeout??
|
|
264
|
-
`)){let U=B.indexOf(":");if(U>=0)H[B.substring(0,U).trim()]=B.substring(U+1).trim()}W.defaultHeaders=_([H,W.defaultHeaders])}if(this._options=W,J)this._workloadIdentityAuth=new M5(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 _([Z.bearerAuth?await this.bearerAuth($):null,Z.adminAPIKeyAuth?await this.adminAPIKeyAuth($):null])}async bearerAuth($){if(this._workloadIdentityAuth)return _([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey==null)return;return _([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth($){if(this.adminAPIKey==null)return;return _([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery($){return yG($)}getUserAgent(){return`${this.constructor.name}/JS ${R$}`}defaultIdempotencyKey(){return`stainless-node-retry-${G5()}`}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 S)throw X;throw new S(`Failed to get token from 'apiKey' function: ${X.message}`,{cause:X})}if(typeof Z!=="string"||!Z)throw new S(`Expected 'apiKey' function argument to return a string but it returned ${Z}`);return this.apiKey=Z,!0}buildURL($,Z,X){let Y=!M(this,h5,"m",Dz).call(this)&&X||this.baseURL,G=LG($)?new URL($):new URL(Y+(Y.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),z=this.defaultQuery(),J=Object.fromEntries(G.searchParams);if(!J5(z)||!J5(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(O4),F=Date.now();if(U instanceof globalThis.Error){let O=`retrying, ${Z} attempts remaining`;if(Y.signal?.aborted)throw new $0;let N=N4(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 P8)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 V5(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 C=`retrying, ${Z} attempts remaining`;return await V5(U.body),s(this).info(`${w} - ${C}`),s(this).debug(`[${W}] response error (${C})`,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 P=await U.text().catch((C)=>O4(C).message),E=NG(P),I=E?void 0:P;throw s(this).debug(`[${W}] response error (${N})`,z$({retryOfRequestLogID:X,url:U.url,status:U.status,headers:U.headers,message:I,durationMs:Date.now()-K})),this.makeStatusError(U.status,E,I,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 x8(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 ${DM}`){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)MG("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=_([G,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Y),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...EG(),"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=_([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:R8($),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,e8,"f").call(this,{body:$,headers:X}),isStreamingBody:!1}}}u5=b,e8=new WeakMap,h5=new WeakSet,Dz=function(){return this.baseURL!=="https://api.openai.com/v1"};b.OpenAI=u5;b.DEFAULT_TIMEOUT=600000;b.OpenAIError=S;b.APIError=r;b.APIConnectionError=$1;b.APIConnectionTimeoutError=Z1;b.APIUserAbortError=$0;b.NotFoundError=E4;b.ConflictError=R4;b.RateLimitError=S4;b.BadRequestError=_4;b.AuthenticationError=P4;b.InternalServerError=C4;b.PermissionDeniedError=D4;b.UnprocessableEntityError=A4;b.InvalidWebhookSignatureError=G$;b.toFile=b8;b.Completions=Q2;b.Chat=z1;b.Embeddings=V2;b.Files=K2;b.Images=T2;b.Audio=W$;b.Moderations=L2;b.Models=F2;b.FineTuning=a0;b.Graders=L1;b.VectorStores=y$;b.Webhooks=_2;b.Beta=i0;b.Batches=G2;b.Uploads=w1;b.Admin=Q1;b.Responses=b$;b.Realtime=x$;b.Conversations=T1;b.Evals=F1;b.Containers=q1;b.Skills=f$;b.Videos=N2;class m5{category="api";provider="openai";name;config;clientFactory;constructor($,Z,X){this.name=$,this.config=Z,this.clientFactory=X??(()=>new b)}async run($,Z){let{tool:X,docs:Y,requiredSources:G,discovery:z}=Z;if(!this.config.model)throw Error(`API target "${this.name}" missing 'model'. API targets must declare an explicit model.`);let J=z?p1(X,z.sourceHint):E$(X,Y,G),W=await this.clientFactory().responses.create({model:this.config.model,instructions:J,input:$,temperature:this.config.temperature??0,max_output_tokens:this.config.maxTokens??4096}),V=typeof W.output_text==="string"?W.output_text:"";return{response:V,allResponses:V?[{type:"final",text:V}]:[],toolsUsed:[],sources:[],metadata:{model:this.config.model,category:this.category,provider:this.provider,target:this.name}}}}import{query as EM}from"@anthropic-ai/claude-agent-sdk";class d5{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??LX,disallowedTools:G?.disallowedTools??this.config.disallowedTools??wX,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 EM({prompt:$,options:B})){if(w.type==="assistant"){let O=w.message?.content;if(Array.isArray(O)){let N="";for(let P of O){if(P.type==="text")N+=P.text;if(P.type==="tool_use"){let E=P;if(!V.includes(E.name))V.push(E.name)}}if(N){let P=U.length===0?"initial":"intermediate";U.push({type:P,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 RM}from"crypto";import{rm as AM}from"fs/promises";import{tmpdir as SM}from"os";import{join as CM}from"path";var IM="codex";class c5{category="cli";provider="codex-cli";name;config;spawnFn;readFileFn;binary;constructor($,Z,X={}){this.name=$,this.config=Z,this.spawnFn=X.spawn??bM,this.readFileFn=X.readFile??fM,this.binary=X.binary??IM}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)}
|
|
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=M5(W.logLevel,"ClientOptions.logLevel",this)??M5(l0("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??V,this.fetchOptions=W.fetchOptions,this.maxRetries=W.maxRetries??2,this.fetch=W.fetch??R8(),x(this,$X,jG,"f");let K=l0("OPENAI_CUSTOM_HEADERS");if(K){let H={};for(let B of K.split(`
|
|
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}=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"}]:void 0,K=await W.responses.create({model:this.config.model,instructions:Q,input:$,temperature:this.config.temperature??0,max_output_tokens:this.config.maxTokens??4096,...V?{tools:V}:{}}),H=typeof K.output_text==="string"?K.output_text:"",B=jM(K.output);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 jM($){if(!Array.isArray($))return[];let Z=!1;for(let X of $)if(X?.type==="web_search_call"){Z=!0;break}return Z?["web_search"]:[]}import{query as xM}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 xM({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 kM}from"crypto";import{rm as bM}from"fs/promises";import{tmpdir as fM}from"os";import{join as yM}from"path";var vM="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??mM,this.readFileFn=X.readFile??dM,this.binary=X.binary??vM}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)}
|
|
265
265
|
|
|
266
266
|
---
|
|
267
267
|
|
|
268
|
-
${$}`,V=
|
|
269
|
-
`)){let G=Y.trim();if(!G)continue;let z;try{z=JSON.parse(G)}catch{continue}let J=xM(z);if(J){let W=Z.length===0?"initial":"intermediate";Z.push({type:W,text:J})}let Q=kM(z);if(Q&&!X.includes(Q))X.push(Q)}return{allResponses:Z,toolsUsed:X}}function xM($){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 kM($){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 bM=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}},fM=async($)=>{let Z=Bun.file($);if(!await Z.exists())throw Error(`Last-message file not found: ${$}`);return Z.text()};function $X($,Z){let X=Z??h0;switch(X.category){case"cli":return yM($,X);case"api":return gM($,X);case"ide":throw Error("IDE targets not yet implemented. Coming soon!");default:throw Error(`Unknown target category: ${X.category}`)}}function yM($,Z){switch(Z.provider){case"claude-code":return new d5($,Z);case"codex-cli":return new c5($,Z);case"gemini-cli":throw Error("Gemini CLI target not yet implemented. Coming soon!");case"amazon-q":throw Error("Amazon Q target not yet implemented. Coming soon!");default:throw Error(`Unknown CLI provider: ${Z.provider}`)}}function gM($,Z){switch(Z.provider){case"anthropic":return new Y5($,Z);case"openai":return new m5($,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 ZX($,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 l5($,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 p5="__matrix__";function vM($){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:p5,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}async function i5($,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 K of J)Y?.(` [${K.id}] ${K.name}`);Y?.("")}let Q=J.map((K)=>K.id),W=vM(Z);if(X.scenarioFilter&&X.scenarioFilter.length>0){let K=new Set(X.scenarioFilter);if(W=W.filter((H)=>K.has(H.scenario.name)),W.length===0)throw Error(`No scenarios matched filter: ${[...K].join(", ")}. Declared scenarios: ${Z.scenarios.map((H)=>H.name).join(", ")}`)}let V="";for(let{scenario:K,targetName:H,contextName:B}of W){let U=hM(H,B);if(K.name!==V){if(V)Y?.("");Y?.(`"${K.name}"`),V=K.name}try{let F=await uM(K,H,B,$,Z,J,Q,X);G.push(F);let T=U?U.padEnd(18):"";if(F.cells){Y?.(` ${T} (matrix mode)`);for(let w of F.cells){let O=e0(w),P=` [${[w.cell.interface,w.cell.source??"-",w.cell.toolset].join(" \xB7 ")}]`.padEnd(40);Y?.(`${P} ${O.icon} ${O.label} (${O.confidence}%)`)}}else if(F.surfaces){Y?.(` ${T} (compare-surfaces mode)`);for(let w of F.surfaces){let O=e0(w),N=` [${w.active.join(",")}]`.padEnd(22);Y?.(`${N} ${O.icon} ${O.label} (${O.confidence}%)`)}}else{let w=e0({answerable:F.answerable??"NO",confidence:F.confidence??0,traps:F.traps??{fired:[],avoided:[]},error:F.error});Y?.(` ${T} ${w.icon} ${w.label} (${w.confidence}%)`)}}catch(F){let T=H==="default"?h0:Z.targets?.[H]??h0,w=K.requiredSources??[],O={scenario:K,answerable:"NO",confidence:0,response:"",reason:"Error during run",citations:{cited:[],required:w,missing:w,unknown:[]},traps:{fired:[],avoided:(K.traps??[]).map((P)=>P.id)},error:F instanceof Error?F.message:String(F),target:{target:H===p5?"matrix":H,category:T.category,provider:T.provider,model:T.model??"unknown"},context:{name:B}};G.push(O);let N=U?U.padEnd(18):"";Y?.(` ${N} \u2717 Error`)}}return Y?.(""),mM($,J,G)}function hM($,Z){if($==="default"&&Z==="default")return"";if(Z==="default")return`[${$}]`;return`[${$}/${Z}]`}async function uM($,Z,X,Y,G,z,J,Q){if($.matrix&&Z===p5)return dM($,X,Y,G,z,Q);let{config:W}=ZX(Z,G.targets),{config:V}=l5(X,G.contexts),K=Q.targetFactory?Q.targetFactory(Z,W):$X(Z,W);if($.compareSurfaces&&$.compareSurfaces.length>0){let E=[],I;for(let A of $.compareSurfaces){let C=new Set(A),D=z.filter((V$)=>C.has(V$.id)),k=($.requiredSources??[]).filter((V$)=>C.has(V$)),i=await K.run($.prompt,{tool:Y,cwd:Y.path,context:V,docs:D,requiredSources:k,onProgress:Q.onProgress}),l=b1({response:i.response,requiredSources:k,registeredIds:A}),R0=N$({response:i.response,traps:$.traps??[]}),A0=R0.fired.length>0,g$=A0?"NO":l.answerable,JX=A0?0:l.confidence,aZ=A0?`Trap fired: ${R0.fired.map((V$)=>`"${V$.id}" (${V$.reason})`).join("; ")}`:l.reason;E.push({active:A,answerable:g$,confidence:JX,response:i.response,reason:aZ,citations:l.citations,traps:R0,allResponses:i.allResponses}),I=i.metadata??I}return{scenario:$,answerable:null,confidence:null,response:null,reason:null,citations:null,traps:null,surfaces:E,target:I,context:{name:X}}}let H=$.requiredSources??[],B=await K.run($.prompt,{tool:Y,cwd:Y.path,context:V,docs:z,requiredSources:H,onProgress:Q.onProgress}),U=N$({response:B.response,traps:$.traps??[]}),F=U.fired.length>0,T=$.requiredSources!==void 0?b1({response:B.response,requiredSources:H,registeredIds:J}):null,w=$.expected!==void 0?a6({response:B.response,expected:$.expected}):null,O,N,P;if(F)O="NO",N=0,P=`Trap fired: ${U.fired.map((E)=>`"${E.id}" (${E.reason})`).join("; ")}`;else{let E=[],I=[];if(T)E.push({answerable:T.answerable,confidence:T.confidence}),I.push(T.reason);if(w){let A=w.total===0?100:Math.round(w.satisfied/w.total*100),C=A===100?"YES":A===0?"NO":"PARTIAL";E.push({answerable:C,confidence:A})}if(E.length===0)O="YES",N=100,P="No traps fired; no other contract declared";else{let A={YES:0,PARTIAL:1,NO:2};O=E.reduce((D,v)=>A[v.answerable]>A[D.answerable]?v:D).answerable,N=Math.round(E.reduce((D,v)=>D+v.confidence,0)/E.length),P=I.filter((D)=>D.length>0).join(" | ")}}return{scenario:$,answerable:O,confidence:N,response:B.response,reason:P,citations:T?T.citations:{cited:[],required:H,missing:[],unknown:[]},traps:U,target:B.metadata,context:{name:X},toolsUsed:B.toolsUsed,sources:B.sources,allResponses:B.allResponses}}function mM($,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 dM($,Z,X,Y,G,z){let{config:J}=l5(Z,Y.contexts),Q=$.matrix??{},W=$.target??"default",V=Q.interfaces??[W],K=Q.sources??[null],H=Q.toolsets??["none"],B=z.cellFilter??{},U=[],F;for(let w of V){if(B.interface&&B.interface!==w)continue;for(let O of K){if(B.source!==void 0&&B.source!==(O??""))continue;for(let N of H){if(B.toolset&&B.toolset!==N)continue;let P=N==="none"?null:Y.toolsets?.[N]??null,E=N!=="none"&&(P?.webSearch===!0||P?.webFetch===!0),I=N!=="none"&&P?.mcpServers?Object.keys(P.mcpServers):[],A=I.length>0,{config:C}=ZX(w,Y.targets);if(N!=="none"){if(E&&A)throw Error(`Toolset "${N}" mixes webSearch/webFetch with mcpServers; declare separate toolsets per shape so provenance can be attributed to one tool path.`);if(!E&&!A)throw Error(`Toolset "${N}" 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(A&&C.provider!=="claude-code")throw Error(`Toolset "${N}" (MCP) is implemented only on the claude-code interface today. Interface "${w}" uses provider "${C.provider}"; rerun with a Claude Code interface or use toolset "none".`);if(E&&C.provider!=="claude-code"&&C.provider!=="anthropic")throw Error(`Toolset "${N}" (web) is implemented on claude-code and anthropic interfaces today. Interface "${w}" uses provider "${C.provider}"; rerun with a supported interface or use toolset "none".`);if(E&&C.provider==="anthropic"&&!P?.webSearch)throw Error(`Toolset "${N}" on anthropic provider requires webSearch: true. The Anthropic API exposes a single server-side web tool; declare webSearch to enable it, or split web/fetch behaviour across separate toolsets.`)}let D=[],v=[],k=[],i=C.provider==="anthropic";if(E)if(i)k.push((g)=>g==="web_search");else{if(P?.webSearch)D.push("WebSearch"),v.push("WebSearch"),k.push((g)=>g==="WebSearch");if(P?.webFetch)D.push("WebFetch"),v.push("WebFetch"),k.push((g)=>g==="WebFetch")}if(A)for(let g of I)D.push(`mcp__${g}__*`),k.push((z0)=>z0.startsWith(`mcp__${g}__`));let l=N==="none"||i?C:{...C,allowedTools:D,disallowedTools:[],mcpServers:A?P?.mcpServers:void 0,maxTurns:Math.max(C.maxTurns??0,15)},R0=z.targetFactory?z.targetFactory(w,l):$X(w,l),A0=N==="none",g$=O==="none",JX=g$||!A0?[]:O===null?G:G.filter((g)=>g.id===O),aZ=g$||!A0?[]:O===null?G.map((g)=>g.id):[O],V$=$.requiredSources??[],Z3=A0?V$.filter((g)=>aZ.includes(g)):[],iz=lM($.prompt,O,G,A0),az=A0?void 0:{sourceHint:pM(O,G)},n0;try{let g=N==="none"?J:void 0;n0=await R0.run(iz,{tool:X,cwd:X.path,context:g,docs:JX,requiredSources:Z3,discovery:az,restrictBuiltinTools:N==="none"?void 0:v,webTools:E&&i?{search:P?.webSearch===!0}:void 0,onProgress:z.onProgress})}catch(g){U.push({cell:{interface:w,source:O,toolset:N},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 QX=N$({response:n0.response,traps:$.traps??[]}),nz=QX.fired.length>0,H$=$.requiredSources!==void 0&&A0?b1({response:n0.response,requiredSources:Z3,registeredIds:aZ}):null,G0=$.expected!==void 0?a6({response:n0.response,expected:$.expected}):null,R2=N!=="none"&&k.length>0?{expected:D,used:(n0.toolsUsed??[]).filter((g)=>k.some((z0)=>z0(g)))}:null,rz=R2!==null&&R2.used.length===0,sz=()=>{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}"`),v$=[];if(z0.length>0)v$.push(`missing includes: ${z0.join(", ")}`);if(S0.length>0)v$.push(`hit excludes: ${S0.join(", ")}`);g.push(v$.length>0?v$.join("; "):`expected checks satisfied (${G0.satisfied}/${G0.total})`)}return g.filter((z0)=>z0.length>0)},A2,S2,C2;if(nz)A2="NO",S2=0,C2=`Trap fired: ${QX.fired.map((g)=>`"${g.id}" (${g.reason})`).join("; ")}`;else if(rz){let g=R2;A2="NO",S2=0;let z0=`Provenance failed: toolset "${N}" configured but none of [${g.expected.join(", ")}] were used (answer rests on model prior knowledge)`,S0=sz();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),v$=S0===100?"YES":S0===0?"NO":"PARTIAL";g.push({answerable:v$,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}"`),nZ=[];if(Q0.length>0)nZ.push(`missing includes: ${Q0.join(", ")}`);if(h$.length>0)nZ.push(`hit excludes: ${h$.join(", ")}`);z0.push(nZ.length>0?nZ.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(" | ")}}U.push({cell:{interface:w,source:O,toolset:N},answerable:A2,confidence:S2,response:n0.response,reason:C2,citations:H$?H$.citations:null,traps:QX,expected:G0?{includes:G0.includes,excludes:G0.excludes,satisfied:G0.satisfied,total:G0.total}:void 0,toolsUsed:n0.toolsUsed,allResponses:n0.allResponses}),F=n0.metadata??F}}}let T=cM($,G);return{scenario:$,answerable:null,confidence:null,response:null,reason:null,citations:null,traps:null,cells:U,verifierSamples:T,target:F,context:{name:Z}}}function cM($,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 lM($,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`${$}
|
|
268
|
+
${$}`,V=yM(fM(),`pickled-codex-${kM()}.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:B,toolsUsed:U}=gM(H.stdout);if(H.exitCode!==0)throw Error(`codex exec failed (exit ${H.exitCode}): ${H.stderr.trim()||"no stderr output"}`);let F="";try{F=(await this.readFileFn(V)).trim()}catch{F=B.length>0?B[B.length-1].text:""}if(B.length>0)B[B.length-1].type="final";return{response:F,allResponses:B,toolsUsed:U,sources:[],metadata:{model:J,category:this.category,provider:this.provider,target:this.name}}}finally{await bM(V,{force:!0})}}}function gM($){let Z=[],X=[];for(let Y of $.split(`
|
|
269
|
+
`)){let G=Y.trim();if(!G)continue;let z;try{z=JSON.parse(G)}catch{continue}let J=hM(z);if(J){let W=Z.length===0?"initial":"intermediate";Z.push({type:W,text:J})}let Q=uM(z);if(Q&&!X.includes(Q))X.push(Q)}return{allResponses:Z,toolsUsed:X}}function hM($){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 uM($){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 mM=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}},dM=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 cM($,X);case"api":return lM($,X);case"ide":throw Error("IDE targets not yet implemented. Coming soon!");default:throw Error(`Unknown target category: ${X.category}`)}}function cM($,Z){switch(Z.provider){case"claude-code":return new l5($,Z);case"codex-cli":return new p5($,Z);case"gemini-cli":throw Error("Gemini CLI target not yet implemented. Coming soon!");case"amazon-q":throw Error("Amazon Q target not yet implemented. Coming soon!");default:throw Error(`Unknown CLI provider: ${Z.provider}`)}}function lM($,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 pM($){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 iM($,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 aM($){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=pM(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=iM(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 aM({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 _=nM(O,N);if(w.name!==F){if(F)Y?.("");Y?.(`"${w.name}"`),F=w.name}try{let P=await rM(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=sM($,J,G);return T.plan={expandedCells:K.length,selectedCells:H.length,seed:B},T}function nM($,Z){if($==="default"&&Z==="default")return"";if(Z==="default")return`[${$}]`;return`[${$}/${Z}]`}async function rM($,Z,X,Y,G,z,J,Q,W){if($.matrix&&Z===YX)return oM($,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 sM($,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 oM($,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")throw Error(`Toolset "${_}" (MCP) is implemented only on the claude-code interface today. Interface "${O}" uses provider "${D.provider}"; rerun with a Claude Code 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=eM($.prompt,N,G,N0),oz=N0?void 0:{sourceHint:$O(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,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=tM($,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 tM($,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 eM($,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
270
|
|
|
271
|
-
${z}`}function
|
|
271
|
+
${z}`}function $O($,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 Cz=($=0)=>(Z)=>`\x1B[${Z+$}m`,Iz=($=0)=>(Z)=>`\x1B[${38+$};5;${Z}m`,jz=($=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]}},Tf=Object.keys(a.modifier),ZO=Object.keys(a.color),XO=Object.keys(a.bgColor),Ff=[...ZO,...XO];function YO(){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=Cz(),a.color.ansi256=Iz(),a.color.ansi16m=jz(),a.bgColor.ansi=Cz(10),a.bgColor.ansi256=Iz(10),a.bgColor.ansi16m=jz(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 GO=YO(),g0=GO;import r5 from"process";import zO from"os";import xz from"tty";function b0($,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,GX;if(b0("no-color")||b0("no-colors")||b0("color=false")||b0("color=never"))GX=0;else if(b0("color")||b0("colors")||b0("color=true")||b0("color=always"))GX=1;function JO(){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 QO($){if($===0)return!1;return{level:$,hasBasic:!0,has256:$>=2,has16m:$>=3}}function WO($,{streamIsTTY:Z,sniffFlags:X=!0}={}){let Y=JO();if(Y!==void 0)GX=Y;let G=X?GX:Y;if(G===0)return 0;if(X){if(b0("color=16m")||b0("color=full")||b0("color=truecolor"))return 3;if(b0("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=zO.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 kz($,Z={}){let X=WO($,{streamIsTTY:$&&$.isTTY,...Z});return QO(X)}var VO={stdout:kz({isTTY:xz.isatty(1)}),stderr:kz({isTTY:xz.isatty(2)})},bz=VO;function fz($,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 yz($,Z,X,Y){let G=0,z="";do{let J=$[Y-1]==="\r";z+=$.slice(G,J?Y-1:Y)+Z+(J?`\r
|
|
272
272
|
`:`
|
|
273
273
|
`)+X,G=Y+1,Y=$.indexOf(`
|
|
274
|
-
`,G)}while(Y!==-1);return z+=$.slice(G),z}var{stdout:
|
|
275
|
-
`);if(z!==-1)Z=
|
|
276
|
-
`)}
|
|
277
|
-
`)
|
|
278
|
-
`);
|
|
274
|
+
`,G)}while(Y!==-1);return z+=$.slice(G),z}var{stdout:vz,stderr:gz}=bz,s5=Symbol("GENERATOR"),D2=Symbol("STYLER"),pZ=Symbol("IS_EMPTY"),hz=["ansi","ansi","ansi256","ansi16m"],E2=Object.create(null),HO=($,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=vz?vz.level:0;$.level=Z.level===void 0?X:Z.level};var KO=($)=>{let Z=(...X)=>X.join(" ");return HO(Z,$),Object.setPrototypeOf(Z,iZ.prototype),Z};function iZ($){return KO($)}Object.setPrototypeOf(iZ.prototype,Function.prototype);for(let[$,Z]of Object.entries(g0))E2[$]={get(){let X=zX(this,t5(Z.open,Z.close,this[D2]),this[pZ]);return Object.defineProperty(this,$,{value:X}),X}};E2.visible={get(){let $=zX(this,this[D2],!0);return Object.defineProperty(this,"visible",{value:$}),$}};var o5=($,Z,X,...Y)=>{if($==="rgb"){if(Z==="ansi16m")return g0[X].ansi16m(...Y);if(Z==="ansi256")return g0[X].ansi256(g0.rgbToAnsi256(...Y));return g0[X].ansi(g0.rgbToAnsi(...Y))}if($==="hex")return o5("rgb",Z,X,...g0.hexToRgb(...Y));return g0[X][$](...Y)},BO=["rgb","hex","ansi256"];for(let $ of BO){E2[$]={get(){let{level:X}=this;return function(...Y){let G=t5(o5($,hz[X],"color",...Y),g0.color.close,this[D2]);return zX(this,G,this[pZ])}}};let Z="bg"+$[0].toUpperCase()+$.slice(1);E2[Z]={get(){let{level:X}=this;return function(...Y){let G=t5(o5($,hz[X],"bgColor",...Y),g0.bgColor.close,this[D2]);return zX(this,G,this[pZ])}}}}var UO=Object.defineProperties(()=>{},{...E2,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}},zX=($,Z,X)=>{let Y=(...G)=>qO(Y,G.length===1?""+G[0]:G.join(" "));return Object.setPrototypeOf(Y,UO),Y[s5]=$,Y[D2]=Z,Y[pZ]=X,Y},qO=($,Z)=>{if($.level<=0||!Z)return $[pZ]?"":Z;let X=$[D2];if(X===void 0)return Z;let{openAll:Y,closeAll:G}=X;if(Z.includes("\x1B"))while(X!==void 0)Z=fz(Z,X.close,X.open),X=X.parent;let z=Z.indexOf(`
|
|
275
|
+
`);if(z!==-1)Z=yz(Z,G,Y,z);return Y+Z+G};Object.defineProperties(iZ.prototype,E2);var TO=iZ(),Rf=iZ({level:gz?gz.level:0});var j=TO;var e5="\u2500".repeat(55);function $3($){if($==="success")return j.green;if($==="warning")return j.yellow;return j.red}function FO($){if($>=70)return j.green;if($>=50)return j.yellow;return j.red}function Z3($){if($.label==="Error")return $.label;return`${$.label} (${$.confidence}%)`}function LO($){let Z=e0({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 wO($){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 MO($){let Z=$.map((X)=>X.scenario.name);return new Set(Z).size!==Z.length}function JX($){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: ${JX($.citations.cited)}`));if($.citations.missing.length>0)X.push(j.dim(`${Z}missing: ${JX($.citations.missing)}`));if($.citations.unknown.length>0)X.push(j.dim(`${Z}unknown: ${JX($.citations.unknown)}`));return X}function uz($,Z){if(!$.traps||!$.citations)return[];return X3({error:$.error,traps:$.traps,reason:$.reason??"",answerable:$.answerable??"NO",citations:$.citations},Z)}function mz($){let{icon:Z,status:X,color:Y}=LO($),G=wO($),z=`${Z} ${X}`;return G?`${G} ${Y(z)}`:Y(z)}function dz($,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=e0(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 cz($,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=e0(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 OO($){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 NO($,Z){let X=$.summary.score,G=`Overall: ${FO(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 lz($,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(JX($.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(`
|
|
276
|
+
`)}if(MO(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(...dz(K," "));else if(K.surfaces)J.push(...cz(K," "));else J.push(` ${mz(K)}`),J.push(...uz(K," "));J.push("")}}else for(let Q of z){if(J.push(`Scenario: ${Q.scenario.name}`),Q.cells)J.push(...dz(Q," "));else if(Q.surfaces)J.push(...cz(Q," "));else J.push(` ${mz(Q)}`),J.push(...uz(Q," "));J.push("")}return J.push(e5),J.push(NO($,Z.threshold)),J.push(j.dim(OO(Y))),J.join(`
|
|
277
|
+
`)}function Y3($,Z={}){console.log(lz($,Z)),console.log()}function QX($,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 PO($){if($.format&&$.format!=="terminal")return $.format;if($.json)return"json";return $.format??"terminal"}async function pz($,Z){let{output:X}=Z,Y=PO(Z),G=_O.resolve($),z;try{z=await a6({targetRepo:G})}catch(H){console.error(j.red(H instanceof Error?H.message:H)),process.exit(1)}let J;if(Y==="json")J=u6(z);else if(Y==="markdown")J=h6(z);else J=m6(z);if(X)await Bun.write(X,J);else await DO(`${J}
|
|
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 DO($){return new Promise((Z,X)=>{process.stdout.write($,(Y)=>{if(Y)X(Y);else Z()})})}import EO from"path";async function nz($,Z){let{json:X,output:Y,verbose:G}=Z,z=(O)=>!X&&console.log(O),J=EO.resolve($),Q;try{Q=await j1(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=k9(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=AO(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,B=Z.scenario?[Z.scenario]:void 0,U;if(Z.sample!==void 0){if(U=iz(Z.sample,"--sample"),U===null)process.exit(1)}let F;if(Z.maxCells!==void 0){if(F=iz(Z.maxCells,"--max-cells"),F===null)process.exit(1)}let T;try{T=await n5(W,Q,{onProgress:G?(O)=>{if(!X)z(j.dim(` ${O}`))}:void 0,cellFilter:H,scenarioFilter:B,plan:Z.plan,maxCells:F,sample:U,seed:Z.seed})}catch(O){console.error(j.red(O instanceof Error?O.message:O)),process.exit(1)}let w=RO({plan:Z.plan===!0,threshold:V,score:T.summary.score});if(Y)await Bun.write(Y,QX(T,{verbose:G}));else if(X)await SO(`${QX(T,{verbose:G})}
|
|
279
|
+
`);else Y3(T,{threshold:V});if(w){if(X||Y)console.error(j.red(`Overall: ${T.summary.score} / 100 \xB7 threshold ${V} \xB7 run fails`)),console.error(j.dim("Review failed scenarios before trusting this surface."));process.exit(1)}}function RO($){if($.plan)return!1;return $.threshold>0&&$.score<$.threshold}function AO($,Z){if($===void 0){if(Z===void 0)return 0;return az(Z,"pickled.yml threshold")}return az($,"--threshold")}function iz($,Z){if(!/^\d+$/.test($))return console.error(j.red(`Invalid ${Z} "${$}". Expected a non-negative integer.`)),null;return Number($)}function az($,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 SO($){return new Promise((Z,X)=>{process.stdout.write($,(Y)=>{if(Y)X(Y);else Z()})})}import CO from"path";var IO=`# pickled.yml - Agent legibility check for your product
|
|
279
280
|
|
|
280
281
|
tool:
|
|
281
282
|
name: "your-product"
|
|
@@ -297,4 +298,4 @@ scenarios:
|
|
|
297
298
|
|
|
298
299
|
# Optional: fail CI if score falls below threshold
|
|
299
300
|
# threshold: 80
|
|
300
|
-
`;async function
|
|
301
|
+
`;async function rz($){let X=`${CO.resolve($)}/pickled.yml`;if(await Bun.file(X).exists())console.error(j.red("pickled.yml already exists")),process.exit(1);await Bun.write(X,IO),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()}M1.name("pickled").description("Test what agents actually understand about your product").version(D3.version);M1.command("init").description("Create a pickled.yml config file").argument("[path]","Path to your project (default: current directory)",".").action(rz);M1.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 wX("--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 wX("--fail-on <level>","Exit non-zero on this severity or higher").choices(["error","warning"]).default("error")).action(pz);M1.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(nz);await M1.parseAsync();
|