mimo-cli 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mimo.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as U5}from"node:module";var N5=Object.create;var{getPrototypeOf:z5,defineProperty:A4,getOwnPropertyNames:V5}=Object;var B5=Object.prototype.hasOwnProperty;function K5($){return this[$]}var H5,T5,f2=($,Y,Z)=>{var w=$!=null&&typeof $==="object";if(w){var X=Y?H5??=new WeakMap:T5??=new WeakMap,W=X.get($);if(W)return W}Z=$!=null?N5(z5($)):{};let G=Y||!$||!$.__esModule?A4(Z,"default",{value:$,enumerable:!0}):Z;for(let Q of V5($))if(!B5.call(G,Q))A4(G,Q,{get:K5.bind($,Q),enumerable:!0});if(w)X.set($,G);return G};var f4=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);var j4=U5(import.meta.url);var R3=f4((Lw,n4)=>{var S3={to($,Y){if(!Y)return`\x1B[${$+1}G`;return`\x1B[${Y+1};${$+1}H`},move($,Y){let Z="";if($<0)Z+=`\x1B[${-$}D`;else if($>0)Z+=`\x1B[${$}C`;if(Y<0)Z+=`\x1B[${-Y}A`;else if(Y>0)Z+=`\x1B[${Y}B`;return Z},up:($=1)=>`\x1B[${$}A`,down:($=1)=>`\x1B[${$}B`,forward:($=1)=>`\x1B[${$}C`,backward:($=1)=>`\x1B[${$}D`,nextLine:($=1)=>"\x1B[E".repeat($),prevLine:($=1)=>"\x1B[F".repeat($),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},S5={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},R5={screen:"\x1B[2J",up:($=1)=>"\x1B[1J".repeat($),down:($=1)=>"\x1B[J".repeat($),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines($){let Y="";for(let Z=0;Z<$;Z++)Y+=this.line+(Z<$-1?S3.up():"");if($)Y+=S3.left;return Y}};n4.exports={cursor:S3,scroll:S5,erase:R5,beep:"\x07"}});var _3=f4((Fw,P3)=>{var D2=process||{},a4=D2.argv||[],I2=D2.env||{},P5=!(!!I2.NO_COLOR||a4.includes("--no-color"))&&(!!I2.FORCE_COLOR||a4.includes("--color")||D2.platform==="win32"||(D2.stdout||{}).isTTY&&I2.TERM!=="dumb"||!!I2.CI),_5=($,Y,Z=$)=>(w)=>{let X=""+w,W=X.indexOf(Y,$.length);return~W?$+A5(X,Y,Z,W)+Y:$+X+Y},A5=($,Y,Z,w)=>{let X="",W=0;do X+=$.substring(W,w)+Z,W=w+Y.length,w=$.indexOf(Y,W);while(~w);return X+$.substring(W)},t4=($=P5)=>{let Y=$?_5:()=>String;return{isColorSupported:$,reset:Y("\x1B[0m","\x1B[0m"),bold:Y("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:Y("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:Y("\x1B[3m","\x1B[23m"),underline:Y("\x1B[4m","\x1B[24m"),inverse:Y("\x1B[7m","\x1B[27m"),hidden:Y("\x1B[8m","\x1B[28m"),strikethrough:Y("\x1B[9m","\x1B[29m"),black:Y("\x1B[30m","\x1B[39m"),red:Y("\x1B[31m","\x1B[39m"),green:Y("\x1B[32m","\x1B[39m"),yellow:Y("\x1B[33m","\x1B[39m"),blue:Y("\x1B[34m","\x1B[39m"),magenta:Y("\x1B[35m","\x1B[39m"),cyan:Y("\x1B[36m","\x1B[39m"),white:Y("\x1B[37m","\x1B[39m"),gray:Y("\x1B[90m","\x1B[39m"),bgBlack:Y("\x1B[40m","\x1B[49m"),bgRed:Y("\x1B[41m","\x1B[49m"),bgGreen:Y("\x1B[42m","\x1B[49m"),bgYellow:Y("\x1B[43m","\x1B[49m"),bgBlue:Y("\x1B[44m","\x1B[49m"),bgMagenta:Y("\x1B[45m","\x1B[49m"),bgCyan:Y("\x1B[46m","\x1B[49m"),bgWhite:Y("\x1B[47m","\x1B[49m"),blackBright:Y("\x1B[90m","\x1B[39m"),redBright:Y("\x1B[91m","\x1B[39m"),greenBright:Y("\x1B[92m","\x1B[39m"),yellowBright:Y("\x1B[93m","\x1B[39m"),blueBright:Y("\x1B[94m","\x1B[39m"),magentaBright:Y("\x1B[95m","\x1B[39m"),cyanBright:Y("\x1B[96m","\x1B[39m"),whiteBright:Y("\x1B[97m","\x1B[39m"),bgBlackBright:Y("\x1B[100m","\x1B[49m"),bgRedBright:Y("\x1B[101m","\x1B[49m"),bgGreenBright:Y("\x1B[102m","\x1B[49m"),bgYellowBright:Y("\x1B[103m","\x1B[49m"),bgBlueBright:Y("\x1B[104m","\x1B[49m"),bgMagentaBright:Y("\x1B[105m","\x1B[49m"),bgCyanBright:Y("\x1B[106m","\x1B[49m"),bgWhiteBright:Y("\x1B[107m","\x1B[49m")}};P3.exports=t4();P3.exports.createColors=t4});function H1($){return $.replace(/-([a-z])/g,(Y,Z)=>Z.toUpperCase())}function b4($){let Y=$.flag.match(/^--([a-z][a-z0-9-]*)/i);return Y?H1(Y[1]):null}function M5($){if($.type==="number"||$.type==="array")return!1;return!$.flag.includes("<")&&!$.flag.includes("[")}function v4($){let Y=new Map;for(let Z of $){let w=Z.flag.split(",").map((X)=>X.trim());if(w.length>=2){let X=w[0].trim(),W=w[1].trim(),G=X.match(/^(-[a-zA-Z])$/),Q=W.match(/^(--[a-z][a-z0-9-]*)/i);if(G&&Q)Y.set(G[1],Q[1])}}return Y}function y4($){let Y=new Set,Z=new Set,w=new Set;for(let X of $){let W=b4(X);if(!W)continue;if(M5(X))Y.add(W);else if(X.type==="number")Z.add(W);else if(X.type==="array")w.add(W)}return{booleans:Y,numbers:Z,arrays:w}}function I4($,Y=[]){let Z=y4(Y),w=v4(Y),X=[],W=0;while(W<$.length){let G=$[W];if(G==="--")break;if(G.startsWith("--")){let Q=G.indexOf("="),z=Q!==-1?G.slice(2,Q):G.slice(2),H=H1(z);if(!Z.booleans.has(H)&&Q===-1)W+=2;else W+=1;continue}if(G.startsWith("-")&&G.length>=2&&G[1]!=="-"){let Q=w.get(G);if(Q){let z=H1(Q.slice(2));if(!Z.booleans.has(z))W+=2;else W+=1}else W+=1;continue}X.push(G),W++}return X}function D4($,Y){let Z=y4(Y),w=v4(Y),X={};for(let G of Y)if(G.default!==void 0){let Q=b4(G);if(Q)X[Q]=G.default}let W=0;while(W<$.length){let G=$[W];if(G==="--help"||G==="-h"){X.help=!0,W++;continue}if(G==="--")break;if(G.startsWith("--")){let Q=G.indexOf("="),z,H;if(Q!==-1)z=G.slice(2,Q),H=G.slice(Q+1);else z=G.slice(2);let T=H1(z);if(z.startsWith("no-")){let K=H1(z.slice(3));if(Z.booleans.has(K)){X[K]=!1,X[`no${K.charAt(0).toUpperCase()}${K.slice(1)}`]=!0,W++;continue}}if(Z.booleans.has(T)){X[T]=!0,W++;continue}if(H===void 0)W++,H=$[W];if(H===void 0)throw Error(`Flag --${z} requires a value.`);if(Z.arrays.has(T)){let K=X[T];if(Array.isArray(K))K.push(H);else X[T]=[H]}else if(Z.numbers.has(T)){let K=Number(H);if(H.trim()===""||!Number.isFinite(K))throw Error(`Flag --${z} requires a numeric value, got "${H}".`);X[T]=K}else X[T]=H;W++;continue}if(G.startsWith("-")&&G.length>=2&&G[1]!=="-"){let Q=w.get(G);if(Q){let z=H1(Q.slice(2));if(Z.booleans.has(z)){X[z]=!0,W++;continue}W++;let H=$[W];if(H===void 0)throw Error(`Flag ${G} requires a value.`);if(Z.arrays.has(z)){let T=X[z];if(Array.isArray(T))T.push(H);else X[z]=[H]}else if(Z.numbers.has(z)){let T=Number(H);if(H.trim()===""||!Number.isFinite(T))throw Error(`Flag ${G} requires a numeric value, got "${H}".`);X[z]=T}else X[z]=H}W++;continue}W++}return X}function j($){return{name:$.name,description:$.description,usage:$.usage,options:$.options,examples:$.examples,apiDocs:$.apiDocs,execute:$.run}}var T1=[{flag:"--api-key <value>",description:"flag.apiKey"},{flag:"--base-url <value>",description:"flag.baseUrl"},{flag:"--output <value>",description:"flag.output",default:"text"},{flag:"--timeout <seconds>",description:"flag.timeout",default:300,type:"number"},{flag:"--quiet",description:"flag.quiet"},{flag:"--verbose",description:"flag.verbose"},{flag:"--no-color",description:"flag.noColor"},{flag:"--dry-run",description:"flag.dryRun"},{flag:"--non-interactive",description:"flag.nonInteractive"},{flag:"--help",description:"flag.help"},{flag:"--version",description:"flag.version"}];var v$="zh";function h4(){return v$}function g4($){if($!=="zh"&&$!=="en")v$="zh";else v$=$}function j2($){if(!$){if((process.env.LANG||process.env.LC_ALL||process.env.LC_MESSAGES||"").startsWith("zh"))v$="zh";else v$="zh";return}if($==="en")v$="en";else v$="zh"}var x5={"main.usage":{zh:"用法:mimo <资源> <命令> [参数]",en:"Usage: mimo <resource> <command> [flags]"},"main.resources":{zh:"可用命令:",en:"Resources:"},"main.globalFlags":{zh:"全局参数:",en:"Global Flags:"},"main.gettingHelp":{zh:"获取帮助:",en:"Getting Help:"},"main.helpHint1":{zh:"在任何命令后添加 --help 查看完整选项、默认值和示例。",en:"Add --help after any command to see its full list of options, defaults,"},"main.helpHint2":{zh:"例如:",en:"and usage examples. For example:"},"main.notLoggedIn":{zh:" 尚未登录。",en:" Not logged in."},"main.loginHint1":{zh:" mimo auth login 使用 API Key 登录",en:" mimo auth login Log in with an API key"},"main.loginHint2":{zh:" mimo auth login --api-key 直接保存 API Key",en:" mimo auth login --api-key Save an API key directly"},"main.interrupted":{zh:`
2
+ import{createRequire as q5}from"node:module";var B5=Object.create;var{getPrototypeOf:K5,defineProperty:j4,getOwnPropertyNames:H5}=Object;var T5=Object.prototype.hasOwnProperty;function U5($){return this[$]}var M5,x5,f2=($,Y,Z)=>{var w=$!=null&&typeof $==="object";if(w){var X=Y?M5??=new WeakMap:x5??=new WeakMap,W=X.get($);if(W)return W}Z=$!=null?B5(K5($)):{};let G=Y||!$||!$.__esModule?j4(Z,"default",{value:$,enumerable:!0}):Z;for(let Q of H5($))if(!T5.call(G,Q))j4(G,Q,{get:U5.bind($,Q),enumerable:!0});if(w)X.set($,G);return G};var b4=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);var v4=q5(import.meta.url);var P3=b4((jw,t4)=>{var R3={to($,Y){if(!Y)return`\x1B[${$+1}G`;return`\x1B[${Y+1};${$+1}H`},move($,Y){let Z="";if($<0)Z+=`\x1B[${-$}D`;else if($>0)Z+=`\x1B[${$}C`;if(Y<0)Z+=`\x1B[${-Y}A`;else if(Y>0)Z+=`\x1B[${Y}B`;return Z},up:($=1)=>`\x1B[${$}A`,down:($=1)=>`\x1B[${$}B`,forward:($=1)=>`\x1B[${$}C`,backward:($=1)=>`\x1B[${$}D`,nextLine:($=1)=>"\x1B[E".repeat($),prevLine:($=1)=>"\x1B[F".repeat($),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},_5={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},A5={screen:"\x1B[2J",up:($=1)=>"\x1B[1J".repeat($),down:($=1)=>"\x1B[J".repeat($),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines($){let Y="";for(let Z=0;Z<$;Z++)Y+=this.line+(Z<$-1?R3.up():"");if($)Y+=R3.left;return Y}};t4.exports={cursor:R3,scroll:_5,erase:A5,beep:"\x07"}});var A3=b4((bw,_3)=>{var D2=process||{},r4=D2.argv||[],I2=D2.env||{},f5=!(!!I2.NO_COLOR||r4.includes("--no-color"))&&(!!I2.FORCE_COLOR||r4.includes("--color")||D2.platform==="win32"||(D2.stdout||{}).isTTY&&I2.TERM!=="dumb"||!!I2.CI),j5=($,Y,Z=$)=>(w)=>{let X=""+w,W=X.indexOf(Y,$.length);return~W?$+b5(X,Y,Z,W)+Y:$+X+Y},b5=($,Y,Z,w)=>{let X="",W=0;do X+=$.substring(W,w)+Z,W=w+Y.length,w=$.indexOf(Y,W);while(~w);return X+$.substring(W)},s4=($=f5)=>{let Y=$?j5:()=>String;return{isColorSupported:$,reset:Y("\x1B[0m","\x1B[0m"),bold:Y("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:Y("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:Y("\x1B[3m","\x1B[23m"),underline:Y("\x1B[4m","\x1B[24m"),inverse:Y("\x1B[7m","\x1B[27m"),hidden:Y("\x1B[8m","\x1B[28m"),strikethrough:Y("\x1B[9m","\x1B[29m"),black:Y("\x1B[30m","\x1B[39m"),red:Y("\x1B[31m","\x1B[39m"),green:Y("\x1B[32m","\x1B[39m"),yellow:Y("\x1B[33m","\x1B[39m"),blue:Y("\x1B[34m","\x1B[39m"),magenta:Y("\x1B[35m","\x1B[39m"),cyan:Y("\x1B[36m","\x1B[39m"),white:Y("\x1B[37m","\x1B[39m"),gray:Y("\x1B[90m","\x1B[39m"),bgBlack:Y("\x1B[40m","\x1B[49m"),bgRed:Y("\x1B[41m","\x1B[49m"),bgGreen:Y("\x1B[42m","\x1B[49m"),bgYellow:Y("\x1B[43m","\x1B[49m"),bgBlue:Y("\x1B[44m","\x1B[49m"),bgMagenta:Y("\x1B[45m","\x1B[49m"),bgCyan:Y("\x1B[46m","\x1B[49m"),bgWhite:Y("\x1B[47m","\x1B[49m"),blackBright:Y("\x1B[90m","\x1B[39m"),redBright:Y("\x1B[91m","\x1B[39m"),greenBright:Y("\x1B[92m","\x1B[39m"),yellowBright:Y("\x1B[93m","\x1B[39m"),blueBright:Y("\x1B[94m","\x1B[39m"),magentaBright:Y("\x1B[95m","\x1B[39m"),cyanBright:Y("\x1B[96m","\x1B[39m"),whiteBright:Y("\x1B[97m","\x1B[39m"),bgBlackBright:Y("\x1B[100m","\x1B[49m"),bgRedBright:Y("\x1B[101m","\x1B[49m"),bgGreenBright:Y("\x1B[102m","\x1B[49m"),bgYellowBright:Y("\x1B[103m","\x1B[49m"),bgBlueBright:Y("\x1B[104m","\x1B[49m"),bgMagentaBright:Y("\x1B[105m","\x1B[49m"),bgCyanBright:Y("\x1B[106m","\x1B[49m"),bgWhiteBright:Y("\x1B[107m","\x1B[49m")}};_3.exports=s4();_3.exports.createColors=s4});function H1($){return $.replace(/-([a-z])/g,(Y,Z)=>Z.toUpperCase())}function y4($){let Y=$.flag.match(/^--([a-z][a-z0-9-]*)/i);return Y?H1(Y[1]):null}function O5($){if($.type==="number"||$.type==="array")return!1;return!$.flag.includes("<")&&!$.flag.includes("[")}function I4($){let Y=new Map;for(let Z of $){let w=Z.flag.split(",").map((X)=>X.trim());if(w.length>=2){let X=w[0].trim(),W=w[1].trim(),G=X.match(/^(-[a-zA-Z])$/),Q=W.match(/^(--[a-z][a-z0-9-]*)/i);if(G&&Q)Y.set(G[1],Q[1])}}return Y}function D4($){let Y=new Set,Z=new Set,w=new Set;for(let X of $){let W=y4(X);if(!W)continue;if(O5(X))Y.add(W);else if(X.type==="number")Z.add(W);else if(X.type==="array")w.add(W)}return{booleans:Y,numbers:Z,arrays:w}}function h4($,Y=[]){let Z=D4(Y),w=I4(Y),X=[],W=0;while(W<$.length){let G=$[W];if(G==="--")break;if(G.startsWith("--")){let Q=G.indexOf("="),V=Q!==-1?G.slice(2,Q):G.slice(2),H=H1(V);if(!Z.booleans.has(H)&&Q===-1)W+=2;else W+=1;continue}if(G.startsWith("-")&&G.length>=2&&G[1]!=="-"){let Q=w.get(G);if(Q){let V=H1(Q.slice(2));if(!Z.booleans.has(V))W+=2;else W+=1}else W+=1;continue}X.push(G),W++}return X}function g4($,Y){let Z=D4(Y),w=I4(Y),X={};for(let G of Y)if(G.default!==void 0){let Q=y4(G);if(Q)X[Q]=G.default}let W=0;while(W<$.length){let G=$[W];if(G==="--help"||G==="-h"){X.help=!0,W++;continue}if(G==="--")break;if(G.startsWith("--")){let Q=G.indexOf("="),V,H;if(Q!==-1)V=G.slice(2,Q),H=G.slice(Q+1);else V=G.slice(2);let T=H1(V);if(V.startsWith("no-")){let K=H1(V.slice(3));if(Z.booleans.has(K)){X[K]=!1,X[`no${K.charAt(0).toUpperCase()}${K.slice(1)}`]=!0,W++;continue}}if(Z.booleans.has(T)){X[T]=!0,W++;continue}if(H===void 0)W++,H=$[W];if(H===void 0)throw Error(`Flag --${V} requires a value.`);if(Z.arrays.has(T)){let K=X[T];if(Array.isArray(K))K.push(H);else X[T]=[H]}else if(Z.numbers.has(T)){let K=Number(H);if(H.trim()===""||!Number.isFinite(K))throw Error(`Flag --${V} requires a numeric value, got "${H}".`);X[T]=K}else X[T]=H;W++;continue}if(G.startsWith("-")&&G.length>=2&&G[1]!=="-"){let Q=w.get(G);if(Q){let V=H1(Q.slice(2));if(Z.booleans.has(V)){X[V]=!0,W++;continue}W++;let H=$[W];if(H===void 0)throw Error(`Flag ${G} requires a value.`);if(Z.arrays.has(V)){let T=X[V];if(Array.isArray(T))T.push(H);else X[V]=[H]}else if(Z.numbers.has(V)){let T=Number(H);if(H.trim()===""||!Number.isFinite(T))throw Error(`Flag ${G} requires a numeric value, got "${H}".`);X[V]=T}else X[V]=H}W++;continue}W++}return X}function f($){return{name:$.name,description:$.description,usage:$.usage,options:$.options,examples:$.examples,apiDocs:$.apiDocs,execute:$.run}}var T1=[{flag:"--api-key <value>",description:"flag.apiKey"},{flag:"--base-url <value>",description:"flag.baseUrl"},{flag:"--output <value>",description:"flag.output",default:"text"},{flag:"--timeout <seconds>",description:"flag.timeout",default:300,type:"number"},{flag:"--quiet",description:"flag.quiet"},{flag:"--verbose",description:"flag.verbose"},{flag:"--no-color",description:"flag.noColor"},{flag:"--dry-run",description:"flag.dryRun"},{flag:"--non-interactive",description:"flag.nonInteractive"},{flag:"--help",description:"flag.help"},{flag:"--version",description:"flag.version"}];var v$="zh";function m4(){return v$}function c4($){if($!=="zh"&&$!=="en")v$="zh";else v$=$}function j2($){if(!$){if((process.env.LANG||process.env.LC_ALL||process.env.LC_MESSAGES||"").startsWith("zh"))v$="zh";else v$="zh";return}if($==="en")v$="en";else v$="zh"}var E5={"main.usage":{zh:"用法:mimo <资源> <命令> [参数]",en:"Usage: mimo <resource> <command> [flags]"},"main.resources":{zh:"可用命令:",en:"Resources:"},"main.globalFlags":{zh:"全局参数:",en:"Global Flags:"},"main.gettingHelp":{zh:"获取帮助:",en:"Getting Help:"},"main.helpHint1":{zh:"在任何命令后添加 --help 查看完整选项、默认值和示例。",en:"Add --help after any command to see its full list of options, defaults,"},"main.helpHint2":{zh:"例如:",en:"and usage examples. For example:"},"main.notLoggedIn":{zh:" 尚未配置 API Key。",en:" No API key configured."},"main.loginHint1":{zh:" mimo auth login 交互式输入 API Key",en:" mimo auth login Enter an API key interactively"},"main.loginHint2":{zh:" mimo auth login --api-key 直接保存 API Key",en:" mimo auth login --api-key Save an API key directly"},"main.interrupted":{zh:`
3
3
  已中断,退出。`,en:`
4
4
  Interrupted. Exiting.`},"main.fatalArgv":{zh:`致命错误:无法读取进程参数。
5
5
  `,en:`Fatal: failed to read process arguments.
@@ -15,154 +15,184 @@ Check: HTTPS_PROXY / HTTP_PROXY env vars, or mimo config show for configured pro
15
15
  重新登录:mimo auth login`,en:`Check your API Key: mimo auth status
16
16
  Re-authenticate: mimo auth login`},"api.402":{zh:"余额不足:",en:"Payment required: "},"api.402Hint":{zh:"账户余额不足,请充值。",en:"Insufficient balance. Please top up your account."},"api.403":{zh:"访问被拒绝(HTTP 403)。",en:"Access denied (HTTP 403)."},"api.403Hint":{zh:`您的 API Key 可能无权访问此资源,或 Key 受限。
17
17
  请检查 API Key 权限。`,en:`Your API Key may not have access to this resource, or the key is restricted.
18
- Check your API Key permissions.`},"api.404":{zh:"未找到:",en:"Not found: "},"api.404Hint":{zh:"请求的模型或功能可能不受支持,请检查模型名称和接口地址。",en:"The requested model or feature may not be supported. Check the model name and endpoint."},"api.421":{zh:"内容被过滤:",en:"Content filtered: "},"api.421Hint":{zh:"您的输入被内容安全过滤器标记,请修改后重试。",en:"Your input was flagged by the content safety filter. Please modify your request and try again."},"api.429":{zh:"请求频率超限:",en:"Rate limit exceeded: "},"api.429Hint":{zh:"请求过于频繁,请稍后重试或检查配额。",en:"You are sending requests too quickly. Please wait and retry, or check your quota."},"api.500":{zh:"服务器内部错误(HTTP 500)。",en:"Server error (HTTP 500)."},"api.500Hint":{zh:"服务器遇到内部错误,请稍后重试。",en:"The server encountered an internal error. Please retry later."},"api.503":{zh:"服务暂不可用(HTTP 503)。",en:"Service unavailable (HTTP 503)."},"api.503Hint":{zh:"服务器暂时过载或维护中,请稍后重试。",en:"The server is temporarily overloaded or under maintenance. Please retry later."},"api.default":{zh:"API 错误:",en:"API error: "},"auth.noCreds":{zh:"未找到认证信息。",en:"No credentials found."},"auth.noCredsHint":{zh:`登录: mimo auth login
18
+ Check your API Key permissions.`},"api.404":{zh:"未找到:",en:"Not found: "},"api.404Hint":{zh:"请求的模型或功能可能不受支持,请检查模型名称和接口地址。",en:"The requested model or feature may not be supported. Check the model name and endpoint."},"api.421":{zh:"内容被过滤:",en:"Content filtered: "},"api.421Hint":{zh:"您的输入被内容安全过滤器标记,请修改后重试。",en:"Your input was flagged by the content safety filter. Please modify your request and try again."},"api.429":{zh:"请求频率超限:",en:"Rate limit exceeded: "},"api.429Hint":{zh:"请求过于频繁,请稍后重试或检查配额。",en:"You are sending requests too quickly. Please wait and retry, or check your quota."},"api.500":{zh:"服务器内部错误(HTTP 500)。",en:"Server error (HTTP 500)."},"api.500Hint":{zh:"服务器遇到内部错误,请稍后重试。",en:"The server encountered an internal error. Please retry later."},"api.503":{zh:"服务暂不可用(HTTP 503)。",en:"Service unavailable (HTTP 503)."},"api.503Hint":{zh:"服务器暂时过载或维护中,请稍后重试。",en:"The server is temporarily overloaded or under maintenance. Please retry later."},"api.default":{zh:"API 错误:",en:"API error: "},"auth.noCreds":{zh:"未找到 API Key。",en:"No API key found."},"auth.noCredsHint":{zh:`登录: mimo auth login
19
19
  直接传入: --api-key <key>
20
20
  环境变量: MIMO_API_KEY=<key>`,en:`Log in: mimo auth login
21
21
  Pass directly: --api-key <key>
22
22
  Set env var: MIMO_API_KEY=<key>`},"auth.noKeyProvided":{zh:"未提供 API Key。",en:"No API key provided."},"auth.noKeyHint":{zh:"使用:mimo auth login --api-key <key>",en:"Use: mimo auth login --api-key <key>"},"auth.keyEmpty":{zh:"API Key 不能为空。",en:"API key cannot be empty."},"auth.keyRequired":{zh:"API Key 为必填项。",en:"API key is required."},"auth.keySaved":{zh:"API Key 已保存至",en:"API key saved to"},"auth.baseUrlAuto":{zh:"接口地址已自动配置:",en:"Base URL auto-configured: "},"auth.promptTitle":{zh:"请输入您的 MiMo API Key:",en:"Please enter your MiMo API key:"},"auth.promptPayKey":{zh:'- 按量计费 Key:以 "sk-" 等非 "tp-" 前缀开头',en:'- Pay-as-you-go Key: starts with "sk-" or other non-"tp-" prefix'},"auth.promptTpKey":{zh:'- TokenPlan Key:以 "tp-" 前缀开头',en:'- TokenPlan Key: starts with "tp-" prefix'},"auth.promptLabel":{zh:"输入 MiMo API Key:",en:"Enter your MiMo API key:"},"auth.logoutNoKey":{zh:"配置文件中未找到 API Key,已处于登出状态。",en:"No API key found in config file. Already logged out."},"auth.logoutDone":{zh:"API Key 已移除,您已登出。",en:"API key removed. You are now logged out."},"cmd.chat.desc":{zh:"发送对话请求",en:"Send a chat completion request"},"cmd.repl.desc":{zh:"交互式多轮对话",en:"Interactive multi-turn REPL conversation"},"cmd.vision.desc":{zh:"多模态理解(图片、音频、视频)",en:"Multi-modal understanding (image, audio, video)"},"cmd.asr.desc":{zh:"语音识别(ASR)",en:"Speech recognition (ASR)"},"cmd.ttsSynth.desc":{zh:"预设音色语音合成",en:"Pre-set voice text-to-speech synthesis"},"cmd.ttsClone.desc":{zh:"声音克隆语音合成",en:"Voice clone text-to-speech synthesis"},"cmd.ttsDesign.desc":{zh:"自定义音色语音合成",en:"Voice design text-to-speech synthesis"},"cmd.ttsVoices.desc":{zh:"列出可用的 TTS 音色",en:"List available TTS voices"},"cmd.authLogin.desc":{zh:"使用 MiMo API Key 登录(自动识别按量计费/TokenPlan)",en:"Log in with a MiMo API key (auto-detects key type: Pay-as-you-go or TokenPlan)"},"cmd.authStatus.desc":{zh:"查看当前认证状态",en:"Show current authentication status"},"cmd.authLogout.desc":{zh:"清除已保存的 API Key",en:"Clear saved API key from config file"},"cmd.configShow.desc":{zh:"显示当前配置",en:"Display current configuration"},"cmd.configSet.desc":{zh:"设置配置项",en:"Set a configuration value"},"cmd.update.desc":{zh:"更新 MiMo CLI",en:"Self-update the MiMo CLI"},"cmd.help.desc":{zh:"显示命令帮助",en:"Show help for commands"},"cmd.language.desc":{zh:"切换界面语言(zh/en)",en:"Switch interface language (zh/en)"},"vision.videoTooLarge":{zh:"视频文件过大:{size}MB(原始)。Base64 编码后将超过 {limit}MB 的 API 限制。",en:"Video file too large: {size}MB (raw). After Base64 encoding it would exceed the {limit}MB API limit."},"vision.videoTooLargeHint":{zh:"请改用 URL 方式传入视频(URL 模式支持最大 300MB),或将视频压缩至 {max}MB 以下。",en:"Please use a URL to pass the video instead (URL mode supports up to 300MB), or compress the video to under {max}MB."},"vision.videoBase64TooLarge":{zh:"视频 Base64 大小 {size}MB 超过 {limit}MB 的 API 限制。",en:"Video Base64 size {size}MB exceeds the {limit}MB API limit."},"vision.videoBase64TooLargeHint":{zh:"请改用 URL 方式传入视频(URL 模式支持最大 300MB),或压缩视频。",en:"Please use a URL to pass the video instead (URL mode supports up to 300MB), or compress the video."},"vision.noMedia":{zh:"至少需要提供 --image、--audio 或 --video 中的一项。",en:"At least one of --image, --audio, or --video is required."},"vision.noPrompt":{zh:"缺少必填参数:--prompt",en:"Missing required flag: --prompt"},"vision.requestFailed":{zh:"多模态请求失败:",en:"Vision request failed: "},"vision.requestFailedHint":{zh:"请检查网络连接和媒体文件格式。",en:"Check your network connection and media file format."},"chat.noMessage":{zh:"缺少必填参数:--message",en:"Missing required flag: --message"},"chat.emptyMessage":{zh:"消息不能为空或仅包含空白字符。",en:"Message cannot be empty or whitespace only."},"chat.messageTooLong":{zh:"消息过长:{len} 字符(上限 {max})。",en:"Message too long: {len} characters (max {max})."},"chat.messageTooLongHint":{zh:"请缩短消息或拆分为多次请求。",en:"Shorten your message or split it into multiple requests."},"chat.streamFailed":{zh:"流式请求失败:",en:"Stream request failed: "},"chat.streamFailedHint":{zh:"请检查网络连接和 API Key。",en:"Check your network connection and API key."},"asr.noFile":{zh:"需要提供音频文件路径。",en:"Audio file path is required."},"asr.streamFailed":{zh:"语音识别流式请求失败:",en:"ASR stream request failed: "},"asr.requestFailed":{zh:"语音识别请求失败:",en:"ASR request failed: "},"asr.checkHint":{zh:"请检查网络连接和音频文件格式。",en:"Check your network connection and audio file format."},"tts.noText":{zh:"--text 为必填项。",en:"--text is required."},"tts.emptyText":{zh:"--text 不能为空或仅包含空白字符。",en:"--text cannot be empty or whitespace only."},"tts.textTooLong":{zh:"文本过长:{len} 字符(上限 {max})。",en:"Text too long: {len} characters (max {max})."},"tts.textTooLongHint":{zh:"请缩短文本或拆分为多次合成请求。",en:"Shorten your text or split into multiple synthesis requests."},"tts.noSample":{zh:"--sample 为必填项。",en:"--sample is required."},"tts.noPrompt":{zh:"--prompt 为必填项。",en:"--prompt is required."},"tts.noTextOrOptimize":{zh:"需要提供 --text 或启用 --optimize-text。",en:"Either --text or --optimize-text is required."},"tts.noAudioData":{zh:"API 响应中缺少音频数据。",en:"API response missing audio data."},"tts.invalidVoice":{zh:"无效音色:",en:"Invalid voice: "},"config.keyRequired":{zh:"--key 为必填项。",en:"--key is required."},"config.valueRequired":{zh:"--value 为必填项。",en:"--value is required."},"config.invalidKey":{zh:"无效的配置键:",en:"Invalid config key: "},"config.invalidKeyChars":{zh:"配置键只能包含字母、数字和下划线。",en:"Config key must only contain letters, numbers, and underscores."},"config.validKeys":{zh:"有效的键:",en:"Valid keys: "},"config.setTimeout":{zh:"timeout 必须为正数。",en:"timeout must be a positive number."},"config.setOutput":{zh:'output 必须为 "text" 或 "json"。',en:'output must be "text" or "json".'},"config.setDone":{zh:"已设置",en:"Set"},"config.invalidActiveKey":{zh:'active_key 必须为 "tp" 或 "sk"。',en:'active_key must be "tp" or "sk".'},"config.switchKey":{zh:"已切换为{type} Key({url})",en:"Switched to {type} key ({url})"},"config.corrupted":{zh:"警告:配置文件已损坏(",en:"Warning: config file is corrupted ("},"config.corruptedHint":{zh:`)。运行 "mimo config set" 重置。
23
23
  `,en:`). Run 'mimo config set' to reset.
24
- `},"update.checking":{zh:"正在检查更新...",en:"Checking for updates..."},"update.checkFailed":{zh:"无法检查更新,请检查网络连接。",en:"Failed to check for updates. Please check your network connection."},"update.currentVersion":{zh:"当前版本:{version}",en:"Current version: {version}"},"update.latestVersion":{zh:"最新版本:{version}",en:"Latest version: {version}"},"update.alreadyLatest":{zh:"已是最新版本,无需更新。",en:"Already up to date."},"update.updating":{zh:"正在更新至 v{version}...",en:"Updating to v{version}..."},"update.success":{zh:"更新成功!已升级至 v{version}。",en:"Update successful! Upgraded to v{version}."},"update.updateFailed":{zh:"npm update 失败,尝试 npm install...",en:"npm update failed, trying npm install..."},"update.installFailed":{zh:"自动更新失败。",en:"Auto-update failed."},"update.manualHint":{zh:"请手动执行:npm install -g mimo-cli@latest",en:"Please run manually: npm install -g mimo-cli@latest"},"repl.intro":{zh:"MiMo 交互对话 — 输入 /exit 退出,/clear 清空对话",en:"MiMo REPL — type /exit to quit, /clear to reset"},"repl.you":{zh:"你",en:"You"},"repl.placeholder":{zh:"输入你的消息...",en:"Type your message..."},"repl.goodbye":{zh:"再见!",en:"Goodbye!"},"repl.cleared":{zh:"对话已清空。",en:"Conversation cleared."},"spinner.synthesizing":{zh:"正在合成语音...",en:"Synthesizing speech..."},"spinner.readingSample":{zh:"正在读取音频样本...",en:"Reading audio sample..."},"spinner.cloning":{zh:"正在合成克隆语音...",en:"Synthesizing cloned speech..."},"spinner.designing":{zh:"正在设计音色...",en:"Designing voice..."},"language.current":{zh:"当前界面语言:",en:"Current interface language: "},"language.changed":{zh:"界面语言已切换为中文。",en:"Interface language changed to English."},"language.invalid":{zh:"无效的语言代码,请使用 zh(中文)或 en(英文)。",en:"Invalid language code. Use zh (Chinese) or en (English)."},"language.hint":{zh:"使用:mimo language zh 或 mimo language en",en:"Usage: mimo language zh or mimo language en"},"flag.apiKey":{zh:"覆盖配置中的 API Key",en:"Override API Key from config"},"flag.baseUrl":{zh:"覆盖接口地址",en:"Override API base URL"},"flag.output":{zh:"输出格式(text/json)",en:"Output format (text/json)"},"flag.timeout":{zh:"请求超时时间(秒)",en:"Request timeout in seconds"},"flag.quiet":{zh:"静默模式,仅输出必要信息",en:"Suppress non-essential output"},"flag.verbose":{zh:"显示详细日志",en:"Show verbose logging"},"flag.noColor":{zh:"禁用彩色输出",en:"Disable colored output"},"flag.dryRun":{zh:"仅打印请求体,不实际执行",en:"Print request body without executing"},"flag.nonInteractive":{zh:"非交互模式",en:"Non-interactive mode"},"flag.help":{zh:"显示帮助信息",en:"Show help"},"flag.version":{zh:"显示版本号",en:"Show version"},"flag.chat.message":{zh:"消息内容",en:"Message text"},"flag.chat.model":{zh:"模型名称(默认:mimo-v2.5-pro)",en:"Model name (default: mimo-v2.5-pro)"},"flag.chat.system":{zh:"系统提示词",en:"System prompt"},"flag.chat.thinking":{zh:"启用深度思考模式",en:"Enable thinking mode"},"flag.chat.search":{zh:"启用联网搜索",en:"Enable web search"},"flag.chat.forceSearch":{zh:"强制联网搜索",en:"Force web search"},"flag.chat.maxKeyword":{zh:"单次搜索最大关键词数量",en:"Max keywords per search"},"flag.chat.searchLimit":{zh:"搜索结果数量限制",en:"Search result limit"},"flag.chat.userCountry":{zh:"用户位置:国家",en:"User location: country"},"flag.chat.userRegion":{zh:"用户位置:地区",en:"User location: region"},"flag.chat.userCity":{zh:"用户位置:城市",en:"User location: city"},"flag.chat.stream":{zh:"流式输出(默认开启,用 --no-stream 关闭)",en:"Streaming output (default: on, use --no-stream to disable)"},"flag.chat.noStream":{zh:"禁用流式输出",en:"Disable streaming output"},"flag.chat.json":{zh:"结构化 JSON 输出",en:"Structured JSON output"},"flag.chat.maxTokens":{zh:"最大生成令牌数",en:"Max completion tokens"},"flag.chat.temperature":{zh:"采样温度",en:"Sampling temperature"},"flag.repl.model":{zh:"模型名称(默认:mimo-v2.5-pro)",en:"Model name (default: mimo-v2.5-pro)"},"flag.repl.thinking":{zh:"启用深度思考模式",en:"Enable thinking mode"},"flag.repl.search":{zh:"启用联网搜索",en:"Enable web search"},"flag.repl.system":{zh:"系统提示词",en:"System prompt"},"flag.vision.image":{zh:"图片路径或 URL",en:"Image file path or URL"},"flag.vision.audio":{zh:"音频路径或 URL",en:"Audio file path or URL"},"flag.vision.video":{zh:"视频路径或 URL",en:"Video file path or URL"},"flag.vision.prompt":{zh:"对内容的提问",en:"Question about the content"},"flag.vision.model":{zh:"模型名称(默认:mimo-v2.5)",en:"Model name (default: mimo-v2.5)"},"flag.vision.stream":{zh:"流式输出(默认开启,用 --no-stream 关闭)",en:"Streaming output (default: on, use --no-stream to disable)"},"flag.vision.noStream":{zh:"禁用流式输出",en:"Disable streaming output"},"flag.vision.fps":{zh:"视频帧率(默认:2)",en:"Video frame rate (default: 2)"},"flag.vision.mediaResolution":{zh:"视频分辨率:default | max",en:"Video resolution: default | max"},"flag.asr.language":{zh:"语言:auto | zh | en(默认:auto)",en:"Language: auto | zh | en (default: auto)"},"flag.asr.stream":{zh:"启用流式输出",en:"Enable streaming output"},"flag.asr.file":{zh:"音频文件路径(替代位置参数)",en:"Audio file path (alternative to positional arg)"},"flag.tts.text":{zh:"待合成文本",en:"Text to synthesize"},"flag.tts.voice":{zh:"音色 ID(默认:mimo_default)",en:"Voice ID (default: mimo_default)"},"flag.tts.style":{zh:"自然语言风格指令",en:"Natural language style instruction"},"flag.tts.format":{zh:"音频格式:wav/mp3/pcm(默认:wav)",en:"Audio format: wav/mp3/pcm (default: wav)"},"flag.tts.out":{zh:"输出文件路径",en:"Output file path"},"flag.tts.sample":{zh:"音频样本文件路径(mp3/wav)",en:"Audio sample file path (mp3/wav)"},"flag.ttsDesign.prompt":{zh:"音色描述文本",en:"Voice description text"},"flag.ttsDesign.text":{zh:"待合成文本(启用 --optimize-text 时可省略)",en:"Text to synthesize (optional if --optimize-text)"},"flag.ttsDesign.optimizeText":{zh:"启用智能文本预览优化",en:"Enable smart text preview optimization"},"flag.config.key":{zh:"要设置的配置键",en:"Config key to set"},"flag.config.value":{zh:"要设置的配置值",en:"Config value to set"},"flag.help.command":{zh:'要查看帮助的命令路径(如 "auth login")',en:'Command path to get help for (e.g. "auth login")'},"flag.auth.apiKey":{zh:"直接保存 API Key(跳过交互式输入)",en:"API key to save (skips interactive prompt)"},"registry.unknownCommand":{zh:"未知命令:mimo {command}",en:"Unknown command: mimo {command}"},"registry.availableCommands":{zh:"可用命令:",en:"Available commands:"},"registry.runHelp":{zh:"运行 mimo {command} --help 查看更多信息。",en:"Run mimo {command} --help for more information."},"registry.runHelpRoot":{zh:"运行 mimo --help 查看可用命令。",en:"Run mimo --help for available commands."},"general.notSet":{zh:"(未设置)",en:"(not set)"},"general.or":{zh:"或",en:"or"}};function V($,Y){let Z=x5[$];if(!Z)return $;let w=Z[v$]||Z.zh||$;if(Y)for(let[X,W]of Object.entries(Y))w=w.replace(new RegExp(`\\{${X}\\}`,"g"),String(W));return w}class m4{root={children:new Map};register($,Y){let Z=$.split(" "),w=this.root;for(let X of Z){if(!w.children.has(X))w.children.set(X,{children:new Map});w=w.children.get(X)}w.command=Y}getAllCommands(){let $=[],Y=(Z)=>{if(Z.command)$.push(Z.command);for(let w of Z.children.values())Y(w)};return Y(this.root),$}resolve($){let Y=this.root,Z=[];for(let w of $){let X=Y.children.get(w);if(!X)break;Y=X,Z.push(w)}if(Y.command)return{command:Y.command,extra:$.slice(Z.length)};if(Z.length>0&&Y.children.size===1){let[,w]=Y.children.entries().next().value;if(w.command)return{command:w.command,extra:$.slice(Z.length)}}if(Z.length>0&&Y.children.size>1){let X=Array.from(Y.children.values()).map((G)=>G.command),W=X[0];if(W&&X.every((G)=>G===W))return{command:W,extra:$.slice(Z.length)}}if(Z.length>0&&Y.children.size>0){let w=Array.from(Y.children.entries()).map(([X,W])=>{if(W.command)return` ${Z.join(" ")} ${X} ${V(W.command.description)}`;let G=Array.from(W.children.keys()).join(", ");return` ${Z.join(" ")} ${X} [${G}]`}).join(`
25
- `);throw Error(`${V("registry.unknownCommand",{command:$.join(" ")})}
24
+ `},"update.checking":{zh:"正在检查更新...",en:"Checking for updates..."},"update.checkFailed":{zh:"无法检查更新,请检查网络连接。",en:"Failed to check for updates. Please check your network connection."},"update.currentVersion":{zh:"当前版本:{version}",en:"Current version: {version}"},"update.latestVersion":{zh:"最新版本:{version}",en:"Latest version: {version}"},"update.alreadyLatest":{zh:"已是最新版本,无需更新。",en:"Already up to date."},"update.updating":{zh:"正在更新至 v{version}...",en:"Updating to v{version}..."},"update.success":{zh:"更新成功!已升级至 v{version}。",en:"Update successful! Upgraded to v{version}."},"update.updateFailed":{zh:"npm update 失败,尝试 npm install...",en:"npm update failed, trying npm install..."},"update.installFailed":{zh:"自动更新失败。",en:"Auto-update failed."},"update.manualHint":{zh:"请手动执行:npm install -g mimo-cli@latest",en:"Please run manually: npm install -g mimo-cli@latest"},"repl.intro":{zh:"MiMo 交互对话 — 输入 /exit 退出,/clear 清空对话",en:"MiMo REPL — type /exit to quit, /clear to reset"},"repl.you":{zh:"你",en:"You"},"repl.placeholder":{zh:"输入你的消息...",en:"Type your message..."},"repl.goodbye":{zh:"再见!",en:"Goodbye!"},"repl.cleared":{zh:"对话已清空。",en:"Conversation cleared."},"spinner.synthesizing":{zh:"正在合成语音...",en:"Synthesizing speech..."},"spinner.readingSample":{zh:"正在读取音频样本...",en:"Reading audio sample..."},"spinner.cloning":{zh:"正在合成克隆语音...",en:"Synthesizing cloned speech..."},"spinner.designing":{zh:"正在设计音色...",en:"Designing voice..."},"language.current":{zh:"当前界面语言:",en:"Current interface language: "},"language.changed":{zh:"界面语言已切换为中文。",en:"Interface language changed to English."},"language.invalid":{zh:"无效的语言代码,请使用 zh(中文)或 en(英文)。",en:"Invalid language code. Use zh (Chinese) or en (English)."},"language.hint":{zh:"使用:mimo language zh 或 mimo language en",en:"Usage: mimo language zh or mimo language en"},"flag.apiKey":{zh:"覆盖配置中的 API Key",en:"Override API Key from config"},"flag.baseUrl":{zh:"覆盖接口地址",en:"Override API base URL"},"flag.output":{zh:"输出格式(text/json)",en:"Output format (text/json)"},"flag.timeout":{zh:"请求超时时间(秒)",en:"Request timeout in seconds"},"flag.quiet":{zh:"静默模式,仅输出必要信息",en:"Suppress non-essential output"},"flag.verbose":{zh:"显示详细日志",en:"Show verbose logging"},"flag.noColor":{zh:"禁用彩色输出",en:"Disable colored output"},"flag.dryRun":{zh:"仅打印请求体,不实际执行",en:"Print request body without executing"},"flag.nonInteractive":{zh:"非交互模式",en:"Non-interactive mode"},"flag.help":{zh:"显示帮助信息",en:"Show help"},"flag.version":{zh:"显示版本号",en:"Show version"},"flag.chat.message":{zh:"消息内容",en:"Message text"},"flag.chat.model":{zh:"模型名称(默认:mimo-v2.5-pro)",en:"Model name (default: mimo-v2.5-pro)"},"flag.chat.system":{zh:"系统提示词",en:"System prompt"},"flag.chat.thinking":{zh:"启用深度思考模式",en:"Enable thinking mode"},"flag.chat.search":{zh:"启用联网搜索",en:"Enable web search"},"flag.chat.forceSearch":{zh:"强制联网搜索",en:"Force web search"},"flag.chat.maxKeyword":{zh:"单次搜索最大关键词数量",en:"Max keywords per search"},"flag.chat.searchLimit":{zh:"搜索结果数量限制",en:"Search result limit"},"flag.chat.userCountry":{zh:"用户位置:国家",en:"User location: country"},"flag.chat.userRegion":{zh:"用户位置:地区",en:"User location: region"},"flag.chat.userCity":{zh:"用户位置:城市",en:"User location: city"},"flag.chat.stream":{zh:"流式输出(默认开启,用 --no-stream 关闭)",en:"Streaming output (default: on, use --no-stream to disable)"},"flag.chat.noStream":{zh:"禁用流式输出",en:"Disable streaming output"},"flag.chat.json":{zh:"结构化 JSON 输出",en:"Structured JSON output"},"flag.chat.maxTokens":{zh:"最大生成令牌数",en:"Max completion tokens"},"flag.chat.temperature":{zh:"采样温度",en:"Sampling temperature"},"flag.repl.model":{zh:"模型名称(默认:mimo-v2.5-pro)",en:"Model name (default: mimo-v2.5-pro)"},"flag.repl.thinking":{zh:"启用深度思考模式",en:"Enable thinking mode"},"flag.repl.search":{zh:"启用联网搜索",en:"Enable web search"},"flag.repl.system":{zh:"系统提示词",en:"System prompt"},"flag.vision.image":{zh:"图片路径或 URL",en:"Image file path or URL"},"flag.vision.audio":{zh:"音频路径或 URL",en:"Audio file path or URL"},"flag.vision.video":{zh:"视频路径或 URL",en:"Video file path or URL"},"flag.vision.prompt":{zh:"对内容的提问",en:"Question about the content"},"flag.vision.model":{zh:"模型名称(默认:mimo-v2.5)",en:"Model name (default: mimo-v2.5)"},"flag.vision.stream":{zh:"流式输出(默认开启,用 --no-stream 关闭)",en:"Streaming output (default: on, use --no-stream to disable)"},"flag.vision.noStream":{zh:"禁用流式输出",en:"Disable streaming output"},"flag.vision.fps":{zh:"视频帧率(默认:2)",en:"Video frame rate (default: 2)"},"flag.vision.mediaResolution":{zh:"视频分辨率:default | max",en:"Video resolution: default | max"},"flag.asr.language":{zh:"语言:auto | zh | en(默认:auto)",en:"Language: auto | zh | en (default: auto)"},"flag.asr.stream":{zh:"启用流式输出",en:"Enable streaming output"},"flag.asr.file":{zh:"音频文件路径(替代位置参数)",en:"Audio file path (alternative to positional arg)"},"flag.tts.text":{zh:"待合成文本",en:"Text to synthesize"},"flag.tts.voice":{zh:"音色 ID(默认:mimo_default)",en:"Voice ID (default: mimo_default)"},"flag.tts.style":{zh:"自然语言风格指令",en:"Natural language style instruction"},"flag.tts.format":{zh:"音频格式:wav/mp3/pcm(默认:wav)",en:"Audio format: wav/mp3/pcm (default: wav)"},"flag.tts.out":{zh:"输出文件路径",en:"Output file path"},"flag.tts.sample":{zh:"音频样本文件路径(mp3/wav)",en:"Audio sample file path (mp3/wav)"},"flag.ttsDesign.prompt":{zh:"音色描述文本",en:"Voice description text"},"flag.ttsDesign.text":{zh:"待合成文本(启用 --optimize-text 时可省略)",en:"Text to synthesize (optional if --optimize-text)"},"flag.ttsDesign.optimizeText":{zh:"启用智能文本预览优化",en:"Enable smart text preview optimization"},"flag.config.key":{zh:"要设置的配置键",en:"Config key to set"},"flag.config.value":{zh:"要设置的配置值",en:"Config value to set"},"flag.help.command":{zh:'要查看帮助的命令路径(如 "auth login")',en:'Command path to get help for (e.g. "auth login")'},"flag.auth.apiKey":{zh:"直接保存 API Key(跳过交互式输入)",en:"API key to save (skips interactive prompt)"},"registry.unknownCommand":{zh:"未知命令:mimo {command}",en:"Unknown command: mimo {command}"},"registry.availableCommands":{zh:"可用命令:",en:"Available commands:"},"registry.runHelp":{zh:"运行 mimo {command} --help 查看更多信息。",en:"Run mimo {command} --help for more information."},"registry.runHelpRoot":{zh:"运行 mimo --help 查看可用命令。",en:"Run mimo --help for available commands."},"cmd.uninstall.desc":{zh:"卸载 exe 安装的 MiMo CLI",en:"Uninstall exe-installed MiMo CLI"},"uninstall.notFound":{zh:"未找到 exe 安装的 MiMo CLI。",en:"No exe-installed MiMo CLI found."},"uninstall.npmHint":{zh:"如通过 npm 安装,请使用:npm uninstall -g mimo-cli",en:"If installed via npm, use: npm uninstall -g mimo-cli"},"uninstall.header":{zh:"MiMo CLI - 卸载程序",en:"MiMo CLI - Uninstaller"},"uninstall.pathRemoved":{zh:"已将安装目录从系统 PATH 中移除",en:"Removed install directory from system PATH"},"uninstall.pathNotPresent":{zh:"安装目录不在系统 PATH 中",en:"Install directory not in system PATH"},"uninstall.keepConfig":{zh:"已保留配置文件(~/.mimo/config.json)",en:"Kept config file (~/.mimo/config.json)"},"uninstall.cleanupDone":{zh:"正在清理程序文件...",en:"Cleaning up program files..."},"uninstall.cleanupStarted":{zh:"正在清理程序文件...",en:"Cleaning up program files..."},"uninstall.done":{zh:"✔ 卸载完成!",en:"✔ Uninstall complete!"},"uninstall.restartHint":{zh:"请关闭当前终端,打开新的 cmd 或 PowerShell 以确保 PATH 更新生效。",en:"Please close this terminal and open a new cmd or PowerShell for PATH changes to take effect."},"general.notSet":{zh:"(未设置)",en:"(not set)"},"general.or":{zh:"或",en:"or"}};function z($,Y){let Z=E5[$];if(!Z)return $;let w=Z[v$]||Z.zh||$;if(Y)for(let[X,W]of Object.entries(Y))w=w.replace(new RegExp(`\\{${X}\\}`,"g"),String(W));return w}class d4{root={children:new Map};register($,Y){let Z=$.split(" "),w=this.root;for(let X of Z){if(!w.children.has(X))w.children.set(X,{children:new Map});w=w.children.get(X)}w.command=Y}getAllCommands(){let $=[],Y=(Z)=>{if(Z.command)$.push(Z.command);for(let w of Z.children.values())Y(w)};return Y(this.root),$}resolve($){let Y=this.root,Z=[];for(let w of $){let X=Y.children.get(w);if(!X)break;Y=X,Z.push(w)}if(Y.command)return{command:Y.command,extra:$.slice(Z.length)};if(Z.length>0&&Y.children.size===1){let[,w]=Y.children.entries().next().value;if(w.command)return{command:w.command,extra:$.slice(Z.length)}}if(Z.length>0&&Y.children.size>1){let X=Array.from(Y.children.values()).map((G)=>G.command),W=X[0];if(W&&X.every((G)=>G===W))return{command:W,extra:$.slice(Z.length)}}if(Z.length>0&&Y.children.size>0){let w=Array.from(Y.children.entries()).map(([X,W])=>{if(W.command)return` ${Z.join(" ")} ${X} ${z(W.command.description)}`;let G=Array.from(W.children.keys()).join(", ");return` ${Z.join(" ")} ${X} [${G}]`}).join(`
25
+ `);throw Error(`${z("registry.unknownCommand",{command:$.join(" ")})}
26
26
 
27
- ${V("registry.availableCommands")}
27
+ ${z("registry.availableCommands")}
28
28
  ${w}
29
29
 
30
- ${V("registry.runHelp",{command:Z.join(" ")})}`)}throw Error(`${V("registry.unknownCommand",{command:$.join(" ")})}
30
+ ${z("registry.runHelp",{command:Z.join(" ")})}`)}throw Error(`${z("registry.unknownCommand",{command:$.join(" ")})}
31
31
 
32
- ${V("registry.runHelpRoot")}`)}bold($,Y){if("isTTY"in Y&&Y.isTTY)return`\x1B[1m${$}\x1B[0m`;return $}accent($,Y){if("isTTY"in Y&&Y.isTTY)return`\x1B[38;2;255;105;0m${$}\x1B[0m`;return $}dim($,Y){if("isTTY"in Y&&Y.isTTY)return`\x1B[2m${$}\x1B[0m`;return $}printHelp($,Y=process.stdout){if($.length===0){this.printRootHelp(Y);return}let Z=this.root;for(let X of $){let W=Z.children.get(X);if(!W){this.printRootHelp(Y);return}Z=W}if(Z.command){this.printCommandHelp(Z.command,Y);return}let w=$.join(" ");Y.write(`
33
- ${this.bold(V("help.usage"),Y)} mimo ${w} <command> [flags]
32
+ ${z("registry.runHelpRoot")}`)}bold($,Y){if("isTTY"in Y&&Y.isTTY)return`\x1B[1m${$}\x1B[0m`;return $}accent($,Y){if("isTTY"in Y&&Y.isTTY)return`\x1B[38;2;255;105;0m${$}\x1B[0m`;return $}dim($,Y){if("isTTY"in Y&&Y.isTTY)return`\x1B[2m${$}\x1B[0m`;return $}printHelp($,Y=process.stdout){if($.length===0){this.printRootHelp(Y);return}let Z=this.root;for(let X of $){let W=Z.children.get(X);if(!W){this.printRootHelp(Y);return}Z=W}if(Z.command){this.printCommandHelp(Z.command,Y);return}let w=$.join(" ");Y.write(`
33
+ ${this.bold(z("help.usage"),Y)} mimo ${w} <command> [flags]
34
34
 
35
- `),Y.write(`${this.bold(V("help.commands"),Y)}
35
+ `),Y.write(`${this.bold(z("help.commands"),Y)}
36
36
  `),this.printChildren(Z,w,Y),Y.write(`
37
37
  `)}printRootHelp($){let Y=["███╗ ███╗███╗ ███╗███████╗","████╗ ████║████╗ ████║██╔════╝","██╔████╔██║██╔████╔██║██╔ ","██║╚██╔╝██║██║╚██╔╝██║██╔ ","██║ ╚═╝ ██║██║ ╚═╝ ██║███████╗","╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝"],Z=[[255,165,0],[255,140,0],[255,105,0],[245,85,0],[230,65,0],[210,45,0]];$.write(`
38
38
  `);for(let T=0;T<Y.length;T++)if("isTTY"in $&&$.isTTY){let[K,U,M]=Z[T];$.write(`\x1B[1;38;2;${K};${U};${M}m${Y[T]}\x1B[0m
39
39
  `)}else $.write(Y[T]+`
40
- `);let w=(T)=>this.bold(T,$),X=(T)=>this.accent(T,$),W=(T)=>this.dim(T,$),G=this.collectTopGroups(),Q="";if(G.length>0){let T=Math.max(...G.map((K)=>K.name.length));Q=`${w(V("main.resources"))}
40
+ `);let w=(T)=>this.bold(T,$),X=(T)=>this.accent(T,$),W=(T)=>this.dim(T,$),G=this.collectTopGroups(),Q="";if(G.length>0){let T=Math.max(...G.map((K)=>K.name.length));Q=`${w(z("main.resources"))}
41
41
  `;for(let K of G)Q+=` ${X(K.name.padEnd(T+2))} ${W(K.description)}
42
42
  `;Q+=`
43
- `}let z=Math.max(...T1.map((T)=>T.flag.length)),H=`${w(V("main.globalFlags"))}
44
- `;for(let T of T1)H+=` ${X(T.flag.padEnd(z+2))} ${W(V(T.description))}
43
+ `}let V=Math.max(...T1.map((T)=>T.flag.length)),H=`${w(z("main.globalFlags"))}
44
+ `;for(let T of T1)H+=` ${X(T.flag.padEnd(V+2))} ${W(z(T.description))}
45
45
  `;$.write(`
46
- ${w(V("main.usage"))}
46
+ ${w(z("main.usage"))}
47
47
 
48
48
  ${Q}${H}
49
- ${w(V("main.gettingHelp"))}
50
- ${W(V("main.helpHint1"))}
51
- ${W(V("main.helpHint2"))} mimo chat --help
49
+ ${w(z("main.gettingHelp"))}
50
+ ${W(z("main.helpHint1"))}
51
+ ${W(z("main.helpHint2"))} mimo chat --help
52
52
  `)}printCommandHelp($,Y){let Z=(W)=>this.bold(W,Y),w=(W)=>this.accent(W,Y),X=(W)=>this.dim(W,Y);if(Y.write(`
53
- ${V($.description)}
54
- `),$.usage)Y.write(`${Z(V("help.usage"))} ${$.usage}
53
+ ${z($.description)}
54
+ `),$.usage)Y.write(`${Z(z("help.usage"))} ${$.usage}
55
55
  `);if($.options&&$.options.length>0){let W=Math.max(...$.options.map((G)=>G.flag.length));Y.write(`
56
- ${Z(V("help.options"))}
57
- `);for(let G of $.options)Y.write(` ${w(G.flag.padEnd(W+2))} ${X(V(G.description))}
56
+ ${Z(z("help.options"))}
57
+ `);for(let G of $.options)Y.write(` ${w(G.flag.padEnd(W+2))} ${X(z(G.description))}
58
58
  `)}if($.examples&&$.examples.length>0){Y.write(`
59
- ${Z(V("help.examples"))}
59
+ ${Z(z("help.examples"))}
60
60
  `);for(let W of $.examples)Y.write(` ${X(W)}
61
61
  `)}if($.apiDocs)Y.write(`
62
- ${Z(V("help.apiRef"))} ${X($.apiDocs)}
62
+ ${Z(z("help.apiRef"))} ${X($.apiDocs)}
63
63
  `);Y.write(`
64
- ${X(V("help.globalHint"))}
65
- `),Y.write(`${X(V("help.globalHintRun"))}
66
- `)}printChildren($,Y,Z){let w=[],X=(G,Q)=>{for(let[z,H]of G.children){if(H.command)w.push({fullName:`${Q} ${z}`,description:V(H.command.description)});if(H.children.size>0)X(H,`${Q} ${z}`)}};X($,Y);let W=Math.max(...w.map((G)=>G.fullName.length));for(let{fullName:G,description:Q}of w)Z.write(` ${this.accent(G.padEnd(W),Z)} ${this.dim(Q,Z)}
67
- `)}collectTopGroups(){let $=[];for(let[Y,Z]of this.root.children)if(Z.command)$.push({name:Y,description:V(Z.command.description)});else if(Z.children.size>0){let w=Array.from(Z.children.keys()),X=Z.children.values().next().value,W=X?.command?.description?V(X.command.description):w.join(", ");$.push({name:Y,description:W})}return $}}var h=new m4;var E={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONTENT_FILTER:10,INVALID_INPUT:11};class L extends Error{exitCode;hint;constructor($,Y=E.GENERAL,Z){super($);this.name="CLIError",this.exitCode=Y,this.hint=Z}toJSON(){return{error:{code:this.exitCode,message:this.message,...this.hint?{hint:this.hint}:{}}}}}function c4($,Y){if($===null||$===void 0)return"";if(typeof $==="string")return $;if(typeof $==="number"||typeof $==="boolean")return String($);if(Array.isArray($)){if($.length===0)return"(empty)";if(typeof $[0]==="object"&&$[0]!==null)return k3(Object.keys($[0]),$.map((Z)=>Object.values(Z).map((w)=>String(w??""))));return $.map(String).join(`
68
- `)}if(typeof $==="object")return F3($);return String($)}function F3($,Y=0){let Z=" ".repeat(Y),w=[];for(let[X,W]of Object.entries($)){if(W===null||W===void 0)continue;if(Array.isArray(W)){w.push(`${Z}${X}:`);for(let G of W)if(typeof G==="object"&&G!==null)w.push(`${Z} - ${F3(G,Y+4).trimStart()}`);else w.push(`${Z} - ${String(G)}`)}else if(typeof W==="object")w.push(`${Z}${X}:`),w.push(F3(W,Y+2));else w.push(`${Z}${X}: ${String(W)}`)}return w.join(`
69
- `)}function k3($,Y){if(Y.length===0)return"(empty)";let Z=$.map((G,Q)=>Math.max(G.length,...Y.map((z)=>(z[Q]??"").length))),w=$.map((G,Q)=>G.toUpperCase().padEnd(Z[Q])).join(" "),X=Z.map((G)=>"-".repeat(G)).join(" "),W=Y.map((G)=>G.map((Q,z)=>(Q??"").padEnd(Z[z])).join(" "));return[w,X,...W].join(`
70
- `)}function d4($){return JSON.stringify($,null,2)}function X$($){if($==="json"||$==="text")return $;if(typeof $==="object"&&$!==null){if($.output==="json"||$.output==="text")return $.output}if(!process.stdout.isTTY)return"json";return"text"}function W$($,Y){switch(X$(Y)){case"json":return d4($);case"text":return c4($)}}function U1($,Y){if(!$.dryRun)return!1;return console.log(W$({request:Y},X$($.output))),!0}function J$($){if(!$||typeof $!=="string")return"****";if($.length<=8)return $.slice(0,2)+"****";return $.slice(0,4)+"****"+$.slice(-4)}function C$($){if(!$||typeof $!=="string")return $;return $.replace(/(?:sk|tp)-[A-Za-z0-9_-]{16,}/g,(Y)=>{return J$(Y)})}function x$($){if($ instanceof L){if(X$(process.env.MIMO_OUTPUT)==="json"){let Z=C$(JSON.stringify($.toJSON(),null,2));process.stderr.write(Z+`
64
+ ${X(z("help.globalHint"))}
65
+ `),Y.write(`${X(z("help.globalHintRun"))}
66
+ `)}printChildren($,Y,Z){let w=[],X=(G,Q)=>{for(let[V,H]of G.children){if(H.command)w.push({fullName:`${Q} ${V}`,description:z(H.command.description)});if(H.children.size>0)X(H,`${Q} ${V}`)}};X($,Y);let W=Math.max(...w.map((G)=>G.fullName.length));for(let{fullName:G,description:Q}of w)Z.write(` ${this.accent(G.padEnd(W),Z)} ${this.dim(Q,Z)}
67
+ `)}collectTopGroups(){let $=[];for(let[Y,Z]of this.root.children)if(Z.command)$.push({name:Y,description:z(Z.command.description)});else if(Z.children.size>0){let w=Array.from(Z.children.keys()),X=Z.children.values().next().value,W=X?.command?.description?z(X.command.description):w.join(", ");$.push({name:Y,description:W})}return $}}var D=new d4;var E={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONTENT_FILTER:10,INVALID_INPUT:11};class L extends Error{exitCode;hint;constructor($,Y=E.GENERAL,Z){super($);this.name="CLIError",this.exitCode=Y,this.hint=Z}toJSON(){return{error:{code:this.exitCode,message:this.message,...this.hint?{hint:this.hint}:{}}}}}function u4($,Y){if($===null||$===void 0)return"";if(typeof $==="string")return $;if(typeof $==="number"||typeof $==="boolean")return String($);if(Array.isArray($)){if($.length===0)return"(empty)";if(typeof $[0]==="object"&&$[0]!==null)return C3(Object.keys($[0]),$.map((Z)=>Object.values(Z).map((w)=>String(w??""))));return $.map(String).join(`
68
+ `)}if(typeof $==="object")return k3($);return String($)}function k3($,Y=0){let Z=" ".repeat(Y),w=[];for(let[X,W]of Object.entries($)){if(W===null||W===void 0)continue;if(Array.isArray(W)){w.push(`${Z}${X}:`);for(let G of W)if(typeof G==="object"&&G!==null)w.push(`${Z} - ${k3(G,Y+4).trimStart()}`);else w.push(`${Z} - ${String(G)}`)}else if(typeof W==="object")w.push(`${Z}${X}:`),w.push(k3(W,Y+2));else w.push(`${Z}${X}: ${String(W)}`)}return w.join(`
69
+ `)}function C3($,Y){if(Y.length===0)return"(empty)";let Z=$.map((G,Q)=>Math.max(G.length,...Y.map((V)=>(V[Q]??"").length))),w=$.map((G,Q)=>G.toUpperCase().padEnd(Z[Q])).join(" "),X=Z.map((G)=>"-".repeat(G)).join(" "),W=Y.map((G)=>G.map((Q,V)=>(Q??"").padEnd(Z[V])).join(" "));return[w,X,...W].join(`
70
+ `)}function l4($){return JSON.stringify($,null,2)}function X$($){if($==="json"||$==="text")return $;if(typeof $==="object"&&$!==null){if($.output==="json"||$.output==="text")return $.output}if(!process.stdout.isTTY)return"json";return"text"}function W$($,Y){switch(X$(Y)){case"json":return l4($);case"text":return u4($)}}function U1($,Y){if(!$.dryRun)return!1;return console.log(W$({request:Y},X$($.output))),!0}function J$($){if(!$||typeof $!=="string")return"****";if($.length<=8)return $.slice(0,2)+"****";return $.slice(0,4)+"****"+$.slice(-4)}function C$($){if(!$||typeof $!=="string")return $;return $.replace(/(?:sk|tp)-[A-Za-z0-9_-]{16,}/g,(Y)=>{return J$(Y)})}function x$($){if($ instanceof L){if(X$(process.env.MIMO_OUTPUT)==="json"){let Z=C$(JSON.stringify($.toJSON(),null,2));process.stderr.write(Z+`
71
71
  `)}else{if(process.stderr.write(`
72
- ${V("error.prefix")} ${C$($.message)}
72
+ ${z("error.prefix")} ${C$($.message)}
73
73
  `),$.hint)process.stderr.write(`
74
74
  ${C$($.hint).split(`
75
75
  `).join(`
76
76
  `)}
77
- `);process.stderr.write(` ${V("error.exitCode",{code:String($.exitCode)})}
78
- `)}process.exit($.exitCode)}if($ instanceof Error){if($.name==="AbortError"||$.name==="TimeoutError"||$.message.includes("timed out")){let X=new L(V("error.timeout"),E.TIMEOUT,V("error.timeoutHint"));return x$(X)}if($ instanceof TypeError&&$.message==="fetch failed"){let X=new L(V("error.network"),E.NETWORK,V("error.networkHint"));return x$(X)}let Y=$.message.toLowerCase();if(Y.includes("failed to fetch")||Y.includes("connection refused")||Y.includes("econnrefused")||Y.includes("connection reset")||Y.includes("econnreset")||Y.includes("network error")||Y.includes("enotfound")||Y.includes("getaddrinfo")||Y.includes("proxy")||Y.includes("socket")||Y.includes("etimedout")||Y.includes("eai_again")){let X=V("error.networkHint");if(Y.includes("proxy"))X=V("error.proxyHint");let W=new L(V("error.network"),E.NETWORK,X);return x$(W)}let w=$.code;if(w==="ENOENT"||w==="EACCES"||w==="ENOSPC"||w==="ENOTDIR"||w==="EISDIR"||w==="EPERM"||w==="EBUSY"){let X=V("error.fsDefault");if(w==="ENOENT")X=V("error.fsEnoent");if(w==="EACCES"||w==="EPERM")X=V("error.fsEacces");if(w==="ENOSPC")X=V("error.fsEnospc");let W=new L(V("error.fsPrefix")+$.message,E.GENERAL,X);return x$(W)}else if(typeof w==="string"&&w.startsWith("E")){let X=new L(V("error.fsPrefix")+$.message,E.GENERAL,V("error.fsDefault"));return x$(X)}if(process.stderr.write(`
79
- ${V("error.prefix")} ${C$($.message)}
77
+ `);process.stderr.write(` ${z("error.exitCode",{code:String($.exitCode)})}
78
+ `)}process.exit($.exitCode)}if($ instanceof Error){if($.name==="AbortError"||$.name==="TimeoutError"||$.message.includes("timed out")){let X=new L(z("error.timeout"),E.TIMEOUT,z("error.timeoutHint"));return x$(X)}if($ instanceof TypeError&&$.message==="fetch failed"){let X=new L(z("error.network"),E.NETWORK,z("error.networkHint"));return x$(X)}let Y=$.message.toLowerCase();if(Y.includes("failed to fetch")||Y.includes("connection refused")||Y.includes("econnrefused")||Y.includes("connection reset")||Y.includes("econnreset")||Y.includes("network error")||Y.includes("enotfound")||Y.includes("getaddrinfo")||Y.includes("proxy")||Y.includes("socket")||Y.includes("etimedout")||Y.includes("eai_again")){let X=z("error.networkHint");if(Y.includes("proxy"))X=z("error.proxyHint");let W=new L(z("error.network"),E.NETWORK,X);return x$(W)}let w=$.code;if(w==="ENOENT"||w==="EACCES"||w==="ENOSPC"||w==="ENOTDIR"||w==="EISDIR"||w==="EPERM"||w==="EBUSY"){let X=z("error.fsDefault");if(w==="ENOENT")X=z("error.fsEnoent");if(w==="EACCES"||w==="EPERM")X=z("error.fsEacces");if(w==="ENOSPC")X=z("error.fsEnospc");let W=new L(z("error.fsPrefix")+$.message,E.GENERAL,X);return x$(W)}else if(typeof w==="string"&&w.startsWith("E")){let X=new L(z("error.fsPrefix")+$.message,E.GENERAL,z("error.fsDefault"));return x$(X)}if(process.stderr.write(`
79
+ ${z("error.prefix")} ${C$($.message)}
80
80
  `),process.env.MIMO_VERBOSE==="1")process.stderr.write(`${C$($.stack??"")}
81
81
  `)}else process.stderr.write(`
82
- ${V("error.prefix")} ${C$(String($))}
83
- `);process.exit(E.GENERAL)}import{readFileSync as L5,writeFileSync as F5,renameSync as k5,existsSync as C5}from"fs";var q5=new Set(["text","json"]);function u4($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Y=$,Z={};if(typeof Y.api_key==="string")Z.api_key=Y.api_key;if(typeof Y.sk_api_key==="string")Z.sk_api_key=Y.sk_api_key;if(Y.active_key==="tp"||Y.active_key==="sk")Z.active_key=Y.active_key;if(typeof Y.base_url==="string"&&Y.base_url.startsWith("http"))Z.base_url=Y.base_url;if(typeof Y.output==="string"&&q5.has(Y.output))Z.output=Y.output;if(typeof Y.timeout==="number"&&Y.timeout>0)Z.timeout=Y.timeout;if(typeof Y.default_model==="string"&&Y.default_model.length>0)Z.default_model=Y.default_model;if(typeof Y.language==="string"&&(Y.language==="zh"||Y.language==="en"))Z.language=Y.language;return Z}import{homedir as O5}from"os";import{join as l4}from"path";import{mkdirSync as E5}from"fs";function p4(){return process.env.MIMO_CONFIG_DIR??l4(O5(),".mimo")}function b2(){return l4(p4(),"config.json")}function i4(){let $=p4();E5($,{recursive:!0,mode:448})}function S$($){if($.startsWith("tp-"))return"https://token-plan-cn.xiaomimimo.com/v1";return}function v2($){if($.apiKey)return{token:$.apiKey,method:"api-key",source:"flag"};let Y=process.env.MIMO_API_KEY;if(Y)return{token:Y,method:"api-key",source:"env"};if($.activeKey==="sk"&&$.fileSkApiKey)return{token:$.fileSkApiKey,method:"api-key",source:"config.json"};if($.fileApiKey)return{token:$.fileApiKey,method:"api-key",source:"config.json"};if($.fileSkApiKey)return{token:$.fileSkApiKey,method:"api-key",source:"config.json"};throw new L("No credentials found.",E.AUTH,`Log in: mimo auth login
82
+ ${z("error.prefix")} ${C$(String($))}
83
+ `);process.exit(E.GENERAL)}import{readFileSync as C5,writeFileSync as S5,renameSync as R5,existsSync as P5}from"fs";var L5=new Set(["text","json"]);function p4($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Y=$,Z={};if(typeof Y.api_key==="string")Z.api_key=Y.api_key;if(typeof Y.sk_api_key==="string")Z.sk_api_key=Y.sk_api_key;if(Y.active_key==="tp"||Y.active_key==="sk")Z.active_key=Y.active_key;if(typeof Y.base_url==="string"&&Y.base_url.startsWith("http"))Z.base_url=Y.base_url;if(typeof Y.output==="string"&&L5.has(Y.output))Z.output=Y.output;if(typeof Y.timeout==="number"&&Y.timeout>0)Z.timeout=Y.timeout;if(typeof Y.default_model==="string"&&Y.default_model.length>0)Z.default_model=Y.default_model;if(typeof Y.language==="string"&&(Y.language==="zh"||Y.language==="en"))Z.language=Y.language;return Z}import{homedir as F5}from"os";import{join as i4}from"path";import{mkdirSync as k5}from"fs";function n4(){return process.env.MIMO_CONFIG_DIR??i4(F5(),".mimo")}function b2(){return i4(n4(),"config.json")}function a4(){let $=n4();k5($,{recursive:!0,mode:448})}function S$($){if($.startsWith("tp-"))return"https://token-plan-cn.xiaomimimo.com/v1";return}function v2($){if($.apiKey)return{token:$.apiKey,method:"api-key",source:"flag"};let Y=process.env.MIMO_API_KEY;if(Y)return{token:Y,method:"api-key",source:"env"};if($.activeKey==="sk"&&$.fileSkApiKey)return{token:$.fileSkApiKey,method:"api-key",source:"config.json"};if($.fileApiKey)return{token:$.fileApiKey,method:"api-key",source:"config.json"};if($.fileSkApiKey)return{token:$.fileSkApiKey,method:"api-key",source:"config.json"};throw new L("No credentials found.",E.AUTH,`Log in: mimo auth login
84
84
  Pass directly: --api-key <key>
85
- Set env var: MIMO_API_KEY=<key>`)}var C3="https://api.xiaomimimo.com/v1";function K$(){let $=b2();if(!C5($))return{};try{return u4(JSON.parse(L5($,"utf-8")))}catch(Y){let Z=Y instanceof Error?Y.message:String(Y);return process.stderr.write(V("config.corrupted")+Z+V("config.corruptedHint")),{}}}async function y$($){i4();let Y=b2(),Z=Y+".tmp";try{F5(Z,JSON.stringify($,null,2)+`
86
- `,{mode:384}),k5(Z,Y)}catch(w){let X=w instanceof Error?w.message:String(w);throw Error(`Failed to write config file: ${X}. Check file permissions for ${Y}`)}}function y2($){let Y=K$(),Z=$.apiKey||void 0,w=Y.api_key,X=Y.sk_api_key,W=Y.active_key||"tp",G;if($.baseUrl)G=$.baseUrl;else if(process.env.MIMO_BASE_URL)G=process.env.MIMO_BASE_URL;else if(Z)G=S$(Z)||Y.base_url||C3;else if(W==="sk"&&X)G=S$(X)||Y.base_url||C3;else G=Y.base_url||C3;let Q=X$($.output||process.env.MIMO_OUTPUT||Y.output),z=process.env.MIMO_TIMEOUT?Number(process.env.MIMO_TIMEOUT):void 0,H=z!==void 0&&Number.isFinite(z)&&z>0?z:void 0,T=$.timeout??H??Y.timeout??300;return{apiKey:Z,fileApiKey:w,fileSkApiKey:X,activeKey:W,configPath:b2(),baseUrl:G,output:Q,timeout:T,defaultModel:Y.default_model,language:Y.language||void 0,verbose:$.verbose||process.env.MIMO_VERBOSE==="1",quiet:$.quiet||!1,noColor:$.noColor||process.env.NO_COLOR!==void 0||!process.stdout.isTTY,dryRun:$.dryRun||!1,nonInteractive:$.nonInteractive||!1}}var Y$=f2(R3(),1),g2=f2(_3(),1);import{stdin as G9,stdout as X9}from"node:process";import*as I$ from"node:readline";import r4 from"node:readline";import{WriteStream as f5}from"node:tty";function j5({onlyFirst:$=!1}={}){let Y=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(Y,$?void 0:"g")}var b5=j5();function W9($){if(typeof $!="string")throw TypeError(`Expected a \`string\`, got \`${typeof $}\``);return $.replace(b5,"")}function J9($){return $&&$.__esModule&&Object.prototype.hasOwnProperty.call($,"default")?$.default:$}var Q9={exports:{}};(function($){var Y={};$.exports=Y,Y.eastAsianWidth=function(w){var X=w.charCodeAt(0),W=w.length==2?w.charCodeAt(1):0,G=X;return 55296<=X&&X<=56319&&56320<=W&&W<=57343&&(X&=1023,W&=1023,G=X<<10|W,G+=65536),G==12288||65281<=G&&G<=65376||65504<=G&&G<=65510?"F":G==8361||65377<=G&&G<=65470||65474<=G&&G<=65479||65482<=G&&G<=65487||65490<=G&&G<=65495||65498<=G&&G<=65500||65512<=G&&G<=65518?"H":4352<=G&&G<=4447||4515<=G&&G<=4519||4602<=G&&G<=4607||9001<=G&&G<=9002||11904<=G&&G<=11929||11931<=G&&G<=12019||12032<=G&&G<=12245||12272<=G&&G<=12283||12289<=G&&G<=12350||12353<=G&&G<=12438||12441<=G&&G<=12543||12549<=G&&G<=12589||12593<=G&&G<=12686||12688<=G&&G<=12730||12736<=G&&G<=12771||12784<=G&&G<=12830||12832<=G&&G<=12871||12880<=G&&G<=13054||13056<=G&&G<=19903||19968<=G&&G<=42124||42128<=G&&G<=42182||43360<=G&&G<=43388||44032<=G&&G<=55203||55216<=G&&G<=55238||55243<=G&&G<=55291||63744<=G&&G<=64255||65040<=G&&G<=65049||65072<=G&&G<=65106||65108<=G&&G<=65126||65128<=G&&G<=65131||110592<=G&&G<=110593||127488<=G&&G<=127490||127504<=G&&G<=127546||127552<=G&&G<=127560||127568<=G&&G<=127569||131072<=G&&G<=194367||177984<=G&&G<=196605||196608<=G&&G<=262141?"W":32<=G&&G<=126||162<=G&&G<=163||165<=G&&G<=166||G==172||G==175||10214<=G&&G<=10221||10629<=G&&G<=10630?"Na":G==161||G==164||167<=G&&G<=168||G==170||173<=G&&G<=174||176<=G&&G<=180||182<=G&&G<=186||188<=G&&G<=191||G==198||G==208||215<=G&&G<=216||222<=G&&G<=225||G==230||232<=G&&G<=234||236<=G&&G<=237||G==240||242<=G&&G<=243||247<=G&&G<=250||G==252||G==254||G==257||G==273||G==275||G==283||294<=G&&G<=295||G==299||305<=G&&G<=307||G==312||319<=G&&G<=322||G==324||328<=G&&G<=331||G==333||338<=G&&G<=339||358<=G&&G<=359||G==363||G==462||G==464||G==466||G==468||G==470||G==472||G==474||G==476||G==593||G==609||G==708||G==711||713<=G&&G<=715||G==717||G==720||728<=G&&G<=731||G==733||G==735||768<=G&&G<=879||913<=G&&G<=929||931<=G&&G<=937||945<=G&&G<=961||963<=G&&G<=969||G==1025||1040<=G&&G<=1103||G==1105||G==8208||8211<=G&&G<=8214||8216<=G&&G<=8217||8220<=G&&G<=8221||8224<=G&&G<=8226||8228<=G&&G<=8231||G==8240||8242<=G&&G<=8243||G==8245||G==8251||G==8254||G==8308||G==8319||8321<=G&&G<=8324||G==8364||G==8451||G==8453||G==8457||G==8467||G==8470||8481<=G&&G<=8482||G==8486||G==8491||8531<=G&&G<=8532||8539<=G&&G<=8542||8544<=G&&G<=8555||8560<=G&&G<=8569||G==8585||8592<=G&&G<=8601||8632<=G&&G<=8633||G==8658||G==8660||G==8679||G==8704||8706<=G&&G<=8707||8711<=G&&G<=8712||G==8715||G==8719||G==8721||G==8725||G==8730||8733<=G&&G<=8736||G==8739||G==8741||8743<=G&&G<=8748||G==8750||8756<=G&&G<=8759||8764<=G&&G<=8765||G==8776||G==8780||G==8786||8800<=G&&G<=8801||8804<=G&&G<=8807||8810<=G&&G<=8811||8814<=G&&G<=8815||8834<=G&&G<=8835||8838<=G&&G<=8839||G==8853||G==8857||G==8869||G==8895||G==8978||9312<=G&&G<=9449||9451<=G&&G<=9547||9552<=G&&G<=9587||9600<=G&&G<=9615||9618<=G&&G<=9621||9632<=G&&G<=9633||9635<=G&&G<=9641||9650<=G&&G<=9651||9654<=G&&G<=9655||9660<=G&&G<=9661||9664<=G&&G<=9665||9670<=G&&G<=9672||G==9675||9678<=G&&G<=9681||9698<=G&&G<=9701||G==9711||9733<=G&&G<=9734||G==9737||9742<=G&&G<=9743||9748<=G&&G<=9749||G==9756||G==9758||G==9792||G==9794||9824<=G&&G<=9825||9827<=G&&G<=9829||9831<=G&&G<=9834||9836<=G&&G<=9837||G==9839||9886<=G&&G<=9887||9918<=G&&G<=9919||9924<=G&&G<=9933||9935<=G&&G<=9953||G==9955||9960<=G&&G<=9983||G==10045||G==10071||10102<=G&&G<=10111||11093<=G&&G<=11097||12872<=G&&G<=12879||57344<=G&&G<=63743||65024<=G&&G<=65039||G==65533||127232<=G&&G<=127242||127248<=G&&G<=127277||127280<=G&&G<=127337||127344<=G&&G<=127386||917760<=G&&G<=917999||983040<=G&&G<=1048573||1048576<=G&&G<=1114109?"A":"N"},Y.characterLength=function(w){var X=this.eastAsianWidth(w);return X=="F"||X=="W"||X=="A"?2:1};function Z(w){return w.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}Y.length=function(w){for(var X=Z(w),W=0,G=0;G<X.length;G++)W=W+this.characterLength(X[G]);return W},Y.slice=function(w,X,W){textLen=Y.length(w),X=X||0,W=W||1,X<0&&(X=textLen+X),W<0&&(W=textLen+W);for(var G="",Q=0,z=Z(w),H=0;H<z.length;H++){var T=z[H],K=Y.length(T);if(Q>=X-(K==2?1:0))if(Q+K<=W)G+=T;else break;Q+=K}return G}})(Q9);var v5=Q9.exports,y5=J9(v5),I5=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g},D5=J9(I5);function e1($,Y={}){if(typeof $!="string"||$.length===0||(Y={ambiguousIsNarrow:!0,...Y},$=W9($),$.length===0))return 0;$=$.replace(D5()," ");let Z=Y.ambiguousIsNarrow?1:2,w=0;for(let X of $){let W=X.codePointAt(0);if(W<=31||W>=127&&W<=159||W>=768&&W<=879)continue;switch(y5.eastAsianWidth(X)){case"F":case"W":w+=2;break;case"A":w+=Z;break;default:w+=1}}return w}var A3=10,s4=($=0)=>(Y)=>`\x1B[${Y+$}m`,o4=($=0)=>(Y)=>`\x1B[${38+$};5;${Y}m`,e4=($=0)=>(Y,Z,w)=>`\x1B[${38+$};2;${Y};${Z};${w}m`,D={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]}};Object.keys(D.modifier);var h5=Object.keys(D.color),g5=Object.keys(D.bgColor);[...h5,...g5];function m5(){let $=new Map;for(let[Y,Z]of Object.entries(D)){for(let[w,X]of Object.entries(Z))D[w]={open:`\x1B[${X[0]}m`,close:`\x1B[${X[1]}m`},Z[w]=D[w],$.set(X[0],X[1]);Object.defineProperty(D,Y,{value:Z,enumerable:!1})}return Object.defineProperty(D,"codes",{value:$,enumerable:!1}),D.color.close="\x1B[39m",D.bgColor.close="\x1B[49m",D.color.ansi=s4(),D.color.ansi256=o4(),D.color.ansi16m=e4(),D.bgColor.ansi=s4(A3),D.bgColor.ansi256=o4(A3),D.bgColor.ansi16m=e4(A3),Object.defineProperties(D,{rgbToAnsi256:{value:(Y,Z,w)=>Y===Z&&Z===w?Y<8?16:Y>248?231:Math.round((Y-8)/247*24)+232:16+36*Math.round(Y/255*5)+6*Math.round(Z/255*5)+Math.round(w/255*5),enumerable:!1},hexToRgb:{value:(Y)=>{let Z=/[a-f\d]{6}|[a-f\d]{3}/i.exec(Y.toString(16));if(!Z)return[0,0,0];let[w]=Z;w.length===3&&(w=[...w].map((W)=>W+W).join(""));let X=Number.parseInt(w,16);return[X>>16&255,X>>8&255,X&255]},enumerable:!1},hexToAnsi256:{value:(Y)=>D.rgbToAnsi256(...D.hexToRgb(Y)),enumerable:!1},ansi256ToAnsi:{value:(Y)=>{if(Y<8)return 30+Y;if(Y<16)return 90+(Y-8);let Z,w,X;if(Y>=232)Z=((Y-232)*10+8)/255,w=Z,X=Z;else{Y-=16;let Q=Y%36;Z=Math.floor(Y/36)/5,w=Math.floor(Q/6)/5,X=Q%6/5}let W=Math.max(Z,w,X)*2;if(W===0)return 30;let G=30+(Math.round(X)<<2|Math.round(w)<<1|Math.round(Z));return W===2&&(G+=60),G},enumerable:!1},rgbToAnsi:{value:(Y,Z,w)=>D.ansi256ToAnsi(D.rgbToAnsi256(Y,Z,w)),enumerable:!1},hexToAnsi:{value:(Y)=>D.ansi256ToAnsi(D.hexToAnsi256(Y)),enumerable:!1}}),D}var c5=m5(),m2=new Set(["\x1B","›"]),d5=39,j3="\x07",N9="[",u5="]",z9="m",b3=`${u5}8;;`,$9=($)=>`${m2.values().next().value}${N9}${$}${z9}`,Y9=($)=>`${m2.values().next().value}${b3}${$}${j3}`,l5=($)=>$.split(" ").map((Y)=>e1(Y)),f3=($,Y,Z)=>{let w=[...Y],X=!1,W=!1,G=e1(W9($[$.length-1]));for(let[Q,z]of w.entries()){let H=e1(z);if(G+H<=Z?$[$.length-1]+=z:($.push(z),G=0),m2.has(z)&&(X=!0,W=w.slice(Q+1).join("").startsWith(b3)),X){W?z===j3&&(X=!1,W=!1):z===z9&&(X=!1);continue}G+=H,G===Z&&Q<w.length-1&&($.push(""),G=0)}!G&&$[$.length-1].length>0&&$.length>1&&($[$.length-2]+=$.pop())},p5=($)=>{let Y=$.split(" "),Z=Y.length;for(;Z>0&&!(e1(Y[Z-1])>0);)Z--;return Z===Y.length?$:Y.slice(0,Z).join(" ")+Y.slice(Z).join("")},i5=($,Y,Z={})=>{if(Z.trim!==!1&&$.trim()==="")return"";let w="",X,W,G=l5($),Q=[""];for(let[H,T]of $.split(" ").entries()){Z.trim!==!1&&(Q[Q.length-1]=Q[Q.length-1].trimStart());let K=e1(Q[Q.length-1]);if(H!==0&&(K>=Y&&(Z.wordWrap===!1||Z.trim===!1)&&(Q.push(""),K=0),(K>0||Z.trim===!1)&&(Q[Q.length-1]+=" ",K++)),Z.hard&&G[H]>Y){let U=Y-K,M=1+Math.floor((G[H]-U-1)/Y);Math.floor((G[H]-1)/Y)<M&&Q.push(""),f3(Q,T,Y);continue}if(K+G[H]>Y&&K>0&&G[H]>0){if(Z.wordWrap===!1&&K<Y){f3(Q,T,Y);continue}Q.push("")}if(K+G[H]>Y&&Z.wordWrap===!1){f3(Q,T,Y);continue}Q[Q.length-1]+=T}Z.trim!==!1&&(Q=Q.map((H)=>p5(H)));let z=[...Q.join(`
87
- `)];for(let[H,T]of z.entries()){if(w+=T,m2.has(T)){let{groups:U}=new RegExp(`(?:\\${N9}(?<code>\\d+)m|\\${b3}(?<uri>.*)${j3})`).exec(z.slice(H).join(""))||{groups:{}};if(U.code!==void 0){let M=Number.parseFloat(U.code);X=M===d5?void 0:M}else U.uri!==void 0&&(W=U.uri.length===0?void 0:U.uri)}let K=c5.codes.get(Number(X));z[H+1]===`
88
- `?(W&&(w+=Y9("")),X&&K&&(w+=$9(K))):T===`
89
- `&&(X&&K&&(w+=$9(X)),W&&(w+=Y9(W)))}return w};function Z9($,Y,Z){return String($).normalize().replace(/\r\n/g,`
85
+ Set env var: MIMO_API_KEY=<key>`)}var S3="https://api.xiaomimimo.com/v1";function K$(){let $=b2();if(!P5($))return{};try{return p4(JSON.parse(C5($,"utf-8")))}catch(Y){let Z=Y instanceof Error?Y.message:String(Y);return process.stderr.write(z("config.corrupted")+Z+z("config.corruptedHint")),{}}}async function y$($){a4();let Y=b2(),Z=Y+".tmp";try{S5(Z,JSON.stringify($,null,2)+`
86
+ `,{mode:384}),R5(Z,Y)}catch(w){let X=w instanceof Error?w.message:String(w);throw Error(`Failed to write config file: ${X}. Check file permissions for ${Y}`)}}function y2($){let Y=K$(),Z=$.apiKey||void 0,w=Y.api_key,X=Y.sk_api_key,W=Y.active_key||"tp",G;if($.baseUrl)G=$.baseUrl;else if(process.env.MIMO_BASE_URL)G=process.env.MIMO_BASE_URL;else if(Z)G=S$(Z)||Y.base_url||S3;else if(W==="sk"&&X)G=S$(X)||Y.base_url||S3;else G=Y.base_url||S3;let Q=X$($.output||process.env.MIMO_OUTPUT||Y.output),V=process.env.MIMO_TIMEOUT?Number(process.env.MIMO_TIMEOUT):void 0,H=V!==void 0&&Number.isFinite(V)&&V>0?V:void 0,T=$.timeout??H??Y.timeout??300;return{apiKey:Z,fileApiKey:w,fileSkApiKey:X,activeKey:W,configPath:b2(),baseUrl:G,output:Q,timeout:T,defaultModel:Y.default_model,language:Y.language||void 0,verbose:$.verbose||process.env.MIMO_VERBOSE==="1",quiet:$.quiet||!1,noColor:$.noColor||process.env.NO_COLOR!==void 0||!process.stdout.isTTY,dryRun:$.dryRun||!1,nonInteractive:$.nonInteractive||!1}}var Y$=f2(P3(),1),g2=f2(A3(),1);import{stdin as W9,stdout as J9}from"node:process";import*as I$ from"node:readline";import o4 from"node:readline";import{WriteStream as v5}from"node:tty";function y5({onlyFirst:$=!1}={}){let Y=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(Y,$?void 0:"g")}var I5=y5();function Q9($){if(typeof $!="string")throw TypeError(`Expected a \`string\`, got \`${typeof $}\``);return $.replace(I5,"")}function z9($){return $&&$.__esModule&&Object.prototype.hasOwnProperty.call($,"default")?$.default:$}var N9={exports:{}};(function($){var Y={};$.exports=Y,Y.eastAsianWidth=function(w){var X=w.charCodeAt(0),W=w.length==2?w.charCodeAt(1):0,G=X;return 55296<=X&&X<=56319&&56320<=W&&W<=57343&&(X&=1023,W&=1023,G=X<<10|W,G+=65536),G==12288||65281<=G&&G<=65376||65504<=G&&G<=65510?"F":G==8361||65377<=G&&G<=65470||65474<=G&&G<=65479||65482<=G&&G<=65487||65490<=G&&G<=65495||65498<=G&&G<=65500||65512<=G&&G<=65518?"H":4352<=G&&G<=4447||4515<=G&&G<=4519||4602<=G&&G<=4607||9001<=G&&G<=9002||11904<=G&&G<=11929||11931<=G&&G<=12019||12032<=G&&G<=12245||12272<=G&&G<=12283||12289<=G&&G<=12350||12353<=G&&G<=12438||12441<=G&&G<=12543||12549<=G&&G<=12589||12593<=G&&G<=12686||12688<=G&&G<=12730||12736<=G&&G<=12771||12784<=G&&G<=12830||12832<=G&&G<=12871||12880<=G&&G<=13054||13056<=G&&G<=19903||19968<=G&&G<=42124||42128<=G&&G<=42182||43360<=G&&G<=43388||44032<=G&&G<=55203||55216<=G&&G<=55238||55243<=G&&G<=55291||63744<=G&&G<=64255||65040<=G&&G<=65049||65072<=G&&G<=65106||65108<=G&&G<=65126||65128<=G&&G<=65131||110592<=G&&G<=110593||127488<=G&&G<=127490||127504<=G&&G<=127546||127552<=G&&G<=127560||127568<=G&&G<=127569||131072<=G&&G<=194367||177984<=G&&G<=196605||196608<=G&&G<=262141?"W":32<=G&&G<=126||162<=G&&G<=163||165<=G&&G<=166||G==172||G==175||10214<=G&&G<=10221||10629<=G&&G<=10630?"Na":G==161||G==164||167<=G&&G<=168||G==170||173<=G&&G<=174||176<=G&&G<=180||182<=G&&G<=186||188<=G&&G<=191||G==198||G==208||215<=G&&G<=216||222<=G&&G<=225||G==230||232<=G&&G<=234||236<=G&&G<=237||G==240||242<=G&&G<=243||247<=G&&G<=250||G==252||G==254||G==257||G==273||G==275||G==283||294<=G&&G<=295||G==299||305<=G&&G<=307||G==312||319<=G&&G<=322||G==324||328<=G&&G<=331||G==333||338<=G&&G<=339||358<=G&&G<=359||G==363||G==462||G==464||G==466||G==468||G==470||G==472||G==474||G==476||G==593||G==609||G==708||G==711||713<=G&&G<=715||G==717||G==720||728<=G&&G<=731||G==733||G==735||768<=G&&G<=879||913<=G&&G<=929||931<=G&&G<=937||945<=G&&G<=961||963<=G&&G<=969||G==1025||1040<=G&&G<=1103||G==1105||G==8208||8211<=G&&G<=8214||8216<=G&&G<=8217||8220<=G&&G<=8221||8224<=G&&G<=8226||8228<=G&&G<=8231||G==8240||8242<=G&&G<=8243||G==8245||G==8251||G==8254||G==8308||G==8319||8321<=G&&G<=8324||G==8364||G==8451||G==8453||G==8457||G==8467||G==8470||8481<=G&&G<=8482||G==8486||G==8491||8531<=G&&G<=8532||8539<=G&&G<=8542||8544<=G&&G<=8555||8560<=G&&G<=8569||G==8585||8592<=G&&G<=8601||8632<=G&&G<=8633||G==8658||G==8660||G==8679||G==8704||8706<=G&&G<=8707||8711<=G&&G<=8712||G==8715||G==8719||G==8721||G==8725||G==8730||8733<=G&&G<=8736||G==8739||G==8741||8743<=G&&G<=8748||G==8750||8756<=G&&G<=8759||8764<=G&&G<=8765||G==8776||G==8780||G==8786||8800<=G&&G<=8801||8804<=G&&G<=8807||8810<=G&&G<=8811||8814<=G&&G<=8815||8834<=G&&G<=8835||8838<=G&&G<=8839||G==8853||G==8857||G==8869||G==8895||G==8978||9312<=G&&G<=9449||9451<=G&&G<=9547||9552<=G&&G<=9587||9600<=G&&G<=9615||9618<=G&&G<=9621||9632<=G&&G<=9633||9635<=G&&G<=9641||9650<=G&&G<=9651||9654<=G&&G<=9655||9660<=G&&G<=9661||9664<=G&&G<=9665||9670<=G&&G<=9672||G==9675||9678<=G&&G<=9681||9698<=G&&G<=9701||G==9711||9733<=G&&G<=9734||G==9737||9742<=G&&G<=9743||9748<=G&&G<=9749||G==9756||G==9758||G==9792||G==9794||9824<=G&&G<=9825||9827<=G&&G<=9829||9831<=G&&G<=9834||9836<=G&&G<=9837||G==9839||9886<=G&&G<=9887||9918<=G&&G<=9919||9924<=G&&G<=9933||9935<=G&&G<=9953||G==9955||9960<=G&&G<=9983||G==10045||G==10071||10102<=G&&G<=10111||11093<=G&&G<=11097||12872<=G&&G<=12879||57344<=G&&G<=63743||65024<=G&&G<=65039||G==65533||127232<=G&&G<=127242||127248<=G&&G<=127277||127280<=G&&G<=127337||127344<=G&&G<=127386||917760<=G&&G<=917999||983040<=G&&G<=1048573||1048576<=G&&G<=1114109?"A":"N"},Y.characterLength=function(w){var X=this.eastAsianWidth(w);return X=="F"||X=="W"||X=="A"?2:1};function Z(w){return w.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}Y.length=function(w){for(var X=Z(w),W=0,G=0;G<X.length;G++)W=W+this.characterLength(X[G]);return W},Y.slice=function(w,X,W){textLen=Y.length(w),X=X||0,W=W||1,X<0&&(X=textLen+X),W<0&&(W=textLen+W);for(var G="",Q=0,V=Z(w),H=0;H<V.length;H++){var T=V[H],K=Y.length(T);if(Q>=X-(K==2?1:0))if(Q+K<=W)G+=T;else break;Q+=K}return G}})(N9);var D5=N9.exports,h5=z9(D5),g5=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g},m5=z9(g5);function e1($,Y={}){if(typeof $!="string"||$.length===0||(Y={ambiguousIsNarrow:!0,...Y},$=Q9($),$.length===0))return 0;$=$.replace(m5()," ");let Z=Y.ambiguousIsNarrow?1:2,w=0;for(let X of $){let W=X.codePointAt(0);if(W<=31||W>=127&&W<=159||W>=768&&W<=879)continue;switch(h5.eastAsianWidth(X)){case"F":case"W":w+=2;break;case"A":w+=Z;break;default:w+=1}}return w}var f3=10,e4=($=0)=>(Y)=>`\x1B[${Y+$}m`,$9=($=0)=>(Y)=>`\x1B[${38+$};5;${Y}m`,Y9=($=0)=>(Y,Z,w)=>`\x1B[${38+$};2;${Y};${Z};${w}m`,h={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]}};Object.keys(h.modifier);var c5=Object.keys(h.color),d5=Object.keys(h.bgColor);[...c5,...d5];function u5(){let $=new Map;for(let[Y,Z]of Object.entries(h)){for(let[w,X]of Object.entries(Z))h[w]={open:`\x1B[${X[0]}m`,close:`\x1B[${X[1]}m`},Z[w]=h[w],$.set(X[0],X[1]);Object.defineProperty(h,Y,{value:Z,enumerable:!1})}return Object.defineProperty(h,"codes",{value:$,enumerable:!1}),h.color.close="\x1B[39m",h.bgColor.close="\x1B[49m",h.color.ansi=e4(),h.color.ansi256=$9(),h.color.ansi16m=Y9(),h.bgColor.ansi=e4(f3),h.bgColor.ansi256=$9(f3),h.bgColor.ansi16m=Y9(f3),Object.defineProperties(h,{rgbToAnsi256:{value:(Y,Z,w)=>Y===Z&&Z===w?Y<8?16:Y>248?231:Math.round((Y-8)/247*24)+232:16+36*Math.round(Y/255*5)+6*Math.round(Z/255*5)+Math.round(w/255*5),enumerable:!1},hexToRgb:{value:(Y)=>{let Z=/[a-f\d]{6}|[a-f\d]{3}/i.exec(Y.toString(16));if(!Z)return[0,0,0];let[w]=Z;w.length===3&&(w=[...w].map((W)=>W+W).join(""));let X=Number.parseInt(w,16);return[X>>16&255,X>>8&255,X&255]},enumerable:!1},hexToAnsi256:{value:(Y)=>h.rgbToAnsi256(...h.hexToRgb(Y)),enumerable:!1},ansi256ToAnsi:{value:(Y)=>{if(Y<8)return 30+Y;if(Y<16)return 90+(Y-8);let Z,w,X;if(Y>=232)Z=((Y-232)*10+8)/255,w=Z,X=Z;else{Y-=16;let Q=Y%36;Z=Math.floor(Y/36)/5,w=Math.floor(Q/6)/5,X=Q%6/5}let W=Math.max(Z,w,X)*2;if(W===0)return 30;let G=30+(Math.round(X)<<2|Math.round(w)<<1|Math.round(Z));return W===2&&(G+=60),G},enumerable:!1},rgbToAnsi:{value:(Y,Z,w)=>h.ansi256ToAnsi(h.rgbToAnsi256(Y,Z,w)),enumerable:!1},hexToAnsi:{value:(Y)=>h.ansi256ToAnsi(h.hexToAnsi256(Y)),enumerable:!1}}),h}var l5=u5(),m2=new Set(["\x1B","›"]),p5=39,b3="\x07",V9="[",i5="]",B9="m",v3=`${i5}8;;`,Z9=($)=>`${m2.values().next().value}${V9}${$}${B9}`,w9=($)=>`${m2.values().next().value}${v3}${$}${b3}`,n5=($)=>$.split(" ").map((Y)=>e1(Y)),j3=($,Y,Z)=>{let w=[...Y],X=!1,W=!1,G=e1(Q9($[$.length-1]));for(let[Q,V]of w.entries()){let H=e1(V);if(G+H<=Z?$[$.length-1]+=V:($.push(V),G=0),m2.has(V)&&(X=!0,W=w.slice(Q+1).join("").startsWith(v3)),X){W?V===b3&&(X=!1,W=!1):V===B9&&(X=!1);continue}G+=H,G===Z&&Q<w.length-1&&($.push(""),G=0)}!G&&$[$.length-1].length>0&&$.length>1&&($[$.length-2]+=$.pop())},a5=($)=>{let Y=$.split(" "),Z=Y.length;for(;Z>0&&!(e1(Y[Z-1])>0);)Z--;return Z===Y.length?$:Y.slice(0,Z).join(" ")+Y.slice(Z).join("")},t5=($,Y,Z={})=>{if(Z.trim!==!1&&$.trim()==="")return"";let w="",X,W,G=n5($),Q=[""];for(let[H,T]of $.split(" ").entries()){Z.trim!==!1&&(Q[Q.length-1]=Q[Q.length-1].trimStart());let K=e1(Q[Q.length-1]);if(H!==0&&(K>=Y&&(Z.wordWrap===!1||Z.trim===!1)&&(Q.push(""),K=0),(K>0||Z.trim===!1)&&(Q[Q.length-1]+=" ",K++)),Z.hard&&G[H]>Y){let U=Y-K,M=1+Math.floor((G[H]-U-1)/Y);Math.floor((G[H]-1)/Y)<M&&Q.push(""),j3(Q,T,Y);continue}if(K+G[H]>Y&&K>0&&G[H]>0){if(Z.wordWrap===!1&&K<Y){j3(Q,T,Y);continue}Q.push("")}if(K+G[H]>Y&&Z.wordWrap===!1){j3(Q,T,Y);continue}Q[Q.length-1]+=T}Z.trim!==!1&&(Q=Q.map((H)=>a5(H)));let V=[...Q.join(`
87
+ `)];for(let[H,T]of V.entries()){if(w+=T,m2.has(T)){let{groups:U}=new RegExp(`(?:\\${V9}(?<code>\\d+)m|\\${v3}(?<uri>.*)${b3})`).exec(V.slice(H).join(""))||{groups:{}};if(U.code!==void 0){let M=Number.parseFloat(U.code);X=M===p5?void 0:M}else U.uri!==void 0&&(W=U.uri.length===0?void 0:U.uri)}let K=l5.codes.get(Number(X));V[H+1]===`
88
+ `?(W&&(w+=w9("")),X&&K&&(w+=Z9(K))):T===`
89
+ `&&(X&&K&&(w+=Z9(X)),W&&(w+=w9(W)))}return w};function G9($,Y,Z){return String($).normalize().replace(/\r\n/g,`
90
90
  `).split(`
91
- `).map((w)=>i5(w,Y,Z)).join(`
92
- `)}var n5=Object.defineProperty,a5=($,Y,Z)=>(Y in $)?n5($,Y,{enumerable:!0,configurable:!0,writable:!0,value:Z}):$[Y]=Z,B$=($,Y,Z)=>(a5($,typeof Y!="symbol"?Y+"":Y,Z),Z);function t5($,Y){if($===Y)return;let Z=$.split(`
91
+ `).map((w)=>t5(w,Y,Z)).join(`
92
+ `)}var r5=Object.defineProperty,s5=($,Y,Z)=>(Y in $)?r5($,Y,{enumerable:!0,configurable:!0,writable:!0,value:Z}):$[Y]=Z,B$=($,Y,Z)=>(s5($,typeof Y!="symbol"?Y+"":Y,Z),Z);function o5($,Y){if($===Y)return;let Z=$.split(`
93
93
  `),w=Y.split(`
94
- `),X=[];for(let W=0;W<Math.max(Z.length,w.length);W++)Z[W]!==w[W]&&X.push(W);return X}var V9=Symbol("clack:cancel");function M1($){return $===V9}function h2($,Y){$.isTTY&&$.setRawMode(Y)}var w9=new Map([["k","up"],["j","down"],["h","left"],["l","right"]]),r5=new Set(["up","down","left","right","space","enter"]);class B9{constructor({render:$,input:Y=G9,output:Z=X9,...w},X=!0){B$(this,"input"),B$(this,"output"),B$(this,"rl"),B$(this,"opts"),B$(this,"_track",!1),B$(this,"_render"),B$(this,"_cursor",0),B$(this,"state","initial"),B$(this,"value"),B$(this,"error",""),B$(this,"subscribers",new Map),B$(this,"_prevFrame",""),this.opts=w,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=$.bind(this),this._track=X,this.input=Y,this.output=Z}prompt(){let $=new f5(0);return $._write=(Y,Z,w)=>{this._track&&(this.value=this.rl.line.replace(/\t/g,""),this._cursor=this.rl.cursor,this.emit("value",this.value)),w()},this.input.pipe($),this.rl=r4.createInterface({input:this.input,output:$,tabSize:2,prompt:"",escapeCodeTimeout:50}),r4.emitKeypressEvents(this.input,this.rl),this.rl.prompt(),this.opts.initialValue!==void 0&&this._track&&this.rl.write(this.opts.initialValue),this.input.on("keypress",this.onKeypress),h2(this.input,!0),this.output.on("resize",this.render),this.render(),new Promise((Y,Z)=>{this.once("submit",()=>{this.output.write(Y$.cursor.show),this.output.off("resize",this.render),h2(this.input,!1),Y(this.value)}),this.once("cancel",()=>{this.output.write(Y$.cursor.show),this.output.off("resize",this.render),h2(this.input,!1),Y(V9)})})}on($,Y){let Z=this.subscribers.get($)??[];Z.push({cb:Y}),this.subscribers.set($,Z)}once($,Y){let Z=this.subscribers.get($)??[];Z.push({cb:Y,once:!0}),this.subscribers.set($,Z)}emit($,...Y){let Z=this.subscribers.get($)??[],w=[];for(let X of Z)X.cb(...Y),X.once&&w.push(()=>Z.splice(Z.indexOf(X),1));for(let X of w)X()}unsubscribe(){this.subscribers.clear()}onKeypress($,Y){if(this.state==="error"&&(this.state="active"),Y?.name&&!this._track&&w9.has(Y.name)&&this.emit("cursor",w9.get(Y.name)),Y?.name&&r5.has(Y.name)&&this.emit("cursor",Y.name),$&&($.toLowerCase()==="y"||$.toLowerCase()==="n")&&this.emit("confirm",$.toLowerCase()==="y"),$==="\t"&&this.opts.placeholder&&(this.value||(this.rl.write(this.opts.placeholder),this.emit("value",this.opts.placeholder))),$&&this.emit("key",$.toLowerCase()),Y?.name==="return"){if(this.opts.validate){let Z=this.opts.validate(this.value);Z&&(this.error=Z,this.state="error",this.rl.write(this.value))}this.state!=="error"&&(this.state="submit")}$==="\x03"&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
95
- `),h2(this.input,!1),this.rl.close(),this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let $=Z9(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
96
- `).length-1;this.output.write(Y$.cursor.move(-999,$*-1))}render(){let $=Z9(this._render(this)??"",process.stdout.columns,{hard:!0});if($!==this._prevFrame){if(this.state==="initial")this.output.write(Y$.cursor.hide);else{let Y=t5(this._prevFrame,$);if(this.restoreCursor(),Y&&Y?.length===1){let Z=Y[0];this.output.write(Y$.cursor.move(0,Z)),this.output.write(Y$.erase.lines(1));let w=$.split(`
94
+ `),X=[];for(let W=0;W<Math.max(Z.length,w.length);W++)Z[W]!==w[W]&&X.push(W);return X}var K9=Symbol("clack:cancel");function M1($){return $===K9}function h2($,Y){$.isTTY&&$.setRawMode(Y)}var X9=new Map([["k","up"],["j","down"],["h","left"],["l","right"]]),e5=new Set(["up","down","left","right","space","enter"]);class H9{constructor({render:$,input:Y=W9,output:Z=J9,...w},X=!0){B$(this,"input"),B$(this,"output"),B$(this,"rl"),B$(this,"opts"),B$(this,"_track",!1),B$(this,"_render"),B$(this,"_cursor",0),B$(this,"state","initial"),B$(this,"value"),B$(this,"error",""),B$(this,"subscribers",new Map),B$(this,"_prevFrame",""),this.opts=w,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=$.bind(this),this._track=X,this.input=Y,this.output=Z}prompt(){let $=new v5(0);return $._write=(Y,Z,w)=>{this._track&&(this.value=this.rl.line.replace(/\t/g,""),this._cursor=this.rl.cursor,this.emit("value",this.value)),w()},this.input.pipe($),this.rl=o4.createInterface({input:this.input,output:$,tabSize:2,prompt:"",escapeCodeTimeout:50}),o4.emitKeypressEvents(this.input,this.rl),this.rl.prompt(),this.opts.initialValue!==void 0&&this._track&&this.rl.write(this.opts.initialValue),this.input.on("keypress",this.onKeypress),h2(this.input,!0),this.output.on("resize",this.render),this.render(),new Promise((Y,Z)=>{this.once("submit",()=>{this.output.write(Y$.cursor.show),this.output.off("resize",this.render),h2(this.input,!1),Y(this.value)}),this.once("cancel",()=>{this.output.write(Y$.cursor.show),this.output.off("resize",this.render),h2(this.input,!1),Y(K9)})})}on($,Y){let Z=this.subscribers.get($)??[];Z.push({cb:Y}),this.subscribers.set($,Z)}once($,Y){let Z=this.subscribers.get($)??[];Z.push({cb:Y,once:!0}),this.subscribers.set($,Z)}emit($,...Y){let Z=this.subscribers.get($)??[],w=[];for(let X of Z)X.cb(...Y),X.once&&w.push(()=>Z.splice(Z.indexOf(X),1));for(let X of w)X()}unsubscribe(){this.subscribers.clear()}onKeypress($,Y){if(this.state==="error"&&(this.state="active"),Y?.name&&!this._track&&X9.has(Y.name)&&this.emit("cursor",X9.get(Y.name)),Y?.name&&e5.has(Y.name)&&this.emit("cursor",Y.name),$&&($.toLowerCase()==="y"||$.toLowerCase()==="n")&&this.emit("confirm",$.toLowerCase()==="y"),$==="\t"&&this.opts.placeholder&&(this.value||(this.rl.write(this.opts.placeholder),this.emit("value",this.opts.placeholder))),$&&this.emit("key",$.toLowerCase()),Y?.name==="return"){if(this.opts.validate){let Z=this.opts.validate(this.value);Z&&(this.error=Z,this.state="error",this.rl.write(this.value))}this.state!=="error"&&(this.state="submit")}$==="\x03"&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
95
+ `),h2(this.input,!1),this.rl.close(),this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let $=G9(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
96
+ `).length-1;this.output.write(Y$.cursor.move(-999,$*-1))}render(){let $=G9(this._render(this)??"",process.stdout.columns,{hard:!0});if($!==this._prevFrame){if(this.state==="initial")this.output.write(Y$.cursor.hide);else{let Y=o5(this._prevFrame,$);if(this.restoreCursor(),Y&&Y?.length===1){let Z=Y[0];this.output.write(Y$.cursor.move(0,Z)),this.output.write(Y$.erase.lines(1));let w=$.split(`
97
97
  `);this.output.write(w[Z]),this._prevFrame=$,this.output.write(Y$.cursor.move(0,w.length-Z-1));return}else if(Y&&Y?.length>1){let Z=Y[0];this.output.write(Y$.cursor.move(0,Z)),this.output.write(Y$.erase.down());let w=$.split(`
98
98
  `).slice(Z);this.output.write(w.join(`
99
- `)),this._prevFrame=$;return}this.output.write(Y$.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}var s5=Object.defineProperty,o5=($,Y,Z)=>(Y in $)?s5($,Y,{enumerable:!0,configurable:!0,writable:!0,value:Z}):$[Y]=Z,e5=($,Y,Z)=>(o5($,typeof Y!="symbol"?Y+"":Y,Z),Z);class v3 extends B9{constructor($){super($),e5(this,"valueWithCursor",""),this.on("finalize",()=>{this.value||(this.value=$.defaultValue),this.valueWithCursor=this.value}),this.on("value",()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.value}${g2.default.inverse(g2.default.hidden("_"))}`;else{let Y=this.value.slice(0,this.cursor),Z=this.value.slice(this.cursor);this.valueWithCursor=`${Y}${g2.default.inverse(Z[0])}${Z.slice(1)}`}})}get cursor(){return this._cursor}}var $8=globalThis.process.platform.startsWith("win");function K9({input:$=G9,output:Y=X9,overwrite:Z=!0,hideCursor:w=!0}={}){let X=I$.createInterface({input:$,output:Y,prompt:"",tabSize:1});I$.emitKeypressEvents($,X),$.isTTY&&$.setRawMode(!0);let W=(G,{name:Q})=>{if(String(G)==="\x03"){w&&Y.write(Y$.cursor.show),process.exit(0);return}if(!Z)return;I$.moveCursor(Y,Q==="return"?0:-1,Q==="return"?-1:0,()=>{I$.clearLine(Y,1,()=>{$.once("keypress",W)})})};return w&&Y.write(Y$.cursor.hide),$.once("keypress",W),()=>{$.off("keypress",W),w&&Y.write(Y$.cursor.show),$.isTTY&&!$8&&$.setRawMode(!1),X.terminal=!1,X.close()}}var _=f2(_3(),1),x1=f2(R3(),1);import H$ from"node:process";function Y8(){return H$.platform!=="win32"?H$.env.TERM!=="linux":Boolean(H$.env.CI)||Boolean(H$.env.WT_SESSION)||Boolean(H$.env.TERMINUS_SUBLIME)||H$.env.ConEmuTask==="{cmd::Cmder}"||H$.env.TERM_PROGRAM==="Terminus-Sublime"||H$.env.TERM_PROGRAM==="vscode"||H$.env.TERM==="xterm-256color"||H$.env.TERM==="alacritty"||H$.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var I3=Y8(),m=($,Y)=>I3?$:Y,Z8=m("◆","*"),T9=m("■","x"),U9=m("▲","x"),h3=m("◇","o"),w8=m("┌","T"),T$=m("│","|"),D3=m("└","—"),Iw=m("●",">"),Dw=m("○"," "),hw=m("◻","[•]"),gw=m("◼","[+]"),mw=m("◻","[ ]"),cw=m("▪","•"),H9=m("─","-"),G8=m("╮","+"),X8=m("├","+"),W8=m("╯","+"),dw=m("●","•"),uw=m("◆","*"),lw=m("▲","!"),pw=m("■","x"),J8=($)=>{switch($){case"initial":case"active":return _.default.cyan(Z8);case"cancel":return _.default.red(T9);case"error":return _.default.yellow(U9);case"submit":return _.default.green(h3)}},c2=($)=>new v3({validate:$.validate,placeholder:$.placeholder,defaultValue:$.defaultValue,initialValue:$.initialValue,render(){let Y=`${_.default.gray(T$)}
100
- ${J8(this.state)} ${$.message}
99
+ `)),this._prevFrame=$;return}this.output.write(Y$.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}var $8=Object.defineProperty,Y8=($,Y,Z)=>(Y in $)?$8($,Y,{enumerable:!0,configurable:!0,writable:!0,value:Z}):$[Y]=Z,Z8=($,Y,Z)=>(Y8($,typeof Y!="symbol"?Y+"":Y,Z),Z);class y3 extends H9{constructor($){super($),Z8(this,"valueWithCursor",""),this.on("finalize",()=>{this.value||(this.value=$.defaultValue),this.valueWithCursor=this.value}),this.on("value",()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.value}${g2.default.inverse(g2.default.hidden("_"))}`;else{let Y=this.value.slice(0,this.cursor),Z=this.value.slice(this.cursor);this.valueWithCursor=`${Y}${g2.default.inverse(Z[0])}${Z.slice(1)}`}})}get cursor(){return this._cursor}}var w8=globalThis.process.platform.startsWith("win");function T9({input:$=W9,output:Y=J9,overwrite:Z=!0,hideCursor:w=!0}={}){let X=I$.createInterface({input:$,output:Y,prompt:"",tabSize:1});I$.emitKeypressEvents($,X),$.isTTY&&$.setRawMode(!0);let W=(G,{name:Q})=>{if(String(G)==="\x03"){w&&Y.write(Y$.cursor.show),process.exit(0);return}if(!Z)return;I$.moveCursor(Y,Q==="return"?0:-1,Q==="return"?-1:0,()=>{I$.clearLine(Y,1,()=>{$.once("keypress",W)})})};return w&&Y.write(Y$.cursor.hide),$.once("keypress",W),()=>{$.off("keypress",W),w&&Y.write(Y$.cursor.show),$.isTTY&&!w8&&$.setRawMode(!1),X.terminal=!1,X.close()}}var _=f2(A3(),1),x1=f2(P3(),1);import H$ from"node:process";function G8(){return H$.platform!=="win32"?H$.env.TERM!=="linux":Boolean(H$.env.CI)||Boolean(H$.env.WT_SESSION)||Boolean(H$.env.TERMINUS_SUBLIME)||H$.env.ConEmuTask==="{cmd::Cmder}"||H$.env.TERM_PROGRAM==="Terminus-Sublime"||H$.env.TERM_PROGRAM==="vscode"||H$.env.TERM==="xterm-256color"||H$.env.TERM==="alacritty"||H$.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var D3=G8(),m=($,Y)=>D3?$:Y,X8=m("◆","*"),M9=m("■","x"),x9=m("▲","x"),g3=m("◇","o"),W8=m("┌","T"),T$=m("│","|"),h3=m("└","—"),iw=m("●",">"),nw=m("○"," "),aw=m("◻","[•]"),tw=m("◼","[+]"),rw=m("◻","[ ]"),sw=m("▪","•"),U9=m("─","-"),J8=m("╮","+"),Q8=m("├","+"),z8=m("╯","+"),ow=m("●","•"),ew=m("◆","*"),$G=m("▲","!"),YG=m("■","x"),N8=($)=>{switch($){case"initial":case"active":return _.default.cyan(X8);case"cancel":return _.default.red(M9);case"error":return _.default.yellow(x9);case"submit":return _.default.green(g3)}},c2=($)=>new y3({validate:$.validate,placeholder:$.placeholder,defaultValue:$.defaultValue,initialValue:$.initialValue,render(){let Y=`${_.default.gray(T$)}
100
+ ${N8(this.state)} ${$.message}
101
101
  `,Z=$.placeholder?_.default.inverse($.placeholder[0])+_.default.dim($.placeholder.slice(1)):_.default.inverse(_.default.hidden("_")),w=this.value?this.valueWithCursor:Z;switch(this.state){case"error":return`${Y.trim()}
102
102
  ${_.default.yellow(T$)} ${w}
103
- ${_.default.yellow(D3)} ${_.default.yellow(this.error)}
103
+ ${_.default.yellow(h3)} ${_.default.yellow(this.error)}
104
104
  `;case"submit":return`${Y}${_.default.gray(T$)} ${_.default.dim(this.value||$.placeholder)}`;case"cancel":return`${Y}${_.default.gray(T$)} ${_.default.strikethrough(_.default.dim(this.value??""))}${this.value?.trim()?`
105
105
  `+_.default.gray(T$):""}`;default:return`${Y}${_.default.cyan(T$)} ${w}
106
- ${_.default.cyan(D3)}
107
- `}}}).prompt();var y3=($)=>$.replace(Q8(),""),M9=($="",Y="")=>{let Z=`
106
+ ${_.default.cyan(h3)}
107
+ `}}}).prompt();var I3=($)=>$.replace(V8(),""),q9=($="",Y="")=>{let Z=`
108
108
  ${$}
109
109
  `.split(`
110
- `),w=y3(Y).length,X=Math.max(Z.reduce((G,Q)=>(Q=y3(Q),Q.length>G?Q.length:G),0),w)+2,W=Z.map((G)=>`${_.default.gray(T$)} ${_.default.dim(G)}${" ".repeat(X-y3(G).length)}${_.default.gray(T$)}`).join(`
110
+ `),w=I3(Y).length,X=Math.max(Z.reduce((G,Q)=>(Q=I3(Q),Q.length>G?Q.length:G),0),w)+2,W=Z.map((G)=>`${_.default.gray(T$)} ${_.default.dim(G)}${" ".repeat(X-I3(G).length)}${_.default.gray(T$)}`).join(`
111
111
  `);process.stdout.write(`${_.default.gray(T$)}
112
- ${_.default.green(h3)} ${_.default.reset(Y)} ${_.default.gray(H9.repeat(Math.max(X-w-1,1))+G8)}
112
+ ${_.default.green(g3)} ${_.default.reset(Y)} ${_.default.gray(U9.repeat(Math.max(X-w-1,1))+J8)}
113
113
  ${W}
114
- ${_.default.gray(X8+H9.repeat(X+2)+W8)}
115
- `)};var x9=($="")=>{process.stdout.write(`${_.default.gray(w8)} ${$}
116
- `)},g3=($="")=>{process.stdout.write(`${_.default.gray(T$)}
117
- ${_.default.gray(D3)} ${$}
118
-
119
- `)};var q9=()=>{let $=I3?["◒","◐","◓","◑"]:["•","o","O","0"],Y=I3?80:120,Z,w,X=!1,W="",G=(T="")=>{X=!0,Z=K9(),W=T.replace(/\.+$/,""),process.stdout.write(`${_.default.gray(T$)}
120
- `);let K=0,U=0;w=setInterval(()=>{let M=_.default.magenta($[K]),q=".".repeat(Math.floor(U)).slice(0,3);process.stdout.write(x1.cursor.move(-999,0)),process.stdout.write(x1.erase.down(1)),process.stdout.write(`${M} ${W}${q}`),K=K+1<$.length?K+1:0,U=U<$.length?U+0.125:0},Y)},Q=(T="",K=0)=>{W=T??W,X=!1,clearInterval(w);let U=K===0?_.default.green(h3):K===1?_.default.red(T9):_.default.red(U9);process.stdout.write(x1.cursor.move(-999,0)),process.stdout.write(x1.erase.down(1)),process.stdout.write(`${U} ${W}
121
- `),Z()},z=(T="")=>{W=T??W},H=(T)=>{let K=T>1?"Something went wrong":"Canceled";X&&Q(K,T)};return process.on("uncaughtExceptionMonitor",()=>H(2)),process.on("unhandledRejection",()=>H(2)),process.on("SIGINT",()=>H(1)),process.on("SIGTERM",()=>H(1)),process.on("exit",H),{start:G,stop:Q,message:z}};function Q8(){let $=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp($,"g")}function $0(){return process.stdout.isTTY===!0}async function O9($,Y){let Z=await c2({message:$,placeholder:Y?.placeholder});if(M1(Z))throw Error("Operation cancelled");let w=Z.trim();if(!w)throw Error("Input cannot be empty");return w}async function E9($){if($.apiKey||$.fileApiKey||$.fileSkApiKey)return;if(process.env.MIMO_API_KEY)return;if(!$0())throw new L(V("auth.noCreds"),E.AUTH,V("auth.noCredsHint"));process.stderr.write(`
122
- Not logged in.
123
- `),process.stderr.write(` mimo auth login Log in with an API key
124
- `),process.stderr.write(` mimo auth login --api-key Save an API key directly
125
-
126
- `),process.exit(E.AUTH)}async function L9($,Y){let Z={...K$()};if(Y.startsWith("tp-"))Z.api_key=Y,Z.active_key="tp";else Z.sk_api_key=Y,Z.active_key="sk";let w=S$(Y);if(w)Z.base_url=w;else Z.base_url="https://api.xiaomimimo.com/v1";await y$(Z),$.fileApiKey=Z.api_key,$.fileSkApiKey=Z.sk_api_key,$.activeKey=Z.active_key;let X=Y.startsWith("tp-")?"TokenPlan":"按量计费";if(process.stderr.write(`${V("auth.keySaved")} ${$.configPath??"~/.mimo/config.json"} (${J$(Y)}, ${X})
127
- `),w)process.stderr.write(`${V("auth.baseUrlAuto")}${w}
128
- `)}async function F9(){process.stderr.write(`
129
- `+V("auth.promptTitle")+`
130
- `),process.stderr.write(" "+V("auth.promptPayKey")+`
131
- `),process.stderr.write(" "+V("auth.promptTpKey")+`
132
-
133
- `);let $=await O9(V("auth.promptLabel"));if(!$)throw new L(V("auth.keyRequired"),E.AUTH);return $}var q1="0.1.6";var k9=j({name:"auth login",description:"cmd.authLogin.desc",usage:"mimo auth login [--api-key <key>]",options:[{flag:"--api-key <key>",description:"flag.auth.apiKey"}],examples:["mimo auth login","mimo auth login --api-key sk-xxxxx # 按量计费 Key","mimo auth login --api-key tp-xxxxx # TokenPlan Key"],async run($,Y){let Z=Y.apiKey;if(!Z){if(!$0())throw new L(V("auth.noKeyProvided"),E.AUTH,V("auth.noKeyHint"));Z=await F9()}if(!Z||Z.trim().length===0)throw new L(V("auth.keyEmpty"),E.AUTH);await L9($,Z.trim())}});var C9=j({name:"auth status",description:"cmd.authStatus.desc",usage:"mimo auth status",async run($,Y){try{let Z=v2($),w=Z.token.startsWith("tp-")?"TokenPlan":"按量计费",X=S$(Z.token),W={authenticated:!0,method:Z.method,activeKey:$.activeKey??"tp",apiKey:J$(Z.token),keyType:w,baseUrl:$.baseUrl||X||"https://api.xiaomimimo.com/v1",source:Z.source,configPath:$.configPath};if($.activeKey==="tp"&&$.fileSkApiKey)W.standbyKey=J$($.fileSkApiKey)+" (按量计费)";else if($.activeKey==="sk"&&$.fileApiKey)W.standbyKey=J$($.fileApiKey)+" (TokenPlan)";console.log(W$(W,$))}catch(Z){if($.verbose)process.stderr.write(`Debug: credential resolution failed — ${Z instanceof Error?Z.message:String(Z)}
134
- `);let w={authenticated:!1,method:null,activeKey:$.activeKey??"tp",apiKey:null,keyType:null,baseUrl:$.baseUrl||"https://api.xiaomimimo.com/v1",source:null,configPath:$.configPath};console.log(W$(w,$))}}});var S9=j({name:"auth logout",description:"cmd.authLogout.desc",usage:"mimo auth logout",async run($,Y){let Z=K$();if(!Z.api_key&&!Z.sk_api_key){process.stderr.write(V("auth.logoutNoKey")+`
135
- `);return}delete Z.api_key,delete Z.sk_api_key,delete Z.active_key,await y$(Z),$.fileApiKey=void 0,$.fileSkApiKey=void 0,$.activeKey=void 0,process.stderr.write(V("auth.logoutDone")+`
136
- `)}});var N8=new Set(["api_key","apiKey","api-key","sk_api_key","skApiKey","sk-api-key"]),R9=j({name:"config show",description:"cmd.configShow.desc",usage:"mimo config show",async run($,Y){let Z=K$(),w={baseUrl:$.baseUrl,output:$.output,timeout:$.timeout,defaultModel:$.defaultModel??V("general.notSet"),activeKey:$.activeKey??"tp",configPath:$.configPath};if(Z.api_key)w.tpApiKey=J$(Z.api_key)+" (TokenPlan)";else w.tpApiKey=V("general.notSet");if(Z.sk_api_key)w.skApiKey=J$(Z.sk_api_key)+" (按量计费)";else w.skApiKey=V("general.notSet");if(Z.base_url)w.fileBaseUrl=Z.base_url;for(let[X,W]of Object.entries(Z))if(X!=="api_key"&&X!=="sk_api_key"&&X!=="base_url"&&X!=="active_key"&&N8.has(X)&&typeof W==="string")w[X]=J$(W);console.log(W$(w,$))}});var P9=new Set(["api_key","sk_api_key","active_key","base_url","output","timeout","default_model","language"]),z8=/^[a-zA-Z0-9_]+$/,_9=j({name:"config set",description:"cmd.configSet.desc",usage:"mimo config set --key <key> --value <value>",options:[{flag:"--key <key>",description:"flag.config.key",required:!0},{flag:"--value <value>",description:"flag.config.value",required:!0}],examples:["mimo config set --key base_url --value https://api.xiaomimimo.com/v1","mimo config set --key output --value json","mimo config set --key timeout --value 60","mimo config set --key default_model --value MiMo-7B-RL"],async run($,Y){let{key:Z,value:w}=Y;if(!Z)throw new L(V("config.keyRequired"),E.USAGE);if(!z8.test(Z))throw new L(V("config.invalidKey")+'"'+Z+'"',E.INVALID_INPUT,V("config.invalidKeyChars"));if(!P9.has(Z))throw new L(V("config.invalidKey")+'"'+Z+'"',E.USAGE,V("config.validKeys")+Array.from(P9).join(", "));if(w===void 0||w==="")throw new L(V("config.valueRequired"),E.USAGE);let X=K$();if(Z==="timeout"){let G=Number(w);if(!Number.isFinite(G)||G<=0)throw new L(V("config.setTimeout"),E.USAGE);X[Z]=G}else if(Z==="output"&&w!=="text"&&w!=="json")throw new L(V("config.setOutput"),E.USAGE);else if(Z==="active_key"&&w!=="tp"&&w!=="sk")throw new L(V("config.invalidActiveKey"),E.USAGE);else X[Z]=w;if(Z==="active_key"){let G=w==="sk"?X.sk_api_key:X.api_key;if(typeof G==="string"){let Q=G.startsWith("tp-")?"https://token-plan-cn.xiaomimimo.com/v1":"https://api.xiaomimimo.com/v1";X.base_url=Q}}await y$(X);let W=Z==="api_key"||Z==="sk_api_key"?J$(String(w)):w;process.stderr.write(V("config.setDone")+" "+Z+" = "+W+`
137
- `)}});import{exec as V8}from"node:child_process";var B8="https://registry.npmjs.org/mimo-cli/latest";function K8($){return new Promise((Y,Z)=>{V8($,{timeout:120000},(w,X,W)=>{if(w)return Z(w);Y((X||"").trim())})})}function H8($,Y){let Z=$.replace(/^v/,"").split(".").map(Number),w=Y.replace(/^v/,"").split(".").map(Number);for(let X=0;X<3;X++){if((Z[X]??0)>(w[X]??0))return 1;if((Z[X]??0)<(w[X]??0))return-1}return 0}var A9=j({name:"update",description:"cmd.update.desc",usage:"mimo update",async run(){process.stderr.write(V("update.checking")+`
138
- `);let $;try{let Z=await fetch(B8);if(!Z.ok)throw Error(`HTTP ${Z.status}`);$=(await Z.json()).version}catch{process.stderr.write(V("update.checkFailed")+`
139
- `),process.stderr.write(V("update.manualHint")+`
140
- `);return}let Y=q1.replace(/^v/,"");if(process.stderr.write(V("update.currentVersion",{version:Y})+`
141
- `),process.stderr.write(V("update.latestVersion",{version:$})+`
142
- `),H8($,Y)<=0){process.stderr.write(V("update.alreadyLatest")+`
143
- `);return}process.stderr.write(V("update.updating",{version:$})+`
144
- `);try{let Z=await K8("npm install -g mimo-cli@latest");if(Z)process.stderr.write(Z+`
145
- `);process.stderr.write(V("update.success",{version:$})+`
146
- `)}catch{process.stderr.write(V("update.installFailed")+`
147
- `),process.stderr.write(V("update.manualHint")+`
148
- `)}}});var f9=j({name:"help",description:"cmd.help.desc",usage:"mimo help [command]",options:[{flag:"--command <path>",description:"flag.help.command"}],async run($,Y){let Z=typeof Y.command==="string"?Y.command.split(" "):[];h.printHelp(Z)}});var j9=j({name:"language",description:"cmd.language.desc",usage:"mimo language <zh|en>",options:[],examples:["mimo language zh","mimo language en"],async run($,Y){let w=Y._positional?.[0];if(!w){process.stderr.write(V("language.current")+h4()+`
149
- `);return}if(w!=="zh"&&w!=="en")process.stderr.write(V("language.invalid")+`
150
- `),process.stderr.write(V("language.hint")+`
151
- `),process.exit(2);let X=K$();X.language=w,await y$(X),g4(w),process.stderr.write(V("language.changed")+`
152
- `)}});function k($,Y,Z,w,X){if(w==="m")throw TypeError("Private method is not writable");if(w==="a"&&!X)throw TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?$!==Y||!X:!Y.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return w==="a"?X.call($,Z):X?X.value=Z:Y.set($,Z),Z}function B($,Y,Z,w){if(Z==="a"&&!w)throw TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?$!==Y||!w:!Y.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?w:Z==="a"?w.call($):w?w.value:Y.get($)}var c3=function(){let{crypto:$}=globalThis;if($?.randomUUID)return c3=$.randomUUID.bind($),$.randomUUID();let Y=new Uint8Array(1),Z=$?()=>$.getRandomValues(Y)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(w)=>(+w^Z()&15>>+w/4).toString(16))};function Y0($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var Z0=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let Y=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)Y.stack=$.stack;if($.cause&&!Y.cause)Y.cause=$.cause;if($.name)Y.name=$.name;return Y}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class O extends Error{}class g extends O{constructor($,Y,Z,w){super(`${g.makeMessage($,Y,Z)}`);this.status=$,this.headers=w,this.requestID=w?.get("x-request-id"),this.error=Y;let X=Y;this.code=X?.code,this.param=X?.param,this.type=X?.type}static makeMessage($,Y,Z){let w=Y?.message?typeof Y.message==="string"?Y.message:JSON.stringify(Y.message):Y?JSON.stringify(Y):Z;if($&&w)return`${$} ${w}`;if($)return`${$} status code (no body)`;if(w)return w;return"(no status code or body)"}static generate($,Y,Z,w){if(!$||!w)return new t$({message:Z,cause:Z0(Y)});let X=Y?.error;if($===400)return new w0($,X,Z,w);if($===401)return new G0($,X,Z,w);if($===403)return new X0($,X,Z,w);if($===404)return new W0($,X,Z,w);if($===409)return new J0($,X,Z,w);if($===422)return new Q0($,X,Z,w);if($===429)return new N0($,X,Z,w);if($>=500)return new z0($,X,Z,w);return new g($,X,Z,w)}}class d extends g{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class t$ extends g{constructor({message:$,cause:Y}){super(void 0,void 0,$||"Connection error.",void 0);if(Y)this.cause=Y}}class r$ extends t${constructor({message:$}={}){super({message:$??"Request timed out."})}}class w0 extends g{}class G0 extends g{}class X0 extends g{}class W0 extends g{}class J0 extends g{}class Q0 extends g{}class N0 extends g{}class z0 extends g{}class V0 extends O{constructor(){super("Could not parse response content as the length limit was reached")}}class B0 extends O{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class R$ extends Error{constructor($){super($)}}class O1 extends g{constructor($,Y,Z){let w="OAuth2 authentication error",X=void 0;if(Y&&typeof Y==="object"){let W=Y;X=W.error;let G=W.error_description;if(G&&typeof G==="string")w=G;else if(X)w=X}super($,Y,w,Z);this.error_code=X}}class d2 extends O{constructor($,Y,Z){super($);this.provider=Y,this.cause=Z}}var U8=/^[a-z][a-z0-9+.-]*:/i,b9=($)=>{return U8.test($)},a=($)=>(a=Array.isArray,a($)),d3=a;function u2($){if(typeof $!=="object")return{};return $??{}}function u3($){if(!$)return!0;for(let Y in $)return!1;return!0}function v9($,Y){return Object.prototype.hasOwnProperty.call($,Y)}function K0($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var y9=($,Y)=>{if(typeof Y!=="number"||!Number.isInteger(Y))throw new O(`${$} must be an integer`);if(Y<0)throw new O(`${$} must be a positive integer`);return Y};var I9=($)=>{try{return JSON.parse($)}catch(Y){return}};var q$=($)=>new Promise((Y)=>setTimeout(Y,$));var D$="6.42.0";var m9=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function M8(){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 x8=()=>{let $=M8();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":D$,"X-Stainless-OS":h9(Deno.build.os),"X-Stainless-Arch":D9(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":D$,"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":D$,"X-Stainless-OS":h9(globalThis.process.platform??"unknown"),"X-Stainless-Arch":D9(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Y=q8();if(Y)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":D$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Y.browser}`,"X-Stainless-Runtime-Version":Y.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":D$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function q8(){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:Y,pattern:Z}of $){let w=Z.exec(navigator.userAgent);if(w){let X=w[1]||0,W=w[2]||0,G=w[3]||0;return{browser:Y,version:`${X}.${W}.${G}`}}}return null}var D9=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},h9=($)=>{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"},g9,c9=()=>{return g9??(g9=x8())};function l2(){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 l3(...$){let Y=globalThis.ReadableStream;if(typeof Y>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Y(...$)}function p2($){let Y=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return l3({start(){},async pull(Z){let{done:w,value:X}=await Y.next();if(w)Z.close();else Z.enqueue(X)},async cancel(){await Y.return?.()}})}function p3($){if($[Symbol.asyncIterator])return $;let Y=$.getReader();return{async next(){try{let Z=await Y.read();if(Z?.done)Y.releaseLock();return Z}catch(Z){throw Y.releaseLock(),Z}},async return(){let Z=Y.cancel();return Y.releaseLock(),await Z,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function i3($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Y=$.getReader(),Z=Y.cancel();Y.releaseLock(),await Z}var u9=({headers:$,body:Y})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Y)}};var n3="RFC3986",a3=($)=>String($),t3={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:a3},l9="RFC1738";var i2=($,Y)=>(i2=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),i2($,Y)),O$=(()=>{let $=[];for(let Y=0;Y<256;++Y)$.push("%"+((Y<16?"0":"")+Y.toString(16)).toUpperCase());return $})();var r3=1024,p9=($,Y,Z,w,X)=>{if($.length===0)return $;let W=$;if(typeof $==="symbol")W=Symbol.prototype.toString.call($);else if(typeof $!=="string")W=String($);if(Z==="iso-8859-1")return escape(W).replace(/%u[0-9a-f]{4}/gi,function(Q){return"%26%23"+parseInt(Q.slice(2),16)+"%3B"});let G="";for(let Q=0;Q<W.length;Q+=r3){let z=W.length>=r3?W.slice(Q,Q+r3):W,H=[];for(let T=0;T<z.length;++T){let K=z.charCodeAt(T);if(K===45||K===46||K===95||K===126||K>=48&&K<=57||K>=65&&K<=90||K>=97&&K<=122||X===l9&&(K===40||K===41)){H[H.length]=z.charAt(T);continue}if(K<128){H[H.length]=O$[K];continue}if(K<2048){H[H.length]=O$[192|K>>6]+O$[128|K&63];continue}if(K<55296||K>=57344){H[H.length]=O$[224|K>>12]+O$[128|K>>6&63]+O$[128|K&63];continue}T+=1,K=65536+((K&1023)<<10|z.charCodeAt(T)&1023),H[H.length]=O$[240|K>>18]+O$[128|K>>12&63]+O$[128|K>>6&63]+O$[128|K&63]}G+=H.join("")}return G};function i9($){if(!$||typeof $!=="object")return!1;return!!($.constructor&&$.constructor.isBuffer&&$.constructor.isBuffer($))}function s3($,Y){if(a($)){let Z=[];for(let w=0;w<$.length;w+=1)Z.push(Y($[w]));return Z}return Y($)}var a9={brackets($){return String($)+"[]"},comma:"comma",indices($,Y){return String($)+"["+Y+"]"},repeat($){return String($)}},t9=function($,Y){Array.prototype.push.apply($,a(Y)?Y:[Y])},n9,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:p9,encodeValuesOnly:!1,format:n3,formatter:a3,indices:!1,serializeDate($){return(n9??(n9=Function.prototype.call.bind(Date.prototype.toISOString)))($)},skipNulls:!1,strictNullHandling:!1};function E8($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}var o3={};function r9($,Y,Z,w,X,W,G,Q,z,H,T,K,U,M,q,P,A,R){let F=$,b=R,v=0,o=!1;while((b=b.get(o3))!==void 0&&!o){let y=b.get($);if(v+=1,typeof y<"u")if(y===v)throw RangeError("Cyclic object value");else o=!0;if(typeof b.get(o3)>"u")v=0}if(typeof H==="function")F=H(Y,F);else if(F instanceof Date)F=U?.(F);else if(Z==="comma"&&a(F))F=s3(F,function(y){if(y instanceof Date)return U?.(y);return y});if(F===null){if(W)return z&&!P?z(Y,u.encoder,A,"key",M):Y;F=""}if(E8(F)||i9(F)){if(z){let y=P?Y:z(Y,u.encoder,A,"key",M);return[q?.(y)+"="+q?.(z(F,u.encoder,A,"value",M))]}return[q?.(Y)+"="+q?.(String(F))]}let e=[];if(typeof F>"u")return e;let I;if(Z==="comma"&&a(F)){if(P&&z)F=s3(F,z);I=[{value:F.length>0?F.join(",")||null:void 0}]}else if(a(H))I=H;else{let y=Object.keys(F);I=T?y.sort(T):y}let $$=Q?String(Y).replace(/\./g,"%2E"):String(Y),k$=w&&a(F)&&F.length===1?$$+"[]":$$;if(X&&a(F)&&F.length===0)return k$+"[]";for(let y=0;y<I.length;++y){let b$=I[y],P4=typeof b$==="object"&&typeof b$.value<"u"?b$.value:F[b$];if(G&&P4===null)continue;let L3=K&&Q?b$.replace(/\./g,"%2E"):b$,Q5=a(F)?typeof Z==="function"?Z(k$,L3):k$:k$+(K?"."+L3:"["+L3+"]");R.set($,v);let _4=new WeakMap;_4.set(o3,R),t9(e,r9(P4,Q5,Z,w,X,W,G,Q,Z==="comma"&&P&&a(F)?null:z,H,T,K,U,M,q,P,A,_4))}return e}function L8($=u){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 Y=$.charset||u.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 Z=n3;if(typeof $.format<"u"){if(!i2(t3,$.format))throw TypeError("Unknown format option provided.");Z=$.format}let w=t3[Z],X=u.filter;if(typeof $.filter==="function"||a($.filter))X=$.filter;let W;if($.arrayFormat&&$.arrayFormat in a9)W=$.arrayFormat;else if("indices"in $)W=$.indices?"indices":"repeat";else W=u.arrayFormat;if("commaRoundTrip"in $&&typeof $.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let G=typeof $.allowDots>"u"?!!$.encodeDotInKeys===!0?!0:u.allowDots:!!$.allowDots;return{addQueryPrefix:typeof $.addQueryPrefix==="boolean"?$.addQueryPrefix:u.addQueryPrefix,allowDots:G,allowEmptyArrays:typeof $.allowEmptyArrays==="boolean"?!!$.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:W,charset:Y,charsetSentinel:typeof $.charsetSentinel==="boolean"?$.charsetSentinel:u.charsetSentinel,commaRoundTrip:!!$.commaRoundTrip,delimiter:typeof $.delimiter>"u"?u.delimiter:$.delimiter,encode:typeof $.encode==="boolean"?$.encode:u.encode,encodeDotInKeys:typeof $.encodeDotInKeys==="boolean"?$.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof $.encoder==="function"?$.encoder:u.encoder,encodeValuesOnly:typeof $.encodeValuesOnly==="boolean"?$.encodeValuesOnly:u.encodeValuesOnly,filter:X,format:Z,formatter:w,serializeDate:typeof $.serializeDate==="function"?$.serializeDate:u.serializeDate,skipNulls:typeof $.skipNulls==="boolean"?$.skipNulls:u.skipNulls,sort:typeof $.sort==="function"?$.sort:null,strictNullHandling:typeof $.strictNullHandling==="boolean"?$.strictNullHandling:u.strictNullHandling}}function s9($,Y={}){let Z=$,w=L8(Y),X,W;if(typeof w.filter==="function")W=w.filter,Z=W("",Z);else if(a(w.filter))W=w.filter,X=W;let G=[];if(typeof Z!=="object"||Z===null)return"";let Q=a9[w.arrayFormat],z=Q==="comma"&&w.commaRoundTrip;if(!X)X=Object.keys(Z);if(w.sort)X.sort(w.sort);let H=new WeakMap;for(let U=0;U<X.length;++U){let M=X[U];if(w.skipNulls&&Z[M]===null)continue;t9(G,r9(Z[M],M,Q,z,w.allowEmptyArrays,w.strictNullHandling,w.skipNulls,w.encodeDotInKeys,w.encode?w.encoder:null,w.filter,w.sort,w.allowDots,w.serializeDate,w.format,w.formatter,w.encodeValuesOnly,w.charset,H))}let T=G.join(w.delimiter),K=w.addQueryPrefix===!0?"?":"";if(w.charsetSentinel)if(w.charset==="iso-8859-1")K+="utf8=%26%2310003%3B&";else K+="utf8=%E2%9C%93&";return T.length>0?K+T:""}function o9($){return s9($,{arrayFormat:"brackets"})}function Y6($){let Y=0;for(let X of $)Y+=X.length;let Z=new Uint8Array(Y),w=0;for(let X of $)Z.set(X,w),w+=X.length;return Z}var e9;function E1($){let Y;return(e9??(Y=new globalThis.TextEncoder,e9=Y.encode.bind(Y)))($)}var $6;function e3($){let Y;return($6??(Y=new globalThis.TextDecoder,$6=Y.decode.bind(Y)))($)}var Q$,N$;class L1{constructor(){Q$.set(this,void 0),N$.set(this,void 0),k(this,Q$,new Uint8Array,"f"),k(this,N$,null,"f")}decode($){if($==null)return[];let Y=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?E1($):$;k(this,Q$,Y6([B(this,Q$,"f"),Y]),"f");let Z=[],w;while((w=k8(B(this,Q$,"f"),B(this,N$,"f")))!=null){if(w.carriage&&B(this,N$,"f")==null){k(this,N$,w.index,"f");continue}if(B(this,N$,"f")!=null&&(w.index!==B(this,N$,"f")+1||w.carriage)){Z.push(e3(B(this,Q$,"f").subarray(0,B(this,N$,"f")-1))),k(this,Q$,B(this,Q$,"f").subarray(B(this,N$,"f")),"f"),k(this,N$,null,"f");continue}let X=B(this,N$,"f")!==null?w.preceding-1:w.preceding,W=e3(B(this,Q$,"f").subarray(0,X));Z.push(W),k(this,Q$,B(this,Q$,"f").subarray(w.index),"f"),k(this,N$,null,"f")}return Z}flush(){if(!B(this,Q$,"f").length)return[];return this.decode(`
153
- `)}}Q$=new WeakMap,N$=new WeakMap;L1.NEWLINE_CHARS=new Set([`
154
- `,"\r"]);L1.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function k8($,Y){for(let X=Y??0;X<$.length;X++){if($[X]===10)return{preceding:X,index:X+1,carriage:!1};if($[X]===13)return{preceding:X,index:X+1,carriage:!0}}return null}function Z6($){for(let w=0;w<$.length-1;w++){if($[w]===10&&$[w+1]===10)return w+2;if($[w]===13&&$[w+1]===13)return w+2;if($[w]===13&&$[w+1]===10&&w+3<$.length&&$[w+2]===13&&$[w+3]===10)return w+4}return-1}var a2={off:0,error:200,warn:300,info:400,debug:500},$4=($,Y,Z)=>{if(!$)return;if(v9(a2,$))return $;c(Z).warn(`${Y} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(a2))}`);return};function H0(){}function n2($,Y,Z){if(!Y||a2[$]>a2[Z])return H0;else return Y[$].bind(Y)}var C8={error:H0,warn:H0,info:H0,debug:H0},w6=new WeakMap;function c($){let Y=$.logger,Z=$.logLevel??"off";if(!Y)return C8;let w=w6.get(Y);if(w&&w[0]===Z)return w[1];let X={error:n2("error",Y,Z),warn:n2("warn",Y,Z),info:n2("info",Y,Z),debug:n2("debug",Y,Z)};return w6.set(Y,[Z,X]),X}var P$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([Y,Z])=>[Y,Y.toLowerCase()==="authorization"||Y.toLowerCase()==="api-key"||Y.toLowerCase()==="x-api-key"||Y.toLowerCase()==="cookie"||Y.toLowerCase()==="set-cookie"?"***":Z]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var T0;class z${constructor($,Y,Z){this.iterator=$,T0.set(this,void 0),this.controller=Y,k(this,T0,Z,"f")}static fromSSEResponse($,Y,Z,w){let X=!1,W=Z?c(Z):console;async function*G(){if(X)throw new O("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let Q=!1;try{for await(let z of S8($,Y)){if(Q)continue;if(z.data.startsWith("[DONE]")){Q=!0;continue}if(z.event===null||!z.event.startsWith("thread.")){let H;try{H=JSON.parse(z.data)}catch(T){throw W.error("Could not parse message into JSON:",z.data),W.error("From chunk:",z.raw),T}if(H&&H.error)throw new g(void 0,H.error,void 0,$.headers);yield w?{event:z.event,data:H}:H}else{let H;try{H=JSON.parse(z.data)}catch(T){throw console.error("Could not parse message into JSON:",z.data),console.error("From chunk:",z.raw),T}if(z.event=="error")throw new g(void 0,H.error,H.message,void 0);yield{event:z.event,data:H}}}Q=!0}catch(z){if(Y0(z))return;throw z}finally{if(!Q)Y.abort()}}return new z$(G,Y,Z)}static fromReadableStream($,Y,Z){let w=!1;async function*X(){let G=new L1,Q=p3($);for await(let z of Q)for(let H of G.decode(z))yield H;for(let z of G.flush())yield z}async function*W(){if(w)throw new O("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");w=!0;let G=!1;try{for await(let Q of X()){if(G)continue;if(Q)yield JSON.parse(Q)}G=!0}catch(Q){if(Y0(Q))return;throw Q}finally{if(!G)Y.abort()}}return new z$(W,Y,Z)}[(T0=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],Y=[],Z=this.iterator(),w=(X)=>{return{next:()=>{if(X.length===0){let W=Z.next();$.push(W),Y.push(W)}return X.shift()}}};return[new z$(()=>w($),this.controller,B(this,T0,"f")),new z$(()=>w(Y),this.controller,B(this,T0,"f"))]}toReadableStream(){let $=this,Y;return l3({async start(){Y=$[Symbol.asyncIterator]()},async pull(Z){try{let{value:w,done:X}=await Y.next();if(X)return Z.close();let W=E1(JSON.stringify(w)+`
155
- `);Z.enqueue(W)}catch(w){Z.error(w)}},async cancel(){await Y.return?.()}})}}async function*S8($,Y){if(!$.body){if(Y.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new O("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 O("Attempted to iterate over a response with no body")}let Z=new G6,w=new L1,X=p3($.body);for await(let W of R8(X))for(let G of w.decode(W)){let Q=Z.decode(G);if(Q)yield Q}for(let W of w.flush()){let G=Z.decode(W);if(G)yield G}}async function*R8($){let Y=new Uint8Array;for await(let Z of $){if(Z==null)continue;let w=Z instanceof ArrayBuffer?new Uint8Array(Z):typeof Z==="string"?E1(Z):Z,X=new Uint8Array(Y.length+w.length);X.set(Y),X.set(w,Y.length),Y=X;let W;while((W=Z6(Y))!==-1)yield Y.slice(0,W),Y=Y.slice(W)}if(Y.length>0)yield Y}class G6{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 X={event:this.event,data:this.data.join(`
156
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push($),$.startsWith(":"))return null;let[Y,Z,w]=P8($,":");if(w.startsWith(" "))w=w.substring(1);if(Y==="event")this.event=w;else if(Y==="data")this.data.push(w);return null}}function P8($,Y){let Z=$.indexOf(Y);if(Z!==-1)return[$.substring(0,Z),Y,$.substring(Z+Y.length)];return[$,"",""]}async function t2($,Y){let{response:Z,requestLogID:w,retryOfRequestLogID:X,startTime:W}=Y,G=await(async()=>{if(Y.options.stream){if(c($).debug("response",Z.status,Z.url,Z.headers,Z.body),Y.options.__streamClass)return Y.options.__streamClass.fromSSEResponse(Z,Y.controller,$,Y.options.__synthesizeEventData);return z$.fromSSEResponse(Z,Y.controller,$,Y.options.__synthesizeEventData)}if(Z.status===204)return null;if(Y.options.__binaryResponse)return Z;let z=Z.headers.get("content-type")?.split(";")[0]?.trim();if(z?.includes("application/json")||z?.endsWith("+json")){if(Z.headers.get("content-length")==="0")return;let U=await Z.json();return Y4(U,Z)}return await Z.text()})();return c($).debug(`[${w}] response parsed`,P$({retryOfRequestLogID:X,url:Z.url,status:Z.status,body:G,durationMs:Date.now()-W})),G}function Y4($,Y){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Y.headers.get("x-request-id"),enumerable:!1})}var U0;class s$ extends Promise{constructor($,Y,Z=t2){super((w)=>{w(null)});this.responsePromise=Y,this.parseResponse=Z,U0.set(this,void 0),k(this,U0,$,"f")}_thenUnwrap($){return new s$(B(this,U0,"f"),this.responsePromise,async(Y,Z)=>Y4($(await this.parseResponse(Y,Z),Z),Z.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,Y]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:Y,request_id:Y.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(B(this,U0,"f"),$));return this.parsedPromise}then($,Y){return this.parse().then($,Y)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}U0=new WeakMap;var r2;class M0{constructor($,Y,Z,w){r2.set(this,void 0),k(this,r2,$,"f"),this.options=w,this.response=Y,this.body=Z}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new O("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await B(this,r2,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(r2=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Y of $.getPaginatedItems())yield Y}}class s2 extends s${constructor($,Y,Z){super($,Y,async(w,X)=>new Z(w,X.response,await t2(w,X),X.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Y of $)yield Y}}class Z$ extends M0{constructor($,Y,Z,w){super($,Y,Z,w);this.data=Z.data||[],this.object=Z.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class S extends M0{constructor($,Y,Z,w){super($,Y,Z,w);this.data=Z.data||[],this.has_more=Z.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.getPaginatedItems(),Y=$[$.length-1]?.id;if(!Y)return null;return{...this.options,query:{...u2(this.options.query),after:Y}}}}class f extends M0{constructor($,Y,Z,w){super($,Y,Z,w);this.data=Z.data||[],this.has_more=Z.has_more||!1,this.last_id=Z.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:{...u2(this.options.query),after:$}}}}class l extends M0{constructor($,Y,Z,w){super($,Y,Z,w);this.data=Z.data||[],this.has_more=Z.has_more||!1,this.next=Z.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:{...u2(this.options.query),after:$}}}}var A8={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},f8="urn:ietf:params:oauth:grant-type:token-exchange";class Z4{constructor($,Y){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=$,this.fetch=Y??l2()}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(),Y={grant_type:f8,subject_token:$,subject_token_type:A8[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};if(this.config.clientId)Y.client_id=this.config.clientId;let Z=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)});if(!Z.ok){let G=await Z.text(),Q=void 0;try{Q=JSON.parse(G)}catch{}if(Z.status===400||Z.status===401||Z.status===403)throw new O1(Z.status,Q,Z.headers);throw g.generate(Z.status,Q,`Token exchange failed with status ${Z.status}`,Z.headers)}let w=await Z.json(),X=w.expires_in||3600,W=Date.now()+X*1000;return this.cachedToken={token:w.access_token,expiresAt:W},w.access_token}isTokenExpired($){return Date.now()>=$.expiresAt}needsRefresh($){let Z=(this.config.refreshBufferSeconds??1200)*1000;return Date.now()>=$.expiresAt-Z}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}}var X4=()=>{if(typeof File>"u"){let{process:$}=globalThis,Y=typeof $?.versions?.node==="string"&&parseInt($.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(Y?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function F1($,Y,Z){return X4(),new File($,Y??"unknown_file",Z)}function x0($){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 o2=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function",h$=async($,Y)=>{if(!w4($.body))return $;return{...$,body:await W6($.body,Y)}},t=async($,Y)=>{return{...$,body:await W6($.body,Y)}},X6=new WeakMap;function j8($){let Y=typeof $==="function"?$:$.fetch,Z=X6.get(Y);if(Z)return Z;let w=(async()=>{try{let X="Response"in Y?Y.Response:(await Y("data:,")).constructor,W=new FormData;if(W.toString()===await new X(W).text())return!1;return!0}catch{return!0}})();return X6.set(Y,w),w}var W6=async($,Y)=>{if(!await j8(Y))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let Z=new FormData;return await Promise.all(Object.entries($||{}).map(([w,X])=>G4(Z,w,X))),Z},J6=($)=>$ instanceof Blob&&("name"in $),b8=($)=>typeof $==="object"&&$!==null&&($ instanceof Response||o2($)||J6($)),w4=($)=>{if(b8($))return!0;if(Array.isArray($))return $.some(w4);if($&&typeof $==="object"){for(let Y in $)if(w4($[Y]))return!0}return!1},G4=async($,Y,Z)=>{if(Z===void 0)return;if(Z==null)throw TypeError(`Received null for "${Y}"; to pass null in FormData, you must use the string 'null'`);if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")$.append(Y,String(Z));else if(Z instanceof Response)$.append(Y,F1([await Z.blob()],x0(Z)));else if(o2(Z))$.append(Y,F1([await new Response(p2(Z)).blob()],x0(Z)));else if(J6(Z))$.append(Y,Z,x0(Z));else if(Array.isArray(Z))await Promise.all(Z.map((w)=>G4($,Y+"[]",w)));else if(typeof Z==="object")await Promise.all(Object.entries(Z).map(([w,X])=>G4($,`${Y}[${w}]`,X)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Z} instead`)};var Q6=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",v8=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&Q6($),y8=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function e2($,Y,Z){if(X4(),$=await $,v8($)){if($ instanceof File)return $;return F1([await $.arrayBuffer()],$.name)}if(y8($)){let X=await $.blob();return Y||(Y=new URL($.url).pathname.split(/[\\/]/).pop()),F1(await W4(X),Y,Z)}let w=await W4($);if(Y||(Y=x0($)),!Z?.type){let X=w.find((W)=>typeof W==="object"&&("type"in W)&&W.type);if(typeof X==="string")Z={...Z,type:X}}return F1(w,Y,Z)}async function W4($){let Y=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Y.push($);else if(Q6($))Y.push($ instanceof Blob?$:await $.arrayBuffer());else if(o2($))for await(let Z of $)Y.push(...await W4(Z));else{let Z=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Z?`; constructor: ${Z}`:""}${I8($)}`)}return Y}function I8($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Z)=>`"${Z}"`).join(", ")}]`}class N{constructor($){this._client=$}}function z6($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var N6=Object.freeze(Object.create(null)),h8=($=z6)=>function(Z,...w){if(Z.length===1)return Z[0];let X=!1,W=[],G=Z.reduce((T,K,U)=>{if(/[?#]/.test(K))X=!0;let M=w[U],q=(X?encodeURIComponent:$)(""+M);if(U!==w.length&&(M==null||typeof M==="object"&&M.toString===Object.getPrototypeOf(Object.getPrototypeOf(M.hasOwnProperty??N6)??N6)?.toString))q=M+"",W.push({start:T.length+K.length,length:q.length,error:`Value of type ${Object.prototype.toString.call(M).slice(8,-1)} is not a valid path parameter`});return T+K+(U===w.length?"":q)},""),Q=G.split(/[?#]/,1)[0],z=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,H;while((H=z.exec(Q))!==null)W.push({start:H.index,length:H[0].length,error:`Value "${H[0]}" can't be safely passed as a path parameter`});if(W.sort((T,K)=>T.start-K.start),W.length>0){let T=0,K=W.reduce((U,M)=>{let q=" ".repeat(M.start-T),P="^".repeat(M.length);return T=M.start+M.length,U+q+P},"");throw new O(`Path parameters result in path with invalid segments:
114
+ ${_.default.gray(Q8+U9.repeat(X+2)+z8)}
115
+ `)};var O9=($="")=>{process.stdout.write(`${_.default.gray(W8)} ${$}
116
+ `)},m3=($="")=>{process.stdout.write(`${_.default.gray(T$)}
117
+ ${_.default.gray(h3)} ${$}
118
+
119
+ `)};var E9=()=>{let $=D3?["◒","◐","◓","◑"]:["•","o","O","0"],Y=D3?80:120,Z,w,X=!1,W="",G=(T="")=>{X=!0,Z=T9(),W=T.replace(/\.+$/,""),process.stdout.write(`${_.default.gray(T$)}
120
+ `);let K=0,U=0;w=setInterval(()=>{let M=_.default.magenta($[K]),q=".".repeat(Math.floor(U)).slice(0,3);process.stdout.write(x1.cursor.move(-999,0)),process.stdout.write(x1.erase.down(1)),process.stdout.write(`${M} ${W}${q}`),K=K+1<$.length?K+1:0,U=U<$.length?U+0.125:0},Y)},Q=(T="",K=0)=>{W=T??W,X=!1,clearInterval(w);let U=K===0?_.default.green(g3):K===1?_.default.red(M9):_.default.red(x9);process.stdout.write(x1.cursor.move(-999,0)),process.stdout.write(x1.erase.down(1)),process.stdout.write(`${U} ${W}
121
+ `),Z()},V=(T="")=>{W=T??W},H=(T)=>{let K=T>1?"Something went wrong":"Canceled";X&&Q(K,T)};return process.on("uncaughtExceptionMonitor",()=>H(2)),process.on("unhandledRejection",()=>H(2)),process.on("SIGINT",()=>H(1)),process.on("SIGTERM",()=>H(1)),process.on("exit",H),{start:G,stop:Q,message:V}};function V8(){let $=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp($,"g")}function $0(){return process.stdout.isTTY===!0}async function L9($,Y){let Z=await c2({message:$,placeholder:Y?.placeholder});if(M1(Z))throw Error("Operation cancelled");let w=Z.trim();if(!w)throw Error("Input cannot be empty");return w}async function F9($){if($.apiKey||$.fileApiKey||$.fileSkApiKey)return;if(process.env.MIMO_API_KEY)return;if(!$0())throw new L(z("auth.noCreds"),E.AUTH,z("auth.noCredsHint"));process.stderr.write(`
122
+ `+z("main.notLoggedIn")+`
123
+ `),process.stderr.write(z("main.loginHint1")+`
124
+ `),process.stderr.write(z("main.loginHint2")+`
125
+
126
+ `),process.exit(E.AUTH)}async function k9($,Y){let Z={...K$()};if(Y.startsWith("tp-"))Z.api_key=Y,Z.active_key="tp";else Z.sk_api_key=Y,Z.active_key="sk";let w=S$(Y);if(w)Z.base_url=w;else Z.base_url="https://api.xiaomimimo.com/v1";await y$(Z),$.fileApiKey=Z.api_key,$.fileSkApiKey=Z.sk_api_key,$.activeKey=Z.active_key;let X=Y.startsWith("tp-")?"TokenPlan":"按量计费";if(process.stderr.write(`${z("auth.keySaved")} ${$.configPath??"~/.mimo/config.json"} (${J$(Y)}, ${X})
127
+ `),w)process.stderr.write(`${z("auth.baseUrlAuto")}${w}
128
+ `)}async function C9(){process.stderr.write(`
129
+ `+z("auth.promptTitle")+`
130
+ `),process.stderr.write(" "+z("auth.promptPayKey")+`
131
+ `),process.stderr.write(" "+z("auth.promptTpKey")+`
132
+
133
+ `);let $=await L9(z("auth.promptLabel"));if(!$)throw new L(z("auth.keyRequired"),E.AUTH);return $}var q1="0.1.8";var S9=f({name:"auth login",description:"cmd.authLogin.desc",usage:"mimo auth login [--api-key <key>]",options:[{flag:"--api-key <key>",description:"flag.auth.apiKey"}],examples:["mimo auth login","mimo auth login --api-key sk-xxxxx # 按量计费 Key","mimo auth login --api-key tp-xxxxx # TokenPlan Key"],async run($,Y){let Z=Y.apiKey;if(!Z){if(!$0())throw new L(z("auth.noKeyProvided"),E.AUTH,z("auth.noKeyHint"));Z=await C9()}if(!Z||Z.trim().length===0)throw new L(z("auth.keyEmpty"),E.AUTH);await k9($,Z.trim())}});var R9=f({name:"auth status",description:"cmd.authStatus.desc",usage:"mimo auth status",async run($,Y){try{let Z=v2($),w=Z.token.startsWith("tp-")?"TokenPlan":"按量计费",X=S$(Z.token),W={authenticated:!0,method:Z.method,activeKey:$.activeKey??"tp",apiKey:J$(Z.token),keyType:w,baseUrl:$.baseUrl||X||"https://api.xiaomimimo.com/v1",source:Z.source,configPath:$.configPath};if($.activeKey==="tp"&&$.fileSkApiKey)W.standbyKey=J$($.fileSkApiKey)+" (按量计费)";else if($.activeKey==="sk"&&$.fileApiKey)W.standbyKey=J$($.fileApiKey)+" (TokenPlan)";console.log(W$(W,$))}catch(Z){if($.verbose)process.stderr.write(`Debug: credential resolution failed — ${Z instanceof Error?Z.message:String(Z)}
134
+ `);let w={authenticated:!1,method:null,activeKey:$.activeKey??"tp",apiKey:null,keyType:null,baseUrl:$.baseUrl||"https://api.xiaomimimo.com/v1",source:null,configPath:$.configPath};console.log(W$(w,$))}}});var P9=f({name:"auth logout",description:"cmd.authLogout.desc",usage:"mimo auth logout",async run($,Y){let Z=K$();if(!Z.api_key&&!Z.sk_api_key){process.stderr.write(z("auth.logoutNoKey")+`
135
+ `);return}delete Z.api_key,delete Z.sk_api_key,delete Z.active_key,await y$(Z),$.fileApiKey=void 0,$.fileSkApiKey=void 0,$.activeKey=void 0,process.stderr.write(z("auth.logoutDone")+`
136
+ `)}});var B8=new Set(["api_key","apiKey","api-key","sk_api_key","skApiKey","sk-api-key"]),_9=f({name:"config show",description:"cmd.configShow.desc",usage:"mimo config show",async run($,Y){let Z=K$(),w={baseUrl:$.baseUrl,output:$.output,timeout:$.timeout,defaultModel:$.defaultModel??z("general.notSet"),activeKey:$.activeKey??"tp",configPath:$.configPath};if(Z.api_key)w.tpApiKey=J$(Z.api_key)+" (TokenPlan)";else w.tpApiKey=z("general.notSet");if(Z.sk_api_key)w.skApiKey=J$(Z.sk_api_key)+" (按量计费)";else w.skApiKey=z("general.notSet");if(Z.base_url)w.fileBaseUrl=Z.base_url;for(let[X,W]of Object.entries(Z))if(X!=="api_key"&&X!=="sk_api_key"&&X!=="base_url"&&X!=="active_key"&&B8.has(X)&&typeof W==="string")w[X]=J$(W);console.log(W$(w,$))}});var A9=new Set(["api_key","sk_api_key","active_key","base_url","output","timeout","default_model","language"]),K8=/^[a-zA-Z0-9_]+$/,f9=f({name:"config set",description:"cmd.configSet.desc",usage:"mimo config set --key <key> --value <value>",options:[{flag:"--key <key>",description:"flag.config.key",required:!0},{flag:"--value <value>",description:"flag.config.value",required:!0}],examples:["mimo config set --key base_url --value https://api.xiaomimimo.com/v1","mimo config set --key output --value json","mimo config set --key timeout --value 60","mimo config set --key default_model --value MiMo-7B-RL"],async run($,Y){let{key:Z,value:w}=Y;if(!Z)throw new L(z("config.keyRequired"),E.USAGE);if(!K8.test(Z))throw new L(z("config.invalidKey")+'"'+Z+'"',E.INVALID_INPUT,z("config.invalidKeyChars"));if(!A9.has(Z))throw new L(z("config.invalidKey")+'"'+Z+'"',E.USAGE,z("config.validKeys")+Array.from(A9).join(", "));if(w===void 0||w==="")throw new L(z("config.valueRequired"),E.USAGE);let X=K$();if(Z==="timeout"){let G=Number(w);if(!Number.isFinite(G)||G<=0)throw new L(z("config.setTimeout"),E.USAGE);X[Z]=G}else if(Z==="output"&&w!=="text"&&w!=="json")throw new L(z("config.setOutput"),E.USAGE);else if(Z==="active_key"&&w!=="tp"&&w!=="sk")throw new L(z("config.invalidActiveKey"),E.USAGE);else X[Z]=w;if(Z==="active_key"){let G=w==="sk"?X.sk_api_key:X.api_key;if(typeof G==="string"){let Q=G.startsWith("tp-")?"https://token-plan-cn.xiaomimimo.com/v1":"https://api.xiaomimimo.com/v1";X.base_url=Q}}await y$(X);let W=Z==="api_key"||Z==="sk_api_key"?J$(String(w)):w;process.stderr.write(z("config.setDone")+" "+Z+" = "+W+`
137
+ `)}});import{exec as H8}from"node:child_process";var T8="https://registry.npmjs.org/mimo-cli/latest";function U8($){return new Promise((Y,Z)=>{H8($,{timeout:120000},(w,X,W)=>{if(w)return Z(w);Y((X||"").trim())})})}function M8($,Y){let Z=$.replace(/^v/,"").split(".").map(Number),w=Y.replace(/^v/,"").split(".").map(Number);for(let X=0;X<3;X++){if((Z[X]??0)>(w[X]??0))return 1;if((Z[X]??0)<(w[X]??0))return-1}return 0}var j9=f({name:"update",description:"cmd.update.desc",usage:"mimo update",async run(){process.stderr.write(z("update.checking")+`
138
+ `);let $;try{let Z=await fetch(T8);if(!Z.ok)throw Error(`HTTP ${Z.status}`);$=(await Z.json()).version}catch{process.stderr.write(z("update.checkFailed")+`
139
+ `),process.stderr.write(z("update.manualHint")+`
140
+ `);return}let Y=q1.replace(/^v/,"");if(process.stderr.write(z("update.currentVersion",{version:Y})+`
141
+ `),process.stderr.write(z("update.latestVersion",{version:$})+`
142
+ `),M8($,Y)<=0){process.stderr.write(z("update.alreadyLatest")+`
143
+ `);return}process.stderr.write(z("update.updating",{version:$})+`
144
+ `);try{let Z=await U8("npm install -g mimo-cli@latest");if(Z)process.stderr.write(Z+`
145
+ `);process.stderr.write(z("update.success",{version:$})+`
146
+ `)}catch{process.stderr.write(z("update.installFailed")+`
147
+ `),process.stderr.write(z("update.manualHint")+`
148
+ `)}}});var b9=f({name:"help",description:"cmd.help.desc",usage:"mimo help [command]",options:[{flag:"--command <path>",description:"flag.help.command"}],async run($,Y){let Z=typeof Y.command==="string"?Y.command.split(" "):[];D.printHelp(Z)}});var v9=f({name:"language",description:"cmd.language.desc",usage:"mimo language <zh|en>",options:[],examples:["mimo language zh","mimo language en"],async run($,Y){let w=Y._positional?.[0];if(!w){process.stderr.write(z("language.current")+m4()+`
149
+ `);return}if(w!=="zh"&&w!=="en")process.stderr.write(z("language.invalid")+`
150
+ `),process.stderr.write(z("language.hint")+`
151
+ `),process.exit(2);let X=K$();X.language=w,await y$(X),c4(w),process.stderr.write(z("language.changed")+`
152
+ `)}});import{execSync as x8,spawn as q8}from"child_process";import{existsSync as O8,writeFileSync as E8,renameSync as L8}from"fs";import{join as d2}from"path";var F8=d2(process.env.LOCALAPPDATA||d2(process.env.USERPROFILE||"C:\\","AppData","Local"),"mimo"),d3=d2(F8,"mimo.exe"),y9=f({name:"uninstall",description:"cmd.uninstall.desc",usage:"mimo uninstall",async run($,Y){if(!O8(d3)){process.stdout.write(`
153
+ ${z("uninstall.notFound")}
154
+ `),process.stdout.write(` ${z("uninstall.npmHint")}
155
+
156
+ `);return}if(process.stdout.write(`
157
+ `),process.stdout.write(` ${z("uninstall.header")}
158
+
159
+ `),k8())process.stdout.write(` ✓ ${z("uninstall.pathRemoved")}
160
+ `);else process.stdout.write(` ✓ ${z("uninstall.pathNotPresent")}
161
+ `);process.stdout.write(` ✓ ${z("uninstall.keepConfig")}
162
+ `);try{L8(d3,d3+".old")}catch{}let X=d2(process.env.TEMP||"C:\\Temp","mimo_uninstall.bat");E8(X,`@echo off\r
163
+ timeout /t 5 /nobreak >nul\r
164
+ rmdir /s /q "%LOCALAPPDATA%\\mimo"\r
165
+ del "%~f0"`,"latin1"),q8("cmd.exe",["/c",X],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),process.stdout.write(`
166
+ ${z("uninstall.done")}
167
+
168
+ `),process.stdout.write(` ${z("uninstall.restartHint")}
169
+
170
+ `)}});function k8(){try{let $=`
171
+ $dir = [Environment]::GetFolderPath('LocalApplicationData') + '\\mimo'
172
+ $p = [Environment]::GetEnvironmentVariable('Path', 'User')
173
+ $parts = $p -split ';' | ForEach-Object { $_.Trim() }
174
+ $newParts = $parts | Where-Object { $_ -ne $dir }
175
+ $newPath = $newParts -join ';'
176
+ if ($newPath -ne $p) {
177
+ [Environment]::SetEnvironmentVariable('Path', $newPath, 'User')
178
+ Write-Output 'REMOVED'
179
+ } else {
180
+ Write-Output 'NOTFOUND'
181
+ }
182
+ `.trim(),Y=Buffer.from($,"utf16le").toString("base64");return x8(`powershell -NoProfile -EncodedCommand ${Y}`,{windowsHide:!0,encoding:"utf-8",timeout:1e4}).trim()==="REMOVED"}catch{return!1}}function k($,Y,Z,w,X){if(w==="m")throw TypeError("Private method is not writable");if(w==="a"&&!X)throw TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?$!==Y||!X:!Y.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return w==="a"?X.call($,Z):X?X.value=Z:Y.set($,Z),Z}function B($,Y,Z,w){if(Z==="a"&&!w)throw TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?$!==Y||!w:!Y.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?w:Z==="a"?w.call($):w?w.value:Y.get($)}var u3=function(){let{crypto:$}=globalThis;if($?.randomUUID)return u3=$.randomUUID.bind($),$.randomUUID();let Y=new Uint8Array(1),Z=$?()=>$.getRandomValues(Y)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(w)=>(+w^Z()&15>>+w/4).toString(16))};function Y0($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var Z0=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let Y=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)Y.stack=$.stack;if($.cause&&!Y.cause)Y.cause=$.cause;if($.name)Y.name=$.name;return Y}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class O extends Error{}class g extends O{constructor($,Y,Z,w){super(`${g.makeMessage($,Y,Z)}`);this.status=$,this.headers=w,this.requestID=w?.get("x-request-id"),this.error=Y;let X=Y;this.code=X?.code,this.param=X?.param,this.type=X?.type}static makeMessage($,Y,Z){let w=Y?.message?typeof Y.message==="string"?Y.message:JSON.stringify(Y.message):Y?JSON.stringify(Y):Z;if($&&w)return`${$} ${w}`;if($)return`${$} status code (no body)`;if(w)return w;return"(no status code or body)"}static generate($,Y,Z,w){if(!$||!w)return new t$({message:Z,cause:Z0(Y)});let X=Y?.error;if($===400)return new w0($,X,Z,w);if($===401)return new G0($,X,Z,w);if($===403)return new X0($,X,Z,w);if($===404)return new W0($,X,Z,w);if($===409)return new J0($,X,Z,w);if($===422)return new Q0($,X,Z,w);if($===429)return new z0($,X,Z,w);if($>=500)return new N0($,X,Z,w);return new g($,X,Z,w)}}class d extends g{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class t$ extends g{constructor({message:$,cause:Y}){super(void 0,void 0,$||"Connection error.",void 0);if(Y)this.cause=Y}}class r$ extends t${constructor({message:$}={}){super({message:$??"Request timed out."})}}class w0 extends g{}class G0 extends g{}class X0 extends g{}class W0 extends g{}class J0 extends g{}class Q0 extends g{}class z0 extends g{}class N0 extends g{}class V0 extends O{constructor(){super("Could not parse response content as the length limit was reached")}}class B0 extends O{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class R$ extends Error{constructor($){super($)}}class O1 extends g{constructor($,Y,Z){let w="OAuth2 authentication error",X=void 0;if(Y&&typeof Y==="object"){let W=Y;X=W.error;let G=W.error_description;if(G&&typeof G==="string")w=G;else if(X)w=X}super($,Y,w,Z);this.error_code=X}}class u2 extends O{constructor($,Y,Z){super($);this.provider=Y,this.cause=Z}}var S8=/^[a-z][a-z0-9+.-]*:/i,I9=($)=>{return S8.test($)},a=($)=>(a=Array.isArray,a($)),l3=a;function l2($){if(typeof $!=="object")return{};return $??{}}function p3($){if(!$)return!0;for(let Y in $)return!1;return!0}function D9($,Y){return Object.prototype.hasOwnProperty.call($,Y)}function K0($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var h9=($,Y)=>{if(typeof Y!=="number"||!Number.isInteger(Y))throw new O(`${$} must be an integer`);if(Y<0)throw new O(`${$} must be a positive integer`);return Y};var g9=($)=>{try{return JSON.parse($)}catch(Y){return}};var q$=($)=>new Promise((Y)=>setTimeout(Y,$));var D$="6.42.0";var u9=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function R8(){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 P8=()=>{let $=R8();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":D$,"X-Stainless-OS":c9(Deno.build.os),"X-Stainless-Arch":m9(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":D$,"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":D$,"X-Stainless-OS":c9(globalThis.process.platform??"unknown"),"X-Stainless-Arch":m9(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Y=_8();if(Y)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":D$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Y.browser}`,"X-Stainless-Runtime-Version":Y.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":D$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function _8(){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:Y,pattern:Z}of $){let w=Z.exec(navigator.userAgent);if(w){let X=w[1]||0,W=w[2]||0,G=w[3]||0;return{browser:Y,version:`${X}.${W}.${G}`}}}return null}var m9=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},c9=($)=>{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"},d9,l9=()=>{return d9??(d9=P8())};function p2(){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 i3(...$){let Y=globalThis.ReadableStream;if(typeof Y>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Y(...$)}function i2($){let Y=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return i3({start(){},async pull(Z){let{done:w,value:X}=await Y.next();if(w)Z.close();else Z.enqueue(X)},async cancel(){await Y.return?.()}})}function n3($){if($[Symbol.asyncIterator])return $;let Y=$.getReader();return{async next(){try{let Z=await Y.read();if(Z?.done)Y.releaseLock();return Z}catch(Z){throw Y.releaseLock(),Z}},async return(){let Z=Y.cancel();return Y.releaseLock(),await Z,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function a3($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Y=$.getReader(),Z=Y.cancel();Y.releaseLock(),await Z}var i9=({headers:$,body:Y})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Y)}};var t3="RFC3986",r3=($)=>String($),s3={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:r3},n9="RFC1738";var n2=($,Y)=>(n2=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),n2($,Y)),O$=(()=>{let $=[];for(let Y=0;Y<256;++Y)$.push("%"+((Y<16?"0":"")+Y.toString(16)).toUpperCase());return $})();var o3=1024,a9=($,Y,Z,w,X)=>{if($.length===0)return $;let W=$;if(typeof $==="symbol")W=Symbol.prototype.toString.call($);else if(typeof $!=="string")W=String($);if(Z==="iso-8859-1")return escape(W).replace(/%u[0-9a-f]{4}/gi,function(Q){return"%26%23"+parseInt(Q.slice(2),16)+"%3B"});let G="";for(let Q=0;Q<W.length;Q+=o3){let V=W.length>=o3?W.slice(Q,Q+o3):W,H=[];for(let T=0;T<V.length;++T){let K=V.charCodeAt(T);if(K===45||K===46||K===95||K===126||K>=48&&K<=57||K>=65&&K<=90||K>=97&&K<=122||X===n9&&(K===40||K===41)){H[H.length]=V.charAt(T);continue}if(K<128){H[H.length]=O$[K];continue}if(K<2048){H[H.length]=O$[192|K>>6]+O$[128|K&63];continue}if(K<55296||K>=57344){H[H.length]=O$[224|K>>12]+O$[128|K>>6&63]+O$[128|K&63];continue}T+=1,K=65536+((K&1023)<<10|V.charCodeAt(T)&1023),H[H.length]=O$[240|K>>18]+O$[128|K>>12&63]+O$[128|K>>6&63]+O$[128|K&63]}G+=H.join("")}return G};function t9($){if(!$||typeof $!=="object")return!1;return!!($.constructor&&$.constructor.isBuffer&&$.constructor.isBuffer($))}function e3($,Y){if(a($)){let Z=[];for(let w=0;w<$.length;w+=1)Z.push(Y($[w]));return Z}return Y($)}var s9={brackets($){return String($)+"[]"},comma:"comma",indices($,Y){return String($)+"["+Y+"]"},repeat($){return String($)}},o9=function($,Y){Array.prototype.push.apply($,a(Y)?Y:[Y])},r9,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:a9,encodeValuesOnly:!1,format:t3,formatter:r3,indices:!1,serializeDate($){return(r9??(r9=Function.prototype.call.bind(Date.prototype.toISOString)))($)},skipNulls:!1,strictNullHandling:!1};function f8($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}var $4={};function e9($,Y,Z,w,X,W,G,Q,V,H,T,K,U,M,q,P,A,R){let F=$,b=R,v=0,o=!1;while((b=b.get($4))!==void 0&&!o){let y=b.get($);if(v+=1,typeof y<"u")if(y===v)throw RangeError("Cyclic object value");else o=!0;if(typeof b.get($4)>"u")v=0}if(typeof H==="function")F=H(Y,F);else if(F instanceof Date)F=U?.(F);else if(Z==="comma"&&a(F))F=e3(F,function(y){if(y instanceof Date)return U?.(y);return y});if(F===null){if(W)return V&&!P?V(Y,u.encoder,A,"key",M):Y;F=""}if(f8(F)||t9(F)){if(V){let y=P?Y:V(Y,u.encoder,A,"key",M);return[q?.(y)+"="+q?.(V(F,u.encoder,A,"value",M))]}return[q?.(Y)+"="+q?.(String(F))]}let e=[];if(typeof F>"u")return e;let I;if(Z==="comma"&&a(F)){if(P&&V)F=e3(F,V);I=[{value:F.length>0?F.join(",")||null:void 0}]}else if(a(H))I=H;else{let y=Object.keys(F);I=T?y.sort(T):y}let $$=Q?String(Y).replace(/\./g,"%2E"):String(Y),k$=w&&a(F)&&F.length===1?$$+"[]":$$;if(X&&a(F)&&F.length===0)return k$+"[]";for(let y=0;y<I.length;++y){let b$=I[y],A4=typeof b$==="object"&&typeof b$.value<"u"?b$.value:F[b$];if(G&&A4===null)continue;let F3=K&&Q?b$.replace(/\./g,"%2E"):b$,V5=a(F)?typeof Z==="function"?Z(k$,F3):k$:k$+(K?"."+F3:"["+F3+"]");R.set($,v);let f4=new WeakMap;f4.set($4,R),o9(e,e9(A4,V5,Z,w,X,W,G,Q,Z==="comma"&&P&&a(F)?null:V,H,T,K,U,M,q,P,A,f4))}return e}function j8($=u){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 Y=$.charset||u.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 Z=t3;if(typeof $.format<"u"){if(!n2(s3,$.format))throw TypeError("Unknown format option provided.");Z=$.format}let w=s3[Z],X=u.filter;if(typeof $.filter==="function"||a($.filter))X=$.filter;let W;if($.arrayFormat&&$.arrayFormat in s9)W=$.arrayFormat;else if("indices"in $)W=$.indices?"indices":"repeat";else W=u.arrayFormat;if("commaRoundTrip"in $&&typeof $.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let G=typeof $.allowDots>"u"?!!$.encodeDotInKeys===!0?!0:u.allowDots:!!$.allowDots;return{addQueryPrefix:typeof $.addQueryPrefix==="boolean"?$.addQueryPrefix:u.addQueryPrefix,allowDots:G,allowEmptyArrays:typeof $.allowEmptyArrays==="boolean"?!!$.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:W,charset:Y,charsetSentinel:typeof $.charsetSentinel==="boolean"?$.charsetSentinel:u.charsetSentinel,commaRoundTrip:!!$.commaRoundTrip,delimiter:typeof $.delimiter>"u"?u.delimiter:$.delimiter,encode:typeof $.encode==="boolean"?$.encode:u.encode,encodeDotInKeys:typeof $.encodeDotInKeys==="boolean"?$.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof $.encoder==="function"?$.encoder:u.encoder,encodeValuesOnly:typeof $.encodeValuesOnly==="boolean"?$.encodeValuesOnly:u.encodeValuesOnly,filter:X,format:Z,formatter:w,serializeDate:typeof $.serializeDate==="function"?$.serializeDate:u.serializeDate,skipNulls:typeof $.skipNulls==="boolean"?$.skipNulls:u.skipNulls,sort:typeof $.sort==="function"?$.sort:null,strictNullHandling:typeof $.strictNullHandling==="boolean"?$.strictNullHandling:u.strictNullHandling}}function $6($,Y={}){let Z=$,w=j8(Y),X,W;if(typeof w.filter==="function")W=w.filter,Z=W("",Z);else if(a(w.filter))W=w.filter,X=W;let G=[];if(typeof Z!=="object"||Z===null)return"";let Q=s9[w.arrayFormat],V=Q==="comma"&&w.commaRoundTrip;if(!X)X=Object.keys(Z);if(w.sort)X.sort(w.sort);let H=new WeakMap;for(let U=0;U<X.length;++U){let M=X[U];if(w.skipNulls&&Z[M]===null)continue;o9(G,e9(Z[M],M,Q,V,w.allowEmptyArrays,w.strictNullHandling,w.skipNulls,w.encodeDotInKeys,w.encode?w.encoder:null,w.filter,w.sort,w.allowDots,w.serializeDate,w.format,w.formatter,w.encodeValuesOnly,w.charset,H))}let T=G.join(w.delimiter),K=w.addQueryPrefix===!0?"?":"";if(w.charsetSentinel)if(w.charset==="iso-8859-1")K+="utf8=%26%2310003%3B&";else K+="utf8=%E2%9C%93&";return T.length>0?K+T:""}function Y6($){return $6($,{arrayFormat:"brackets"})}function G6($){let Y=0;for(let X of $)Y+=X.length;let Z=new Uint8Array(Y),w=0;for(let X of $)Z.set(X,w),w+=X.length;return Z}var Z6;function E1($){let Y;return(Z6??(Y=new globalThis.TextEncoder,Z6=Y.encode.bind(Y)))($)}var w6;function Y4($){let Y;return(w6??(Y=new globalThis.TextDecoder,w6=Y.decode.bind(Y)))($)}var Q$,z$;class L1{constructor(){Q$.set(this,void 0),z$.set(this,void 0),k(this,Q$,new Uint8Array,"f"),k(this,z$,null,"f")}decode($){if($==null)return[];let Y=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?E1($):$;k(this,Q$,G6([B(this,Q$,"f"),Y]),"f");let Z=[],w;while((w=v8(B(this,Q$,"f"),B(this,z$,"f")))!=null){if(w.carriage&&B(this,z$,"f")==null){k(this,z$,w.index,"f");continue}if(B(this,z$,"f")!=null&&(w.index!==B(this,z$,"f")+1||w.carriage)){Z.push(Y4(B(this,Q$,"f").subarray(0,B(this,z$,"f")-1))),k(this,Q$,B(this,Q$,"f").subarray(B(this,z$,"f")),"f"),k(this,z$,null,"f");continue}let X=B(this,z$,"f")!==null?w.preceding-1:w.preceding,W=Y4(B(this,Q$,"f").subarray(0,X));Z.push(W),k(this,Q$,B(this,Q$,"f").subarray(w.index),"f"),k(this,z$,null,"f")}return Z}flush(){if(!B(this,Q$,"f").length)return[];return this.decode(`
183
+ `)}}Q$=new WeakMap,z$=new WeakMap;L1.NEWLINE_CHARS=new Set([`
184
+ `,"\r"]);L1.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function v8($,Y){for(let X=Y??0;X<$.length;X++){if($[X]===10)return{preceding:X,index:X+1,carriage:!1};if($[X]===13)return{preceding:X,index:X+1,carriage:!0}}return null}function X6($){for(let w=0;w<$.length-1;w++){if($[w]===10&&$[w+1]===10)return w+2;if($[w]===13&&$[w+1]===13)return w+2;if($[w]===13&&$[w+1]===10&&w+3<$.length&&$[w+2]===13&&$[w+3]===10)return w+4}return-1}var t2={off:0,error:200,warn:300,info:400,debug:500},Z4=($,Y,Z)=>{if(!$)return;if(D9(t2,$))return $;c(Z).warn(`${Y} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(t2))}`);return};function H0(){}function a2($,Y,Z){if(!Y||t2[$]>t2[Z])return H0;else return Y[$].bind(Y)}var y8={error:H0,warn:H0,info:H0,debug:H0},W6=new WeakMap;function c($){let Y=$.logger,Z=$.logLevel??"off";if(!Y)return y8;let w=W6.get(Y);if(w&&w[0]===Z)return w[1];let X={error:a2("error",Y,Z),warn:a2("warn",Y,Z),info:a2("info",Y,Z),debug:a2("debug",Y,Z)};return W6.set(Y,[Z,X]),X}var P$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([Y,Z])=>[Y,Y.toLowerCase()==="authorization"||Y.toLowerCase()==="api-key"||Y.toLowerCase()==="x-api-key"||Y.toLowerCase()==="cookie"||Y.toLowerCase()==="set-cookie"?"***":Z]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var T0;class N${constructor($,Y,Z){this.iterator=$,T0.set(this,void 0),this.controller=Y,k(this,T0,Z,"f")}static fromSSEResponse($,Y,Z,w){let X=!1,W=Z?c(Z):console;async function*G(){if(X)throw new O("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let Q=!1;try{for await(let V of I8($,Y)){if(Q)continue;if(V.data.startsWith("[DONE]")){Q=!0;continue}if(V.event===null||!V.event.startsWith("thread.")){let H;try{H=JSON.parse(V.data)}catch(T){throw W.error("Could not parse message into JSON:",V.data),W.error("From chunk:",V.raw),T}if(H&&H.error)throw new g(void 0,H.error,void 0,$.headers);yield w?{event:V.event,data:H}:H}else{let H;try{H=JSON.parse(V.data)}catch(T){throw console.error("Could not parse message into JSON:",V.data),console.error("From chunk:",V.raw),T}if(V.event=="error")throw new g(void 0,H.error,H.message,void 0);yield{event:V.event,data:H}}}Q=!0}catch(V){if(Y0(V))return;throw V}finally{if(!Q)Y.abort()}}return new N$(G,Y,Z)}static fromReadableStream($,Y,Z){let w=!1;async function*X(){let G=new L1,Q=n3($);for await(let V of Q)for(let H of G.decode(V))yield H;for(let V of G.flush())yield V}async function*W(){if(w)throw new O("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");w=!0;let G=!1;try{for await(let Q of X()){if(G)continue;if(Q)yield JSON.parse(Q)}G=!0}catch(Q){if(Y0(Q))return;throw Q}finally{if(!G)Y.abort()}}return new N$(W,Y,Z)}[(T0=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],Y=[],Z=this.iterator(),w=(X)=>{return{next:()=>{if(X.length===0){let W=Z.next();$.push(W),Y.push(W)}return X.shift()}}};return[new N$(()=>w($),this.controller,B(this,T0,"f")),new N$(()=>w(Y),this.controller,B(this,T0,"f"))]}toReadableStream(){let $=this,Y;return i3({async start(){Y=$[Symbol.asyncIterator]()},async pull(Z){try{let{value:w,done:X}=await Y.next();if(X)return Z.close();let W=E1(JSON.stringify(w)+`
185
+ `);Z.enqueue(W)}catch(w){Z.error(w)}},async cancel(){await Y.return?.()}})}}async function*I8($,Y){if(!$.body){if(Y.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new O("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 O("Attempted to iterate over a response with no body")}let Z=new J6,w=new L1,X=n3($.body);for await(let W of D8(X))for(let G of w.decode(W)){let Q=Z.decode(G);if(Q)yield Q}for(let W of w.flush()){let G=Z.decode(W);if(G)yield G}}async function*D8($){let Y=new Uint8Array;for await(let Z of $){if(Z==null)continue;let w=Z instanceof ArrayBuffer?new Uint8Array(Z):typeof Z==="string"?E1(Z):Z,X=new Uint8Array(Y.length+w.length);X.set(Y),X.set(w,Y.length),Y=X;let W;while((W=X6(Y))!==-1)yield Y.slice(0,W),Y=Y.slice(W)}if(Y.length>0)yield Y}class J6{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 X={event:this.event,data:this.data.join(`
186
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push($),$.startsWith(":"))return null;let[Y,Z,w]=h8($,":");if(w.startsWith(" "))w=w.substring(1);if(Y==="event")this.event=w;else if(Y==="data")this.data.push(w);return null}}function h8($,Y){let Z=$.indexOf(Y);if(Z!==-1)return[$.substring(0,Z),Y,$.substring(Z+Y.length)];return[$,"",""]}async function r2($,Y){let{response:Z,requestLogID:w,retryOfRequestLogID:X,startTime:W}=Y,G=await(async()=>{if(Y.options.stream){if(c($).debug("response",Z.status,Z.url,Z.headers,Z.body),Y.options.__streamClass)return Y.options.__streamClass.fromSSEResponse(Z,Y.controller,$,Y.options.__synthesizeEventData);return N$.fromSSEResponse(Z,Y.controller,$,Y.options.__synthesizeEventData)}if(Z.status===204)return null;if(Y.options.__binaryResponse)return Z;let V=Z.headers.get("content-type")?.split(";")[0]?.trim();if(V?.includes("application/json")||V?.endsWith("+json")){if(Z.headers.get("content-length")==="0")return;let U=await Z.json();return w4(U,Z)}return await Z.text()})();return c($).debug(`[${w}] response parsed`,P$({retryOfRequestLogID:X,url:Z.url,status:Z.status,body:G,durationMs:Date.now()-W})),G}function w4($,Y){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Y.headers.get("x-request-id"),enumerable:!1})}var U0;class s$ extends Promise{constructor($,Y,Z=r2){super((w)=>{w(null)});this.responsePromise=Y,this.parseResponse=Z,U0.set(this,void 0),k(this,U0,$,"f")}_thenUnwrap($){return new s$(B(this,U0,"f"),this.responsePromise,async(Y,Z)=>w4($(await this.parseResponse(Y,Z),Z),Z.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,Y]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:Y,request_id:Y.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(B(this,U0,"f"),$));return this.parsedPromise}then($,Y){return this.parse().then($,Y)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}U0=new WeakMap;var s2;class M0{constructor($,Y,Z,w){s2.set(this,void 0),k(this,s2,$,"f"),this.options=w,this.response=Y,this.body=Z}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new O("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await B(this,s2,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(s2=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Y of $.getPaginatedItems())yield Y}}class o2 extends s${constructor($,Y,Z){super($,Y,async(w,X)=>new Z(w,X.response,await r2(w,X),X.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Y of $)yield Y}}class Z$ extends M0{constructor($,Y,Z,w){super($,Y,Z,w);this.data=Z.data||[],this.object=Z.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class S extends M0{constructor($,Y,Z,w){super($,Y,Z,w);this.data=Z.data||[],this.has_more=Z.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.getPaginatedItems(),Y=$[$.length-1]?.id;if(!Y)return null;return{...this.options,query:{...l2(this.options.query),after:Y}}}}class j extends M0{constructor($,Y,Z,w){super($,Y,Z,w);this.data=Z.data||[],this.has_more=Z.has_more||!1,this.last_id=Z.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:{...l2(this.options.query),after:$}}}}class l extends M0{constructor($,Y,Z,w){super($,Y,Z,w);this.data=Z.data||[],this.has_more=Z.has_more||!1,this.next=Z.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:{...l2(this.options.query),after:$}}}}var m8={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},c8="urn:ietf:params:oauth:grant-type:token-exchange";class G4{constructor($,Y){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=$,this.fetch=Y??p2()}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(),Y={grant_type:c8,subject_token:$,subject_token_type:m8[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};if(this.config.clientId)Y.client_id=this.config.clientId;let Z=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)});if(!Z.ok){let G=await Z.text(),Q=void 0;try{Q=JSON.parse(G)}catch{}if(Z.status===400||Z.status===401||Z.status===403)throw new O1(Z.status,Q,Z.headers);throw g.generate(Z.status,Q,`Token exchange failed with status ${Z.status}`,Z.headers)}let w=await Z.json(),X=w.expires_in||3600,W=Date.now()+X*1000;return this.cachedToken={token:w.access_token,expiresAt:W},w.access_token}isTokenExpired($){return Date.now()>=$.expiresAt}needsRefresh($){let Z=(this.config.refreshBufferSeconds??1200)*1000;return Date.now()>=$.expiresAt-Z}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}}var J4=()=>{if(typeof File>"u"){let{process:$}=globalThis,Y=typeof $?.versions?.node==="string"&&parseInt($.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(Y?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function F1($,Y,Z){return J4(),new File($,Y??"unknown_file",Z)}function x0($){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 e2=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function",h$=async($,Y)=>{if(!X4($.body))return $;return{...$,body:await z6($.body,Y)}},t=async($,Y)=>{return{...$,body:await z6($.body,Y)}},Q6=new WeakMap;function d8($){let Y=typeof $==="function"?$:$.fetch,Z=Q6.get(Y);if(Z)return Z;let w=(async()=>{try{let X="Response"in Y?Y.Response:(await Y("data:,")).constructor,W=new FormData;if(W.toString()===await new X(W).text())return!1;return!0}catch{return!0}})();return Q6.set(Y,w),w}var z6=async($,Y)=>{if(!await d8(Y))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let Z=new FormData;return await Promise.all(Object.entries($||{}).map(([w,X])=>W4(Z,w,X))),Z},N6=($)=>$ instanceof Blob&&("name"in $),u8=($)=>typeof $==="object"&&$!==null&&($ instanceof Response||e2($)||N6($)),X4=($)=>{if(u8($))return!0;if(Array.isArray($))return $.some(X4);if($&&typeof $==="object"){for(let Y in $)if(X4($[Y]))return!0}return!1},W4=async($,Y,Z)=>{if(Z===void 0)return;if(Z==null)throw TypeError(`Received null for "${Y}"; to pass null in FormData, you must use the string 'null'`);if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")$.append(Y,String(Z));else if(Z instanceof Response)$.append(Y,F1([await Z.blob()],x0(Z)));else if(e2(Z))$.append(Y,F1([await new Response(i2(Z)).blob()],x0(Z)));else if(N6(Z))$.append(Y,Z,x0(Z));else if(Array.isArray(Z))await Promise.all(Z.map((w)=>W4($,Y+"[]",w)));else if(typeof Z==="object")await Promise.all(Object.entries(Z).map(([w,X])=>W4($,`${Y}[${w}]`,X)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Z} instead`)};var V6=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",l8=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&V6($),p8=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function $3($,Y,Z){if(J4(),$=await $,l8($)){if($ instanceof File)return $;return F1([await $.arrayBuffer()],$.name)}if(p8($)){let X=await $.blob();return Y||(Y=new URL($.url).pathname.split(/[\\/]/).pop()),F1(await Q4(X),Y,Z)}let w=await Q4($);if(Y||(Y=x0($)),!Z?.type){let X=w.find((W)=>typeof W==="object"&&("type"in W)&&W.type);if(typeof X==="string")Z={...Z,type:X}}return F1(w,Y,Z)}async function Q4($){let Y=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Y.push($);else if(V6($))Y.push($ instanceof Blob?$:await $.arrayBuffer());else if(e2($))for await(let Z of $)Y.push(...await Q4(Z));else{let Z=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Z?`; constructor: ${Z}`:""}${i8($)}`)}return Y}function i8($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Z)=>`"${Z}"`).join(", ")}]`}class N{constructor($){this._client=$}}function K6($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var B6=Object.freeze(Object.create(null)),a8=($=K6)=>function(Z,...w){if(Z.length===1)return Z[0];let X=!1,W=[],G=Z.reduce((T,K,U)=>{if(/[?#]/.test(K))X=!0;let M=w[U],q=(X?encodeURIComponent:$)(""+M);if(U!==w.length&&(M==null||typeof M==="object"&&M.toString===Object.getPrototypeOf(Object.getPrototypeOf(M.hasOwnProperty??B6)??B6)?.toString))q=M+"",W.push({start:T.length+K.length,length:q.length,error:`Value of type ${Object.prototype.toString.call(M).slice(8,-1)} is not a valid path parameter`});return T+K+(U===w.length?"":q)},""),Q=G.split(/[?#]/,1)[0],V=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,H;while((H=V.exec(Q))!==null)W.push({start:H.index,length:H[0].length,error:`Value "${H[0]}" can't be safely passed as a path parameter`});if(W.sort((T,K)=>T.start-K.start),W.length>0){let T=0,K=W.reduce((U,M)=>{let q=" ".repeat(M.start-T),P="^".repeat(M.length);return T=M.start+M.length,U+q+P},"");throw new O(`Path parameters result in path with invalid segments:
157
187
  ${W.map((U)=>U.error).join(`
158
188
  `)}
159
189
  ${G}
160
- ${K}`)}return G},J=h8(z6);class k1 extends N{list($,Y={},Z){return this._client.getAPIList(J`/chat/completions/${$}/messages`,S,{query:Y,...Z,__security:{bearerAuth:!0}})}}function q0($){return $!==void 0&&"function"in $&&$.function!==void 0}function O0($){return $?.$brand==="auto-parseable-response-format"}function o$($){return $?.$brand==="auto-parseable-tool"}function B6($,Y){if(!Y||!J4(Y))return{...$,choices:$.choices.map((Z)=>{return H6(Z.message.tool_calls),{...Z,message:{...Z.message,parsed:null,...Z.message.tool_calls?{tool_calls:Z.message.tool_calls}:void 0}}})};return E0($,Y)}function E0($,Y){let Z=$.choices.map((w)=>{if(w.finish_reason==="length")throw new V0;if(w.finish_reason==="content_filter")throw new B0;return H6(w.message.tool_calls),{...w,message:{...w.message,...w.message.tool_calls?{tool_calls:w.message.tool_calls?.map((X)=>c8(Y,X))??void 0}:void 0,parsed:w.message.content&&!w.message.refusal?m8(Y,w.message.content):null}}});return{...$,choices:Z}}function m8($,Y){if($.response_format?.type!=="json_schema")return null;if($.response_format?.type==="json_schema"){if("$parseRaw"in $.response_format)return $.response_format.$parseRaw(Y);return JSON.parse(Y)}return null}function c8($,Y){let Z=$.tools?.find((w)=>q0(w)&&w.function?.name===Y.function.name);return{...Y,function:{...Y.function,parsed_arguments:o$(Z)?Z.$parseRaw(Y.function.arguments):Z?.function.strict?JSON.parse(Y.function.arguments):null}}}function K6($,Y){if(!$||!("tools"in $)||!$.tools)return!1;let Z=$.tools?.find((w)=>q0(w)&&w.function?.name===Y.function.name);return q0(Z)&&(o$(Z)||Z?.function.strict||!1)}function J4($){if(O0($.response_format))return!0;return $.tools?.some((Y)=>o$(Y)||Y.type==="function"&&Y.function.strict===!0)??!1}function H6($){for(let Y of $||[])if(Y.type!=="function")throw new O(`Currently only \`function\` tool calls are supported; Received \`${Y.type}\``)}function T6($){for(let Y of $??[]){if(Y.type!=="function")throw new O(`Currently only \`function\` tool types support auto-parsing; Received \`${Y.type}\``);if(Y.function.strict!==!0)throw new O(`The \`${Y.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var C1=($)=>{return $?.role==="assistant"},Q4=($)=>{return $?.role==="tool"};var N4,$3,Y3,L0,F0,Z3,k0,_$,C0,w3,G3,S1,U6;class e${constructor(){N4.add(this),this.controller=new AbortController,$3.set(this,void 0),Y3.set(this,()=>{}),L0.set(this,()=>{}),F0.set(this,void 0),Z3.set(this,()=>{}),k0.set(this,()=>{}),_$.set(this,{}),C0.set(this,!1),w3.set(this,!1),G3.set(this,!1),S1.set(this,!1),k(this,$3,new Promise(($,Y)=>{k(this,Y3,$,"f"),k(this,L0,Y,"f")}),"f"),k(this,F0,new Promise(($,Y)=>{k(this,Z3,$,"f"),k(this,k0,Y,"f")}),"f"),B(this,$3,"f").catch(()=>{}),B(this,F0,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},B(this,N4,"m",U6).bind(this))},0)}_connected(){if(this.ended)return;B(this,Y3,"f").call(this),this._emit("connect")}get ended(){return B(this,C0,"f")}get errored(){return B(this,w3,"f")}get aborted(){return B(this,G3,"f")}abort(){this.controller.abort()}on($,Y){return(B(this,_$,"f")[$]||(B(this,_$,"f")[$]=[])).push({listener:Y}),this}off($,Y){let Z=B(this,_$,"f")[$];if(!Z)return this;let w=Z.findIndex((X)=>X.listener===Y);if(w>=0)Z.splice(w,1);return this}once($,Y){return(B(this,_$,"f")[$]||(B(this,_$,"f")[$]=[])).push({listener:Y,once:!0}),this}emitted($){return new Promise((Y,Z)=>{if(k(this,S1,!0,"f"),$!=="error")this.once("error",Z);this.once($,Y)})}async done(){k(this,S1,!0,"f"),await B(this,F0,"f")}_emit($,...Y){if(B(this,C0,"f"))return;if($==="end")k(this,C0,!0,"f"),B(this,Z3,"f").call(this);let Z=B(this,_$,"f")[$];if(Z)B(this,_$,"f")[$]=Z.filter((w)=>!w.once),Z.forEach(({listener:w})=>w(...Y));if($==="abort"){let w=Y[0];if(!B(this,S1,"f")&&!Z?.length)Promise.reject(w);B(this,L0,"f").call(this,w),B(this,k0,"f").call(this,w),this._emit("end");return}if($==="error"){let w=Y[0];if(!B(this,S1,"f")&&!Z?.length)Promise.reject(w);B(this,L0,"f").call(this,w),B(this,k0,"f").call(this,w),this._emit("end")}}_emitFinal(){}}$3=new WeakMap,Y3=new WeakMap,L0=new WeakMap,F0=new WeakMap,Z3=new WeakMap,k0=new WeakMap,_$=new WeakMap,C0=new WeakMap,w3=new WeakMap,G3=new WeakMap,S1=new WeakMap,N4=new WeakSet,U6=function(Y){if(k(this,w3,!0,"f"),Y instanceof Error&&Y.name==="AbortError")Y=new d;if(Y instanceof d)return k(this,G3,!0,"f"),this._emit("abort",Y);if(Y instanceof O)return this._emit("error",Y);if(Y instanceof Error){let Z=new O(Y.message);return Z.cause=Y,this._emit("error",Z)}return this._emit("error",new O(String(Y)))};function M6($){return typeof $.parse==="function"}var w$,z4,X3,V4,B4,K4,x6,q6,d8=10;class S0 extends e${constructor(){super(...arguments);w$.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion($){this._chatCompletions.push($),this._emit("chatCompletion",$);let Y=$.choices[0]?.message;if(Y)this._addMessage(Y);return $}_addMessage($,Y=!0){if(!("content"in $))$.content=null;if(this.messages.push($),Y){if(this._emit("message",$),Q4($)&&$.content)this._emit("functionToolCallResult",$.content);else if(C1($)&&$.tool_calls){for(let Z of $.tool_calls)if(Z.type==="function")this._emit("functionToolCall",Z.function)}}}async finalChatCompletion(){await this.done();let $=this._chatCompletions[this._chatCompletions.length-1];if(!$)throw new O("stream ended without producing a ChatCompletion");return $}async finalContent(){return await this.done(),B(this,w$,"m",z4).call(this)}async finalMessage(){return await this.done(),B(this,w$,"m",X3).call(this)}async finalFunctionToolCall(){return await this.done(),B(this,w$,"m",V4).call(this)}async finalFunctionToolCallResult(){return await this.done(),B(this,w$,"m",B4).call(this)}async totalUsage(){return await this.done(),B(this,w$,"m",K4).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let $=this._chatCompletions[this._chatCompletions.length-1];if($)this._emit("finalChatCompletion",$);let Y=B(this,w$,"m",X3).call(this);if(Y)this._emit("finalMessage",Y);let Z=B(this,w$,"m",z4).call(this);if(Z)this._emit("finalContent",Z);let w=B(this,w$,"m",V4).call(this);if(w)this._emit("finalFunctionToolCall",w);let X=B(this,w$,"m",B4).call(this);if(X!=null)this._emit("finalFunctionToolCallResult",X);if(this._chatCompletions.some((W)=>W.usage))this._emit("totalUsage",B(this,w$,"m",K4).call(this))}async _createChatCompletion($,Y,Z){let w=Z?.signal;if(w){if(w.aborted)this.controller.abort();w.addEventListener("abort",()=>this.controller.abort())}B(this,w$,"m",x6).call(this,Y);let X=await $.chat.completions.create({...Y,stream:!1},{...Z,signal:this.controller.signal});return this._connected(),this._addChatCompletion(E0(X,Y))}async _runChatCompletion($,Y,Z){for(let w of Y.messages)this._addMessage(w,!1);return await this._createChatCompletion($,Y,Z)}async _runTools($,Y,Z){let{tool_choice:X="auto",stream:W,...G}=Y,Q=typeof X!=="string"&&X.type==="function"&&X?.function?.name,{maxChatCompletions:z=d8}=Z||{},H=Y.tools.map((U)=>{if(o$(U)){if(!U.$callback)throw new O("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:U.$callback,name:U.function.name,description:U.function.description||"",parameters:U.function.parameters,parse:U.$parseRaw,strict:!0}}}return U}),T={};for(let U of H)if(U.type==="function")T[U.function.name||U.function.function.name]=U.function;let K="tools"in Y?H.map((U)=>U.type==="function"?{type:"function",function:{name:U.function.name||U.function.function.name,parameters:U.function.parameters,description:U.function.description,strict:U.function.strict}}:U):void 0;for(let U of Y.messages)this._addMessage(U,!1);for(let U=0;U<z;++U){let q=(await this._createChatCompletion($,{...G,tool_choice:X,tools:K,messages:[...this.messages]},Z)).choices[0]?.message;if(!q)throw new O("missing message in ChatCompletion response");if(!q.tool_calls?.length)return;for(let P of q.tool_calls){if(P.type!=="function")continue;let A=P.id,{name:R,arguments:F}=P.function,b=T[R];if(!b){let I=`Invalid tool_call: ${JSON.stringify(R)}. Available options are: ${Object.keys(T).map(($$)=>JSON.stringify($$)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:A,content:I});continue}else if(Q&&Q!==R){let I=`Invalid tool_call: ${JSON.stringify(R)}. ${JSON.stringify(Q)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:A,content:I});continue}let v;try{v=M6(b)?await b.parse(F):F}catch(I){let $$=I instanceof Error?I.message:String(I);this._addMessage({role:"tool",tool_call_id:A,content:$$});continue}let o=await b.function(v,this),e=B(this,w$,"m",q6).call(this,o);if(this._addMessage({role:"tool",tool_call_id:A,content:e}),Q)return}}return}}w$=new WeakSet,z4=function(){return B(this,w$,"m",X3).call(this).content??null},X3=function(){let Y=this.messages.length;while(Y-- >0){let Z=this.messages[Y];if(C1(Z))return{...Z,content:Z.content??null,refusal:Z.refusal??null}}throw new O("stream ended without producing a ChatCompletionMessage with role=assistant")},V4=function(){for(let Y=this.messages.length-1;Y>=0;Y--){let Z=this.messages[Y];if(C1(Z)&&Z?.tool_calls?.length)return Z.tool_calls.filter((w)=>w.type==="function").at(-1)?.function}return},B4=function(){for(let Y=this.messages.length-1;Y>=0;Y--){let Z=this.messages[Y];if(Q4(Z)&&Z.content!=null&&typeof Z.content==="string"&&this.messages.some((w)=>w.role==="assistant"&&w.tool_calls?.some((X)=>X.type==="function"&&X.id===Z.tool_call_id)))return Z.content}return},K4=function(){let Y={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:Z}of this._chatCompletions)if(Z)Y.completion_tokens+=Z.completion_tokens,Y.prompt_tokens+=Z.prompt_tokens,Y.total_tokens+=Z.total_tokens;return Y},x6=function(Y){if(Y.n!=null&&Y.n>1)throw new O("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},q6=function(Y){return typeof Y==="string"?Y:Y===void 0?"undefined":JSON.stringify(Y)};class R0 extends S0{static runTools($,Y,Z){let w=new R0,X={...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"runTools"}};return w._run(()=>w._runTools($,Y,X)),w}_addMessage($,Y=!0){if(super._addMessage($,Y),C1($)&&$.content)this._emit("content",$.content)}}var i={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 O6 extends Error{}class E6 extends Error{}function u8($,Y=i.ALL){if(typeof $!=="string")throw TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw Error(`${$} is empty`);return l8($.trim(),Y)}var l8=($,Y)=>{let Z=$.length,w=0,X=(U)=>{throw new O6(`${U} at position ${w}`)},W=(U)=>{throw new E6(`${U} at position ${w}`)},G=()=>{if(K(),w>=Z)X("Unexpected end of input");if($[w]==='"')return Q();if($[w]==="{")return z();if($[w]==="[")return H();if($.substring(w,w+4)==="null"||i.NULL&Y&&Z-w<4&&"null".startsWith($.substring(w)))return w+=4,null;if($.substring(w,w+4)==="true"||i.BOOL&Y&&Z-w<4&&"true".startsWith($.substring(w)))return w+=4,!0;if($.substring(w,w+5)==="false"||i.BOOL&Y&&Z-w<5&&"false".startsWith($.substring(w)))return w+=5,!1;if($.substring(w,w+8)==="Infinity"||i.INFINITY&Y&&Z-w<8&&"Infinity".startsWith($.substring(w)))return w+=8,1/0;if($.substring(w,w+9)==="-Infinity"||i.MINUS_INFINITY&Y&&1<Z-w&&Z-w<9&&"-Infinity".startsWith($.substring(w)))return w+=9,-1/0;if($.substring(w,w+3)==="NaN"||i.NAN&Y&&Z-w<3&&"NaN".startsWith($.substring(w)))return w+=3,NaN;return T()},Q=()=>{let U=w,M=!1;w++;while(w<Z&&($[w]!=='"'||M&&$[w-1]==="\\"))M=$[w]==="\\"?!M:!1,w++;if($.charAt(w)=='"')try{return JSON.parse($.substring(U,++w-Number(M)))}catch(q){W(String(q))}else if(i.STR&Y)try{return JSON.parse($.substring(U,w-Number(M))+'"')}catch(q){return JSON.parse($.substring(U,$.lastIndexOf("\\"))+'"')}X("Unterminated string literal")},z=()=>{w++,K();let U={};try{while($[w]!=="}"){if(K(),w>=Z&&i.OBJ&Y)return U;let M=Q();K(),w++;try{let q=G();Object.defineProperty(U,M,{value:q,writable:!0,enumerable:!0,configurable:!0})}catch(q){if(i.OBJ&Y)return U;else throw q}if(K(),$[w]===",")w++}}catch(M){if(i.OBJ&Y)return U;else X("Expected '}' at end of object")}return w++,U},H=()=>{w++;let U=[];try{while($[w]!=="]")if(U.push(G()),K(),$[w]===",")w++}catch(M){if(i.ARR&Y)return U;X("Expected ']' at end of array")}return w++,U},T=()=>{if(w===0){if($==="-"&&i.NUM&Y)X("Not sure what '-' is");try{return JSON.parse($)}catch(M){if(i.NUM&Y)try{if($[$.length-1]===".")return JSON.parse($.substring(0,$.lastIndexOf(".")));return JSON.parse($.substring(0,$.lastIndexOf("e")))}catch(q){}W(String(M))}}let U=w;if($[w]==="-")w++;while($[w]&&!",]}".includes($[w]))w++;if(w==Z&&!(i.NUM&Y))X("Unterminated number literal");try{return JSON.parse($.substring(U,w))}catch(M){if($.substring(U,w)==="-"&&i.NUM&Y)X("Not sure what '-' is");try{return JSON.parse($.substring(U,$.lastIndexOf("e")))}catch(q){W(String(q))}}},K=()=>{while(w<Z&&`
161
- \r `.includes($[w]))w++};return G()},H4=($)=>u8($,i.ALL^i.NUM);var p,A$,R1,g$,T4,W3,U4,M4,x4,J3,q4,L6;class m$ extends S0{constructor($){super();p.add(this),A$.set(this,void 0),R1.set(this,void 0),g$.set(this,void 0),k(this,A$,$,"f"),k(this,R1,[],"f")}get currentChatCompletionSnapshot(){return B(this,g$,"f")}static fromReadableStream($){let Y=new m$(null);return Y._run(()=>Y._fromReadableStream($)),Y}static createChatCompletion($,Y,Z){let w=new m$(Y);return w._run(()=>w._runChatCompletion($,{...Y,stream:!0},{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),w}async _createChatCompletion($,Y,Z){super._createChatCompletion;let w=Z?.signal;if(w){if(w.aborted)this.controller.abort();w.addEventListener("abort",()=>this.controller.abort())}B(this,p,"m",T4).call(this);let X=await $.chat.completions.create({...Y,stream:!0},{...Z,signal:this.controller.signal});this._connected();for await(let W of X)B(this,p,"m",U4).call(this,W);if(X.controller.signal?.aborted)throw new d;return this._addChatCompletion(B(this,p,"m",J3).call(this))}async _fromReadableStream($,Y){let Z=Y?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}B(this,p,"m",T4).call(this),this._connected();let w=z$.fromReadableStream($,this.controller),X;for await(let W of w){if(X&&X!==W.id)this._addChatCompletion(B(this,p,"m",J3).call(this));B(this,p,"m",U4).call(this,W),X=W.id}if(w.controller.signal?.aborted)throw new d;return this._addChatCompletion(B(this,p,"m",J3).call(this))}[(A$=new WeakMap,R1=new WeakMap,g$=new WeakMap,p=new WeakSet,T4=function(){if(this.ended)return;k(this,g$,void 0,"f")},W3=function(Y){let Z=B(this,R1,"f")[Y.index];if(Z)return Z;return Z={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},B(this,R1,"f")[Y.index]=Z,Z},U4=function(Y){if(this.ended)return;let Z=B(this,p,"m",L6).call(this,Y);this._emit("chunk",Y,Z);for(let w of Y.choices){let X=Z.choices[w.index];if(w.delta.content!=null&&X.message?.role==="assistant"&&X.message?.content)this._emit("content",w.delta.content,X.message.content),this._emit("content.delta",{delta:w.delta.content,snapshot:X.message.content,parsed:X.message.parsed});if(w.delta.refusal!=null&&X.message?.role==="assistant"&&X.message?.refusal)this._emit("refusal.delta",{delta:w.delta.refusal,snapshot:X.message.refusal});if(w.logprobs?.content!=null&&X.message?.role==="assistant")this._emit("logprobs.content.delta",{content:w.logprobs?.content,snapshot:X.logprobs?.content??[]});if(w.logprobs?.refusal!=null&&X.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:w.logprobs?.refusal,snapshot:X.logprobs?.refusal??[]});let W=B(this,p,"m",W3).call(this,X);if(X.finish_reason){if(B(this,p,"m",x4).call(this,X),W.current_tool_call_index!=null)B(this,p,"m",M4).call(this,X,W.current_tool_call_index)}for(let G of w.delta.tool_calls??[]){if(W.current_tool_call_index!==G.index){if(B(this,p,"m",x4).call(this,X),W.current_tool_call_index!=null)B(this,p,"m",M4).call(this,X,W.current_tool_call_index)}W.current_tool_call_index=G.index}for(let G of w.delta.tool_calls??[]){let Q=X.message.tool_calls?.[G.index];if(!Q?.type)continue;if(Q?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:Q.function?.name,index:G.index,arguments:Q.function.arguments,parsed_arguments:Q.function.parsed_arguments,arguments_delta:G.function?.arguments??""});else k6(Q?.type)}}},M4=function(Y,Z){if(B(this,p,"m",W3).call(this,Y).done_tool_calls.has(Z))return;let X=Y.message.tool_calls?.[Z];if(!X)throw Error("no tool call snapshot");if(!X.type)throw Error("tool call snapshot missing `type`");if(X.type==="function"){let W=B(this,A$,"f")?.tools?.find((G)=>q0(G)&&G.function.name===X.function.name);this._emit("tool_calls.function.arguments.done",{name:X.function.name,index:Z,arguments:X.function.arguments,parsed_arguments:o$(W)?W.$parseRaw(X.function.arguments):W?.function.strict?JSON.parse(X.function.arguments):null})}else k6(X.type)},x4=function(Y){let Z=B(this,p,"m",W3).call(this,Y);if(Y.message.content&&!Z.content_done){Z.content_done=!0;let w=B(this,p,"m",q4).call(this);this._emit("content.done",{content:Y.message.content,parsed:w?w.$parseRaw(Y.message.content):null})}if(Y.message.refusal&&!Z.refusal_done)Z.refusal_done=!0,this._emit("refusal.done",{refusal:Y.message.refusal});if(Y.logprobs?.content&&!Z.logprobs_content_done)Z.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:Y.logprobs.content});if(Y.logprobs?.refusal&&!Z.logprobs_refusal_done)Z.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:Y.logprobs.refusal})},J3=function(){if(this.ended)throw new O("stream has ended, this shouldn't happen");let Y=B(this,g$,"f");if(!Y)throw new O("request ended without sending any chunks");return k(this,g$,void 0,"f"),k(this,R1,[],"f"),p8(Y,B(this,A$,"f"))},q4=function(){let Y=B(this,A$,"f")?.response_format;if(O0(Y))return Y;return null},L6=function(Y){var Z,w,X,W;let G=B(this,g$,"f"),{choices:Q,...z}=Y;if(!G)G=k(this,g$,{...z,choices:[]},"f");else Object.assign(G,z);for(let{delta:H,finish_reason:T,index:K,logprobs:U=null,...M}of Y.choices){let q=G.choices[K];if(!q)q=G.choices[K]={finish_reason:T,index:K,message:{},logprobs:U,...M};if(U)if(!q.logprobs)q.logprobs=Object.assign({},U);else{let{content:o,refusal:e,...I}=U;if(F6(I),Object.assign(q.logprobs,I),o)(Z=q.logprobs).content??(Z.content=[]),q.logprobs.content.push(...o);if(e)(w=q.logprobs).refusal??(w.refusal=[]),q.logprobs.refusal.push(...e)}if(T){if(q.finish_reason=T,B(this,A$,"f")&&J4(B(this,A$,"f"))){if(T==="length")throw new V0;if(T==="content_filter")throw new B0}}if(Object.assign(q,M),!H)continue;let{content:P,refusal:A,function_call:R,role:F,tool_calls:b,...v}=H;if(F6(v),Object.assign(q.message,v),A)q.message.refusal=(q.message.refusal||"")+A;if(F)q.message.role=F;if(R)if(!q.message.function_call)q.message.function_call=R;else{if(R.name)q.message.function_call.name=R.name;if(R.arguments)(X=q.message.function_call).arguments??(X.arguments=""),q.message.function_call.arguments+=R.arguments}if(P){if(q.message.content=(q.message.content||"")+P,!q.message.refusal&&B(this,p,"m",q4).call(this))q.message.parsed=H4(q.message.content)}if(b){if(!q.message.tool_calls)q.message.tool_calls=[];for(let{index:o,id:e,type:I,function:$$,...k$}of b){let y=(W=q.message.tool_calls)[o]??(W[o]={});if(Object.assign(y,k$),e)y.id=e;if(I)y.type=I;if($$)y.function??(y.function={name:$$.name??"",arguments:""});if($$?.name)y.function.name=$$.name;if($$?.arguments){if(y.function.arguments+=$$.arguments,K6(B(this,A$,"f"),y))y.function.parsed_arguments=H4(y.function.arguments)}}}}return G},Symbol.asyncIterator)](){let $=[],Y=[],Z=!1;return this.on("chunk",(w)=>{let X=Y.shift();if(X)X.resolve(w);else $.push(w)}),this.on("end",()=>{Z=!0;for(let w of Y)w.resolve(void 0);Y.length=0}),this.on("abort",(w)=>{Z=!0;for(let X of Y)X.reject(w);Y.length=0}),this.on("error",(w)=>{Z=!0;for(let X of Y)X.reject(w);Y.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((X,W)=>Y.push({resolve:X,reject:W})).then((X)=>X?{value:X,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 z$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function p8($,Y){let{id:Z,choices:w,created:X,model:W,system_fingerprint:G,...Q}=$,z={...Q,id:Z,choices:w.map(({message:H,finish_reason:T,index:K,logprobs:U,...M})=>{if(!T)throw new O(`missing finish_reason for choice ${K}`);let{content:q=null,function_call:P,tool_calls:A,...R}=H,F=H.role;if(!F)throw new O(`missing role for choice ${K}`);if(P){let{arguments:b,name:v}=P;if(b==null)throw new O(`missing function_call.arguments for choice ${K}`);if(!v)throw new O(`missing function_call.name for choice ${K}`);return{...M,message:{content:q,function_call:{arguments:b,name:v},role:F,refusal:H.refusal??null},finish_reason:T,index:K,logprobs:U}}if(A)return{...M,index:K,finish_reason:T,logprobs:U,message:{...R,role:F,content:q,refusal:H.refusal??null,tool_calls:A.map((b,v)=>{let{function:o,type:e,id:I,...$$}=b,{arguments:k$,name:y,...b$}=o||{};if(I==null)throw new O(`missing choices[${K}].tool_calls[${v}].id
162
- ${Q3($)}`);if(e==null)throw new O(`missing choices[${K}].tool_calls[${v}].type
163
- ${Q3($)}`);if(y==null)throw new O(`missing choices[${K}].tool_calls[${v}].function.name
164
- ${Q3($)}`);if(k$==null)throw new O(`missing choices[${K}].tool_calls[${v}].function.arguments
165
- ${Q3($)}`);return{...$$,id:I,type:e,function:{...b$,name:y,arguments:k$}}})}};return{...M,message:{...R,content:q,role:F,refusal:H.refusal??null},finish_reason:T,index:K,logprobs:U}}),created:X,model:W,object:"chat.completion",...G?{system_fingerprint:G}:{}};return B6(z,Y)}function Q3($){return JSON.stringify($)}function F6($){return}function k6($){}class P1 extends m${static fromReadableStream($){let Y=new P1(null);return Y._run(()=>Y._fromReadableStream($)),Y}static runTools($,Y,Z){let w=new P1(Y),X={...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"runTools"}};return w._run(()=>w._runTools($,Y,X)),w}}class c$ extends N{constructor(){super(...arguments);this.messages=new k1(this._client)}create($,Y){return this._client.post("/chat/completions",{body:$,...Y,stream:$.stream??!1,__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/chat/completions/${$}`,{...Y,__security:{bearerAuth:!0}})}update($,Y,Z){return this._client.post(J`/chat/completions/${$}`,{body:Y,...Z,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/chat/completions",S,{query:$,...Y,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/chat/completions/${$}`,{...Y,__security:{bearerAuth:!0}})}parse($,Y){return T6($.tools),this._client.chat.completions.create($,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((Z)=>E0(Z,$))}runTools($,Y){if($.stream)return P1.runTools(this._client,$,Y);return R0.runTools(this._client,$,Y)}stream($,Y){return m$.createChatCompletion(this._client,$,Y)}}c$.Messages=k1;class $1 extends N{constructor(){super(...arguments);this.completions=new c$(this._client)}}$1.Completions=c$;class P0 extends N{create($,Y){return this._client.post("/organization/admin_api_keys",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y){return this._client.get(J`/organization/admin_api_keys/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/admin_api_keys",S,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/admin_api_keys/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}}class _0 extends N{list($={},Y){return this._client.getAPIList("/organization/audit_logs",f,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}}class A0 extends N{create($,Y){return this._client.post("/organization/certificates",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y={},Z){return this._client.get(J`/organization/certificates/${$}`,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/certificates/${$}`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/certificates",f,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/certificates/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}activate($,Y){return this._client.getAPIList("/organization/certificates/activate",Z$,{body:$,method:"post",...Y,__security:{adminAPIKeyAuth:!0}})}deactivate($,Y){return this._client.getAPIList("/organization/certificates/deactivate",Z$,{body:$,method:"post",...Y,__security:{adminAPIKeyAuth:!0}})}}class f0 extends N{retrieve($){return this._client.get("/organization/data_retention",{...$,__security:{adminAPIKeyAuth:!0}})}update($,Y){return this._client.post("/organization/data_retention",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}}class j0 extends N{create($,Y){return this._client.post("/organization/invites",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y){return this._client.get(J`/organization/invites/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/invites",f,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/invites/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}}class b0 extends N{create($,Y){return this._client.post("/organization/roles",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y){return this._client.get(J`/organization/roles/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/roles/${$}`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/roles",l,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/roles/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}}class v0 extends N{create($,Y){return this._client.post("/organization/spend_alerts",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/spend_alerts/${$}`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/spend_alerts",f,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/spend_alerts/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}}class y0 extends N{audioSpeeches($,Y){return this._client.get("/organization/usage/audio_speeches",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions($,Y){return this._client.get("/organization/usage/audio_transcriptions",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions($,Y){return this._client.get("/organization/usage/code_interpreter_sessions",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}completions($,Y){return this._client.get("/organization/usage/completions",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}costs($,Y){return this._client.get("/organization/costs",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}embeddings($,Y){return this._client.get("/organization/usage/embeddings",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls($,Y){return this._client.get("/organization/usage/file_search_calls",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}images($,Y){return this._client.get("/organization/usage/images",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}moderations($,Y){return this._client.get("/organization/usage/moderations",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}vectorStores($,Y){return this._client.get("/organization/usage/vector_stores",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}webSearchCalls($,Y){return this._client.get("/organization/usage/web_search_calls",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}}class I0 extends N{create($,Y,Z){return this._client.post(J`/organization/groups/${$}/roles`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{group_id:w}=Y;return this._client.get(J`/organization/groups/${w}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/groups/${$}/roles`,l,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{group_id:w}=Y;return this._client.delete(J`/organization/groups/${w}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class D0 extends N{create($,Y,Z){return this._client.post(J`/organization/groups/${$}/users`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{group_id:w}=Y;return this._client.get(J`/organization/groups/${w}/users/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/groups/${$}/users`,l,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{group_id:w}=Y;return this._client.delete(J`/organization/groups/${w}/users/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class Y1 extends N{constructor(){super(...arguments);this.users=new D0(this._client),this.roles=new I0(this._client)}create($,Y){return this._client.post("/organization/groups",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y){return this._client.get(J`/organization/groups/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/groups/${$}`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/groups",l,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/groups/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}}Y1.Users=D0;Y1.Roles=I0;class h0 extends N{retrieve($,Y,Z){let{project_id:w}=Y;return this._client.get(J`/organization/projects/${w}/api_keys/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/projects/${$}/api_keys`,f,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w}=Y;return this._client.delete(J`/organization/projects/${w}/api_keys/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class g0 extends N{list($,Y={},Z){return this._client.getAPIList(J`/organization/projects/${$}/certificates`,f,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}activate($,Y,Z){return this._client.getAPIList(J`/organization/projects/${$}/certificates/activate`,Z$,{body:Y,method:"post",...Z,__security:{adminAPIKeyAuth:!0}})}deactivate($,Y,Z){return this._client.getAPIList(J`/organization/projects/${$}/certificates/deactivate`,Z$,{body:Y,method:"post",...Z,__security:{adminAPIKeyAuth:!0}})}}class m0 extends N{retrieve($,Y){return this._client.get(J`/organization/projects/${$}/data_retention`,{...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/projects/${$}/data_retention`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}}class c0 extends N{retrieve($,Y){return this._client.get(J`/organization/projects/${$}/hosted_tool_permissions`,{...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/projects/${$}/hosted_tool_permissions`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}}class d0 extends N{retrieve($,Y){return this._client.get(J`/organization/projects/${$}/model_permissions`,{...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/projects/${$}/model_permissions`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/projects/${$}/model_permissions`,{...Y,__security:{adminAPIKeyAuth:!0}})}}class u0 extends N{listRateLimits($,Y={},Z){return this._client.getAPIList(J`/organization/projects/${$}/rate_limits`,f,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}updateRateLimit($,Y,Z){let{project_id:w,...X}=Y;return this._client.post(J`/organization/projects/${w}/rate_limits/${$}`,{body:X,...Z,__security:{adminAPIKeyAuth:!0}})}}class l0 extends N{create($,Y,Z){return this._client.post(J`/projects/${$}/roles`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{project_id:w}=Y;return this._client.get(J`/projects/${w}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){let{project_id:w,...X}=Y;return this._client.post(J`/projects/${w}/roles/${$}`,{body:X,...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/projects/${$}/roles`,l,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w}=Y;return this._client.delete(J`/projects/${w}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class p0 extends N{create($,Y,Z){return this._client.post(J`/organization/projects/${$}/service_accounts`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{project_id:w}=Y;return this._client.get(J`/organization/projects/${w}/service_accounts/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){let{project_id:w,...X}=Y;return this._client.post(J`/organization/projects/${w}/service_accounts/${$}`,{body:X,...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/projects/${$}/service_accounts`,f,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w}=Y;return this._client.delete(J`/organization/projects/${w}/service_accounts/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class i0 extends N{create($,Y,Z){return this._client.post(J`/organization/projects/${$}/spend_alerts`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){let{project_id:w,...X}=Y;return this._client.post(J`/organization/projects/${w}/spend_alerts/${$}`,{body:X,...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/projects/${$}/spend_alerts`,f,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w}=Y;return this._client.delete(J`/organization/projects/${w}/spend_alerts/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class n0 extends N{create($,Y,Z){let{project_id:w,...X}=Y;return this._client.post(J`/projects/${w}/groups/${$}/roles`,{body:X,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{project_id:w,group_id:X}=Y;return this._client.get(J`/projects/${w}/groups/${X}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y,Z){let{project_id:w,...X}=Y;return this._client.getAPIList(J`/projects/${w}/groups/${$}/roles`,l,{query:X,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w,group_id:X}=Y;return this._client.delete(J`/projects/${w}/groups/${X}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class _1 extends N{constructor(){super(...arguments);this.roles=new n0(this._client)}create($,Y,Z){return this._client.post(J`/organization/projects/${$}/groups`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{project_id:w,...X}=Y;return this._client.get(J`/organization/projects/${w}/groups/${$}`,{query:X,...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/projects/${$}/groups`,l,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w}=Y;return this._client.delete(J`/organization/projects/${w}/groups/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}_1.Roles=n0;class a0 extends N{create($,Y,Z){let{project_id:w,...X}=Y;return this._client.post(J`/projects/${w}/users/${$}/roles`,{body:X,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{project_id:w,user_id:X}=Y;return this._client.get(J`/projects/${w}/users/${X}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y,Z){let{project_id:w,...X}=Y;return this._client.getAPIList(J`/projects/${w}/users/${$}/roles`,l,{query:X,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w,user_id:X}=Y;return this._client.delete(J`/projects/${w}/users/${X}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class A1 extends N{constructor(){super(...arguments);this.roles=new a0(this._client)}create($,Y,Z){return this._client.post(J`/organization/projects/${$}/users`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{project_id:w}=Y;return this._client.get(J`/organization/projects/${w}/users/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){let{project_id:w,...X}=Y;return this._client.post(J`/organization/projects/${w}/users/${$}`,{body:X,...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/projects/${$}/users`,f,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w}=Y;return this._client.delete(J`/organization/projects/${w}/users/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}A1.Roles=a0;class r extends N{constructor(){super(...arguments);this.users=new A1(this._client),this.serviceAccounts=new p0(this._client),this.apiKeys=new h0(this._client),this.rateLimits=new u0(this._client),this.modelPermissions=new d0(this._client),this.hostedToolPermissions=new c0(this._client),this.groups=new _1(this._client),this.roles=new l0(this._client),this.dataRetention=new m0(this._client),this.spendAlerts=new i0(this._client),this.certificates=new g0(this._client)}create($,Y){return this._client.post("/organization/projects",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y){return this._client.get(J`/organization/projects/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/projects/${$}`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/projects",f,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}archive($,Y){return this._client.post(J`/organization/projects/${$}/archive`,{...Y,__security:{adminAPIKeyAuth:!0}})}}r.Users=A1;r.ServiceAccounts=p0;r.APIKeys=h0;r.RateLimits=u0;r.ModelPermissions=d0;r.HostedToolPermissions=c0;r.Groups=_1;r.Roles=l0;r.DataRetention=m0;r.SpendAlerts=i0;r.Certificates=g0;class t0 extends N{create($,Y,Z){return this._client.post(J`/organization/users/${$}/roles`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{user_id:w}=Y;return this._client.get(J`/organization/users/${w}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/users/${$}/roles`,l,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{user_id:w}=Y;return this._client.delete(J`/organization/users/${w}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class f1 extends N{constructor(){super(...arguments);this.roles=new t0(this._client)}retrieve($,Y){return this._client.get(J`/organization/users/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/users/${$}`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/users",f,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/users/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}}f1.Roles=t0;class s extends N{constructor(){super(...arguments);this.auditLogs=new _0(this._client),this.adminAPIKeys=new P0(this._client),this.usage=new y0(this._client),this.invites=new j0(this._client),this.users=new f1(this._client),this.groups=new Y1(this._client),this.roles=new b0(this._client),this.dataRetention=new f0(this._client),this.spendAlerts=new v0(this._client),this.certificates=new A0(this._client),this.projects=new r(this._client)}}s.AuditLogs=_0;s.AdminAPIKeys=P0;s.Usage=y0;s.Invites=j0;s.Users=f1;s.Groups=Y1;s.Roles=b0;s.DataRetention=f0;s.SpendAlerts=v0;s.Certificates=A0;s.Projects=r;class Z1 extends N{constructor(){super(...arguments);this.organization=new s(this._client)}}Z1.Organization=s;var C6=Symbol("brand.privateNullableHeaders");function*EY($){if(!$)return;if(C6 in $){let{values:w,nulls:X}=$;yield*w.entries();for(let W of X)yield[W,null];return}let Y=!1,Z;if($ instanceof Headers)Z=$.entries();else if(d3($))Z=$;else Y=!0,Z=Object.entries($??{});for(let w of Z){let X=w[0];if(typeof X!=="string")throw TypeError("expected header name to be a string");let W=d3(w[1])?w[1]:[w[1]],G=!1;for(let Q of W){if(Q===void 0)continue;if(Y&&!G)G=!0,yield[X,null];yield[X,Q]}}}var x=($)=>{let Y=new Headers,Z=new Set;for(let w of $){let X=new Set;for(let[W,G]of EY(w)){let Q=W.toLowerCase();if(!X.has(Q))Y.delete(W),X.add(Q);if(G===null)Y.delete(W),Z.add(Q);else Y.append(W,G),Z.delete(Q)}}return{[C6]:!0,values:Y,nulls:Z}};class r0 extends N{create($,Y){return this._client.post("/audio/speech",{body:$,...Y,headers:x([{Accept:"application/octet-stream"},Y?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class s0 extends N{create($,Y){return this._client.post("/audio/transcriptions",t({body:$,...Y,stream:$.stream??!1,__metadata:{model:$.model},__security:{bearerAuth:!0}},this._client))}}class o0 extends N{create($,Y){return this._client.post("/audio/translations",t({body:$,...Y,__metadata:{model:$.model},__security:{bearerAuth:!0}},this._client))}}class f$ extends N{constructor(){super(...arguments);this.transcriptions=new s0(this._client),this.translations=new o0(this._client),this.speech=new r0(this._client)}}f$.Transcriptions=s0;f$.Translations=o0;f$.Speech=r0;class j1 extends N{create($,Y){return this._client.post("/batches",{body:$,...Y,__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/batches/${$}`,{...Y,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/batches",S,{query:$,...Y,__security:{bearerAuth:!0}})}cancel($,Y){return this._client.post(J`/batches/${$}/cancel`,{...Y,__security:{bearerAuth:!0}})}}class e0 extends N{create($,Y){return this._client.post("/assistants",{body:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/assistants/${$}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}update($,Y,Z){return this._client.post(J`/assistants/${$}`,{body:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/assistants",S,{query:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/assistants/${$}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}}class $2 extends N{create($,Y){return this._client.post("/realtime/sessions",{body:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}}class Y2 extends N{create($,Y){return this._client.post("/realtime/transcription_sessions",{body:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}}class w1 extends N{constructor(){super(...arguments);this.sessions=new $2(this._client),this.transcriptionSessions=new Y2(this._client)}}w1.Sessions=$2;w1.TranscriptionSessions=Y2;class Z2 extends N{create($,Y){return this._client.post("/chatkit/sessions",{body:$,...Y,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers]),__security:{bearerAuth:!0}})}cancel($,Y){return this._client.post(J`/chatkit/sessions/${$}/cancel`,{...Y,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers]),__security:{bearerAuth:!0}})}}class w2 extends N{retrieve($,Y){return this._client.get(J`/chatkit/threads/${$}`,{...Y,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers]),__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/chatkit/threads",f,{query:$,...Y,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers]),__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/chatkit/threads/${$}`,{...Y,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers]),__security:{bearerAuth:!0}})}listItems($,Y={},Z){return this._client.getAPIList(J`/chatkit/threads/${$}/items`,f,{query:Y,...Z,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers]),__security:{bearerAuth:!0}})}}class G1 extends N{constructor(){super(...arguments);this.sessions=new Z2(this._client),this.threads=new w2(this._client)}}G1.Sessions=Z2;G1.Threads=w2;class G2 extends N{create($,Y,Z){return this._client.post(J`/threads/${$}/messages`,{body:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}retrieve($,Y,Z){let{thread_id:w}=Y;return this._client.get(J`/threads/${w}/messages/${$}`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}update($,Y,Z){let{thread_id:w,...X}=Y;return this._client.post(J`/threads/${w}/messages/${$}`,{body:X,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/threads/${$}/messages`,S,{query:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}delete($,Y,Z){let{thread_id:w}=Y;return this._client.delete(J`/threads/${w}/messages/${$}`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}class X2 extends N{retrieve($,Y,Z){let{thread_id:w,run_id:X,...W}=Y;return this._client.get(J`/threads/${w}/runs/${X}/steps/${$}`,{query:W,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}list($,Y,Z){let{thread_id:w,...X}=Y;return this._client.getAPIList(J`/threads/${w}/runs/${$}/steps`,S,{query:X,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}var S6=($)=>{if(typeof Buffer<"u"){let Y=Buffer.from($,"base64");return Array.from(new Float32Array(Y.buffer,Y.byteOffset,Y.length/Float32Array.BYTES_PER_ELEMENT))}else{let Y=atob($),Z=Y.length,w=new Uint8Array(Z);for(let X=0;X<Z;X++)w[X]=Y.charCodeAt(X);return Array.from(new Float32Array(w.buffer))}};var U$=($)=>{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 n,W1,O4,E$,N3,M$,J1,b1,X1,B3,V$,z3,V3,Q2,W2,J2,R6,P6,_6,A6,f6,j6,b6;class d$ extends e${constructor(){super(...arguments);n.add(this),O4.set(this,[]),E$.set(this,{}),N3.set(this,{}),M$.set(this,void 0),J1.set(this,void 0),b1.set(this,void 0),X1.set(this,void 0),B3.set(this,void 0),V$.set(this,void 0),z3.set(this,void 0),V3.set(this,void 0),Q2.set(this,void 0)}[(O4=new WeakMap,E$=new WeakMap,N3=new WeakMap,M$=new WeakMap,J1=new WeakMap,b1=new WeakMap,X1=new WeakMap,B3=new WeakMap,V$=new WeakMap,z3=new WeakMap,V3=new WeakMap,Q2=new WeakMap,n=new WeakSet,Symbol.asyncIterator)](){let $=[],Y=[],Z=!1;return this.on("event",(w)=>{let X=Y.shift();if(X)X.resolve(w);else $.push(w)}),this.on("end",()=>{Z=!0;for(let w of Y)w.resolve(void 0);Y.length=0}),this.on("abort",(w)=>{Z=!0;for(let X of Y)X.reject(w);Y.length=0}),this.on("error",(w)=>{Z=!0;for(let X of Y)X.reject(w);Y.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((X,W)=>Y.push({resolve:X,reject:W})).then((X)=>X?{value:X,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 Y=new W1;return Y._run(()=>Y._fromReadableStream($)),Y}async _fromReadableStream($,Y){let Z=Y?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}this._connected();let w=z$.fromReadableStream($,this.controller);for await(let X of w)B(this,n,"m",W2).call(this,X);if(w.controller.signal?.aborted)throw new d;return this._addRun(B(this,n,"m",J2).call(this))}toReadableStream(){return new z$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream($,Y,Z,w){let X=new W1;return X._run(()=>X._runToolAssistantStream($,Y,Z,{...w,headers:{...w?.headers,"X-Stainless-Helper-Method":"stream"}})),X}async _createToolAssistantStream($,Y,Z,w){let X=w?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let W={...Z,stream:!0},G=await $.submitToolOutputs(Y,W,{...w,signal:this.controller.signal});this._connected();for await(let Q of G)B(this,n,"m",W2).call(this,Q);if(G.controller.signal?.aborted)throw new d;return this._addRun(B(this,n,"m",J2).call(this))}static createThreadAssistantStream($,Y,Z){let w=new W1;return w._run(()=>w._threadAssistantStream($,Y,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),w}static createAssistantStream($,Y,Z,w){let X=new W1;return X._run(()=>X._runAssistantStream($,Y,Z,{...w,headers:{...w?.headers,"X-Stainless-Helper-Method":"stream"}})),X}currentEvent(){return B(this,z3,"f")}currentRun(){return B(this,V3,"f")}currentMessageSnapshot(){return B(this,M$,"f")}currentRunStepSnapshot(){return B(this,Q2,"f")}async finalRunSteps(){return await this.done(),Object.values(B(this,E$,"f"))}async finalMessages(){return await this.done(),Object.values(B(this,N3,"f"))}async finalRun(){if(await this.done(),!B(this,J1,"f"))throw Error("Final run was not received.");return B(this,J1,"f")}async _createThreadAssistantStream($,Y,Z){let w=Z?.signal;if(w){if(w.aborted)this.controller.abort();w.addEventListener("abort",()=>this.controller.abort())}let X={...Y,stream:!0},W=await $.createAndRun(X,{...Z,signal:this.controller.signal});this._connected();for await(let G of W)B(this,n,"m",W2).call(this,G);if(W.controller.signal?.aborted)throw new d;return this._addRun(B(this,n,"m",J2).call(this))}async _createAssistantStream($,Y,Z,w){let X=w?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let W={...Z,stream:!0},G=await $.create(Y,W,{...w,signal:this.controller.signal});this._connected();for await(let Q of G)B(this,n,"m",W2).call(this,Q);if(G.controller.signal?.aborted)throw new d;return this._addRun(B(this,n,"m",J2).call(this))}static accumulateDelta($,Y){for(let[Z,w]of Object.entries(Y)){if(!$.hasOwnProperty(Z)){$[Z]=w;continue}let X=$[Z];if(X===null||X===void 0){$[Z]=w;continue}if(Z==="index"||Z==="type"){$[Z]=w;continue}if(typeof X==="string"&&typeof w==="string")X+=w;else if(typeof X==="number"&&typeof w==="number")X+=w;else if(K0(X)&&K0(w))X=this.accumulateDelta(X,w);else if(Array.isArray(X)&&Array.isArray(w)){if(X.every((W)=>typeof W==="string"||typeof W==="number")){X.push(...w);continue}for(let W of w){if(!K0(W))throw Error(`Expected array delta entry to be an object but got: ${W}`);let G=W.index;if(G==null)throw console.error(W),Error("Expected array delta entry to have an `index` property");if(typeof G!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${G}`);let Q=X[G];if(Q==null)X.push(W);else X[G]=this.accumulateDelta(Q,W)}continue}else throw Error(`Unhandled record type: ${Z}, deltaValue: ${w}, accValue: ${X}`);$[Z]=X}return $}_addRun($){return $}async _threadAssistantStream($,Y,Z){return await this._createThreadAssistantStream(Y,$,Z)}async _runAssistantStream($,Y,Z,w){return await this._createAssistantStream(Y,$,Z,w)}async _runToolAssistantStream($,Y,Z,w){return await this._createToolAssistantStream(Y,$,Z,w)}}W1=d$,W2=function(Y){if(this.ended)return;switch(k(this,z3,Y,"f"),B(this,n,"m",_6).call(this,Y),Y.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":B(this,n,"m",b6).call(this,Y);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":B(this,n,"m",P6).call(this,Y);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":B(this,n,"m",R6).call(this,Y);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:vY(Y)}},J2=function(){if(this.ended)throw new O("stream has ended, this shouldn't happen");if(!B(this,J1,"f"))throw Error("Final run has not been received");return B(this,J1,"f")},R6=function(Y){let[Z,w]=B(this,n,"m",f6).call(this,Y,B(this,M$,"f"));k(this,M$,Z,"f"),B(this,N3,"f")[Z.id]=Z;for(let X of w){let W=Z.content[X.index];if(W?.type=="text")this._emit("textCreated",W.text)}switch(Y.event){case"thread.message.created":this._emit("messageCreated",Y.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",Y.data.delta,Z),Y.data.delta.content)for(let X of Y.data.delta.content){if(X.type=="text"&&X.text){let W=X.text,G=Z.content[X.index];if(G&&G.type=="text")this._emit("textDelta",W,G.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(X.index!=B(this,b1,"f")){if(B(this,X1,"f"))switch(B(this,X1,"f").type){case"text":this._emit("textDone",B(this,X1,"f").text,B(this,M$,"f"));break;case"image_file":this._emit("imageFileDone",B(this,X1,"f").image_file,B(this,M$,"f"));break}k(this,b1,X.index,"f")}k(this,X1,Z.content[X.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(B(this,b1,"f")!==void 0){let X=Y.data.content[B(this,b1,"f")];if(X)switch(X.type){case"image_file":this._emit("imageFileDone",X.image_file,B(this,M$,"f"));break;case"text":this._emit("textDone",X.text,B(this,M$,"f"));break}}if(B(this,M$,"f"))this._emit("messageDone",Y.data);k(this,M$,void 0,"f")}},P6=function(Y){let Z=B(this,n,"m",A6).call(this,Y);switch(k(this,Q2,Z,"f"),Y.event){case"thread.run.step.created":this._emit("runStepCreated",Y.data);break;case"thread.run.step.delta":let w=Y.data.delta;if(w.step_details&&w.step_details.type=="tool_calls"&&w.step_details.tool_calls&&Z.step_details.type=="tool_calls")for(let W of w.step_details.tool_calls)if(W.index==B(this,B3,"f"))this._emit("toolCallDelta",W,Z.step_details.tool_calls[W.index]);else{if(B(this,V$,"f"))this._emit("toolCallDone",B(this,V$,"f"));if(k(this,B3,W.index,"f"),k(this,V$,Z.step_details.tool_calls[W.index],"f"),B(this,V$,"f"))this._emit("toolCallCreated",B(this,V$,"f"))}this._emit("runStepDelta",Y.data.delta,Z);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(k(this,Q2,void 0,"f"),Y.data.step_details.type=="tool_calls"){if(B(this,V$,"f"))this._emit("toolCallDone",B(this,V$,"f")),k(this,V$,void 0,"f")}this._emit("runStepDone",Y.data,Z);break;case"thread.run.step.in_progress":break}},_6=function(Y){B(this,O4,"f").push(Y),this._emit("event",Y)},A6=function(Y){switch(Y.event){case"thread.run.step.created":return B(this,E$,"f")[Y.data.id]=Y.data,Y.data;case"thread.run.step.delta":let Z=B(this,E$,"f")[Y.data.id];if(!Z)throw Error("Received a RunStepDelta before creation of a snapshot");let w=Y.data;if(w.delta){let X=W1.accumulateDelta(Z,w.delta);B(this,E$,"f")[Y.data.id]=X}return B(this,E$,"f")[Y.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":B(this,E$,"f")[Y.data.id]=Y.data;break}if(B(this,E$,"f")[Y.data.id])return B(this,E$,"f")[Y.data.id];throw Error("No snapshot available")},f6=function(Y,Z){let w=[];switch(Y.event){case"thread.message.created":return[Y.data,w];case"thread.message.delta":if(!Z)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let X=Y.data;if(X.delta.content)for(let W of X.delta.content)if(W.index in Z.content){let G=Z.content[W.index];Z.content[W.index]=B(this,n,"m",j6).call(this,W,G)}else Z.content[W.index]=W,w.push(W);return[Z,w];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(Z)return[Z,w];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},j6=function(Y,Z){return W1.accumulateDelta(Z,Y)},b6=function(Y){switch(k(this,V3,Y.data,"f"),Y.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(k(this,J1,Y.data,"f"),B(this,V$,"f"))this._emit("toolCallDone",B(this,V$,"f")),k(this,V$,void 0,"f");break;case"thread.run.cancelling":break}};function vY($){}class v1 extends N{constructor(){super(...arguments);this.steps=new X2(this._client)}create($,Y,Z){let{include:w,...X}=Y;return this._client.post(J`/threads/${$}/runs`,{query:{include:w},body:X,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),stream:Y.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve($,Y,Z){let{thread_id:w}=Y;return this._client.get(J`/threads/${w}/runs/${$}`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}update($,Y,Z){let{thread_id:w,...X}=Y;return this._client.post(J`/threads/${w}/runs/${$}`,{body:X,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/threads/${$}/runs`,S,{query:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}cancel($,Y,Z){let{thread_id:w}=Y;return this._client.post(J`/threads/${w}/runs/${$}/cancel`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}async createAndPoll($,Y,Z){let w=await this.create($,Y,Z);return await this.poll(w.id,{thread_id:$},Z)}createAndStream($,Y,Z){return d$.createAssistantStream($,this._client.beta.threads.runs,Y,Z)}async poll($,Y,Z){let w=x([Z?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":Z?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:X,response:W}=await this.retrieve($,Y,{...Z,headers:{...Z?.headers,...w}}).withResponse();switch(X.status){case"queued":case"in_progress":case"cancelling":let G=5000;if(Z?.pollIntervalMs)G=Z.pollIntervalMs;else{let Q=W.headers.get("openai-poll-after-ms");if(Q){let z=parseInt(Q);if(!isNaN(z))G=z}}await q$(G);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return X}}}stream($,Y,Z){return d$.createAssistantStream($,this._client.beta.threads.runs,Y,Z)}submitToolOutputs($,Y,Z){let{thread_id:w,...X}=Y;return this._client.post(J`/threads/${w}/runs/${$}/submit_tool_outputs`,{body:X,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),stream:Y.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll($,Y,Z){let w=await this.submitToolOutputs($,Y,Z);return await this.poll(w.id,Y,Z)}submitToolOutputsStream($,Y,Z){return d$.createToolAssistantStream($,this._client.beta.threads.runs,Y,Z)}}v1.Steps=X2;class Q1 extends N{constructor(){super(...arguments);this.runs=new v1(this._client),this.messages=new G2(this._client)}create($={},Y){return this._client.post("/threads",{body:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/threads/${$}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}update($,Y,Z){return this._client.post(J`/threads/${$}`,{body:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/threads/${$}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}createAndRun($,Y){return this._client.post("/threads/runs",{body:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),stream:$.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll($,Y){let Z=await this.createAndRun($,Y);return await this.runs.poll(Z.id,{thread_id:Z.thread_id},Y)}createAndRunStream($,Y){return d$.createThreadAssistantStream($,this._client.beta.threads,Y)}}Q1.Runs=v1;Q1.Messages=G2;class L$ extends N{constructor(){super(...arguments);this.realtime=new w1(this._client),this.chatkit=new G1(this._client),this.assistants=new e0(this._client),this.threads=new Q1(this._client)}}L$.Realtime=w1;L$.ChatKit=G1;L$.Assistants=e0;L$.Threads=Q1;class y1 extends N{create($,Y){return this._client.post("/completions",{body:$,...Y,stream:$.stream??!1,__security:{bearerAuth:!0}})}}class N2 extends N{retrieve($,Y,Z){let{container_id:w}=Y;return this._client.get(J`/containers/${w}/files/${$}/content`,{...Z,headers:x([{Accept:"application/binary"},Z?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class I1 extends N{constructor(){super(...arguments);this.content=new N2(this._client)}create($,Y,Z){return this._client.post(J`/containers/${$}/files`,h$({body:Y,...Z,__security:{bearerAuth:!0}},this._client))}retrieve($,Y,Z){let{container_id:w}=Y;return this._client.get(J`/containers/${w}/files/${$}`,{...Z,__security:{bearerAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/containers/${$}/files`,S,{query:Y,...Z,__security:{bearerAuth:!0}})}delete($,Y,Z){let{container_id:w}=Y;return this._client.delete(J`/containers/${w}/files/${$}`,{...Z,headers:x([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}}I1.Content=N2;class N1 extends N{constructor(){super(...arguments);this.files=new I1(this._client)}create($,Y){return this._client.post("/containers",{body:$,...Y,__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/containers/${$}`,{...Y,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/containers",S,{query:$,...Y,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/containers/${$}`,{...Y,headers:x([{Accept:"*/*"},Y?.headers]),__security:{bearerAuth:!0}})}}N1.Files=I1;class z2 extends N{create($,Y,Z){let{include:w,...X}=Y;return this._client.post(J`/conversations/${$}/items`,{query:{include:w},body:X,...Z,__security:{bearerAuth:!0}})}retrieve($,Y,Z){let{conversation_id:w,...X}=Y;return this._client.get(J`/conversations/${w}/items/${$}`,{query:X,...Z,__security:{bearerAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/conversations/${$}/items`,f,{query:Y,...Z,__security:{bearerAuth:!0}})}delete($,Y,Z){let{conversation_id:w}=Y;return this._client.delete(J`/conversations/${w}/items/${$}`,{...Z,__security:{bearerAuth:!0}})}}class z1 extends N{constructor(){super(...arguments);this.items=new z2(this._client)}create($={},Y){return this._client.post("/conversations",{body:$,...Y,__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/conversations/${$}`,{...Y,__security:{bearerAuth:!0}})}update($,Y,Z){return this._client.post(J`/conversations/${$}`,{body:Y,...Z,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/conversations/${$}`,{...Y,__security:{bearerAuth:!0}})}}z1.Items=z2;class D1 extends N{create($,Y){let Z=!!$.encoding_format,w=Z?$.encoding_format:"base64";if(Z)c(this._client).debug("embeddings/user defined encoding_format:",$.encoding_format);let X=this._client.post("/embeddings",{body:{...$,encoding_format:w},...Y,__security:{bearerAuth:!0}});if(Z)return X;return c(this._client).debug("embeddings/decoding base64 embeddings from base64"),X._thenUnwrap((W)=>{if(W&&W.data)W.data.forEach((G)=>{let Q=G.embedding;G.embedding=S6(Q)});return W})}}class V2 extends N{retrieve($,Y,Z){let{eval_id:w,run_id:X}=Y;return this._client.get(J`/evals/${w}/runs/${X}/output_items/${$}`,{...Z,__security:{bearerAuth:!0}})}list($,Y,Z){let{eval_id:w,...X}=Y;return this._client.getAPIList(J`/evals/${w}/runs/${$}/output_items`,S,{query:X,...Z,__security:{bearerAuth:!0}})}}class h1 extends N{constructor(){super(...arguments);this.outputItems=new V2(this._client)}create($,Y,Z){return this._client.post(J`/evals/${$}/runs`,{body:Y,...Z,__security:{bearerAuth:!0}})}retrieve($,Y,Z){let{eval_id:w}=Y;return this._client.get(J`/evals/${w}/runs/${$}`,{...Z,__security:{bearerAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/evals/${$}/runs`,S,{query:Y,...Z,__security:{bearerAuth:!0}})}delete($,Y,Z){let{eval_id:w}=Y;return this._client.delete(J`/evals/${w}/runs/${$}`,{...Z,__security:{bearerAuth:!0}})}cancel($,Y,Z){let{eval_id:w}=Y;return this._client.post(J`/evals/${w}/runs/${$}`,{...Z,__security:{bearerAuth:!0}})}}h1.OutputItems=V2;class V1 extends N{constructor(){super(...arguments);this.runs=new h1(this._client)}create($,Y){return this._client.post("/evals",{body:$,...Y,__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/evals/${$}`,{...Y,__security:{bearerAuth:!0}})}update($,Y,Z){return this._client.post(J`/evals/${$}`,{body:Y,...Z,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/evals",S,{query:$,...Y,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/evals/${$}`,{...Y,__security:{bearerAuth:!0}})}}V1.Runs=h1;class g1 extends N{create($,Y){return this._client.post("/files",t({body:$,...Y,__security:{bearerAuth:!0}},this._client))}retrieve($,Y){return this._client.get(J`/files/${$}`,{...Y,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/files",S,{query:$,...Y,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/files/${$}`,{...Y,__security:{bearerAuth:!0}})}content($,Y){return this._client.get(J`/files/${$}/content`,{...Y,headers:x([{Accept:"application/binary"},Y?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing($,{pollInterval:Y=5000,maxWait:Z=1800000}={}){let w=new Set(["processed","error","deleted"]),X=Date.now(),W=await this.retrieve($);while(!W.status||!w.has(W.status))if(await q$(Y),W=await this.retrieve($),Date.now()-X>Z)throw new r$({message:`Giving up on waiting for file ${$} to finish processing after ${Z} milliseconds.`});return W}}class B2 extends N{}class K2 extends N{run($,Y){return this._client.post("/fine_tuning/alpha/graders/run",{body:$,...Y,__security:{bearerAuth:!0}})}validate($,Y){return this._client.post("/fine_tuning/alpha/graders/validate",{body:$,...Y,__security:{bearerAuth:!0}})}}class m1 extends N{constructor(){super(...arguments);this.graders=new K2(this._client)}}m1.Graders=K2;class H2 extends N{create($,Y,Z){return this._client.getAPIList(J`/fine_tuning/checkpoints/${$}/permissions`,Z$,{body:Y,method:"post",...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y={},Z){return this._client.get(J`/fine_tuning/checkpoints/${$}/permissions`,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/fine_tuning/checkpoints/${$}/permissions`,f,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{fine_tuned_model_checkpoint:w}=Y;return this._client.delete(J`/fine_tuning/checkpoints/${w}/permissions/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class c1 extends N{constructor(){super(...arguments);this.permissions=new H2(this._client)}}c1.Permissions=H2;class T2 extends N{list($,Y={},Z){return this._client.getAPIList(J`/fine_tuning/jobs/${$}/checkpoints`,S,{query:Y,...Z,__security:{bearerAuth:!0}})}}class d1 extends N{constructor(){super(...arguments);this.checkpoints=new T2(this._client)}create($,Y){return this._client.post("/fine_tuning/jobs",{body:$,...Y,__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/fine_tuning/jobs/${$}`,{...Y,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/fine_tuning/jobs",S,{query:$,...Y,__security:{bearerAuth:!0}})}cancel($,Y){return this._client.post(J`/fine_tuning/jobs/${$}/cancel`,{...Y,__security:{bearerAuth:!0}})}listEvents($,Y={},Z){return this._client.getAPIList(J`/fine_tuning/jobs/${$}/events`,S,{query:Y,...Z,__security:{bearerAuth:!0}})}pause($,Y){return this._client.post(J`/fine_tuning/jobs/${$}/pause`,{...Y,__security:{bearerAuth:!0}})}resume($,Y){return this._client.post(J`/fine_tuning/jobs/${$}/resume`,{...Y,__security:{bearerAuth:!0}})}}d1.Checkpoints=T2;class F$ extends N{constructor(){super(...arguments);this.methods=new B2(this._client),this.jobs=new d1(this._client),this.checkpoints=new c1(this._client),this.alpha=new m1(this._client)}}F$.Methods=B2;F$.Jobs=d1;F$.Checkpoints=c1;F$.Alpha=m1;class U2 extends N{}class B1 extends N{constructor(){super(...arguments);this.graderModels=new U2(this._client)}}B1.GraderModels=U2;class u1 extends N{createVariation($,Y){return this._client.post("/images/variations",t({body:$,...Y,__security:{bearerAuth:!0}},this._client))}edit($,Y){return this._client.post("/images/edits",t({body:$,...Y,stream:$.stream??!1,__security:{bearerAuth:!0}},this._client))}generate($,Y){return this._client.post("/images/generations",{body:$,...Y,stream:$.stream??!1,__security:{bearerAuth:!0}})}}class l1 extends N{retrieve($,Y){return this._client.get(J`/models/${$}`,{...Y,__security:{bearerAuth:!0}})}list($){return this._client.getAPIList("/models",Z$,{...$,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/models/${$}`,{...Y,__security:{bearerAuth:!0}})}}class p1 extends N{create($,Y){return this._client.post("/moderations",{body:$,...Y,__security:{bearerAuth:!0}})}}class M2 extends N{accept($,Y,Z){return this._client.post(J`/realtime/calls/${$}/accept`,{body:Y,...Z,headers:x([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}hangup($,Y){return this._client.post(J`/realtime/calls/${$}/hangup`,{...Y,headers:x([{Accept:"*/*"},Y?.headers]),__security:{bearerAuth:!0}})}refer($,Y,Z){return this._client.post(J`/realtime/calls/${$}/refer`,{body:Y,...Z,headers:x([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}reject($,Y={},Z){return this._client.post(J`/realtime/calls/${$}/reject`,{body:Y,...Z,headers:x([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}}class x2 extends N{create($,Y){return this._client.post("/realtime/client_secrets",{body:$,...Y,__security:{bearerAuth:!0}})}}class u$ extends N{constructor(){super(...arguments);this.clientSecrets=new x2(this._client),this.calls=new M2(this._client)}}u$.ClientSecrets=x2;u$.Calls=M2;function v6($,Y){if(!Y||!eY(Y))return{...$,output_parsed:null,output:$.output.map((Z)=>{if(Z.type==="function_call")return{...Z,parsed_arguments:null};if(Z.type==="message")return{...Z,content:Z.content.map((w)=>({...w,parsed:null}))};else return Z})};return E4($,Y)}function E4($,Y){let Z=$.output.map((X)=>{if(X.type==="function_call")return{...X,parsed_arguments:ZZ(Y,X)};if(X.type==="message"){let W=X.content.map((G)=>{if(G.type==="output_text")return{...G,parsed:oY(Y,G.text)};return G});return{...X,content:W}}return X}),w=Object.assign({},$,{output:Z});if(!Object.getOwnPropertyDescriptor($,"output_text"))q2(w);return Object.defineProperty(w,"output_parsed",{enumerable:!0,get(){for(let X of w.output){if(X.type!=="message")continue;for(let W of X.content)if(W.type==="output_text"&&W.parsed!==null)return W.parsed}return null}}),w}function oY($,Y){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(Y);return JSON.parse(Y)}function eY($){if(O0($.text?.format))return!0;return!1}function $Z($){return $?.$brand==="auto-parseable-tool"}function YZ($,Y){return $.find((Z)=>Z.type==="function"&&Z.name===Y)}function ZZ($,Y){let Z=YZ($.tools??[],Y.name);return{...Y,...Y,parsed_arguments:$Z(Z)?Z.$parseRaw(Y.arguments):Z?.strict?JSON.parse(Y.arguments):null}}function q2($){let Y=[];for(let Z of $.output){if(Z.type!=="message")continue;for(let w of Z.content)if(w.type==="output_text")Y.push(w.text)}$.output_text=Y.join("")}var i1,K3,l$,H3,y6,I6,D6,h6;class T3 extends e${constructor($){super();i1.add(this),K3.set(this,void 0),l$.set(this,void 0),H3.set(this,void 0),k(this,K3,$,"f")}static createResponse($,Y,Z){let w=new T3(Y);return w._run(()=>w._createOrRetrieveResponse($,Y,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),w}async _createOrRetrieveResponse($,Y,Z){let w=Z?.signal;if(w){if(w.aborted)this.controller.abort();w.addEventListener("abort",()=>this.controller.abort())}B(this,i1,"m",y6).call(this);let X,W=null;if("response_id"in Y)X=await $.responses.retrieve(Y.response_id,{stream:!0},{...Z,signal:this.controller.signal,stream:!0}),W=Y.starting_after??null;else X=await $.responses.create({...Y,stream:!0},{...Z,signal:this.controller.signal});this._connected();for await(let G of X)B(this,i1,"m",I6).call(this,G,W);if(X.controller.signal?.aborted)throw new d;return B(this,i1,"m",D6).call(this)}[(K3=new WeakMap,l$=new WeakMap,H3=new WeakMap,i1=new WeakSet,y6=function(){if(this.ended)return;k(this,l$,void 0,"f")},I6=function(Y,Z){if(this.ended)return;let w=(W,G)=>{if(Z==null||G.sequence_number>Z)this._emit(W,G)},X=B(this,i1,"m",h6).call(this,Y);switch(w("event",Y),Y.type){case"response.output_text.delta":{let W=X.output[Y.output_index];if(!W)throw new O(`missing output at index ${Y.output_index}`);if(W.type==="message"){let G=W.content[Y.content_index];if(!G)throw new O(`missing content at index ${Y.content_index}`);if(G.type!=="output_text")throw new O(`expected content to be 'output_text', got ${G.type}`);w("response.output_text.delta",{...Y,snapshot:G.text})}break}case"response.function_call_arguments.delta":{let W=X.output[Y.output_index];if(!W)throw new O(`missing output at index ${Y.output_index}`);if(W.type==="function_call")w("response.function_call_arguments.delta",{...Y,snapshot:W.arguments});break}default:w(Y.type,Y);break}},D6=function(){if(this.ended)throw new O("stream has ended, this shouldn't happen");let Y=B(this,l$,"f");if(!Y)throw new O("request ended without sending any events");k(this,l$,void 0,"f");let Z=wZ(Y,B(this,K3,"f"));return k(this,H3,Z,"f"),Z},h6=function(Y){let Z=B(this,l$,"f");if(!Z){if(Y.type!=="response.created")throw new O(`When snapshot hasn't been set yet, expected 'response.created' event, got ${Y.type}`);return Z=k(this,l$,Y.response,"f"),Z}switch(Y.type){case"response.output_item.added":{Z.output.push(Y.item);break}case"response.content_part.added":{let w=Z.output[Y.output_index];if(!w)throw new O(`missing output at index ${Y.output_index}`);let X=w.type,W=Y.part;if(X==="message"&&W.type!=="reasoning_text")w.content.push(W);else if(X==="reasoning"&&W.type==="reasoning_text"){if(!w.content)w.content=[];w.content.push(W)}break}case"response.output_text.delta":{let w=Z.output[Y.output_index];if(!w)throw new O(`missing output at index ${Y.output_index}`);if(w.type==="message"){let X=w.content[Y.content_index];if(!X)throw new O(`missing content at index ${Y.content_index}`);if(X.type!=="output_text")throw new O(`expected content to be 'output_text', got ${X.type}`);X.text+=Y.delta}break}case"response.function_call_arguments.delta":{let w=Z.output[Y.output_index];if(!w)throw new O(`missing output at index ${Y.output_index}`);if(w.type==="function_call")w.arguments+=Y.delta;break}case"response.reasoning_text.delta":{let w=Z.output[Y.output_index];if(!w)throw new O(`missing output at index ${Y.output_index}`);if(w.type==="reasoning"){let X=w.content?.[Y.content_index];if(!X)throw new O(`missing content at index ${Y.content_index}`);if(X.type!=="reasoning_text")throw new O(`expected content to be 'reasoning_text', got ${X.type}`);X.text+=Y.delta}break}case"response.completed":{k(this,l$,Y.response,"f");break}}return Z},Symbol.asyncIterator)](){let $=[],Y=[],Z=!1;return this.on("event",(w)=>{let X=Y.shift();if(X)X.resolve(w);else $.push(w)}),this.on("end",()=>{Z=!0;for(let w of Y)w.resolve(void 0);Y.length=0}),this.on("abort",(w)=>{Z=!0;for(let X of Y)X.reject(w);Y.length=0}),this.on("error",(w)=>{Z=!0;for(let X of Y)X.reject(w);Y.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((X,W)=>Y.push({resolve:X,reject:W})).then((X)=>X?{value:X,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 $=B(this,H3,"f");if(!$)throw new O("stream ended without producing a ChatCompletion");return $}}function wZ($,Y){return v6($,Y)}class O2 extends N{list($,Y={},Z){return this._client.getAPIList(J`/responses/${$}/input_items`,S,{query:Y,...Z,__security:{bearerAuth:!0}})}}class E2 extends N{count($={},Y){return this._client.post("/responses/input_tokens",{body:$,...Y,__security:{bearerAuth:!0}})}}class j$ extends N{constructor(){super(...arguments);this.inputItems=new O2(this._client),this.inputTokens=new E2(this._client)}create($,Y){return this._client.post("/responses",{body:$,...Y,stream:$.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap((Z)=>{if("object"in Z&&Z.object==="response")q2(Z);return Z})}retrieve($,Y={},Z){return this._client.get(J`/responses/${$}`,{query:Y,...Z,stream:Y?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap((w)=>{if("object"in w&&w.object==="response")q2(w);return w})}delete($,Y){return this._client.delete(J`/responses/${$}`,{...Y,headers:x([{Accept:"*/*"},Y?.headers]),__security:{bearerAuth:!0}})}parse($,Y){return this._client.responses.create($,Y)._thenUnwrap((Z)=>E4(Z,$))}stream($,Y){return T3.createResponse(this._client,$,Y)}cancel($,Y){return this._client.post(J`/responses/${$}/cancel`,{...Y,__security:{bearerAuth:!0}})}compact($,Y){return this._client.post("/responses/compact",{body:$,...Y,__security:{bearerAuth:!0}})}}j$.InputItems=O2;j$.InputTokens=E2;class L2 extends N{retrieve($,Y){return this._client.get(J`/skills/${$}/content`,{...Y,headers:x([{Accept:"application/binary"},Y?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class F2 extends N{retrieve($,Y,Z){let{skill_id:w}=Y;return this._client.get(J`/skills/${w}/versions/${$}/content`,{...Z,headers:x([{Accept:"application/binary"},Z?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class n1 extends N{constructor(){super(...arguments);this.content=new F2(this._client)}create($,Y={},Z){return this._client.post(J`/skills/${$}/versions`,h$({body:Y,...Z,__security:{bearerAuth:!0}},this._client))}retrieve($,Y,Z){let{skill_id:w}=Y;return this._client.get(J`/skills/${w}/versions/${$}`,{...Z,__security:{bearerAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/skills/${$}/versions`,S,{query:Y,...Z,__security:{bearerAuth:!0}})}delete($,Y,Z){let{skill_id:w}=Y;return this._client.delete(J`/skills/${w}/versions/${$}`,{...Z,__security:{bearerAuth:!0}})}}n1.Content=F2;class p$ extends N{constructor(){super(...arguments);this.content=new L2(this._client),this.versions=new n1(this._client)}create($={},Y){return this._client.post("/skills",h$({body:$,...Y,__security:{bearerAuth:!0}},this._client))}retrieve($,Y){return this._client.get(J`/skills/${$}`,{...Y,__security:{bearerAuth:!0}})}update($,Y,Z){return this._client.post(J`/skills/${$}`,{body:Y,...Z,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/skills",S,{query:$,...Y,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/skills/${$}`,{...Y,__security:{bearerAuth:!0}})}}p$.Content=L2;p$.Versions=n1;class k2 extends N{create($,Y,Z){return this._client.post(J`/uploads/${$}/parts`,t({body:Y,...Z,__security:{bearerAuth:!0}},this._client))}}class K1 extends N{constructor(){super(...arguments);this.parts=new k2(this._client)}create($,Y){return this._client.post("/uploads",{body:$,...Y,__security:{bearerAuth:!0}})}cancel($,Y){return this._client.post(J`/uploads/${$}/cancel`,{...Y,__security:{bearerAuth:!0}})}complete($,Y,Z){return this._client.post(J`/uploads/${$}/complete`,{body:Y,...Z,__security:{bearerAuth:!0}})}}K1.Parts=k2;var g6=async($)=>{let Y=await Promise.allSettled($),Z=Y.filter((X)=>X.status==="rejected");if(Z.length){for(let X of Z)console.error(X.reason);throw Error(`${Z.length} promise(s) failed - see the above errors`)}let w=[];for(let X of Y)if(X.status==="fulfilled")w.push(X.value);return w};class C2 extends N{create($,Y,Z){return this._client.post(J`/vector_stores/${$}/file_batches`,{body:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}retrieve($,Y,Z){let{vector_store_id:w}=Y;return this._client.get(J`/vector_stores/${w}/file_batches/${$}`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}cancel($,Y,Z){let{vector_store_id:w}=Y;return this._client.post(J`/vector_stores/${w}/file_batches/${$}/cancel`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}async createAndPoll($,Y,Z){let w=await this.create($,Y);return await this.poll($,w.id,Z)}listFiles($,Y,Z){let{vector_store_id:w,...X}=Y;return this._client.getAPIList(J`/vector_stores/${w}/file_batches/${$}/files`,S,{query:X,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}async poll($,Y,Z){let w=x([Z?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":Z?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:X,response:W}=await this.retrieve(Y,{vector_store_id:$},{...Z,headers:w}).withResponse();switch(X.status){case"in_progress":let G=5000;if(Z?.pollIntervalMs)G=Z.pollIntervalMs;else{let Q=W.headers.get("openai-poll-after-ms");if(Q){let z=parseInt(Q);if(!isNaN(z))G=z}}await q$(G);break;case"failed":case"cancelled":case"completed":return X}}}async uploadAndPoll($,{files:Y,fileIds:Z=[]},w){if(Y==null||Y.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let X=w?.maxConcurrency??5,W=Math.min(X,Y.length),G=this._client,Q=Y.values(),z=[...Z];async function H(K){for(let U of K){let M=await G.files.create({file:U,purpose:"assistants"},w);z.push(M.id)}}let T=Array(W).fill(Q).map(H);return await g6(T),await this.createAndPoll($,{file_ids:z})}}class S2 extends N{create($,Y,Z){return this._client.post(J`/vector_stores/${$}/files`,{body:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}retrieve($,Y,Z){let{vector_store_id:w}=Y;return this._client.get(J`/vector_stores/${w}/files/${$}`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}update($,Y,Z){let{vector_store_id:w,...X}=Y;return this._client.post(J`/vector_stores/${w}/files/${$}`,{body:X,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/vector_stores/${$}/files`,S,{query:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}delete($,Y,Z){let{vector_store_id:w}=Y;return this._client.delete(J`/vector_stores/${w}/files/${$}`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}async createAndPoll($,Y,Z){let w=await this.create($,Y,Z);return await this.poll($,w.id,Z)}async poll($,Y,Z){let w=x([Z?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":Z?.pollIntervalMs?.toString()??void 0}]);while(!0){let X=await this.retrieve(Y,{vector_store_id:$},{...Z,headers:w}).withResponse(),W=X.data;switch(W.status){case"in_progress":let G=5000;if(Z?.pollIntervalMs)G=Z.pollIntervalMs;else{let Q=X.response.headers.get("openai-poll-after-ms");if(Q){let z=parseInt(Q);if(!isNaN(z))G=z}}await q$(G);break;case"failed":case"completed":return W}}}async upload($,Y,Z){let w=await this._client.files.create({file:Y,purpose:"assistants"},Z);return this.create($,{file_id:w.id},Z)}async uploadAndPoll($,Y,Z){let w=await this.upload($,Y,Z);return await this.poll($,w.id,Z)}content($,Y,Z){let{vector_store_id:w}=Y;return this._client.getAPIList(J`/vector_stores/${w}/files/${$}/content`,Z$,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}class i$ extends N{constructor(){super(...arguments);this.files=new S2(this._client),this.fileBatches=new C2(this._client)}create($,Y){return this._client.post("/vector_stores",{body:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/vector_stores/${$}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}update($,Y,Z){return this._client.post(J`/vector_stores/${$}`,{body:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/vector_stores",S,{query:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/vector_stores/${$}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}search($,Y,Z){return this._client.getAPIList(J`/vector_stores/${$}/search`,Z$,{body:Y,method:"post",...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}i$.Files=S2;i$.FileBatches=C2;class a1 extends N{create($,Y){return this._client.post("/videos",t({body:$,...Y,__security:{bearerAuth:!0}},this._client))}retrieve($,Y){return this._client.get(J`/videos/${$}`,{...Y,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/videos",f,{query:$,...Y,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/videos/${$}`,{...Y,__security:{bearerAuth:!0}})}createCharacter($,Y){return this._client.post("/videos/characters",t({body:$,...Y,__security:{bearerAuth:!0}},this._client))}downloadContent($,Y={},Z){return this._client.get(J`/videos/${$}/content`,{query:Y,...Z,headers:x([{Accept:"application/binary"},Z?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit($,Y){return this._client.post("/videos/edits",t({body:$,...Y,__security:{bearerAuth:!0}},this._client))}extend($,Y){return this._client.post("/videos/extensions",t({body:$,...Y,__security:{bearerAuth:!0}},this._client))}getCharacter($,Y){return this._client.get(J`/videos/characters/${$}`,{...Y,__security:{bearerAuth:!0}})}remix($,Y,Z){return this._client.post(J`/videos/${$}/remix`,h$({body:Y,...Z,__security:{bearerAuth:!0}},this._client))}}var t1,m6,U3;class r1 extends N{constructor(){super(...arguments);t1.add(this)}async unwrap($,Y,Z=this._client.webhookSecret,w=300){return await this.verifySignature($,Y,Z,w),JSON.parse($)}async verifySignature($,Y,Z=this._client.webhookSecret,w=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");B(this,t1,"m",m6).call(this,Z);let X=x([Y]).values,W=B(this,t1,"m",U3).call(this,X,"webhook-signature"),G=B(this,t1,"m",U3).call(this,X,"webhook-timestamp"),Q=B(this,t1,"m",U3).call(this,X,"webhook-id"),z=parseInt(G,10);if(isNaN(z))throw new R$("Invalid webhook timestamp format");let H=Math.floor(Date.now()/1000);if(H-z>w)throw new R$("Webhook timestamp is too old");if(z>H+w)throw new R$("Webhook timestamp is too new");let T=W.split(" ").map((q)=>q.startsWith("v1,")?q.substring(3):q),K=Z.startsWith("whsec_")?Buffer.from(Z.replace("whsec_",""),"base64"):Buffer.from(Z,"utf-8"),U=Q?`${Q}.${G}.${$}`:`${G}.${$}`,M=await crypto.subtle.importKey("raw",K,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let q of T)try{let P=Buffer.from(q,"base64");if(await crypto.subtle.verify("HMAC",M,P,new TextEncoder().encode(U)))return}catch{continue}throw new R$("The given webhook signature does not match the expected signature")}}t1=new WeakSet,m6=function(Y){if(typeof Y!=="string"||Y.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")},U3=function(Y,Z){if(!Y)throw Error("Headers are required");let w=Y.get(Z);if(w===null||w===void 0)throw Error(`Missing required header: ${Z}`);return w};var L4,F4,M3,d6,BZ="workload-identity-auth";class C{constructor({baseURL:$=U$("OPENAI_BASE_URL"),apiKey:Y=U$("OPENAI_API_KEY")??null,adminAPIKey:Z=U$("OPENAI_ADMIN_KEY")??null,organization:w=U$("OPENAI_ORG_ID")??null,project:X=U$("OPENAI_PROJECT_ID")??null,webhookSecret:W=U$("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:G,...Q}={}){L4.add(this),M3.set(this,void 0),this.completions=new y1(this),this.chat=new $1(this),this.embeddings=new D1(this),this.files=new g1(this),this.images=new u1(this),this.audio=new f$(this),this.moderations=new p1(this),this.models=new l1(this),this.fineTuning=new F$(this),this.graders=new B1(this),this.vectorStores=new i$(this),this.webhooks=new r1(this),this.beta=new L$(this),this.batches=new j1(this),this.uploads=new K1(this),this.admin=new Z1(this),this.responses=new j$(this),this.realtime=new u$(this),this.conversations=new z1(this),this.evals=new V1(this),this.containers=new N1(this),this.skills=new p$(this),this.videos=new a1(this);let z={apiKey:Y,adminAPIKey:Z,organization:w,project:X,webhookSecret:W,workloadIdentity:G,...Q,baseURL:$||"https://api.openai.com/v1"};if(Y&&G)throw new O("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!Y&&!Z&&!G)throw new O("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!z.dangerouslyAllowBrowser&&m9())throw new O(`It looks like you're running in a browser-like environment.
190
+ ${K}`)}return G},J=a8(K6);class k1 extends N{list($,Y={},Z){return this._client.getAPIList(J`/chat/completions/${$}/messages`,S,{query:Y,...Z,__security:{bearerAuth:!0}})}}function q0($){return $!==void 0&&"function"in $&&$.function!==void 0}function O0($){return $?.$brand==="auto-parseable-response-format"}function o$($){return $?.$brand==="auto-parseable-tool"}function T6($,Y){if(!Y||!z4(Y))return{...$,choices:$.choices.map((Z)=>{return M6(Z.message.tool_calls),{...Z,message:{...Z.message,parsed:null,...Z.message.tool_calls?{tool_calls:Z.message.tool_calls}:void 0}}})};return E0($,Y)}function E0($,Y){let Z=$.choices.map((w)=>{if(w.finish_reason==="length")throw new V0;if(w.finish_reason==="content_filter")throw new B0;return M6(w.message.tool_calls),{...w,message:{...w.message,...w.message.tool_calls?{tool_calls:w.message.tool_calls?.map((X)=>s8(Y,X))??void 0}:void 0,parsed:w.message.content&&!w.message.refusal?r8(Y,w.message.content):null}}});return{...$,choices:Z}}function r8($,Y){if($.response_format?.type!=="json_schema")return null;if($.response_format?.type==="json_schema"){if("$parseRaw"in $.response_format)return $.response_format.$parseRaw(Y);return JSON.parse(Y)}return null}function s8($,Y){let Z=$.tools?.find((w)=>q0(w)&&w.function?.name===Y.function.name);return{...Y,function:{...Y.function,parsed_arguments:o$(Z)?Z.$parseRaw(Y.function.arguments):Z?.function.strict?JSON.parse(Y.function.arguments):null}}}function U6($,Y){if(!$||!("tools"in $)||!$.tools)return!1;let Z=$.tools?.find((w)=>q0(w)&&w.function?.name===Y.function.name);return q0(Z)&&(o$(Z)||Z?.function.strict||!1)}function z4($){if(O0($.response_format))return!0;return $.tools?.some((Y)=>o$(Y)||Y.type==="function"&&Y.function.strict===!0)??!1}function M6($){for(let Y of $||[])if(Y.type!=="function")throw new O(`Currently only \`function\` tool calls are supported; Received \`${Y.type}\``)}function x6($){for(let Y of $??[]){if(Y.type!=="function")throw new O(`Currently only \`function\` tool types support auto-parsing; Received \`${Y.type}\``);if(Y.function.strict!==!0)throw new O(`The \`${Y.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var C1=($)=>{return $?.role==="assistant"},N4=($)=>{return $?.role==="tool"};var V4,Y3,Z3,L0,F0,w3,k0,_$,C0,G3,X3,S1,q6;class e${constructor(){V4.add(this),this.controller=new AbortController,Y3.set(this,void 0),Z3.set(this,()=>{}),L0.set(this,()=>{}),F0.set(this,void 0),w3.set(this,()=>{}),k0.set(this,()=>{}),_$.set(this,{}),C0.set(this,!1),G3.set(this,!1),X3.set(this,!1),S1.set(this,!1),k(this,Y3,new Promise(($,Y)=>{k(this,Z3,$,"f"),k(this,L0,Y,"f")}),"f"),k(this,F0,new Promise(($,Y)=>{k(this,w3,$,"f"),k(this,k0,Y,"f")}),"f"),B(this,Y3,"f").catch(()=>{}),B(this,F0,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},B(this,V4,"m",q6).bind(this))},0)}_connected(){if(this.ended)return;B(this,Z3,"f").call(this),this._emit("connect")}get ended(){return B(this,C0,"f")}get errored(){return B(this,G3,"f")}get aborted(){return B(this,X3,"f")}abort(){this.controller.abort()}on($,Y){return(B(this,_$,"f")[$]||(B(this,_$,"f")[$]=[])).push({listener:Y}),this}off($,Y){let Z=B(this,_$,"f")[$];if(!Z)return this;let w=Z.findIndex((X)=>X.listener===Y);if(w>=0)Z.splice(w,1);return this}once($,Y){return(B(this,_$,"f")[$]||(B(this,_$,"f")[$]=[])).push({listener:Y,once:!0}),this}emitted($){return new Promise((Y,Z)=>{if(k(this,S1,!0,"f"),$!=="error")this.once("error",Z);this.once($,Y)})}async done(){k(this,S1,!0,"f"),await B(this,F0,"f")}_emit($,...Y){if(B(this,C0,"f"))return;if($==="end")k(this,C0,!0,"f"),B(this,w3,"f").call(this);let Z=B(this,_$,"f")[$];if(Z)B(this,_$,"f")[$]=Z.filter((w)=>!w.once),Z.forEach(({listener:w})=>w(...Y));if($==="abort"){let w=Y[0];if(!B(this,S1,"f")&&!Z?.length)Promise.reject(w);B(this,L0,"f").call(this,w),B(this,k0,"f").call(this,w),this._emit("end");return}if($==="error"){let w=Y[0];if(!B(this,S1,"f")&&!Z?.length)Promise.reject(w);B(this,L0,"f").call(this,w),B(this,k0,"f").call(this,w),this._emit("end")}}_emitFinal(){}}Y3=new WeakMap,Z3=new WeakMap,L0=new WeakMap,F0=new WeakMap,w3=new WeakMap,k0=new WeakMap,_$=new WeakMap,C0=new WeakMap,G3=new WeakMap,X3=new WeakMap,S1=new WeakMap,V4=new WeakSet,q6=function(Y){if(k(this,G3,!0,"f"),Y instanceof Error&&Y.name==="AbortError")Y=new d;if(Y instanceof d)return k(this,X3,!0,"f"),this._emit("abort",Y);if(Y instanceof O)return this._emit("error",Y);if(Y instanceof Error){let Z=new O(Y.message);return Z.cause=Y,this._emit("error",Z)}return this._emit("error",new O(String(Y)))};function O6($){return typeof $.parse==="function"}var w$,B4,W3,K4,H4,T4,E6,L6,o8=10;class S0 extends e${constructor(){super(...arguments);w$.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion($){this._chatCompletions.push($),this._emit("chatCompletion",$);let Y=$.choices[0]?.message;if(Y)this._addMessage(Y);return $}_addMessage($,Y=!0){if(!("content"in $))$.content=null;if(this.messages.push($),Y){if(this._emit("message",$),N4($)&&$.content)this._emit("functionToolCallResult",$.content);else if(C1($)&&$.tool_calls){for(let Z of $.tool_calls)if(Z.type==="function")this._emit("functionToolCall",Z.function)}}}async finalChatCompletion(){await this.done();let $=this._chatCompletions[this._chatCompletions.length-1];if(!$)throw new O("stream ended without producing a ChatCompletion");return $}async finalContent(){return await this.done(),B(this,w$,"m",B4).call(this)}async finalMessage(){return await this.done(),B(this,w$,"m",W3).call(this)}async finalFunctionToolCall(){return await this.done(),B(this,w$,"m",K4).call(this)}async finalFunctionToolCallResult(){return await this.done(),B(this,w$,"m",H4).call(this)}async totalUsage(){return await this.done(),B(this,w$,"m",T4).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let $=this._chatCompletions[this._chatCompletions.length-1];if($)this._emit("finalChatCompletion",$);let Y=B(this,w$,"m",W3).call(this);if(Y)this._emit("finalMessage",Y);let Z=B(this,w$,"m",B4).call(this);if(Z)this._emit("finalContent",Z);let w=B(this,w$,"m",K4).call(this);if(w)this._emit("finalFunctionToolCall",w);let X=B(this,w$,"m",H4).call(this);if(X!=null)this._emit("finalFunctionToolCallResult",X);if(this._chatCompletions.some((W)=>W.usage))this._emit("totalUsage",B(this,w$,"m",T4).call(this))}async _createChatCompletion($,Y,Z){let w=Z?.signal;if(w){if(w.aborted)this.controller.abort();w.addEventListener("abort",()=>this.controller.abort())}B(this,w$,"m",E6).call(this,Y);let X=await $.chat.completions.create({...Y,stream:!1},{...Z,signal:this.controller.signal});return this._connected(),this._addChatCompletion(E0(X,Y))}async _runChatCompletion($,Y,Z){for(let w of Y.messages)this._addMessage(w,!1);return await this._createChatCompletion($,Y,Z)}async _runTools($,Y,Z){let{tool_choice:X="auto",stream:W,...G}=Y,Q=typeof X!=="string"&&X.type==="function"&&X?.function?.name,{maxChatCompletions:V=o8}=Z||{},H=Y.tools.map((U)=>{if(o$(U)){if(!U.$callback)throw new O("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:U.$callback,name:U.function.name,description:U.function.description||"",parameters:U.function.parameters,parse:U.$parseRaw,strict:!0}}}return U}),T={};for(let U of H)if(U.type==="function")T[U.function.name||U.function.function.name]=U.function;let K="tools"in Y?H.map((U)=>U.type==="function"?{type:"function",function:{name:U.function.name||U.function.function.name,parameters:U.function.parameters,description:U.function.description,strict:U.function.strict}}:U):void 0;for(let U of Y.messages)this._addMessage(U,!1);for(let U=0;U<V;++U){let q=(await this._createChatCompletion($,{...G,tool_choice:X,tools:K,messages:[...this.messages]},Z)).choices[0]?.message;if(!q)throw new O("missing message in ChatCompletion response");if(!q.tool_calls?.length)return;for(let P of q.tool_calls){if(P.type!=="function")continue;let A=P.id,{name:R,arguments:F}=P.function,b=T[R];if(!b){let I=`Invalid tool_call: ${JSON.stringify(R)}. Available options are: ${Object.keys(T).map(($$)=>JSON.stringify($$)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:A,content:I});continue}else if(Q&&Q!==R){let I=`Invalid tool_call: ${JSON.stringify(R)}. ${JSON.stringify(Q)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:A,content:I});continue}let v;try{v=O6(b)?await b.parse(F):F}catch(I){let $$=I instanceof Error?I.message:String(I);this._addMessage({role:"tool",tool_call_id:A,content:$$});continue}let o=await b.function(v,this),e=B(this,w$,"m",L6).call(this,o);if(this._addMessage({role:"tool",tool_call_id:A,content:e}),Q)return}}return}}w$=new WeakSet,B4=function(){return B(this,w$,"m",W3).call(this).content??null},W3=function(){let Y=this.messages.length;while(Y-- >0){let Z=this.messages[Y];if(C1(Z))return{...Z,content:Z.content??null,refusal:Z.refusal??null}}throw new O("stream ended without producing a ChatCompletionMessage with role=assistant")},K4=function(){for(let Y=this.messages.length-1;Y>=0;Y--){let Z=this.messages[Y];if(C1(Z)&&Z?.tool_calls?.length)return Z.tool_calls.filter((w)=>w.type==="function").at(-1)?.function}return},H4=function(){for(let Y=this.messages.length-1;Y>=0;Y--){let Z=this.messages[Y];if(N4(Z)&&Z.content!=null&&typeof Z.content==="string"&&this.messages.some((w)=>w.role==="assistant"&&w.tool_calls?.some((X)=>X.type==="function"&&X.id===Z.tool_call_id)))return Z.content}return},T4=function(){let Y={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:Z}of this._chatCompletions)if(Z)Y.completion_tokens+=Z.completion_tokens,Y.prompt_tokens+=Z.prompt_tokens,Y.total_tokens+=Z.total_tokens;return Y},E6=function(Y){if(Y.n!=null&&Y.n>1)throw new O("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},L6=function(Y){return typeof Y==="string"?Y:Y===void 0?"undefined":JSON.stringify(Y)};class R0 extends S0{static runTools($,Y,Z){let w=new R0,X={...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"runTools"}};return w._run(()=>w._runTools($,Y,X)),w}_addMessage($,Y=!0){if(super._addMessage($,Y),C1($)&&$.content)this._emit("content",$.content)}}var i={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 F6 extends Error{}class k6 extends Error{}function e8($,Y=i.ALL){if(typeof $!=="string")throw TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw Error(`${$} is empty`);return $Y($.trim(),Y)}var $Y=($,Y)=>{let Z=$.length,w=0,X=(U)=>{throw new F6(`${U} at position ${w}`)},W=(U)=>{throw new k6(`${U} at position ${w}`)},G=()=>{if(K(),w>=Z)X("Unexpected end of input");if($[w]==='"')return Q();if($[w]==="{")return V();if($[w]==="[")return H();if($.substring(w,w+4)==="null"||i.NULL&Y&&Z-w<4&&"null".startsWith($.substring(w)))return w+=4,null;if($.substring(w,w+4)==="true"||i.BOOL&Y&&Z-w<4&&"true".startsWith($.substring(w)))return w+=4,!0;if($.substring(w,w+5)==="false"||i.BOOL&Y&&Z-w<5&&"false".startsWith($.substring(w)))return w+=5,!1;if($.substring(w,w+8)==="Infinity"||i.INFINITY&Y&&Z-w<8&&"Infinity".startsWith($.substring(w)))return w+=8,1/0;if($.substring(w,w+9)==="-Infinity"||i.MINUS_INFINITY&Y&&1<Z-w&&Z-w<9&&"-Infinity".startsWith($.substring(w)))return w+=9,-1/0;if($.substring(w,w+3)==="NaN"||i.NAN&Y&&Z-w<3&&"NaN".startsWith($.substring(w)))return w+=3,NaN;return T()},Q=()=>{let U=w,M=!1;w++;while(w<Z&&($[w]!=='"'||M&&$[w-1]==="\\"))M=$[w]==="\\"?!M:!1,w++;if($.charAt(w)=='"')try{return JSON.parse($.substring(U,++w-Number(M)))}catch(q){W(String(q))}else if(i.STR&Y)try{return JSON.parse($.substring(U,w-Number(M))+'"')}catch(q){return JSON.parse($.substring(U,$.lastIndexOf("\\"))+'"')}X("Unterminated string literal")},V=()=>{w++,K();let U={};try{while($[w]!=="}"){if(K(),w>=Z&&i.OBJ&Y)return U;let M=Q();K(),w++;try{let q=G();Object.defineProperty(U,M,{value:q,writable:!0,enumerable:!0,configurable:!0})}catch(q){if(i.OBJ&Y)return U;else throw q}if(K(),$[w]===",")w++}}catch(M){if(i.OBJ&Y)return U;else X("Expected '}' at end of object")}return w++,U},H=()=>{w++;let U=[];try{while($[w]!=="]")if(U.push(G()),K(),$[w]===",")w++}catch(M){if(i.ARR&Y)return U;X("Expected ']' at end of array")}return w++,U},T=()=>{if(w===0){if($==="-"&&i.NUM&Y)X("Not sure what '-' is");try{return JSON.parse($)}catch(M){if(i.NUM&Y)try{if($[$.length-1]===".")return JSON.parse($.substring(0,$.lastIndexOf(".")));return JSON.parse($.substring(0,$.lastIndexOf("e")))}catch(q){}W(String(M))}}let U=w;if($[w]==="-")w++;while($[w]&&!",]}".includes($[w]))w++;if(w==Z&&!(i.NUM&Y))X("Unterminated number literal");try{return JSON.parse($.substring(U,w))}catch(M){if($.substring(U,w)==="-"&&i.NUM&Y)X("Not sure what '-' is");try{return JSON.parse($.substring(U,$.lastIndexOf("e")))}catch(q){W(String(q))}}},K=()=>{while(w<Z&&`
191
+ \r `.includes($[w]))w++};return G()},U4=($)=>e8($,i.ALL^i.NUM);var p,A$,R1,g$,M4,J3,x4,q4,O4,Q3,E4,C6;class m$ extends S0{constructor($){super();p.add(this),A$.set(this,void 0),R1.set(this,void 0),g$.set(this,void 0),k(this,A$,$,"f"),k(this,R1,[],"f")}get currentChatCompletionSnapshot(){return B(this,g$,"f")}static fromReadableStream($){let Y=new m$(null);return Y._run(()=>Y._fromReadableStream($)),Y}static createChatCompletion($,Y,Z){let w=new m$(Y);return w._run(()=>w._runChatCompletion($,{...Y,stream:!0},{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),w}async _createChatCompletion($,Y,Z){super._createChatCompletion;let w=Z?.signal;if(w){if(w.aborted)this.controller.abort();w.addEventListener("abort",()=>this.controller.abort())}B(this,p,"m",M4).call(this);let X=await $.chat.completions.create({...Y,stream:!0},{...Z,signal:this.controller.signal});this._connected();for await(let W of X)B(this,p,"m",x4).call(this,W);if(X.controller.signal?.aborted)throw new d;return this._addChatCompletion(B(this,p,"m",Q3).call(this))}async _fromReadableStream($,Y){let Z=Y?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}B(this,p,"m",M4).call(this),this._connected();let w=N$.fromReadableStream($,this.controller),X;for await(let W of w){if(X&&X!==W.id)this._addChatCompletion(B(this,p,"m",Q3).call(this));B(this,p,"m",x4).call(this,W),X=W.id}if(w.controller.signal?.aborted)throw new d;return this._addChatCompletion(B(this,p,"m",Q3).call(this))}[(A$=new WeakMap,R1=new WeakMap,g$=new WeakMap,p=new WeakSet,M4=function(){if(this.ended)return;k(this,g$,void 0,"f")},J3=function(Y){let Z=B(this,R1,"f")[Y.index];if(Z)return Z;return Z={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},B(this,R1,"f")[Y.index]=Z,Z},x4=function(Y){if(this.ended)return;let Z=B(this,p,"m",C6).call(this,Y);this._emit("chunk",Y,Z);for(let w of Y.choices){let X=Z.choices[w.index];if(w.delta.content!=null&&X.message?.role==="assistant"&&X.message?.content)this._emit("content",w.delta.content,X.message.content),this._emit("content.delta",{delta:w.delta.content,snapshot:X.message.content,parsed:X.message.parsed});if(w.delta.refusal!=null&&X.message?.role==="assistant"&&X.message?.refusal)this._emit("refusal.delta",{delta:w.delta.refusal,snapshot:X.message.refusal});if(w.logprobs?.content!=null&&X.message?.role==="assistant")this._emit("logprobs.content.delta",{content:w.logprobs?.content,snapshot:X.logprobs?.content??[]});if(w.logprobs?.refusal!=null&&X.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:w.logprobs?.refusal,snapshot:X.logprobs?.refusal??[]});let W=B(this,p,"m",J3).call(this,X);if(X.finish_reason){if(B(this,p,"m",O4).call(this,X),W.current_tool_call_index!=null)B(this,p,"m",q4).call(this,X,W.current_tool_call_index)}for(let G of w.delta.tool_calls??[]){if(W.current_tool_call_index!==G.index){if(B(this,p,"m",O4).call(this,X),W.current_tool_call_index!=null)B(this,p,"m",q4).call(this,X,W.current_tool_call_index)}W.current_tool_call_index=G.index}for(let G of w.delta.tool_calls??[]){let Q=X.message.tool_calls?.[G.index];if(!Q?.type)continue;if(Q?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:Q.function?.name,index:G.index,arguments:Q.function.arguments,parsed_arguments:Q.function.parsed_arguments,arguments_delta:G.function?.arguments??""});else R6(Q?.type)}}},q4=function(Y,Z){if(B(this,p,"m",J3).call(this,Y).done_tool_calls.has(Z))return;let X=Y.message.tool_calls?.[Z];if(!X)throw Error("no tool call snapshot");if(!X.type)throw Error("tool call snapshot missing `type`");if(X.type==="function"){let W=B(this,A$,"f")?.tools?.find((G)=>q0(G)&&G.function.name===X.function.name);this._emit("tool_calls.function.arguments.done",{name:X.function.name,index:Z,arguments:X.function.arguments,parsed_arguments:o$(W)?W.$parseRaw(X.function.arguments):W?.function.strict?JSON.parse(X.function.arguments):null})}else R6(X.type)},O4=function(Y){let Z=B(this,p,"m",J3).call(this,Y);if(Y.message.content&&!Z.content_done){Z.content_done=!0;let w=B(this,p,"m",E4).call(this);this._emit("content.done",{content:Y.message.content,parsed:w?w.$parseRaw(Y.message.content):null})}if(Y.message.refusal&&!Z.refusal_done)Z.refusal_done=!0,this._emit("refusal.done",{refusal:Y.message.refusal});if(Y.logprobs?.content&&!Z.logprobs_content_done)Z.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:Y.logprobs.content});if(Y.logprobs?.refusal&&!Z.logprobs_refusal_done)Z.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:Y.logprobs.refusal})},Q3=function(){if(this.ended)throw new O("stream has ended, this shouldn't happen");let Y=B(this,g$,"f");if(!Y)throw new O("request ended without sending any chunks");return k(this,g$,void 0,"f"),k(this,R1,[],"f"),YY(Y,B(this,A$,"f"))},E4=function(){let Y=B(this,A$,"f")?.response_format;if(O0(Y))return Y;return null},C6=function(Y){var Z,w,X,W;let G=B(this,g$,"f"),{choices:Q,...V}=Y;if(!G)G=k(this,g$,{...V,choices:[]},"f");else Object.assign(G,V);for(let{delta:H,finish_reason:T,index:K,logprobs:U=null,...M}of Y.choices){let q=G.choices[K];if(!q)q=G.choices[K]={finish_reason:T,index:K,message:{},logprobs:U,...M};if(U)if(!q.logprobs)q.logprobs=Object.assign({},U);else{let{content:o,refusal:e,...I}=U;if(S6(I),Object.assign(q.logprobs,I),o)(Z=q.logprobs).content??(Z.content=[]),q.logprobs.content.push(...o);if(e)(w=q.logprobs).refusal??(w.refusal=[]),q.logprobs.refusal.push(...e)}if(T){if(q.finish_reason=T,B(this,A$,"f")&&z4(B(this,A$,"f"))){if(T==="length")throw new V0;if(T==="content_filter")throw new B0}}if(Object.assign(q,M),!H)continue;let{content:P,refusal:A,function_call:R,role:F,tool_calls:b,...v}=H;if(S6(v),Object.assign(q.message,v),A)q.message.refusal=(q.message.refusal||"")+A;if(F)q.message.role=F;if(R)if(!q.message.function_call)q.message.function_call=R;else{if(R.name)q.message.function_call.name=R.name;if(R.arguments)(X=q.message.function_call).arguments??(X.arguments=""),q.message.function_call.arguments+=R.arguments}if(P){if(q.message.content=(q.message.content||"")+P,!q.message.refusal&&B(this,p,"m",E4).call(this))q.message.parsed=U4(q.message.content)}if(b){if(!q.message.tool_calls)q.message.tool_calls=[];for(let{index:o,id:e,type:I,function:$$,...k$}of b){let y=(W=q.message.tool_calls)[o]??(W[o]={});if(Object.assign(y,k$),e)y.id=e;if(I)y.type=I;if($$)y.function??(y.function={name:$$.name??"",arguments:""});if($$?.name)y.function.name=$$.name;if($$?.arguments){if(y.function.arguments+=$$.arguments,U6(B(this,A$,"f"),y))y.function.parsed_arguments=U4(y.function.arguments)}}}}return G},Symbol.asyncIterator)](){let $=[],Y=[],Z=!1;return this.on("chunk",(w)=>{let X=Y.shift();if(X)X.resolve(w);else $.push(w)}),this.on("end",()=>{Z=!0;for(let w of Y)w.resolve(void 0);Y.length=0}),this.on("abort",(w)=>{Z=!0;for(let X of Y)X.reject(w);Y.length=0}),this.on("error",(w)=>{Z=!0;for(let X of Y)X.reject(w);Y.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((X,W)=>Y.push({resolve:X,reject:W})).then((X)=>X?{value:X,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 N$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function YY($,Y){let{id:Z,choices:w,created:X,model:W,system_fingerprint:G,...Q}=$,V={...Q,id:Z,choices:w.map(({message:H,finish_reason:T,index:K,logprobs:U,...M})=>{if(!T)throw new O(`missing finish_reason for choice ${K}`);let{content:q=null,function_call:P,tool_calls:A,...R}=H,F=H.role;if(!F)throw new O(`missing role for choice ${K}`);if(P){let{arguments:b,name:v}=P;if(b==null)throw new O(`missing function_call.arguments for choice ${K}`);if(!v)throw new O(`missing function_call.name for choice ${K}`);return{...M,message:{content:q,function_call:{arguments:b,name:v},role:F,refusal:H.refusal??null},finish_reason:T,index:K,logprobs:U}}if(A)return{...M,index:K,finish_reason:T,logprobs:U,message:{...R,role:F,content:q,refusal:H.refusal??null,tool_calls:A.map((b,v)=>{let{function:o,type:e,id:I,...$$}=b,{arguments:k$,name:y,...b$}=o||{};if(I==null)throw new O(`missing choices[${K}].tool_calls[${v}].id
192
+ ${z3($)}`);if(e==null)throw new O(`missing choices[${K}].tool_calls[${v}].type
193
+ ${z3($)}`);if(y==null)throw new O(`missing choices[${K}].tool_calls[${v}].function.name
194
+ ${z3($)}`);if(k$==null)throw new O(`missing choices[${K}].tool_calls[${v}].function.arguments
195
+ ${z3($)}`);return{...$$,id:I,type:e,function:{...b$,name:y,arguments:k$}}})}};return{...M,message:{...R,content:q,role:F,refusal:H.refusal??null},finish_reason:T,index:K,logprobs:U}}),created:X,model:W,object:"chat.completion",...G?{system_fingerprint:G}:{}};return T6(V,Y)}function z3($){return JSON.stringify($)}function S6($){return}function R6($){}class P1 extends m${static fromReadableStream($){let Y=new P1(null);return Y._run(()=>Y._fromReadableStream($)),Y}static runTools($,Y,Z){let w=new P1(Y),X={...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"runTools"}};return w._run(()=>w._runTools($,Y,X)),w}}class c$ extends N{constructor(){super(...arguments);this.messages=new k1(this._client)}create($,Y){return this._client.post("/chat/completions",{body:$,...Y,stream:$.stream??!1,__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/chat/completions/${$}`,{...Y,__security:{bearerAuth:!0}})}update($,Y,Z){return this._client.post(J`/chat/completions/${$}`,{body:Y,...Z,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/chat/completions",S,{query:$,...Y,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/chat/completions/${$}`,{...Y,__security:{bearerAuth:!0}})}parse($,Y){return x6($.tools),this._client.chat.completions.create($,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((Z)=>E0(Z,$))}runTools($,Y){if($.stream)return P1.runTools(this._client,$,Y);return R0.runTools(this._client,$,Y)}stream($,Y){return m$.createChatCompletion(this._client,$,Y)}}c$.Messages=k1;class $1 extends N{constructor(){super(...arguments);this.completions=new c$(this._client)}}$1.Completions=c$;class P0 extends N{create($,Y){return this._client.post("/organization/admin_api_keys",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y){return this._client.get(J`/organization/admin_api_keys/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/admin_api_keys",S,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/admin_api_keys/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}}class _0 extends N{list($={},Y){return this._client.getAPIList("/organization/audit_logs",j,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}}class A0 extends N{create($,Y){return this._client.post("/organization/certificates",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y={},Z){return this._client.get(J`/organization/certificates/${$}`,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/certificates/${$}`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/certificates",j,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/certificates/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}activate($,Y){return this._client.getAPIList("/organization/certificates/activate",Z$,{body:$,method:"post",...Y,__security:{adminAPIKeyAuth:!0}})}deactivate($,Y){return this._client.getAPIList("/organization/certificates/deactivate",Z$,{body:$,method:"post",...Y,__security:{adminAPIKeyAuth:!0}})}}class f0 extends N{retrieve($){return this._client.get("/organization/data_retention",{...$,__security:{adminAPIKeyAuth:!0}})}update($,Y){return this._client.post("/organization/data_retention",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}}class j0 extends N{create($,Y){return this._client.post("/organization/invites",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y){return this._client.get(J`/organization/invites/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/invites",j,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/invites/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}}class b0 extends N{create($,Y){return this._client.post("/organization/roles",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y){return this._client.get(J`/organization/roles/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/roles/${$}`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/roles",l,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/roles/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}}class v0 extends N{create($,Y){return this._client.post("/organization/spend_alerts",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/spend_alerts/${$}`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/spend_alerts",j,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/spend_alerts/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}}class y0 extends N{audioSpeeches($,Y){return this._client.get("/organization/usage/audio_speeches",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions($,Y){return this._client.get("/organization/usage/audio_transcriptions",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions($,Y){return this._client.get("/organization/usage/code_interpreter_sessions",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}completions($,Y){return this._client.get("/organization/usage/completions",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}costs($,Y){return this._client.get("/organization/costs",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}embeddings($,Y){return this._client.get("/organization/usage/embeddings",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls($,Y){return this._client.get("/organization/usage/file_search_calls",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}images($,Y){return this._client.get("/organization/usage/images",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}moderations($,Y){return this._client.get("/organization/usage/moderations",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}vectorStores($,Y){return this._client.get("/organization/usage/vector_stores",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}webSearchCalls($,Y){return this._client.get("/organization/usage/web_search_calls",{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}}class I0 extends N{create($,Y,Z){return this._client.post(J`/organization/groups/${$}/roles`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{group_id:w}=Y;return this._client.get(J`/organization/groups/${w}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/groups/${$}/roles`,l,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{group_id:w}=Y;return this._client.delete(J`/organization/groups/${w}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class D0 extends N{create($,Y,Z){return this._client.post(J`/organization/groups/${$}/users`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{group_id:w}=Y;return this._client.get(J`/organization/groups/${w}/users/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/groups/${$}/users`,l,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{group_id:w}=Y;return this._client.delete(J`/organization/groups/${w}/users/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class Y1 extends N{constructor(){super(...arguments);this.users=new D0(this._client),this.roles=new I0(this._client)}create($,Y){return this._client.post("/organization/groups",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y){return this._client.get(J`/organization/groups/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/groups/${$}`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/groups",l,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/groups/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}}Y1.Users=D0;Y1.Roles=I0;class h0 extends N{retrieve($,Y,Z){let{project_id:w}=Y;return this._client.get(J`/organization/projects/${w}/api_keys/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/projects/${$}/api_keys`,j,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w}=Y;return this._client.delete(J`/organization/projects/${w}/api_keys/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class g0 extends N{list($,Y={},Z){return this._client.getAPIList(J`/organization/projects/${$}/certificates`,j,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}activate($,Y,Z){return this._client.getAPIList(J`/organization/projects/${$}/certificates/activate`,Z$,{body:Y,method:"post",...Z,__security:{adminAPIKeyAuth:!0}})}deactivate($,Y,Z){return this._client.getAPIList(J`/organization/projects/${$}/certificates/deactivate`,Z$,{body:Y,method:"post",...Z,__security:{adminAPIKeyAuth:!0}})}}class m0 extends N{retrieve($,Y){return this._client.get(J`/organization/projects/${$}/data_retention`,{...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/projects/${$}/data_retention`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}}class c0 extends N{retrieve($,Y){return this._client.get(J`/organization/projects/${$}/hosted_tool_permissions`,{...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/projects/${$}/hosted_tool_permissions`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}}class d0 extends N{retrieve($,Y){return this._client.get(J`/organization/projects/${$}/model_permissions`,{...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/projects/${$}/model_permissions`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/projects/${$}/model_permissions`,{...Y,__security:{adminAPIKeyAuth:!0}})}}class u0 extends N{listRateLimits($,Y={},Z){return this._client.getAPIList(J`/organization/projects/${$}/rate_limits`,j,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}updateRateLimit($,Y,Z){let{project_id:w,...X}=Y;return this._client.post(J`/organization/projects/${w}/rate_limits/${$}`,{body:X,...Z,__security:{adminAPIKeyAuth:!0}})}}class l0 extends N{create($,Y,Z){return this._client.post(J`/projects/${$}/roles`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{project_id:w}=Y;return this._client.get(J`/projects/${w}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){let{project_id:w,...X}=Y;return this._client.post(J`/projects/${w}/roles/${$}`,{body:X,...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/projects/${$}/roles`,l,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w}=Y;return this._client.delete(J`/projects/${w}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class p0 extends N{create($,Y,Z){return this._client.post(J`/organization/projects/${$}/service_accounts`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{project_id:w}=Y;return this._client.get(J`/organization/projects/${w}/service_accounts/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){let{project_id:w,...X}=Y;return this._client.post(J`/organization/projects/${w}/service_accounts/${$}`,{body:X,...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/projects/${$}/service_accounts`,j,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w}=Y;return this._client.delete(J`/organization/projects/${w}/service_accounts/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class i0 extends N{create($,Y,Z){return this._client.post(J`/organization/projects/${$}/spend_alerts`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){let{project_id:w,...X}=Y;return this._client.post(J`/organization/projects/${w}/spend_alerts/${$}`,{body:X,...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/projects/${$}/spend_alerts`,j,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w}=Y;return this._client.delete(J`/organization/projects/${w}/spend_alerts/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class n0 extends N{create($,Y,Z){let{project_id:w,...X}=Y;return this._client.post(J`/projects/${w}/groups/${$}/roles`,{body:X,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{project_id:w,group_id:X}=Y;return this._client.get(J`/projects/${w}/groups/${X}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y,Z){let{project_id:w,...X}=Y;return this._client.getAPIList(J`/projects/${w}/groups/${$}/roles`,l,{query:X,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w,group_id:X}=Y;return this._client.delete(J`/projects/${w}/groups/${X}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class _1 extends N{constructor(){super(...arguments);this.roles=new n0(this._client)}create($,Y,Z){return this._client.post(J`/organization/projects/${$}/groups`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{project_id:w,...X}=Y;return this._client.get(J`/organization/projects/${w}/groups/${$}`,{query:X,...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/projects/${$}/groups`,l,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w}=Y;return this._client.delete(J`/organization/projects/${w}/groups/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}_1.Roles=n0;class a0 extends N{create($,Y,Z){let{project_id:w,...X}=Y;return this._client.post(J`/projects/${w}/users/${$}/roles`,{body:X,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{project_id:w,user_id:X}=Y;return this._client.get(J`/projects/${w}/users/${X}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y,Z){let{project_id:w,...X}=Y;return this._client.getAPIList(J`/projects/${w}/users/${$}/roles`,l,{query:X,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w,user_id:X}=Y;return this._client.delete(J`/projects/${w}/users/${X}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class A1 extends N{constructor(){super(...arguments);this.roles=new a0(this._client)}create($,Y,Z){return this._client.post(J`/organization/projects/${$}/users`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{project_id:w}=Y;return this._client.get(J`/organization/projects/${w}/users/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){let{project_id:w,...X}=Y;return this._client.post(J`/organization/projects/${w}/users/${$}`,{body:X,...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/projects/${$}/users`,j,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{project_id:w}=Y;return this._client.delete(J`/organization/projects/${w}/users/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}A1.Roles=a0;class r extends N{constructor(){super(...arguments);this.users=new A1(this._client),this.serviceAccounts=new p0(this._client),this.apiKeys=new h0(this._client),this.rateLimits=new u0(this._client),this.modelPermissions=new d0(this._client),this.hostedToolPermissions=new c0(this._client),this.groups=new _1(this._client),this.roles=new l0(this._client),this.dataRetention=new m0(this._client),this.spendAlerts=new i0(this._client),this.certificates=new g0(this._client)}create($,Y){return this._client.post("/organization/projects",{body:$,...Y,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y){return this._client.get(J`/organization/projects/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/projects/${$}`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/projects",j,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}archive($,Y){return this._client.post(J`/organization/projects/${$}/archive`,{...Y,__security:{adminAPIKeyAuth:!0}})}}r.Users=A1;r.ServiceAccounts=p0;r.APIKeys=h0;r.RateLimits=u0;r.ModelPermissions=d0;r.HostedToolPermissions=c0;r.Groups=_1;r.Roles=l0;r.DataRetention=m0;r.SpendAlerts=i0;r.Certificates=g0;class t0 extends N{create($,Y,Z){return this._client.post(J`/organization/users/${$}/roles`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y,Z){let{user_id:w}=Y;return this._client.get(J`/organization/users/${w}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/organization/users/${$}/roles`,l,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{user_id:w}=Y;return this._client.delete(J`/organization/users/${w}/roles/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class f1 extends N{constructor(){super(...arguments);this.roles=new t0(this._client)}retrieve($,Y){return this._client.get(J`/organization/users/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}update($,Y,Z){return this._client.post(J`/organization/users/${$}`,{body:Y,...Z,__security:{adminAPIKeyAuth:!0}})}list($={},Y){return this._client.getAPIList("/organization/users",j,{query:$,...Y,__security:{adminAPIKeyAuth:!0}})}delete($,Y){return this._client.delete(J`/organization/users/${$}`,{...Y,__security:{adminAPIKeyAuth:!0}})}}f1.Roles=t0;class s extends N{constructor(){super(...arguments);this.auditLogs=new _0(this._client),this.adminAPIKeys=new P0(this._client),this.usage=new y0(this._client),this.invites=new j0(this._client),this.users=new f1(this._client),this.groups=new Y1(this._client),this.roles=new b0(this._client),this.dataRetention=new f0(this._client),this.spendAlerts=new v0(this._client),this.certificates=new A0(this._client),this.projects=new r(this._client)}}s.AuditLogs=_0;s.AdminAPIKeys=P0;s.Usage=y0;s.Invites=j0;s.Users=f1;s.Groups=Y1;s.Roles=b0;s.DataRetention=f0;s.SpendAlerts=v0;s.Certificates=A0;s.Projects=r;class Z1 extends N{constructor(){super(...arguments);this.organization=new s(this._client)}}Z1.Organization=s;var P6=Symbol("brand.privateNullableHeaders");function*fY($){if(!$)return;if(P6 in $){let{values:w,nulls:X}=$;yield*w.entries();for(let W of X)yield[W,null];return}let Y=!1,Z;if($ instanceof Headers)Z=$.entries();else if(l3($))Z=$;else Y=!0,Z=Object.entries($??{});for(let w of Z){let X=w[0];if(typeof X!=="string")throw TypeError("expected header name to be a string");let W=l3(w[1])?w[1]:[w[1]],G=!1;for(let Q of W){if(Q===void 0)continue;if(Y&&!G)G=!0,yield[X,null];yield[X,Q]}}}var x=($)=>{let Y=new Headers,Z=new Set;for(let w of $){let X=new Set;for(let[W,G]of fY(w)){let Q=W.toLowerCase();if(!X.has(Q))Y.delete(W),X.add(Q);if(G===null)Y.delete(W),Z.add(Q);else Y.append(W,G),Z.delete(Q)}}return{[P6]:!0,values:Y,nulls:Z}};class r0 extends N{create($,Y){return this._client.post("/audio/speech",{body:$,...Y,headers:x([{Accept:"application/octet-stream"},Y?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class s0 extends N{create($,Y){return this._client.post("/audio/transcriptions",t({body:$,...Y,stream:$.stream??!1,__metadata:{model:$.model},__security:{bearerAuth:!0}},this._client))}}class o0 extends N{create($,Y){return this._client.post("/audio/translations",t({body:$,...Y,__metadata:{model:$.model},__security:{bearerAuth:!0}},this._client))}}class f$ extends N{constructor(){super(...arguments);this.transcriptions=new s0(this._client),this.translations=new o0(this._client),this.speech=new r0(this._client)}}f$.Transcriptions=s0;f$.Translations=o0;f$.Speech=r0;class j1 extends N{create($,Y){return this._client.post("/batches",{body:$,...Y,__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/batches/${$}`,{...Y,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/batches",S,{query:$,...Y,__security:{bearerAuth:!0}})}cancel($,Y){return this._client.post(J`/batches/${$}/cancel`,{...Y,__security:{bearerAuth:!0}})}}class e0 extends N{create($,Y){return this._client.post("/assistants",{body:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/assistants/${$}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}update($,Y,Z){return this._client.post(J`/assistants/${$}`,{body:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/assistants",S,{query:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/assistants/${$}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}}class $2 extends N{create($,Y){return this._client.post("/realtime/sessions",{body:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}}class Y2 extends N{create($,Y){return this._client.post("/realtime/transcription_sessions",{body:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}}class w1 extends N{constructor(){super(...arguments);this.sessions=new $2(this._client),this.transcriptionSessions=new Y2(this._client)}}w1.Sessions=$2;w1.TranscriptionSessions=Y2;class Z2 extends N{create($,Y){return this._client.post("/chatkit/sessions",{body:$,...Y,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers]),__security:{bearerAuth:!0}})}cancel($,Y){return this._client.post(J`/chatkit/sessions/${$}/cancel`,{...Y,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers]),__security:{bearerAuth:!0}})}}class w2 extends N{retrieve($,Y){return this._client.get(J`/chatkit/threads/${$}`,{...Y,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers]),__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/chatkit/threads",j,{query:$,...Y,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers]),__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/chatkit/threads/${$}`,{...Y,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers]),__security:{bearerAuth:!0}})}listItems($,Y={},Z){return this._client.getAPIList(J`/chatkit/threads/${$}/items`,j,{query:Y,...Z,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers]),__security:{bearerAuth:!0}})}}class G1 extends N{constructor(){super(...arguments);this.sessions=new Z2(this._client),this.threads=new w2(this._client)}}G1.Sessions=Z2;G1.Threads=w2;class G2 extends N{create($,Y,Z){return this._client.post(J`/threads/${$}/messages`,{body:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}retrieve($,Y,Z){let{thread_id:w}=Y;return this._client.get(J`/threads/${w}/messages/${$}`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}update($,Y,Z){let{thread_id:w,...X}=Y;return this._client.post(J`/threads/${w}/messages/${$}`,{body:X,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/threads/${$}/messages`,S,{query:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}delete($,Y,Z){let{thread_id:w}=Y;return this._client.delete(J`/threads/${w}/messages/${$}`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}class X2 extends N{retrieve($,Y,Z){let{thread_id:w,run_id:X,...W}=Y;return this._client.get(J`/threads/${w}/runs/${X}/steps/${$}`,{query:W,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}list($,Y,Z){let{thread_id:w,...X}=Y;return this._client.getAPIList(J`/threads/${w}/runs/${$}/steps`,S,{query:X,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}var _6=($)=>{if(typeof Buffer<"u"){let Y=Buffer.from($,"base64");return Array.from(new Float32Array(Y.buffer,Y.byteOffset,Y.length/Float32Array.BYTES_PER_ELEMENT))}else{let Y=atob($),Z=Y.length,w=new Uint8Array(Z);for(let X=0;X<Z;X++)w[X]=Y.charCodeAt(X);return Array.from(new Float32Array(w.buffer))}};var U$=($)=>{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 n,W1,L4,E$,N3,M$,J1,b1,X1,K3,V$,V3,B3,Q2,W2,J2,A6,f6,j6,b6,v6,y6,I6;class d$ extends e${constructor(){super(...arguments);n.add(this),L4.set(this,[]),E$.set(this,{}),N3.set(this,{}),M$.set(this,void 0),J1.set(this,void 0),b1.set(this,void 0),X1.set(this,void 0),K3.set(this,void 0),V$.set(this,void 0),V3.set(this,void 0),B3.set(this,void 0),Q2.set(this,void 0)}[(L4=new WeakMap,E$=new WeakMap,N3=new WeakMap,M$=new WeakMap,J1=new WeakMap,b1=new WeakMap,X1=new WeakMap,K3=new WeakMap,V$=new WeakMap,V3=new WeakMap,B3=new WeakMap,Q2=new WeakMap,n=new WeakSet,Symbol.asyncIterator)](){let $=[],Y=[],Z=!1;return this.on("event",(w)=>{let X=Y.shift();if(X)X.resolve(w);else $.push(w)}),this.on("end",()=>{Z=!0;for(let w of Y)w.resolve(void 0);Y.length=0}),this.on("abort",(w)=>{Z=!0;for(let X of Y)X.reject(w);Y.length=0}),this.on("error",(w)=>{Z=!0;for(let X of Y)X.reject(w);Y.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((X,W)=>Y.push({resolve:X,reject:W})).then((X)=>X?{value:X,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 Y=new W1;return Y._run(()=>Y._fromReadableStream($)),Y}async _fromReadableStream($,Y){let Z=Y?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}this._connected();let w=N$.fromReadableStream($,this.controller);for await(let X of w)B(this,n,"m",W2).call(this,X);if(w.controller.signal?.aborted)throw new d;return this._addRun(B(this,n,"m",J2).call(this))}toReadableStream(){return new N$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream($,Y,Z,w){let X=new W1;return X._run(()=>X._runToolAssistantStream($,Y,Z,{...w,headers:{...w?.headers,"X-Stainless-Helper-Method":"stream"}})),X}async _createToolAssistantStream($,Y,Z,w){let X=w?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let W={...Z,stream:!0},G=await $.submitToolOutputs(Y,W,{...w,signal:this.controller.signal});this._connected();for await(let Q of G)B(this,n,"m",W2).call(this,Q);if(G.controller.signal?.aborted)throw new d;return this._addRun(B(this,n,"m",J2).call(this))}static createThreadAssistantStream($,Y,Z){let w=new W1;return w._run(()=>w._threadAssistantStream($,Y,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),w}static createAssistantStream($,Y,Z,w){let X=new W1;return X._run(()=>X._runAssistantStream($,Y,Z,{...w,headers:{...w?.headers,"X-Stainless-Helper-Method":"stream"}})),X}currentEvent(){return B(this,V3,"f")}currentRun(){return B(this,B3,"f")}currentMessageSnapshot(){return B(this,M$,"f")}currentRunStepSnapshot(){return B(this,Q2,"f")}async finalRunSteps(){return await this.done(),Object.values(B(this,E$,"f"))}async finalMessages(){return await this.done(),Object.values(B(this,N3,"f"))}async finalRun(){if(await this.done(),!B(this,J1,"f"))throw Error("Final run was not received.");return B(this,J1,"f")}async _createThreadAssistantStream($,Y,Z){let w=Z?.signal;if(w){if(w.aborted)this.controller.abort();w.addEventListener("abort",()=>this.controller.abort())}let X={...Y,stream:!0},W=await $.createAndRun(X,{...Z,signal:this.controller.signal});this._connected();for await(let G of W)B(this,n,"m",W2).call(this,G);if(W.controller.signal?.aborted)throw new d;return this._addRun(B(this,n,"m",J2).call(this))}async _createAssistantStream($,Y,Z,w){let X=w?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let W={...Z,stream:!0},G=await $.create(Y,W,{...w,signal:this.controller.signal});this._connected();for await(let Q of G)B(this,n,"m",W2).call(this,Q);if(G.controller.signal?.aborted)throw new d;return this._addRun(B(this,n,"m",J2).call(this))}static accumulateDelta($,Y){for(let[Z,w]of Object.entries(Y)){if(!$.hasOwnProperty(Z)){$[Z]=w;continue}let X=$[Z];if(X===null||X===void 0){$[Z]=w;continue}if(Z==="index"||Z==="type"){$[Z]=w;continue}if(typeof X==="string"&&typeof w==="string")X+=w;else if(typeof X==="number"&&typeof w==="number")X+=w;else if(K0(X)&&K0(w))X=this.accumulateDelta(X,w);else if(Array.isArray(X)&&Array.isArray(w)){if(X.every((W)=>typeof W==="string"||typeof W==="number")){X.push(...w);continue}for(let W of w){if(!K0(W))throw Error(`Expected array delta entry to be an object but got: ${W}`);let G=W.index;if(G==null)throw console.error(W),Error("Expected array delta entry to have an `index` property");if(typeof G!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${G}`);let Q=X[G];if(Q==null)X.push(W);else X[G]=this.accumulateDelta(Q,W)}continue}else throw Error(`Unhandled record type: ${Z}, deltaValue: ${w}, accValue: ${X}`);$[Z]=X}return $}_addRun($){return $}async _threadAssistantStream($,Y,Z){return await this._createThreadAssistantStream(Y,$,Z)}async _runAssistantStream($,Y,Z,w){return await this._createAssistantStream(Y,$,Z,w)}async _runToolAssistantStream($,Y,Z,w){return await this._createToolAssistantStream(Y,$,Z,w)}}W1=d$,W2=function(Y){if(this.ended)return;switch(k(this,V3,Y,"f"),B(this,n,"m",j6).call(this,Y),Y.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":B(this,n,"m",I6).call(this,Y);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":B(this,n,"m",f6).call(this,Y);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":B(this,n,"m",A6).call(this,Y);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:lY(Y)}},J2=function(){if(this.ended)throw new O("stream has ended, this shouldn't happen");if(!B(this,J1,"f"))throw Error("Final run has not been received");return B(this,J1,"f")},A6=function(Y){let[Z,w]=B(this,n,"m",v6).call(this,Y,B(this,M$,"f"));k(this,M$,Z,"f"),B(this,N3,"f")[Z.id]=Z;for(let X of w){let W=Z.content[X.index];if(W?.type=="text")this._emit("textCreated",W.text)}switch(Y.event){case"thread.message.created":this._emit("messageCreated",Y.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",Y.data.delta,Z),Y.data.delta.content)for(let X of Y.data.delta.content){if(X.type=="text"&&X.text){let W=X.text,G=Z.content[X.index];if(G&&G.type=="text")this._emit("textDelta",W,G.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(X.index!=B(this,b1,"f")){if(B(this,X1,"f"))switch(B(this,X1,"f").type){case"text":this._emit("textDone",B(this,X1,"f").text,B(this,M$,"f"));break;case"image_file":this._emit("imageFileDone",B(this,X1,"f").image_file,B(this,M$,"f"));break}k(this,b1,X.index,"f")}k(this,X1,Z.content[X.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(B(this,b1,"f")!==void 0){let X=Y.data.content[B(this,b1,"f")];if(X)switch(X.type){case"image_file":this._emit("imageFileDone",X.image_file,B(this,M$,"f"));break;case"text":this._emit("textDone",X.text,B(this,M$,"f"));break}}if(B(this,M$,"f"))this._emit("messageDone",Y.data);k(this,M$,void 0,"f")}},f6=function(Y){let Z=B(this,n,"m",b6).call(this,Y);switch(k(this,Q2,Z,"f"),Y.event){case"thread.run.step.created":this._emit("runStepCreated",Y.data);break;case"thread.run.step.delta":let w=Y.data.delta;if(w.step_details&&w.step_details.type=="tool_calls"&&w.step_details.tool_calls&&Z.step_details.type=="tool_calls")for(let W of w.step_details.tool_calls)if(W.index==B(this,K3,"f"))this._emit("toolCallDelta",W,Z.step_details.tool_calls[W.index]);else{if(B(this,V$,"f"))this._emit("toolCallDone",B(this,V$,"f"));if(k(this,K3,W.index,"f"),k(this,V$,Z.step_details.tool_calls[W.index],"f"),B(this,V$,"f"))this._emit("toolCallCreated",B(this,V$,"f"))}this._emit("runStepDelta",Y.data.delta,Z);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(k(this,Q2,void 0,"f"),Y.data.step_details.type=="tool_calls"){if(B(this,V$,"f"))this._emit("toolCallDone",B(this,V$,"f")),k(this,V$,void 0,"f")}this._emit("runStepDone",Y.data,Z);break;case"thread.run.step.in_progress":break}},j6=function(Y){B(this,L4,"f").push(Y),this._emit("event",Y)},b6=function(Y){switch(Y.event){case"thread.run.step.created":return B(this,E$,"f")[Y.data.id]=Y.data,Y.data;case"thread.run.step.delta":let Z=B(this,E$,"f")[Y.data.id];if(!Z)throw Error("Received a RunStepDelta before creation of a snapshot");let w=Y.data;if(w.delta){let X=W1.accumulateDelta(Z,w.delta);B(this,E$,"f")[Y.data.id]=X}return B(this,E$,"f")[Y.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":B(this,E$,"f")[Y.data.id]=Y.data;break}if(B(this,E$,"f")[Y.data.id])return B(this,E$,"f")[Y.data.id];throw Error("No snapshot available")},v6=function(Y,Z){let w=[];switch(Y.event){case"thread.message.created":return[Y.data,w];case"thread.message.delta":if(!Z)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let X=Y.data;if(X.delta.content)for(let W of X.delta.content)if(W.index in Z.content){let G=Z.content[W.index];Z.content[W.index]=B(this,n,"m",y6).call(this,W,G)}else Z.content[W.index]=W,w.push(W);return[Z,w];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(Z)return[Z,w];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},y6=function(Y,Z){return W1.accumulateDelta(Z,Y)},I6=function(Y){switch(k(this,B3,Y.data,"f"),Y.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(k(this,J1,Y.data,"f"),B(this,V$,"f"))this._emit("toolCallDone",B(this,V$,"f")),k(this,V$,void 0,"f");break;case"thread.run.cancelling":break}};function lY($){}class v1 extends N{constructor(){super(...arguments);this.steps=new X2(this._client)}create($,Y,Z){let{include:w,...X}=Y;return this._client.post(J`/threads/${$}/runs`,{query:{include:w},body:X,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),stream:Y.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve($,Y,Z){let{thread_id:w}=Y;return this._client.get(J`/threads/${w}/runs/${$}`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}update($,Y,Z){let{thread_id:w,...X}=Y;return this._client.post(J`/threads/${w}/runs/${$}`,{body:X,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/threads/${$}/runs`,S,{query:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}cancel($,Y,Z){let{thread_id:w}=Y;return this._client.post(J`/threads/${w}/runs/${$}/cancel`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}async createAndPoll($,Y,Z){let w=await this.create($,Y,Z);return await this.poll(w.id,{thread_id:$},Z)}createAndStream($,Y,Z){return d$.createAssistantStream($,this._client.beta.threads.runs,Y,Z)}async poll($,Y,Z){let w=x([Z?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":Z?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:X,response:W}=await this.retrieve($,Y,{...Z,headers:{...Z?.headers,...w}}).withResponse();switch(X.status){case"queued":case"in_progress":case"cancelling":let G=5000;if(Z?.pollIntervalMs)G=Z.pollIntervalMs;else{let Q=W.headers.get("openai-poll-after-ms");if(Q){let V=parseInt(Q);if(!isNaN(V))G=V}}await q$(G);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return X}}}stream($,Y,Z){return d$.createAssistantStream($,this._client.beta.threads.runs,Y,Z)}submitToolOutputs($,Y,Z){let{thread_id:w,...X}=Y;return this._client.post(J`/threads/${w}/runs/${$}/submit_tool_outputs`,{body:X,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),stream:Y.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll($,Y,Z){let w=await this.submitToolOutputs($,Y,Z);return await this.poll(w.id,Y,Z)}submitToolOutputsStream($,Y,Z){return d$.createToolAssistantStream($,this._client.beta.threads.runs,Y,Z)}}v1.Steps=X2;class Q1 extends N{constructor(){super(...arguments);this.runs=new v1(this._client),this.messages=new G2(this._client)}create($={},Y){return this._client.post("/threads",{body:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/threads/${$}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}update($,Y,Z){return this._client.post(J`/threads/${$}`,{body:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/threads/${$}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}createAndRun($,Y){return this._client.post("/threads/runs",{body:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),stream:$.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll($,Y){let Z=await this.createAndRun($,Y);return await this.runs.poll(Z.id,{thread_id:Z.thread_id},Y)}createAndRunStream($,Y){return d$.createThreadAssistantStream($,this._client.beta.threads,Y)}}Q1.Runs=v1;Q1.Messages=G2;class L$ extends N{constructor(){super(...arguments);this.realtime=new w1(this._client),this.chatkit=new G1(this._client),this.assistants=new e0(this._client),this.threads=new Q1(this._client)}}L$.Realtime=w1;L$.ChatKit=G1;L$.Assistants=e0;L$.Threads=Q1;class y1 extends N{create($,Y){return this._client.post("/completions",{body:$,...Y,stream:$.stream??!1,__security:{bearerAuth:!0}})}}class z2 extends N{retrieve($,Y,Z){let{container_id:w}=Y;return this._client.get(J`/containers/${w}/files/${$}/content`,{...Z,headers:x([{Accept:"application/binary"},Z?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class I1 extends N{constructor(){super(...arguments);this.content=new z2(this._client)}create($,Y,Z){return this._client.post(J`/containers/${$}/files`,h$({body:Y,...Z,__security:{bearerAuth:!0}},this._client))}retrieve($,Y,Z){let{container_id:w}=Y;return this._client.get(J`/containers/${w}/files/${$}`,{...Z,__security:{bearerAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/containers/${$}/files`,S,{query:Y,...Z,__security:{bearerAuth:!0}})}delete($,Y,Z){let{container_id:w}=Y;return this._client.delete(J`/containers/${w}/files/${$}`,{...Z,headers:x([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}}I1.Content=z2;class z1 extends N{constructor(){super(...arguments);this.files=new I1(this._client)}create($,Y){return this._client.post("/containers",{body:$,...Y,__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/containers/${$}`,{...Y,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/containers",S,{query:$,...Y,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/containers/${$}`,{...Y,headers:x([{Accept:"*/*"},Y?.headers]),__security:{bearerAuth:!0}})}}z1.Files=I1;class N2 extends N{create($,Y,Z){let{include:w,...X}=Y;return this._client.post(J`/conversations/${$}/items`,{query:{include:w},body:X,...Z,__security:{bearerAuth:!0}})}retrieve($,Y,Z){let{conversation_id:w,...X}=Y;return this._client.get(J`/conversations/${w}/items/${$}`,{query:X,...Z,__security:{bearerAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/conversations/${$}/items`,j,{query:Y,...Z,__security:{bearerAuth:!0}})}delete($,Y,Z){let{conversation_id:w}=Y;return this._client.delete(J`/conversations/${w}/items/${$}`,{...Z,__security:{bearerAuth:!0}})}}class N1 extends N{constructor(){super(...arguments);this.items=new N2(this._client)}create($={},Y){return this._client.post("/conversations",{body:$,...Y,__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/conversations/${$}`,{...Y,__security:{bearerAuth:!0}})}update($,Y,Z){return this._client.post(J`/conversations/${$}`,{body:Y,...Z,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/conversations/${$}`,{...Y,__security:{bearerAuth:!0}})}}N1.Items=N2;class D1 extends N{create($,Y){let Z=!!$.encoding_format,w=Z?$.encoding_format:"base64";if(Z)c(this._client).debug("embeddings/user defined encoding_format:",$.encoding_format);let X=this._client.post("/embeddings",{body:{...$,encoding_format:w},...Y,__security:{bearerAuth:!0}});if(Z)return X;return c(this._client).debug("embeddings/decoding base64 embeddings from base64"),X._thenUnwrap((W)=>{if(W&&W.data)W.data.forEach((G)=>{let Q=G.embedding;G.embedding=_6(Q)});return W})}}class V2 extends N{retrieve($,Y,Z){let{eval_id:w,run_id:X}=Y;return this._client.get(J`/evals/${w}/runs/${X}/output_items/${$}`,{...Z,__security:{bearerAuth:!0}})}list($,Y,Z){let{eval_id:w,...X}=Y;return this._client.getAPIList(J`/evals/${w}/runs/${$}/output_items`,S,{query:X,...Z,__security:{bearerAuth:!0}})}}class h1 extends N{constructor(){super(...arguments);this.outputItems=new V2(this._client)}create($,Y,Z){return this._client.post(J`/evals/${$}/runs`,{body:Y,...Z,__security:{bearerAuth:!0}})}retrieve($,Y,Z){let{eval_id:w}=Y;return this._client.get(J`/evals/${w}/runs/${$}`,{...Z,__security:{bearerAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/evals/${$}/runs`,S,{query:Y,...Z,__security:{bearerAuth:!0}})}delete($,Y,Z){let{eval_id:w}=Y;return this._client.delete(J`/evals/${w}/runs/${$}`,{...Z,__security:{bearerAuth:!0}})}cancel($,Y,Z){let{eval_id:w}=Y;return this._client.post(J`/evals/${w}/runs/${$}`,{...Z,__security:{bearerAuth:!0}})}}h1.OutputItems=V2;class V1 extends N{constructor(){super(...arguments);this.runs=new h1(this._client)}create($,Y){return this._client.post("/evals",{body:$,...Y,__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/evals/${$}`,{...Y,__security:{bearerAuth:!0}})}update($,Y,Z){return this._client.post(J`/evals/${$}`,{body:Y,...Z,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/evals",S,{query:$,...Y,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/evals/${$}`,{...Y,__security:{bearerAuth:!0}})}}V1.Runs=h1;class g1 extends N{create($,Y){return this._client.post("/files",t({body:$,...Y,__security:{bearerAuth:!0}},this._client))}retrieve($,Y){return this._client.get(J`/files/${$}`,{...Y,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/files",S,{query:$,...Y,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/files/${$}`,{...Y,__security:{bearerAuth:!0}})}content($,Y){return this._client.get(J`/files/${$}/content`,{...Y,headers:x([{Accept:"application/binary"},Y?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing($,{pollInterval:Y=5000,maxWait:Z=1800000}={}){let w=new Set(["processed","error","deleted"]),X=Date.now(),W=await this.retrieve($);while(!W.status||!w.has(W.status))if(await q$(Y),W=await this.retrieve($),Date.now()-X>Z)throw new r$({message:`Giving up on waiting for file ${$} to finish processing after ${Z} milliseconds.`});return W}}class B2 extends N{}class K2 extends N{run($,Y){return this._client.post("/fine_tuning/alpha/graders/run",{body:$,...Y,__security:{bearerAuth:!0}})}validate($,Y){return this._client.post("/fine_tuning/alpha/graders/validate",{body:$,...Y,__security:{bearerAuth:!0}})}}class m1 extends N{constructor(){super(...arguments);this.graders=new K2(this._client)}}m1.Graders=K2;class H2 extends N{create($,Y,Z){return this._client.getAPIList(J`/fine_tuning/checkpoints/${$}/permissions`,Z$,{body:Y,method:"post",...Z,__security:{adminAPIKeyAuth:!0}})}retrieve($,Y={},Z){return this._client.get(J`/fine_tuning/checkpoints/${$}/permissions`,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/fine_tuning/checkpoints/${$}/permissions`,j,{query:Y,...Z,__security:{adminAPIKeyAuth:!0}})}delete($,Y,Z){let{fine_tuned_model_checkpoint:w}=Y;return this._client.delete(J`/fine_tuning/checkpoints/${w}/permissions/${$}`,{...Z,__security:{adminAPIKeyAuth:!0}})}}class c1 extends N{constructor(){super(...arguments);this.permissions=new H2(this._client)}}c1.Permissions=H2;class T2 extends N{list($,Y={},Z){return this._client.getAPIList(J`/fine_tuning/jobs/${$}/checkpoints`,S,{query:Y,...Z,__security:{bearerAuth:!0}})}}class d1 extends N{constructor(){super(...arguments);this.checkpoints=new T2(this._client)}create($,Y){return this._client.post("/fine_tuning/jobs",{body:$,...Y,__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/fine_tuning/jobs/${$}`,{...Y,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/fine_tuning/jobs",S,{query:$,...Y,__security:{bearerAuth:!0}})}cancel($,Y){return this._client.post(J`/fine_tuning/jobs/${$}/cancel`,{...Y,__security:{bearerAuth:!0}})}listEvents($,Y={},Z){return this._client.getAPIList(J`/fine_tuning/jobs/${$}/events`,S,{query:Y,...Z,__security:{bearerAuth:!0}})}pause($,Y){return this._client.post(J`/fine_tuning/jobs/${$}/pause`,{...Y,__security:{bearerAuth:!0}})}resume($,Y){return this._client.post(J`/fine_tuning/jobs/${$}/resume`,{...Y,__security:{bearerAuth:!0}})}}d1.Checkpoints=T2;class F$ extends N{constructor(){super(...arguments);this.methods=new B2(this._client),this.jobs=new d1(this._client),this.checkpoints=new c1(this._client),this.alpha=new m1(this._client)}}F$.Methods=B2;F$.Jobs=d1;F$.Checkpoints=c1;F$.Alpha=m1;class U2 extends N{}class B1 extends N{constructor(){super(...arguments);this.graderModels=new U2(this._client)}}B1.GraderModels=U2;class u1 extends N{createVariation($,Y){return this._client.post("/images/variations",t({body:$,...Y,__security:{bearerAuth:!0}},this._client))}edit($,Y){return this._client.post("/images/edits",t({body:$,...Y,stream:$.stream??!1,__security:{bearerAuth:!0}},this._client))}generate($,Y){return this._client.post("/images/generations",{body:$,...Y,stream:$.stream??!1,__security:{bearerAuth:!0}})}}class l1 extends N{retrieve($,Y){return this._client.get(J`/models/${$}`,{...Y,__security:{bearerAuth:!0}})}list($){return this._client.getAPIList("/models",Z$,{...$,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/models/${$}`,{...Y,__security:{bearerAuth:!0}})}}class p1 extends N{create($,Y){return this._client.post("/moderations",{body:$,...Y,__security:{bearerAuth:!0}})}}class M2 extends N{accept($,Y,Z){return this._client.post(J`/realtime/calls/${$}/accept`,{body:Y,...Z,headers:x([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}hangup($,Y){return this._client.post(J`/realtime/calls/${$}/hangup`,{...Y,headers:x([{Accept:"*/*"},Y?.headers]),__security:{bearerAuth:!0}})}refer($,Y,Z){return this._client.post(J`/realtime/calls/${$}/refer`,{body:Y,...Z,headers:x([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}reject($,Y={},Z){return this._client.post(J`/realtime/calls/${$}/reject`,{body:Y,...Z,headers:x([{Accept:"*/*"},Z?.headers]),__security:{bearerAuth:!0}})}}class x2 extends N{create($,Y){return this._client.post("/realtime/client_secrets",{body:$,...Y,__security:{bearerAuth:!0}})}}class u$ extends N{constructor(){super(...arguments);this.clientSecrets=new x2(this._client),this.calls=new M2(this._client)}}u$.ClientSecrets=x2;u$.Calls=M2;function D6($,Y){if(!Y||!zZ(Y))return{...$,output_parsed:null,output:$.output.map((Z)=>{if(Z.type==="function_call")return{...Z,parsed_arguments:null};if(Z.type==="message")return{...Z,content:Z.content.map((w)=>({...w,parsed:null}))};else return Z})};return F4($,Y)}function F4($,Y){let Z=$.output.map((X)=>{if(X.type==="function_call")return{...X,parsed_arguments:BZ(Y,X)};if(X.type==="message"){let W=X.content.map((G)=>{if(G.type==="output_text")return{...G,parsed:QZ(Y,G.text)};return G});return{...X,content:W}}return X}),w=Object.assign({},$,{output:Z});if(!Object.getOwnPropertyDescriptor($,"output_text"))q2(w);return Object.defineProperty(w,"output_parsed",{enumerable:!0,get(){for(let X of w.output){if(X.type!=="message")continue;for(let W of X.content)if(W.type==="output_text"&&W.parsed!==null)return W.parsed}return null}}),w}function QZ($,Y){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(Y);return JSON.parse(Y)}function zZ($){if(O0($.text?.format))return!0;return!1}function NZ($){return $?.$brand==="auto-parseable-tool"}function VZ($,Y){return $.find((Z)=>Z.type==="function"&&Z.name===Y)}function BZ($,Y){let Z=VZ($.tools??[],Y.name);return{...Y,...Y,parsed_arguments:NZ(Z)?Z.$parseRaw(Y.arguments):Z?.strict?JSON.parse(Y.arguments):null}}function q2($){let Y=[];for(let Z of $.output){if(Z.type!=="message")continue;for(let w of Z.content)if(w.type==="output_text")Y.push(w.text)}$.output_text=Y.join("")}var i1,H3,l$,T3,h6,g6,m6,c6;class U3 extends e${constructor($){super();i1.add(this),H3.set(this,void 0),l$.set(this,void 0),T3.set(this,void 0),k(this,H3,$,"f")}static createResponse($,Y,Z){let w=new U3(Y);return w._run(()=>w._createOrRetrieveResponse($,Y,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),w}async _createOrRetrieveResponse($,Y,Z){let w=Z?.signal;if(w){if(w.aborted)this.controller.abort();w.addEventListener("abort",()=>this.controller.abort())}B(this,i1,"m",h6).call(this);let X,W=null;if("response_id"in Y)X=await $.responses.retrieve(Y.response_id,{stream:!0},{...Z,signal:this.controller.signal,stream:!0}),W=Y.starting_after??null;else X=await $.responses.create({...Y,stream:!0},{...Z,signal:this.controller.signal});this._connected();for await(let G of X)B(this,i1,"m",g6).call(this,G,W);if(X.controller.signal?.aborted)throw new d;return B(this,i1,"m",m6).call(this)}[(H3=new WeakMap,l$=new WeakMap,T3=new WeakMap,i1=new WeakSet,h6=function(){if(this.ended)return;k(this,l$,void 0,"f")},g6=function(Y,Z){if(this.ended)return;let w=(W,G)=>{if(Z==null||G.sequence_number>Z)this._emit(W,G)},X=B(this,i1,"m",c6).call(this,Y);switch(w("event",Y),Y.type){case"response.output_text.delta":{let W=X.output[Y.output_index];if(!W)throw new O(`missing output at index ${Y.output_index}`);if(W.type==="message"){let G=W.content[Y.content_index];if(!G)throw new O(`missing content at index ${Y.content_index}`);if(G.type!=="output_text")throw new O(`expected content to be 'output_text', got ${G.type}`);w("response.output_text.delta",{...Y,snapshot:G.text})}break}case"response.function_call_arguments.delta":{let W=X.output[Y.output_index];if(!W)throw new O(`missing output at index ${Y.output_index}`);if(W.type==="function_call")w("response.function_call_arguments.delta",{...Y,snapshot:W.arguments});break}default:w(Y.type,Y);break}},m6=function(){if(this.ended)throw new O("stream has ended, this shouldn't happen");let Y=B(this,l$,"f");if(!Y)throw new O("request ended without sending any events");k(this,l$,void 0,"f");let Z=KZ(Y,B(this,H3,"f"));return k(this,T3,Z,"f"),Z},c6=function(Y){let Z=B(this,l$,"f");if(!Z){if(Y.type!=="response.created")throw new O(`When snapshot hasn't been set yet, expected 'response.created' event, got ${Y.type}`);return Z=k(this,l$,Y.response,"f"),Z}switch(Y.type){case"response.output_item.added":{Z.output.push(Y.item);break}case"response.content_part.added":{let w=Z.output[Y.output_index];if(!w)throw new O(`missing output at index ${Y.output_index}`);let X=w.type,W=Y.part;if(X==="message"&&W.type!=="reasoning_text")w.content.push(W);else if(X==="reasoning"&&W.type==="reasoning_text"){if(!w.content)w.content=[];w.content.push(W)}break}case"response.output_text.delta":{let w=Z.output[Y.output_index];if(!w)throw new O(`missing output at index ${Y.output_index}`);if(w.type==="message"){let X=w.content[Y.content_index];if(!X)throw new O(`missing content at index ${Y.content_index}`);if(X.type!=="output_text")throw new O(`expected content to be 'output_text', got ${X.type}`);X.text+=Y.delta}break}case"response.function_call_arguments.delta":{let w=Z.output[Y.output_index];if(!w)throw new O(`missing output at index ${Y.output_index}`);if(w.type==="function_call")w.arguments+=Y.delta;break}case"response.reasoning_text.delta":{let w=Z.output[Y.output_index];if(!w)throw new O(`missing output at index ${Y.output_index}`);if(w.type==="reasoning"){let X=w.content?.[Y.content_index];if(!X)throw new O(`missing content at index ${Y.content_index}`);if(X.type!=="reasoning_text")throw new O(`expected content to be 'reasoning_text', got ${X.type}`);X.text+=Y.delta}break}case"response.completed":{k(this,l$,Y.response,"f");break}}return Z},Symbol.asyncIterator)](){let $=[],Y=[],Z=!1;return this.on("event",(w)=>{let X=Y.shift();if(X)X.resolve(w);else $.push(w)}),this.on("end",()=>{Z=!0;for(let w of Y)w.resolve(void 0);Y.length=0}),this.on("abort",(w)=>{Z=!0;for(let X of Y)X.reject(w);Y.length=0}),this.on("error",(w)=>{Z=!0;for(let X of Y)X.reject(w);Y.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((X,W)=>Y.push({resolve:X,reject:W})).then((X)=>X?{value:X,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 $=B(this,T3,"f");if(!$)throw new O("stream ended without producing a ChatCompletion");return $}}function KZ($,Y){return D6($,Y)}class O2 extends N{list($,Y={},Z){return this._client.getAPIList(J`/responses/${$}/input_items`,S,{query:Y,...Z,__security:{bearerAuth:!0}})}}class E2 extends N{count($={},Y){return this._client.post("/responses/input_tokens",{body:$,...Y,__security:{bearerAuth:!0}})}}class j$ extends N{constructor(){super(...arguments);this.inputItems=new O2(this._client),this.inputTokens=new E2(this._client)}create($,Y){return this._client.post("/responses",{body:$,...Y,stream:$.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap((Z)=>{if("object"in Z&&Z.object==="response")q2(Z);return Z})}retrieve($,Y={},Z){return this._client.get(J`/responses/${$}`,{query:Y,...Z,stream:Y?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap((w)=>{if("object"in w&&w.object==="response")q2(w);return w})}delete($,Y){return this._client.delete(J`/responses/${$}`,{...Y,headers:x([{Accept:"*/*"},Y?.headers]),__security:{bearerAuth:!0}})}parse($,Y){return this._client.responses.create($,Y)._thenUnwrap((Z)=>F4(Z,$))}stream($,Y){return U3.createResponse(this._client,$,Y)}cancel($,Y){return this._client.post(J`/responses/${$}/cancel`,{...Y,__security:{bearerAuth:!0}})}compact($,Y){return this._client.post("/responses/compact",{body:$,...Y,__security:{bearerAuth:!0}})}}j$.InputItems=O2;j$.InputTokens=E2;class L2 extends N{retrieve($,Y){return this._client.get(J`/skills/${$}/content`,{...Y,headers:x([{Accept:"application/binary"},Y?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class F2 extends N{retrieve($,Y,Z){let{skill_id:w}=Y;return this._client.get(J`/skills/${w}/versions/${$}/content`,{...Z,headers:x([{Accept:"application/binary"},Z?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class n1 extends N{constructor(){super(...arguments);this.content=new F2(this._client)}create($,Y={},Z){return this._client.post(J`/skills/${$}/versions`,h$({body:Y,...Z,__security:{bearerAuth:!0}},this._client))}retrieve($,Y,Z){let{skill_id:w}=Y;return this._client.get(J`/skills/${w}/versions/${$}`,{...Z,__security:{bearerAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/skills/${$}/versions`,S,{query:Y,...Z,__security:{bearerAuth:!0}})}delete($,Y,Z){let{skill_id:w}=Y;return this._client.delete(J`/skills/${w}/versions/${$}`,{...Z,__security:{bearerAuth:!0}})}}n1.Content=F2;class p$ extends N{constructor(){super(...arguments);this.content=new L2(this._client),this.versions=new n1(this._client)}create($={},Y){return this._client.post("/skills",h$({body:$,...Y,__security:{bearerAuth:!0}},this._client))}retrieve($,Y){return this._client.get(J`/skills/${$}`,{...Y,__security:{bearerAuth:!0}})}update($,Y,Z){return this._client.post(J`/skills/${$}`,{body:Y,...Z,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/skills",S,{query:$,...Y,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/skills/${$}`,{...Y,__security:{bearerAuth:!0}})}}p$.Content=L2;p$.Versions=n1;class k2 extends N{create($,Y,Z){return this._client.post(J`/uploads/${$}/parts`,t({body:Y,...Z,__security:{bearerAuth:!0}},this._client))}}class K1 extends N{constructor(){super(...arguments);this.parts=new k2(this._client)}create($,Y){return this._client.post("/uploads",{body:$,...Y,__security:{bearerAuth:!0}})}cancel($,Y){return this._client.post(J`/uploads/${$}/cancel`,{...Y,__security:{bearerAuth:!0}})}complete($,Y,Z){return this._client.post(J`/uploads/${$}/complete`,{body:Y,...Z,__security:{bearerAuth:!0}})}}K1.Parts=k2;var d6=async($)=>{let Y=await Promise.allSettled($),Z=Y.filter((X)=>X.status==="rejected");if(Z.length){for(let X of Z)console.error(X.reason);throw Error(`${Z.length} promise(s) failed - see the above errors`)}let w=[];for(let X of Y)if(X.status==="fulfilled")w.push(X.value);return w};class C2 extends N{create($,Y,Z){return this._client.post(J`/vector_stores/${$}/file_batches`,{body:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}retrieve($,Y,Z){let{vector_store_id:w}=Y;return this._client.get(J`/vector_stores/${w}/file_batches/${$}`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}cancel($,Y,Z){let{vector_store_id:w}=Y;return this._client.post(J`/vector_stores/${w}/file_batches/${$}/cancel`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}async createAndPoll($,Y,Z){let w=await this.create($,Y);return await this.poll($,w.id,Z)}listFiles($,Y,Z){let{vector_store_id:w,...X}=Y;return this._client.getAPIList(J`/vector_stores/${w}/file_batches/${$}/files`,S,{query:X,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}async poll($,Y,Z){let w=x([Z?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":Z?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:X,response:W}=await this.retrieve(Y,{vector_store_id:$},{...Z,headers:w}).withResponse();switch(X.status){case"in_progress":let G=5000;if(Z?.pollIntervalMs)G=Z.pollIntervalMs;else{let Q=W.headers.get("openai-poll-after-ms");if(Q){let V=parseInt(Q);if(!isNaN(V))G=V}}await q$(G);break;case"failed":case"cancelled":case"completed":return X}}}async uploadAndPoll($,{files:Y,fileIds:Z=[]},w){if(Y==null||Y.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let X=w?.maxConcurrency??5,W=Math.min(X,Y.length),G=this._client,Q=Y.values(),V=[...Z];async function H(K){for(let U of K){let M=await G.files.create({file:U,purpose:"assistants"},w);V.push(M.id)}}let T=Array(W).fill(Q).map(H);return await d6(T),await this.createAndPoll($,{file_ids:V})}}class S2 extends N{create($,Y,Z){return this._client.post(J`/vector_stores/${$}/files`,{body:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}retrieve($,Y,Z){let{vector_store_id:w}=Y;return this._client.get(J`/vector_stores/${w}/files/${$}`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}update($,Y,Z){let{vector_store_id:w,...X}=Y;return this._client.post(J`/vector_stores/${w}/files/${$}`,{body:X,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}list($,Y={},Z){return this._client.getAPIList(J`/vector_stores/${$}/files`,S,{query:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}delete($,Y,Z){let{vector_store_id:w}=Y;return this._client.delete(J`/vector_stores/${w}/files/${$}`,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}async createAndPoll($,Y,Z){let w=await this.create($,Y,Z);return await this.poll($,w.id,Z)}async poll($,Y,Z){let w=x([Z?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":Z?.pollIntervalMs?.toString()??void 0}]);while(!0){let X=await this.retrieve(Y,{vector_store_id:$},{...Z,headers:w}).withResponse(),W=X.data;switch(W.status){case"in_progress":let G=5000;if(Z?.pollIntervalMs)G=Z.pollIntervalMs;else{let Q=X.response.headers.get("openai-poll-after-ms");if(Q){let V=parseInt(Q);if(!isNaN(V))G=V}}await q$(G);break;case"failed":case"completed":return W}}}async upload($,Y,Z){let w=await this._client.files.create({file:Y,purpose:"assistants"},Z);return this.create($,{file_id:w.id},Z)}async uploadAndPoll($,Y,Z){let w=await this.upload($,Y,Z);return await this.poll($,w.id,Z)}content($,Y,Z){let{vector_store_id:w}=Y;return this._client.getAPIList(J`/vector_stores/${w}/files/${$}/content`,Z$,{...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}class i$ extends N{constructor(){super(...arguments);this.files=new S2(this._client),this.fileBatches=new C2(this._client)}create($,Y){return this._client.post("/vector_stores",{body:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}retrieve($,Y){return this._client.get(J`/vector_stores/${$}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}update($,Y,Z){return this._client.post(J`/vector_stores/${$}`,{body:Y,...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/vector_stores",S,{query:$,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/vector_stores/${$}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),__security:{bearerAuth:!0}})}search($,Y,Z){return this._client.getAPIList(J`/vector_stores/${$}/search`,Z$,{body:Y,method:"post",...Z,headers:x([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),__security:{bearerAuth:!0}})}}i$.Files=S2;i$.FileBatches=C2;class a1 extends N{create($,Y){return this._client.post("/videos",t({body:$,...Y,__security:{bearerAuth:!0}},this._client))}retrieve($,Y){return this._client.get(J`/videos/${$}`,{...Y,__security:{bearerAuth:!0}})}list($={},Y){return this._client.getAPIList("/videos",j,{query:$,...Y,__security:{bearerAuth:!0}})}delete($,Y){return this._client.delete(J`/videos/${$}`,{...Y,__security:{bearerAuth:!0}})}createCharacter($,Y){return this._client.post("/videos/characters",t({body:$,...Y,__security:{bearerAuth:!0}},this._client))}downloadContent($,Y={},Z){return this._client.get(J`/videos/${$}/content`,{query:Y,...Z,headers:x([{Accept:"application/binary"},Z?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit($,Y){return this._client.post("/videos/edits",t({body:$,...Y,__security:{bearerAuth:!0}},this._client))}extend($,Y){return this._client.post("/videos/extensions",t({body:$,...Y,__security:{bearerAuth:!0}},this._client))}getCharacter($,Y){return this._client.get(J`/videos/characters/${$}`,{...Y,__security:{bearerAuth:!0}})}remix($,Y,Z){return this._client.post(J`/videos/${$}/remix`,h$({body:Y,...Z,__security:{bearerAuth:!0}},this._client))}}var t1,u6,M3;class r1 extends N{constructor(){super(...arguments);t1.add(this)}async unwrap($,Y,Z=this._client.webhookSecret,w=300){return await this.verifySignature($,Y,Z,w),JSON.parse($)}async verifySignature($,Y,Z=this._client.webhookSecret,w=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");B(this,t1,"m",u6).call(this,Z);let X=x([Y]).values,W=B(this,t1,"m",M3).call(this,X,"webhook-signature"),G=B(this,t1,"m",M3).call(this,X,"webhook-timestamp"),Q=B(this,t1,"m",M3).call(this,X,"webhook-id"),V=parseInt(G,10);if(isNaN(V))throw new R$("Invalid webhook timestamp format");let H=Math.floor(Date.now()/1000);if(H-V>w)throw new R$("Webhook timestamp is too old");if(V>H+w)throw new R$("Webhook timestamp is too new");let T=W.split(" ").map((q)=>q.startsWith("v1,")?q.substring(3):q),K=Z.startsWith("whsec_")?Buffer.from(Z.replace("whsec_",""),"base64"):Buffer.from(Z,"utf-8"),U=Q?`${Q}.${G}.${$}`:`${G}.${$}`,M=await crypto.subtle.importKey("raw",K,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let q of T)try{let P=Buffer.from(q,"base64");if(await crypto.subtle.verify("HMAC",M,P,new TextEncoder().encode(U)))return}catch{continue}throw new R$("The given webhook signature does not match the expected signature")}}t1=new WeakSet,u6=function(Y){if(typeof Y!=="string"||Y.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")},M3=function(Y,Z){if(!Y)throw Error("Headers are required");let w=Y.get(Z);if(w===null||w===void 0)throw Error(`Missing required header: ${Z}`);return w};var k4,C4,x3,p6,LZ="workload-identity-auth";class C{constructor({baseURL:$=U$("OPENAI_BASE_URL"),apiKey:Y=U$("OPENAI_API_KEY")??null,adminAPIKey:Z=U$("OPENAI_ADMIN_KEY")??null,organization:w=U$("OPENAI_ORG_ID")??null,project:X=U$("OPENAI_PROJECT_ID")??null,webhookSecret:W=U$("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:G,...Q}={}){k4.add(this),x3.set(this,void 0),this.completions=new y1(this),this.chat=new $1(this),this.embeddings=new D1(this),this.files=new g1(this),this.images=new u1(this),this.audio=new f$(this),this.moderations=new p1(this),this.models=new l1(this),this.fineTuning=new F$(this),this.graders=new B1(this),this.vectorStores=new i$(this),this.webhooks=new r1(this),this.beta=new L$(this),this.batches=new j1(this),this.uploads=new K1(this),this.admin=new Z1(this),this.responses=new j$(this),this.realtime=new u$(this),this.conversations=new N1(this),this.evals=new V1(this),this.containers=new z1(this),this.skills=new p$(this),this.videos=new a1(this);let V={apiKey:Y,adminAPIKey:Z,organization:w,project:X,webhookSecret:W,workloadIdentity:G,...Q,baseURL:$||"https://api.openai.com/v1"};if(Y&&G)throw new O("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!Y&&!Z&&!G)throw new O("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!V.dangerouslyAllowBrowser&&u9())throw new O(`It looks like you're running in a browser-like environment.
166
196
 
167
197
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
168
198
  If you understand the risks and have appropriate mitigations in place,
@@ -171,40 +201,40 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
171
201
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
172
202
 
173
203
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
174
- `);this.baseURL=z.baseURL,this.timeout=z.timeout??F4.DEFAULT_TIMEOUT,this.logger=z.logger??console;let H="warn";this.logLevel=H,this.logLevel=$4(z.logLevel,"ClientOptions.logLevel",this)??$4(U$("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??H,this.fetchOptions=z.fetchOptions,this.maxRetries=z.maxRetries??2,this.fetch=z.fetch??l2(),k(this,M3,u9,"f");let T=U$("OPENAI_CUSTOM_HEADERS");if(T){let K={};for(let U of T.split(`
175
- `)){let M=U.indexOf(":");if(M>=0)K[U.substring(0,M).trim()]=U.substring(M+1).trim()}z.defaultHeaders=x([K,z.defaultHeaders])}if(this._options=z,G)this._workloadIdentityAuth=new Z4(G,this.fetch);this.apiKey=typeof Y==="string"?Y:null,this.adminAPIKey=Z,this.organization=w,this.project=X,this.webhookSecret=W}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:Y},Z={bearerAuth:!0,adminAPIKeyAuth:!0}){if($.get("authorization")||$.get("api-key"))return;if(Y.has("authorization")||Y.has("api-key"))return;if(this._workloadIdentityAuth&&Z.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($,Y={bearerAuth:!0,adminAPIKeyAuth:!0}){return x([Y.bearerAuth?await this.bearerAuth($):null,Y.adminAPIKeyAuth?await this.adminAPIKeyAuth($):null])}async bearerAuth($){if(this._workloadIdentityAuth)return x([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey==null)return;return x([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth($){if(this.adminAPIKey==null)return;return x([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery($){return o9($)}getUserAgent(){return`${this.constructor.name}/JS ${D$}`}defaultIdempotencyKey(){return`stainless-node-retry-${c3()}`}makeStatusError($,Y,Z,w){return g.generate($,Y,Z,w)}async _callApiKey(){let $=this._options.apiKey;if(typeof $!=="function")return!1;let Y;try{Y=await $()}catch(Z){if(Z instanceof O)throw Z;throw new O(`Failed to get token from 'apiKey' function: ${Z.message}`,{cause:Z})}if(typeof Y!=="string"||!Y)throw new O(`Expected 'apiKey' function argument to return a string but it returned ${Y}`);return this.apiKey=Y,!0}buildURL($,Y,Z){let w=!B(this,L4,"m",d6).call(this)&&Z||this.baseURL,X=b9($)?new URL($):new URL(w+(w.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),W=this.defaultQuery(),G=Object.fromEntries(X.searchParams);if(!u3(W)||!u3(G))Y={...G,...W,...Y};if(typeof Y==="object"&&Y&&!Array.isArray(Y))X.search=this.stringifyQuery(Y);return X.toString()}async prepareOptions($){if(($.__security??{bearerAuth:!0}).bearerAuth)await this._callApiKey()}async prepareRequest($,{url:Y,options:Z}){}get($,Y){return this.methodRequest("get",$,Y)}post($,Y){return this.methodRequest("post",$,Y)}patch($,Y){return this.methodRequest("patch",$,Y)}put($,Y){return this.methodRequest("put",$,Y)}delete($,Y){return this.methodRequest("delete",$,Y)}methodRequest($,Y,Z){return this.request(Promise.resolve(Z).then((w)=>{return{method:$,path:Y,...w}}))}request($,Y=null){return new s$(this,this.makeRequest($,Y,void 0))}async makeRequest($,Y,Z){let w=await $,X=w.maxRetries??this.maxRetries;if(Y==null)Y=X;await this.prepareOptions(w);let{req:W,url:G,timeout:Q}=await this.buildRequest(w,{retryCount:X-Y});await this.prepareRequest(W,{url:G,options:w});let z="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),H=Z===void 0?"":`, retryOf: ${Z}`,T=Date.now();if(c(this).debug(`[${z}] sending request`,P$({retryOfRequestLogID:Z,method:w.method,url:G,options:w,headers:W.headers})),w.signal?.aborted)throw new d;let K=w.__security??{bearerAuth:!0},U=new AbortController,M=await this.fetchWithAuth(G,W,Q,U,K).catch(Z0),q=Date.now();if(M instanceof globalThis.Error){let R=`retrying, ${Y} attempts remaining`;if(w.signal?.aborted)throw new d;let F=Y0(M)||/timed? ?out/i.test(String(M)+("cause"in M?String(M.cause):""));if(Y)return c(this).info(`[${z}] connection ${F?"timed out":"failed"} - ${R}`),c(this).debug(`[${z}] connection ${F?"timed out":"failed"} (${R})`,P$({retryOfRequestLogID:Z,url:G,durationMs:q-T,message:M.message})),this.retryRequest(w,Y,Z??z);if(c(this).info(`[${z}] connection ${F?"timed out":"failed"} - error; no more retries left`),c(this).debug(`[${z}] connection ${F?"timed out":"failed"} (error; no more retries left)`,P$({retryOfRequestLogID:Z,url:G,durationMs:q-T,message:M.message})),M instanceof O1||M instanceof d2)throw M;if(F)throw new r$;throw new t$({message:KZ(M),cause:M})}let P=[...M.headers.entries()].filter(([R])=>R==="x-request-id").map(([R,F])=>", "+R+": "+JSON.stringify(F)).join(""),A=`[${z}${H}${P}] ${W.method} ${G} ${M.ok?"succeeded":"failed"} with status ${M.status} in ${q-T}ms`;if(!M.ok){if(M.status===401&&this._workloadIdentityAuth&&K.bearerAuth&&!w.__metadata?.hasStreamingBody&&!w.__metadata?.workloadIdentityTokenRefreshed)return await i3(M.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...w,__metadata:{...w.__metadata,workloadIdentityTokenRefreshed:!0}},Y,Z??z);let R=await this.shouldRetry(M);if(Y&&R){let I=`retrying, ${Y} attempts remaining`;return await i3(M.body),c(this).info(`${A} - ${I}`),c(this).debug(`[${z}] response error (${I})`,P$({retryOfRequestLogID:Z,url:M.url,status:M.status,headers:M.headers,durationMs:q-T})),this.retryRequest(w,Y,Z??z,M.headers)}let F=R?"error; no more retries left":"error; not retryable";c(this).info(`${A} - ${F}`);let b=await M.text().catch((I)=>Z0(I).message),v=I9(b),o=v?void 0:b;throw c(this).debug(`[${z}] response error (${F})`,P$({retryOfRequestLogID:Z,url:M.url,status:M.status,headers:M.headers,message:o,durationMs:Date.now()-T})),this.makeStatusError(M.status,v,o,M.headers)}return c(this).info(A),c(this).debug(`[${z}] response start`,P$({retryOfRequestLogID:Z,url:M.url,status:M.status,headers:M.headers,durationMs:q-T})),{response:M,options:w,controller:U,requestLogID:z,retryOfRequestLogID:Z,startTime:T}}getAPIList($,Y,Z){return this.requestAPIList(Y,Z&&"then"in Z?Z.then((w)=>({method:"get",path:$,...w})):{method:"get",path:$,...Z})}requestAPIList($,Y){let Z=this.makeRequest(Y,null,void 0);return new s2(this,Z,$)}async fetchWithAuth($,Y,Z,w,X={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&X.bearerAuth){let G=Y.headers,Q=G.get("Authorization");if(!Q||Q===`Bearer ${BZ}`){let z=await this._workloadIdentityAuth.getToken();G.set("Authorization",`Bearer ${z}`)}}return await this.fetchWithTimeout($,Y,Z,w)}async fetchWithTimeout($,Y,Z,w){let{signal:X,method:W,...G}=Y||{},Q=this._makeAbort(w);if(X)X.addEventListener("abort",Q,{once:!0});let z=setTimeout(Q,Z),H=globalThis.ReadableStream&&G.body instanceof globalThis.ReadableStream||typeof G.body==="object"&&G.body!==null&&Symbol.asyncIterator in G.body,T={signal:w.signal,...H?{duplex:"half"}:{},method:"GET",...G};if(W)T.method=W.toUpperCase();try{return await this.fetch.call(void 0,$,T)}finally{clearTimeout(z)}}async shouldRetry($){let Y=$.headers.get("x-should-retry");if(Y==="true")return!0;if(Y==="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($,Y,Z,w){let X,W=w?.get("retry-after-ms");if(W){let Q=parseFloat(W);if(!Number.isNaN(Q))X=Q}let G=w?.get("retry-after");if(G&&!X){let Q=parseFloat(G);if(!Number.isNaN(Q))X=Q*1000;else X=Date.parse(G)-Date.now()}if(X===void 0){let Q=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(Y,Q)}return await q$(X),this.makeRequest($,Y-1,Z)}calculateDefaultRetryTimeoutMillis($,Y){let X=Y-$,W=Math.min(0.5*Math.pow(2,X),8),G=1-Math.random()*0.25;return W*G*1000}async buildRequest($,{retryCount:Y=0}={}){let Z={...$},{method:w,path:X,query:W,defaultBaseURL:G}=Z,Q=this.buildURL(X,W,G);if("timeout"in Z)y9("timeout",Z.timeout);Z.timeout=Z.timeout??this.timeout;let{bodyHeaders:z,body:H,isStreamingBody:T}=this.buildBody({options:Z});if(T)$.__metadata={...$.__metadata,hasStreamingBody:!0};let K=await this.buildHeaders({options:$,method:w,bodyHeaders:z,retryCount:Y});return{req:{method:w,headers:K,...Z.signal&&{signal:Z.signal},...globalThis.ReadableStream&&H instanceof globalThis.ReadableStream&&{duplex:"half"},...H&&{body:H},...this.fetchOptions??{},...Z.fetchOptions??{}},url:Q,timeout:Z.timeout}}async buildHeaders({options:$,method:Y,bodyHeaders:Z,retryCount:w}){let X={};if(this.idempotencyHeader&&Y!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();X[this.idempotencyHeader]=$.idempotencyKey}let W=x([X,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(w),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...c9(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders($,$.__security??{bearerAuth:!0}),this._options.defaultHeaders,Z,$.headers]);return this.validateHeaders(W,$.__security??{bearerAuth:!0}),W.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:Y}}){if(!$)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let Z=x([Y]),w=typeof globalThis.ReadableStream<"u"&&$ instanceof globalThis.ReadableStream,X=!w&&(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"&&Z.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||w)return{bodyHeaders:void 0,body:$,isStreamingBody:!X};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:p2($),isStreamingBody:!0};else if(typeof $==="object"&&Z.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{...B(this,M3,"f").call(this,{body:$,headers:Z}),isStreamingBody:!1}}}F4=C,M3=new WeakMap,L4=new WeakSet,d6=function(){return this.baseURL!=="https://api.openai.com/v1"};C.OpenAI=F4;C.DEFAULT_TIMEOUT=600000;C.OpenAIError=O;C.APIError=g;C.APIConnectionError=t$;C.APIConnectionTimeoutError=r$;C.APIUserAbortError=d;C.NotFoundError=W0;C.ConflictError=J0;C.RateLimitError=N0;C.BadRequestError=w0;C.AuthenticationError=G0;C.InternalServerError=z0;C.PermissionDeniedError=X0;C.UnprocessableEntityError=Q0;C.InvalidWebhookSignatureError=R$;C.toFile=e2;C.Completions=y1;C.Chat=$1;C.Embeddings=D1;C.Files=g1;C.Images=u1;C.Audio=f$;C.Moderations=p1;C.Models=l1;C.FineTuning=F$;C.Graders=B1;C.VectorStores=i$;C.Webhooks=r1;C.Beta=L$;C.Batches=j1;C.Uploads=K1;C.Admin=Z1;C.Responses=j$;C.Realtime=u$;C.Conversations=z1;C.Evals=V1;C.Containers=N1;C.Skills=p$;C.Videos=a1;function KZ($){if(HZ($))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });";return}function HZ($){let Y=$;for(let Z=0;Z<8&&Y&&typeof Y==="object";Z++){let w=Y;if(w.code==="UND_ERR_INVALID_ARG"&&typeof w.message==="string"&&w.message.includes("invalid onRequestStart method"))return!0;Y=w.cause}return!1}function R2($,Y,Z){let w=C$(Y.error?.message||Y.message||Y.msg||`HTTP ${$}`);switch($){case 400:return new L(V("api.400")+w,E.USAGE,V("api.400Hint"));case 401:return new L(V("api.401"),E.AUTH,V("api.401Hint"));case 402:return new L(V("api.402")+w,E.QUOTA,V("api.402Hint"));case 403:return new L(V("api.403"),E.AUTH,V("api.403Hint"));case 404:return new L(V("api.404")+w,E.USAGE,V("api.404Hint"));case 421:return new L(V("api.421")+w,E.CONTENT_FILTER,V("api.421Hint"));case 429:return new L(V("api.429")+w,E.QUOTA,V("api.429Hint"));case 500:return new L(V("api.500"),E.NETWORK,V("api.500Hint"));case 503:return new L(V("api.503"),E.NETWORK,V("api.503Hint"));default:return new L(V("api.default")+w+" (HTTP "+$+")",E.GENERAL)}}function n$($){return{role:typeof $.role==="string"?$.role:void 0,content:typeof $.content==="string"?$.content:void 0,reasoning_content:typeof $.reasoning_content==="string"?$.reasoning_content:void 0,annotations:Array.isArray($.annotations)?$.annotations:void 0}}function u6($){let Y=$.usage;if(typeof Y==="object"&&Y!==null)return Y;return}function a$($){if("controller"in $){let Y=$.controller;if(Y&&typeof Y==="object"&&Y!==null&&"abort"in Y)Y.abort()}}function l6($){if("url"in $){let Y=$.url;return typeof Y==="string"?Y:""}return""}function x3($){return l6($)}function q3($){if($ instanceof L)return $;if($ instanceof C.APIConnectionError)return new L("Network request failed.",E.NETWORK,`Check your network connection.
176
- To use a proxy: set HTTPS_PROXY env var, or run: mimo config set proxy http://HOST:PORT`);if($ instanceof C.RateLimitError){let Y=$.error??{};return R2($.status??429,Y,x3($))}if($ instanceof C.AuthenticationError){let Y=$.error??{};return R2($.status??401,Y,x3($))}if($ instanceof C.BadRequestError){let Y=$.error??{};return R2($.status??400,Y,x3($))}if($ instanceof C.APIError){let Y=$.error??{};return R2($.status??0,Y,x3($))}if($ instanceof Error){if($.name==="AbortError"||$.name==="TimeoutError"||$.message.includes("timed out"))return new L("Request timed out.",E.TIMEOUT,"Try increasing --timeout (e.g. --timeout 60).");return new L($.message,E.GENERAL)}return new L(String($),E.GENERAL)}function TZ($){if($){let Z={apiKey:$.apiKey,fileApiKey:$.fileApiKey,fileSkApiKey:$.fileSkApiKey,activeKey:$.activeKey};try{return v2(Z).token}catch{}}let Y=process.env.MIMO_API_KEY??process.env.MIMO_API_TOKEN;if(Y)return Y;throw new L("No API key provided.",E.AUTH,`Set your API key:
204
+ `);this.baseURL=V.baseURL,this.timeout=V.timeout??C4.DEFAULT_TIMEOUT,this.logger=V.logger??console;let H="warn";this.logLevel=H,this.logLevel=Z4(V.logLevel,"ClientOptions.logLevel",this)??Z4(U$("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??H,this.fetchOptions=V.fetchOptions,this.maxRetries=V.maxRetries??2,this.fetch=V.fetch??p2(),k(this,x3,i9,"f");let T=U$("OPENAI_CUSTOM_HEADERS");if(T){let K={};for(let U of T.split(`
205
+ `)){let M=U.indexOf(":");if(M>=0)K[U.substring(0,M).trim()]=U.substring(M+1).trim()}V.defaultHeaders=x([K,V.defaultHeaders])}if(this._options=V,G)this._workloadIdentityAuth=new G4(G,this.fetch);this.apiKey=typeof Y==="string"?Y:null,this.adminAPIKey=Z,this.organization=w,this.project=X,this.webhookSecret=W}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:Y},Z={bearerAuth:!0,adminAPIKeyAuth:!0}){if($.get("authorization")||$.get("api-key"))return;if(Y.has("authorization")||Y.has("api-key"))return;if(this._workloadIdentityAuth&&Z.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($,Y={bearerAuth:!0,adminAPIKeyAuth:!0}){return x([Y.bearerAuth?await this.bearerAuth($):null,Y.adminAPIKeyAuth?await this.adminAPIKeyAuth($):null])}async bearerAuth($){if(this._workloadIdentityAuth)return x([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey==null)return;return x([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth($){if(this.adminAPIKey==null)return;return x([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery($){return Y6($)}getUserAgent(){return`${this.constructor.name}/JS ${D$}`}defaultIdempotencyKey(){return`stainless-node-retry-${u3()}`}makeStatusError($,Y,Z,w){return g.generate($,Y,Z,w)}async _callApiKey(){let $=this._options.apiKey;if(typeof $!=="function")return!1;let Y;try{Y=await $()}catch(Z){if(Z instanceof O)throw Z;throw new O(`Failed to get token from 'apiKey' function: ${Z.message}`,{cause:Z})}if(typeof Y!=="string"||!Y)throw new O(`Expected 'apiKey' function argument to return a string but it returned ${Y}`);return this.apiKey=Y,!0}buildURL($,Y,Z){let w=!B(this,k4,"m",p6).call(this)&&Z||this.baseURL,X=I9($)?new URL($):new URL(w+(w.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),W=this.defaultQuery(),G=Object.fromEntries(X.searchParams);if(!p3(W)||!p3(G))Y={...G,...W,...Y};if(typeof Y==="object"&&Y&&!Array.isArray(Y))X.search=this.stringifyQuery(Y);return X.toString()}async prepareOptions($){if(($.__security??{bearerAuth:!0}).bearerAuth)await this._callApiKey()}async prepareRequest($,{url:Y,options:Z}){}get($,Y){return this.methodRequest("get",$,Y)}post($,Y){return this.methodRequest("post",$,Y)}patch($,Y){return this.methodRequest("patch",$,Y)}put($,Y){return this.methodRequest("put",$,Y)}delete($,Y){return this.methodRequest("delete",$,Y)}methodRequest($,Y,Z){return this.request(Promise.resolve(Z).then((w)=>{return{method:$,path:Y,...w}}))}request($,Y=null){return new s$(this,this.makeRequest($,Y,void 0))}async makeRequest($,Y,Z){let w=await $,X=w.maxRetries??this.maxRetries;if(Y==null)Y=X;await this.prepareOptions(w);let{req:W,url:G,timeout:Q}=await this.buildRequest(w,{retryCount:X-Y});await this.prepareRequest(W,{url:G,options:w});let V="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),H=Z===void 0?"":`, retryOf: ${Z}`,T=Date.now();if(c(this).debug(`[${V}] sending request`,P$({retryOfRequestLogID:Z,method:w.method,url:G,options:w,headers:W.headers})),w.signal?.aborted)throw new d;let K=w.__security??{bearerAuth:!0},U=new AbortController,M=await this.fetchWithAuth(G,W,Q,U,K).catch(Z0),q=Date.now();if(M instanceof globalThis.Error){let R=`retrying, ${Y} attempts remaining`;if(w.signal?.aborted)throw new d;let F=Y0(M)||/timed? ?out/i.test(String(M)+("cause"in M?String(M.cause):""));if(Y)return c(this).info(`[${V}] connection ${F?"timed out":"failed"} - ${R}`),c(this).debug(`[${V}] connection ${F?"timed out":"failed"} (${R})`,P$({retryOfRequestLogID:Z,url:G,durationMs:q-T,message:M.message})),this.retryRequest(w,Y,Z??V);if(c(this).info(`[${V}] connection ${F?"timed out":"failed"} - error; no more retries left`),c(this).debug(`[${V}] connection ${F?"timed out":"failed"} (error; no more retries left)`,P$({retryOfRequestLogID:Z,url:G,durationMs:q-T,message:M.message})),M instanceof O1||M instanceof u2)throw M;if(F)throw new r$;throw new t$({message:FZ(M),cause:M})}let P=[...M.headers.entries()].filter(([R])=>R==="x-request-id").map(([R,F])=>", "+R+": "+JSON.stringify(F)).join(""),A=`[${V}${H}${P}] ${W.method} ${G} ${M.ok?"succeeded":"failed"} with status ${M.status} in ${q-T}ms`;if(!M.ok){if(M.status===401&&this._workloadIdentityAuth&&K.bearerAuth&&!w.__metadata?.hasStreamingBody&&!w.__metadata?.workloadIdentityTokenRefreshed)return await a3(M.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...w,__metadata:{...w.__metadata,workloadIdentityTokenRefreshed:!0}},Y,Z??V);let R=await this.shouldRetry(M);if(Y&&R){let I=`retrying, ${Y} attempts remaining`;return await a3(M.body),c(this).info(`${A} - ${I}`),c(this).debug(`[${V}] response error (${I})`,P$({retryOfRequestLogID:Z,url:M.url,status:M.status,headers:M.headers,durationMs:q-T})),this.retryRequest(w,Y,Z??V,M.headers)}let F=R?"error; no more retries left":"error; not retryable";c(this).info(`${A} - ${F}`);let b=await M.text().catch((I)=>Z0(I).message),v=g9(b),o=v?void 0:b;throw c(this).debug(`[${V}] response error (${F})`,P$({retryOfRequestLogID:Z,url:M.url,status:M.status,headers:M.headers,message:o,durationMs:Date.now()-T})),this.makeStatusError(M.status,v,o,M.headers)}return c(this).info(A),c(this).debug(`[${V}] response start`,P$({retryOfRequestLogID:Z,url:M.url,status:M.status,headers:M.headers,durationMs:q-T})),{response:M,options:w,controller:U,requestLogID:V,retryOfRequestLogID:Z,startTime:T}}getAPIList($,Y,Z){return this.requestAPIList(Y,Z&&"then"in Z?Z.then((w)=>({method:"get",path:$,...w})):{method:"get",path:$,...Z})}requestAPIList($,Y){let Z=this.makeRequest(Y,null,void 0);return new o2(this,Z,$)}async fetchWithAuth($,Y,Z,w,X={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&X.bearerAuth){let G=Y.headers,Q=G.get("Authorization");if(!Q||Q===`Bearer ${LZ}`){let V=await this._workloadIdentityAuth.getToken();G.set("Authorization",`Bearer ${V}`)}}return await this.fetchWithTimeout($,Y,Z,w)}async fetchWithTimeout($,Y,Z,w){let{signal:X,method:W,...G}=Y||{},Q=this._makeAbort(w);if(X)X.addEventListener("abort",Q,{once:!0});let V=setTimeout(Q,Z),H=globalThis.ReadableStream&&G.body instanceof globalThis.ReadableStream||typeof G.body==="object"&&G.body!==null&&Symbol.asyncIterator in G.body,T={signal:w.signal,...H?{duplex:"half"}:{},method:"GET",...G};if(W)T.method=W.toUpperCase();try{return await this.fetch.call(void 0,$,T)}finally{clearTimeout(V)}}async shouldRetry($){let Y=$.headers.get("x-should-retry");if(Y==="true")return!0;if(Y==="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($,Y,Z,w){let X,W=w?.get("retry-after-ms");if(W){let Q=parseFloat(W);if(!Number.isNaN(Q))X=Q}let G=w?.get("retry-after");if(G&&!X){let Q=parseFloat(G);if(!Number.isNaN(Q))X=Q*1000;else X=Date.parse(G)-Date.now()}if(X===void 0){let Q=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(Y,Q)}return await q$(X),this.makeRequest($,Y-1,Z)}calculateDefaultRetryTimeoutMillis($,Y){let X=Y-$,W=Math.min(0.5*Math.pow(2,X),8),G=1-Math.random()*0.25;return W*G*1000}async buildRequest($,{retryCount:Y=0}={}){let Z={...$},{method:w,path:X,query:W,defaultBaseURL:G}=Z,Q=this.buildURL(X,W,G);if("timeout"in Z)h9("timeout",Z.timeout);Z.timeout=Z.timeout??this.timeout;let{bodyHeaders:V,body:H,isStreamingBody:T}=this.buildBody({options:Z});if(T)$.__metadata={...$.__metadata,hasStreamingBody:!0};let K=await this.buildHeaders({options:$,method:w,bodyHeaders:V,retryCount:Y});return{req:{method:w,headers:K,...Z.signal&&{signal:Z.signal},...globalThis.ReadableStream&&H instanceof globalThis.ReadableStream&&{duplex:"half"},...H&&{body:H},...this.fetchOptions??{},...Z.fetchOptions??{}},url:Q,timeout:Z.timeout}}async buildHeaders({options:$,method:Y,bodyHeaders:Z,retryCount:w}){let X={};if(this.idempotencyHeader&&Y!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();X[this.idempotencyHeader]=$.idempotencyKey}let W=x([X,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(w),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...l9(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders($,$.__security??{bearerAuth:!0}),this._options.defaultHeaders,Z,$.headers]);return this.validateHeaders(W,$.__security??{bearerAuth:!0}),W.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:Y}}){if(!$)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let Z=x([Y]),w=typeof globalThis.ReadableStream<"u"&&$ instanceof globalThis.ReadableStream,X=!w&&(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"&&Z.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||w)return{bodyHeaders:void 0,body:$,isStreamingBody:!X};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:i2($),isStreamingBody:!0};else if(typeof $==="object"&&Z.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{...B(this,x3,"f").call(this,{body:$,headers:Z}),isStreamingBody:!1}}}C4=C,x3=new WeakMap,k4=new WeakSet,p6=function(){return this.baseURL!=="https://api.openai.com/v1"};C.OpenAI=C4;C.DEFAULT_TIMEOUT=600000;C.OpenAIError=O;C.APIError=g;C.APIConnectionError=t$;C.APIConnectionTimeoutError=r$;C.APIUserAbortError=d;C.NotFoundError=W0;C.ConflictError=J0;C.RateLimitError=z0;C.BadRequestError=w0;C.AuthenticationError=G0;C.InternalServerError=N0;C.PermissionDeniedError=X0;C.UnprocessableEntityError=Q0;C.InvalidWebhookSignatureError=R$;C.toFile=$3;C.Completions=y1;C.Chat=$1;C.Embeddings=D1;C.Files=g1;C.Images=u1;C.Audio=f$;C.Moderations=p1;C.Models=l1;C.FineTuning=F$;C.Graders=B1;C.VectorStores=i$;C.Webhooks=r1;C.Beta=L$;C.Batches=j1;C.Uploads=K1;C.Admin=Z1;C.Responses=j$;C.Realtime=u$;C.Conversations=N1;C.Evals=V1;C.Containers=z1;C.Skills=p$;C.Videos=a1;function FZ($){if(kZ($))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });";return}function kZ($){let Y=$;for(let Z=0;Z<8&&Y&&typeof Y==="object";Z++){let w=Y;if(w.code==="UND_ERR_INVALID_ARG"&&typeof w.message==="string"&&w.message.includes("invalid onRequestStart method"))return!0;Y=w.cause}return!1}function R2($,Y,Z){let w=C$(Y.error?.message||Y.message||Y.msg||`HTTP ${$}`);switch($){case 400:return new L(z("api.400")+w,E.USAGE,z("api.400Hint"));case 401:return new L(z("api.401"),E.AUTH,z("api.401Hint"));case 402:return new L(z("api.402")+w,E.QUOTA,z("api.402Hint"));case 403:return new L(z("api.403"),E.AUTH,z("api.403Hint"));case 404:return new L(z("api.404")+w,E.USAGE,z("api.404Hint"));case 421:return new L(z("api.421")+w,E.CONTENT_FILTER,z("api.421Hint"));case 429:return new L(z("api.429")+w,E.QUOTA,z("api.429Hint"));case 500:return new L(z("api.500"),E.NETWORK,z("api.500Hint"));case 503:return new L(z("api.503"),E.NETWORK,z("api.503Hint"));default:return new L(z("api.default")+w+" (HTTP "+$+")",E.GENERAL)}}function n$($){return{role:typeof $.role==="string"?$.role:void 0,content:typeof $.content==="string"?$.content:void 0,reasoning_content:typeof $.reasoning_content==="string"?$.reasoning_content:void 0,annotations:Array.isArray($.annotations)?$.annotations:void 0}}function i6($){let Y=$.usage;if(typeof Y==="object"&&Y!==null)return Y;return}function a$($){if("controller"in $){let Y=$.controller;if(Y&&typeof Y==="object"&&Y!==null&&"abort"in Y)Y.abort()}}function n6($){if("url"in $){let Y=$.url;return typeof Y==="string"?Y:""}return""}function q3($){return n6($)}function O3($){if($ instanceof L)return $;if($ instanceof C.APIConnectionError)return new L("Network request failed.",E.NETWORK,`Check your network connection.
206
+ To use a proxy: set HTTPS_PROXY env var, or run: mimo config set proxy http://HOST:PORT`);if($ instanceof C.RateLimitError){let Y=$.error??{};return R2($.status??429,Y,q3($))}if($ instanceof C.AuthenticationError){let Y=$.error??{};return R2($.status??401,Y,q3($))}if($ instanceof C.BadRequestError){let Y=$.error??{};return R2($.status??400,Y,q3($))}if($ instanceof C.APIError){let Y=$.error??{};return R2($.status??0,Y,q3($))}if($ instanceof Error){if($.name==="AbortError"||$.name==="TimeoutError"||$.message.includes("timed out"))return new L("Request timed out.",E.TIMEOUT,"Try increasing --timeout (e.g. --timeout 60).");return new L($.message,E.GENERAL)}return new L(String($),E.GENERAL)}function CZ($){if($){let Z={apiKey:$.apiKey,fileApiKey:$.fileApiKey,fileSkApiKey:$.fileSkApiKey,activeKey:$.activeKey};try{return v2(Z).token}catch{}}let Y=process.env.MIMO_API_KEY??process.env.MIMO_API_TOKEN;if(Y)return Y;throw new L("No API key provided.",E.AUTH,`Set your API key:
177
207
  `+` mimo auth login — interactive login
178
208
  `+` export MIMO_API_KEY=... — via environment variable
179
- `+" mimo chat --api-key ... — via flag")}function UZ($){if($?.baseURL)return $.baseURL;if($?.baseUrl)return $.baseUrl;if(process.env.MIMO_BASE_URL)return process.env.MIMO_BASE_URL;let Z=$?.activeKey==="sk"?$?.fileSkApiKey||$?.apiKey||$?.fileApiKey:$?.apiKey||$?.fileApiKey||$?.fileSkApiKey;if(Z){let w=S$(Z);if(w)return w}return}function G$($){let Y=TZ($),Z=UZ($);return new k4({apiKey:Y,baseURL:Z,timeout:$?.timeout})}var MZ="https://api.xiaomimimo.com/v1",xZ=300;class k4{openai;constructor($){this.openai=new C({apiKey:$.apiKey,baseURL:$.baseURL||MZ,timeout:($.timeout??xZ)*1000,defaultHeaders:{"User-Agent":`mimo-cli/${q1}`}})}buildRequestParams($,Y){let{thinking:Z,asr_options:w,audio:X,tools:W,...G}=$,Q={...G,stream:Y,thinking:Z,asr_options:w,audio:X};if(W&&W.length>0)Q.tools=W;return Q}async chatCompletion($){try{let Y=this.buildRequestParams($,!1);return await this.openai.chat.completions.create(Y)}catch(Y){throw q3(Y)}}async chatCompletionStream($){try{let Y=this.buildRequestParams($,!0);return await this.openai.chat.completions.create(Y)}catch(Y){throw q3(Y)}}async chat($){if($.stream===!0)return this.chatCompletionStream($);return this.chatCompletion($)}get raw(){return this.openai}}function C4($,Y){let Z=[];if($)Z.push(`\x1B[2m\x1B[90m${$}\x1B[39m\x1B[22m`);if(Y)Z.push(Y);return Z.join(`
209
+ `+" mimo chat --api-key ... — via flag")}function SZ($){if($?.baseURL)return $.baseURL;if($?.baseUrl)return $.baseUrl;if(process.env.MIMO_BASE_URL)return process.env.MIMO_BASE_URL;let Z=$?.activeKey==="sk"?$?.fileSkApiKey||$?.apiKey||$?.fileApiKey:$?.apiKey||$?.fileApiKey||$?.fileSkApiKey;if(Z){let w=S$(Z);if(w)return w}return}function G$($){let Y=CZ($),Z=SZ($);return new S4({apiKey:Y,baseURL:Z,timeout:$?.timeout})}var RZ="https://api.xiaomimimo.com/v1",PZ=300;class S4{openai;constructor($){this.openai=new C({apiKey:$.apiKey,baseURL:$.baseURL||RZ,timeout:($.timeout??PZ)*1000,defaultHeaders:{"User-Agent":`mimo-cli/${q1}`}})}buildRequestParams($,Y){let{thinking:Z,asr_options:w,audio:X,tools:W,...G}=$,Q={...G,stream:Y,thinking:Z,asr_options:w,audio:X};if(W&&W.length>0)Q.tools=W;return Q}async chatCompletion($){try{let Y=this.buildRequestParams($,!1);return await this.openai.chat.completions.create(Y)}catch(Y){throw O3(Y)}}async chatCompletionStream($){try{let Y=this.buildRequestParams($,!0);return await this.openai.chat.completions.create(Y)}catch(Y){throw O3(Y)}}async chat($){if($.stream===!0)return this.chatCompletionStream($);return this.chatCompletion($)}get raw(){return this.openai}}function R4($,Y){let Z=[];if($)Z.push(`\x1B[2m\x1B[90m${$}\x1B[39m\x1B[22m`);if(Y)Z.push(Y);return Z.join(`
180
210
 
181
211
  `)}function P2($){if(!$||$.length===0)return"";let Y=[];for(let Z=0;Z<$.length;Z++){let w=$[Z],W=[`[${Z+1}]`];if(w.title)W.push(w.title);if(w.url)W.push(`\x1B[36m${w.url}\x1B[39m`);if(w.summary)W.push(`— ${w.summary}`);Y.push(W.join(" "))}return Y.join(`
182
- `)}var p6=j({name:"chat",description:"cmd.chat.desc",usage:"mimo chat --message <text> [flags]",options:[{flag:"-m, --message <text>",description:"flag.chat.message",required:!0},{flag:"--model <model>",description:"flag.chat.model"},{flag:"-s, --system <text>",description:"flag.chat.system"},{flag:"--thinking",description:"flag.chat.thinking"},{flag:"--search",description:"flag.chat.search"},{flag:"--force-search",description:"flag.chat.forceSearch"},{flag:"--max-keyword <n>",description:"flag.chat.maxKeyword",type:"number"},{flag:"--search-limit <n>",description:"flag.chat.searchLimit",type:"number"},{flag:"--user-country <country>",description:"flag.chat.userCountry"},{flag:"--user-region <region>",description:"flag.chat.userRegion"},{flag:"--user-city <city>",description:"flag.chat.userCity"},{flag:"--stream",description:"flag.chat.stream",default:!0},{flag:"--no-stream",description:"flag.chat.noStream"},{flag:"--json",description:"flag.chat.json"},{flag:"--max-tokens <n>",description:"flag.chat.maxTokens",type:"number"},{flag:"--temperature <n>",description:"flag.chat.temperature",type:"number"}],examples:['mimo chat --message "What is MiMo?"','mimo chat -m "Hello" --model mimo-v2.5-pro --thinking','mimo chat -m "Latest news" --search','mimo chat -m "武汉明天天气" --search --user-city 武汉','mimo chat -m "Return JSON" --json --no-stream'],async run($,Y){let Z=Y,w=G$($),X=Z.message;if(!X)throw new L(V("chat.noMessage"),E.USAGE,"Usage: mimo chat --message <text>");if(X.trim().length===0)throw new L(V("chat.emptyMessage"),E.USAGE,"Provide a non-empty message with --message <text>");let W=1e5;if(X.length>W)throw new L(V("chat.messageTooLong",{len:String(X.length),max:String(W)}),E.USAGE,V("chat.messageTooLongHint"));let G=Z.model??"mimo-v2.5-pro",Q=Z.noStream?!1:Z.stream!==!1,z=[];if(Z.system)z.push({role:"system",content:Z.system});z.push({role:"user",content:X});let H={model:G,messages:z,stream:Q};if(Z.thinking)H.thinking={type:"enabled"};if(Z.search){let T={type:"web_search"};if(Z.forceSearch)T.force_search=!0;if(Z.maxKeyword!==void 0)T.max_keyword=Z.maxKeyword;if(Z.searchLimit!==void 0)T.limit=Z.searchLimit;if(Z.userCountry||Z.userRegion||Z.userCity)T.user_location={type:"approximate",...Z.userCountry&&{country:Z.userCountry},...Z.userRegion&&{region:Z.userRegion},...Z.userCity&&{city:Z.userCity}};H.tools=[T]}if(Z.json)H.response_format={type:"json_object"};if(Z.maxTokens!==void 0)H.max_completion_tokens=Z.maxTokens;if(Z.temperature!==void 0)H.temperature=Z.temperature;if($.dryRun){console.log(JSON.stringify({request:H},null,2));return}if(Q){let T="",K="",U=[],M="\x1B[2m",q="\x1B[90m",P="\x1B[0m",A=await w.chatCompletionStream(H);try{for await(let R of A){for(let b of R.choices){let v=n$(b.delta);if(v?.reasoning_content)K+=v.reasoning_content,process.stdout.write(`${M}${q}${v.reasoning_content}${P}`);if(v?.content)T+=v.content,process.stdout.write(v.content);if(v?.annotations)U.push(...v.annotations)}let F=u6(R);if(F&&$.verbose)process.stderr.write(`
212
+ `)}var a6=f({name:"chat",description:"cmd.chat.desc",usage:"mimo chat --message <text> [flags]",options:[{flag:"-m, --message <text>",description:"flag.chat.message",required:!0},{flag:"--model <model>",description:"flag.chat.model"},{flag:"-s, --system <text>",description:"flag.chat.system"},{flag:"--thinking",description:"flag.chat.thinking"},{flag:"--search",description:"flag.chat.search"},{flag:"--force-search",description:"flag.chat.forceSearch"},{flag:"--max-keyword <n>",description:"flag.chat.maxKeyword",type:"number"},{flag:"--search-limit <n>",description:"flag.chat.searchLimit",type:"number"},{flag:"--user-country <country>",description:"flag.chat.userCountry"},{flag:"--user-region <region>",description:"flag.chat.userRegion"},{flag:"--user-city <city>",description:"flag.chat.userCity"},{flag:"--stream",description:"flag.chat.stream",default:!0},{flag:"--no-stream",description:"flag.chat.noStream"},{flag:"--json",description:"flag.chat.json"},{flag:"--max-tokens <n>",description:"flag.chat.maxTokens",type:"number"},{flag:"--temperature <n>",description:"flag.chat.temperature",type:"number"}],examples:['mimo chat --message "What is MiMo?"','mimo chat -m "Hello" --model mimo-v2.5-pro --thinking','mimo chat -m "Latest news" --search','mimo chat -m "武汉明天天气" --search --user-city 武汉','mimo chat -m "Return JSON" --json --no-stream'],async run($,Y){let Z=Y,w=G$($),X=Z.message;if(!X)throw new L(z("chat.noMessage"),E.USAGE,"Usage: mimo chat --message <text>");if(X.trim().length===0)throw new L(z("chat.emptyMessage"),E.USAGE,"Provide a non-empty message with --message <text>");let W=1e5;if(X.length>W)throw new L(z("chat.messageTooLong",{len:String(X.length),max:String(W)}),E.USAGE,z("chat.messageTooLongHint"));let G=Z.model??"mimo-v2.5-pro",Q=Z.noStream?!1:Z.stream!==!1,V=[];if(Z.system)V.push({role:"system",content:Z.system});V.push({role:"user",content:X});let H={model:G,messages:V,stream:Q};if(Z.thinking)H.thinking={type:"enabled"};if(Z.search){let T={type:"web_search"};if(Z.forceSearch)T.force_search=!0;if(Z.maxKeyword!==void 0)T.max_keyword=Z.maxKeyword;if(Z.searchLimit!==void 0)T.limit=Z.searchLimit;if(Z.userCountry||Z.userRegion||Z.userCity)T.user_location={type:"approximate",...Z.userCountry&&{country:Z.userCountry},...Z.userRegion&&{region:Z.userRegion},...Z.userCity&&{city:Z.userCity}};H.tools=[T]}if(Z.json)H.response_format={type:"json_object"};if(Z.maxTokens!==void 0)H.max_completion_tokens=Z.maxTokens;if(Z.temperature!==void 0)H.temperature=Z.temperature;if($.dryRun){console.log(JSON.stringify({request:H},null,2));return}if(Q){let T="",K="",U=[],M="\x1B[2m",q="\x1B[90m",P="\x1B[0m",A=await w.chatCompletionStream(H);try{for await(let R of A){for(let b of R.choices){let v=n$(b.delta);if(v?.reasoning_content)K+=v.reasoning_content,process.stdout.write(`${M}${q}${v.reasoning_content}${P}`);if(v?.content)T+=v.content,process.stdout.write(v.content);if(v?.annotations)U.push(...v.annotations)}let F=i6(R);if(F&&$.verbose)process.stderr.write(`
183
213
 
184
214
  Tokens: prompt=${F.prompt_tokens}, completion=${F.completion_tokens}, total=${F.total_tokens}
185
- `)}}catch(R){throw new L(V("chat.streamFailed")+(R instanceof Error?R.message:String(R)),E.NETWORK,V("chat.streamFailedHint"))}finally{a$(A)}if(process.stdout.write(`
215
+ `)}}catch(R){throw new L(z("chat.streamFailed")+(R instanceof Error?R.message:String(R)),E.NETWORK,z("chat.streamFailedHint"))}finally{a$(A)}if(process.stdout.write(`
186
216
  `),U.length>0)process.stdout.write(`
187
217
  `+P2(U)+`
188
- `)}else{let T=await w.chatCompletion(H);for(let K of T.choices){let U=K.message,M="";if(U?.reasoning_content&&U?.content)M=C4(U.reasoning_content,U.content);else if(U?.content)M=U.content;else if(U?.reasoning_content)M=C4(U.reasoning_content,"");if(M)console.log(M);if(U?.annotations&&U.annotations.length>0)console.log(`
218
+ `)}else{let T=await w.chatCompletion(H);for(let K of T.choices){let U=K.message,M="";if(U?.reasoning_content&&U?.content)M=R4(U.reasoning_content,U.content);else if(U?.content)M=U.content;else if(U?.reasoning_content)M=R4(U.reasoning_content,"");if(M)console.log(M);if(U?.annotations&&U.annotations.length>0)console.log(`
189
219
  `+P2(U.annotations))}if(T.usage&&$.verbose)process.stderr.write(`
190
220
  Tokens: prompt=${T.usage.prompt_tokens}, completion=${T.usage.completion_tokens}, total=${T.usage.total_tokens}
191
- `)}}});var i6=j({name:"repl",description:"cmd.repl.desc",usage:"mimo repl [flags]",options:[{flag:"--model <model>",description:"flag.repl.model"},{flag:"--thinking",description:"flag.repl.thinking"},{flag:"--search",description:"flag.repl.search"},{flag:"-s, --system <text>",description:"flag.repl.system"}],examples:["mimo repl",'mimo repl --thinking --system "You are a helpful coding assistant"',"mimo repl --search"],async run($,Y){let Z=Y,w=G$($),X=Z.model??"mimo-v2.5-pro",W=[];if(Z.system)W.push({role:"system",content:Z.system});x9(V("repl.intro"));while(!0){let G=await c2({message:V("repl.you"),placeholder:V("repl.placeholder")});if(M1(G)){g3(V("repl.goodbye"));break}let Q=G.trim();if(!Q)continue;if(Q==="/exit"||Q==="/quit"){g3(V("repl.goodbye"));break}if(Q==="/clear"){if(W.length=0,Z.system)W.push({role:"system",content:Z.system});M9(V("repl.cleared"));continue}W.push({role:"user",content:Q});let z={model:X,messages:W,stream:!0};if(Z.thinking)z.thinking={type:"enabled"};if(Z.search)z.tools=[{type:"web_search"}];let H="",T="",K=[],U="\x1B[2m",M="\x1B[90m",q="\x1B[0m";process.stdout.write(`
192
- `);try{let A=await w.chatCompletionStream(z);try{for await(let R of A)for(let F of R.choices){let b=n$(F.delta);if(b?.reasoning_content)T+=b.reasoning_content,process.stdout.write(`${U}${M}${b.reasoning_content}${q}`);if(b?.content)H+=b.content,process.stdout.write(b.content);if(b?.annotations)K.push(...b.annotations)}}finally{a$(A)}}catch(A){process.stdout.write(`
221
+ `)}}});var t6=f({name:"repl",description:"cmd.repl.desc",usage:"mimo repl [flags]",options:[{flag:"--model <model>",description:"flag.repl.model"},{flag:"--thinking",description:"flag.repl.thinking"},{flag:"--search",description:"flag.repl.search"},{flag:"-s, --system <text>",description:"flag.repl.system"}],examples:["mimo repl",'mimo repl --thinking --system "You are a helpful coding assistant"',"mimo repl --search"],async run($,Y){let Z=Y,w=G$($),X=Z.model??"mimo-v2.5-pro",W=[];if(Z.system)W.push({role:"system",content:Z.system});O9(z("repl.intro"));while(!0){let G=await c2({message:z("repl.you"),placeholder:z("repl.placeholder")});if(M1(G)){m3(z("repl.goodbye"));break}let Q=G.trim();if(!Q)continue;if(Q==="/exit"||Q==="/quit"){m3(z("repl.goodbye"));break}if(Q==="/clear"){if(W.length=0,Z.system)W.push({role:"system",content:Z.system});q9(z("repl.cleared"));continue}W.push({role:"user",content:Q});let V={model:X,messages:W,stream:!0};if(Z.thinking)V.thinking={type:"enabled"};if(Z.search)V.tools=[{type:"web_search"}];let H="",T="",K=[],U="\x1B[2m",M="\x1B[90m",q="\x1B[0m";process.stdout.write(`
222
+ `);try{let A=await w.chatCompletionStream(V);try{for await(let R of A)for(let F of R.choices){let b=n$(F.delta);if(b?.reasoning_content)T+=b.reasoning_content,process.stdout.write(`${U}${M}${b.reasoning_content}${q}`);if(b?.content)H+=b.content,process.stdout.write(b.content);if(b?.annotations)K.push(...b.annotations)}}finally{a$(A)}}catch(A){process.stdout.write(`
193
223
 
194
224
  Error: ${A instanceof Error?A.message:String(A)}
195
225
  `),W.pop();continue}if(process.stdout.write(`
196
226
  `),K.length>0)process.stdout.write(`
197
227
  `+P2(K)+`
198
- `);let P={role:"assistant",content:H};if(T)P.reasoning_content=T;W.push(P)}}});import{readFile as qZ,stat as OZ}from"node:fs/promises";import{extname as EZ}from"node:path";var n6={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"};async function LZ($){let Y=EZ($).toLowerCase(),Z=n6[Y];if(!Z)throw Error(`Unsupported image format: "${Y}". Supported formats: ${Object.keys(n6).join(", ")}`);if((await OZ($)).size===0)throw Error(`Image file is empty: "${$}"`);let W=(await qZ($)).toString("base64");return`data:${Z};base64,${W}`}async function a6($){if($.startsWith("http://")||$.startsWith("https://"))return $;if($.startsWith("data:"))return $;return LZ($)}import{readFile as FZ,stat as kZ}from"node:fs/promises";import{extname as t6}from"node:path";var S4={".wav":"audio/wav",".mp3":"audio/mpeg"},r6=Object.keys(S4);async function s1($){let Y=t6($).toLowerCase(),Z=S4[Y];if(!Z)throw Error(`Unsupported audio format: "${Y}". Supported formats: ${r6.join(", ")}`);let X=(await FZ($)).toString("base64");return`data:${Z};base64,${X}`}async function O3($,Y=10){let Z=t6($).toLowerCase();if(!S4[Z])throw Error(`Unsupported audio format: "${Z}". Supported formats: ${r6.join(", ")}`);let w=await kZ($);if(w.size===0)throw Error(`Audio file is empty: "${$}"`);let X=w.size/1048576;if(X>Y)throw Error(`Audio file too large: ${X.toFixed(2)}MB exceeds the ${Y}MB limit.`)}import{readFile as CZ,stat as SZ}from"node:fs/promises";import{extname as RZ}from"node:path";var o6={".mp4":"video/mp4",".mov":"video/quicktime",".avi":"video/x-msvideo",".wmv":"video/x-ms-wmv"},PZ=Object.keys(o6),E3=50,s6=E3*0.75;async function e6($){let Y=RZ($).toLowerCase(),Z=o6[Y];if(!Z)throw Error(`Unsupported video format: "${Y}". Supported formats: ${PZ.join(", ")}`);let w=await SZ($);if(w.size===0)throw Error(`Video file is empty: "${$}"`);let X=w.size/1048576;if(X>s6)throw Error(V("vision.videoTooLarge",{size:X.toFixed(2),limit:String(E3)})+" "+V("vision.videoTooLargeHint",{max:s6.toFixed(1)}));let G=(await CZ($)).toString("base64"),Q=Buffer.byteLength(G,"utf-8")/1048576;if(Q>E3)throw Error(V("vision.videoBase64TooLarge",{size:Q.toFixed(2),limit:String(E3)})+" "+V("vision.videoBase64TooLargeHint"));return`data:${Z};base64,${G}`}function $5($){return $.startsWith("http://")||$.startsWith("https://")}var Y5=j({name:"vision",description:"cmd.vision.desc",usage:"mimo vision --image <path|url> --prompt <text> [flags]",options:[{flag:"--image <path|url>",description:"flag.vision.image"},{flag:"--audio <path|url>",description:"flag.vision.audio"},{flag:"--video <path|url>",description:"flag.vision.video"},{flag:"-p, --prompt <text>",description:"flag.vision.prompt",required:!0},{flag:"--model <model>",description:"flag.vision.model"},{flag:"--stream",description:"flag.vision.stream",default:!0},{flag:"--no-stream",description:"flag.vision.noStream"},{flag:"--fps <n>",description:"flag.vision.fps",type:"number"},{flag:"--media-resolution <value>",description:"flag.vision.mediaResolution"}],examples:['mimo vision --image photo.jpg -p "Describe this image"','mimo vision --image https://example.com/img.png -p "What is in this picture?"','mimo vision --audio recording.mp3 -p "Transcribe this audio"','mimo vision --video clip.mp4 -p "Summarize this video" --fps 1','mimo vision --image a.jpg --audio b.mp3 -p "Compare the image and audio"'],async run($,Y){let Z=Y,w=G$($);if(!Z.image&&!Z.audio&&!Z.video)throw new L(V("vision.noMedia"),E.USAGE,"mimo vision --image <路径|URL> --prompt <文本>");if(!Z.prompt)throw new L(V("vision.noPrompt"),E.USAGE,"mimo vision --image <路径|URL> -p <文本>");let X=Z.model??"mimo-v2.5",W=Z.noStream?!1:Z.stream!==!1,G=[];if(Z.image){let H=await a6(Z.image);G.push({type:"image_url",image_url:{url:H}})}if(Z.audio)if($5(Z.audio))G.push({type:"input_audio",input_audio:{data:Z.audio}});else{let H=await s1(Z.audio);G.push({type:"input_audio",input_audio:{data:H}})}if(Z.video){let H;if($5(Z.video))H=Z.video;else H=await e6(Z.video);let T={type:"video_url",video_url:{url:H}};if(Z.fps!==void 0)T.fps=Z.fps;if(Z.mediaResolution)T.media_resolution=Z.mediaResolution;G.push(T)}G.push({type:"text",text:Z.prompt});let z={model:X,messages:[{role:"user",content:G}],stream:W};if($.dryRun){console.log(JSON.stringify({request:z},null,2));return}if(W){let H="",T="",K="\x1B[2m",U="\x1B[90m",M="\x1B[0m",q=await w.chatCompletionStream(z);try{for await(let P of q)for(let A of P.choices){let R=n$(A.delta);if(R?.reasoning_content)T+=R.reasoning_content,process.stdout.write(`${K}${U}${R.reasoning_content}${M}`);if(R?.content)H+=R.content,process.stdout.write(R.content)}}catch(P){throw new L(V("vision.requestFailed")+(P instanceof Error?P.message:String(P)),E.NETWORK,V("vision.requestFailedHint"))}finally{a$(q)}process.stdout.write(`
199
- `)}else{let H=await w.chatCompletion(z);for(let T of H.choices){let K=T.message;if(K?.reasoning_content&&K?.content)console.log(`[Thinking] ${K.reasoning_content}
228
+ `);let P={role:"assistant",content:H};if(T)P.reasoning_content=T;W.push(P)}}});import{readFile as _Z,stat as AZ}from"node:fs/promises";import{extname as fZ}from"node:path";var r6={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"};async function jZ($){let Y=fZ($).toLowerCase(),Z=r6[Y];if(!Z)throw Error(`Unsupported image format: "${Y}". Supported formats: ${Object.keys(r6).join(", ")}`);if((await AZ($)).size===0)throw Error(`Image file is empty: "${$}"`);let W=(await _Z($)).toString("base64");return`data:${Z};base64,${W}`}async function s6($){if($.startsWith("http://")||$.startsWith("https://"))return $;if($.startsWith("data:"))return $;return jZ($)}import{readFile as bZ,stat as vZ}from"node:fs/promises";import{extname as o6}from"node:path";var P4={".wav":"audio/wav",".mp3":"audio/mpeg"},e6=Object.keys(P4);async function s1($){let Y=o6($).toLowerCase(),Z=P4[Y];if(!Z)throw Error(`Unsupported audio format: "${Y}". Supported formats: ${e6.join(", ")}`);let X=(await bZ($)).toString("base64");return`data:${Z};base64,${X}`}async function E3($,Y=10){let Z=o6($).toLowerCase();if(!P4[Z])throw Error(`Unsupported audio format: "${Z}". Supported formats: ${e6.join(", ")}`);let w=await vZ($);if(w.size===0)throw Error(`Audio file is empty: "${$}"`);let X=w.size/1048576;if(X>Y)throw Error(`Audio file too large: ${X.toFixed(2)}MB exceeds the ${Y}MB limit.`)}import{readFile as yZ,stat as IZ}from"node:fs/promises";import{extname as DZ}from"node:path";var Y5={".mp4":"video/mp4",".mov":"video/quicktime",".avi":"video/x-msvideo",".wmv":"video/x-ms-wmv"},hZ=Object.keys(Y5),L3=50,$5=L3*0.75;async function Z5($){let Y=DZ($).toLowerCase(),Z=Y5[Y];if(!Z)throw Error(`Unsupported video format: "${Y}". Supported formats: ${hZ.join(", ")}`);let w=await IZ($);if(w.size===0)throw Error(`Video file is empty: "${$}"`);let X=w.size/1048576;if(X>$5)throw Error(z("vision.videoTooLarge",{size:X.toFixed(2),limit:String(L3)})+" "+z("vision.videoTooLargeHint",{max:$5.toFixed(1)}));let G=(await yZ($)).toString("base64"),Q=Buffer.byteLength(G,"utf-8")/1048576;if(Q>L3)throw Error(z("vision.videoBase64TooLarge",{size:Q.toFixed(2),limit:String(L3)})+" "+z("vision.videoBase64TooLargeHint"));return`data:${Z};base64,${G}`}function w5($){return $.startsWith("http://")||$.startsWith("https://")}var G5=f({name:"vision",description:"cmd.vision.desc",usage:"mimo vision --image <path|url> --prompt <text> [flags]",options:[{flag:"--image <path|url>",description:"flag.vision.image"},{flag:"--audio <path|url>",description:"flag.vision.audio"},{flag:"--video <path|url>",description:"flag.vision.video"},{flag:"-p, --prompt <text>",description:"flag.vision.prompt",required:!0},{flag:"--model <model>",description:"flag.vision.model"},{flag:"--stream",description:"flag.vision.stream",default:!0},{flag:"--no-stream",description:"flag.vision.noStream"},{flag:"--fps <n>",description:"flag.vision.fps",type:"number"},{flag:"--media-resolution <value>",description:"flag.vision.mediaResolution"}],examples:['mimo vision --image photo.jpg -p "Describe this image"','mimo vision --image https://example.com/img.png -p "What is in this picture?"','mimo vision --audio recording.mp3 -p "Transcribe this audio"','mimo vision --video clip.mp4 -p "Summarize this video" --fps 1','mimo vision --image a.jpg --audio b.mp3 -p "Compare the image and audio"'],async run($,Y){let Z=Y,w=G$($);if(!Z.image&&!Z.audio&&!Z.video)throw new L(z("vision.noMedia"),E.USAGE,"mimo vision --image <路径|URL> --prompt <文本>");if(!Z.prompt)throw new L(z("vision.noPrompt"),E.USAGE,"mimo vision --image <路径|URL> -p <文本>");let X=Z.model??"mimo-v2.5",W=Z.noStream?!1:Z.stream!==!1,G=[];if(Z.image){let H=await s6(Z.image);G.push({type:"image_url",image_url:{url:H}})}if(Z.audio)if(w5(Z.audio))G.push({type:"input_audio",input_audio:{data:Z.audio}});else{let H=await s1(Z.audio);G.push({type:"input_audio",input_audio:{data:H}})}if(Z.video){let H;if(w5(Z.video))H=Z.video;else H=await Z5(Z.video);let T={type:"video_url",video_url:{url:H}};if(Z.fps!==void 0)T.fps=Z.fps;if(Z.mediaResolution)T.media_resolution=Z.mediaResolution;G.push(T)}G.push({type:"text",text:Z.prompt});let V={model:X,messages:[{role:"user",content:G}],stream:W};if($.dryRun){console.log(JSON.stringify({request:V},null,2));return}if(W){let H="",T="",K="\x1B[2m",U="\x1B[90m",M="\x1B[0m",q=await w.chatCompletionStream(V);try{for await(let P of q)for(let A of P.choices){let R=n$(A.delta);if(R?.reasoning_content)T+=R.reasoning_content,process.stdout.write(`${K}${U}${R.reasoning_content}${M}`);if(R?.content)H+=R.content,process.stdout.write(R.content)}}catch(P){throw new L(z("vision.requestFailed")+(P instanceof Error?P.message:String(P)),E.NETWORK,z("vision.requestFailedHint"))}finally{a$(q)}process.stdout.write(`
229
+ `)}else{let H=await w.chatCompletion(V);for(let T of H.choices){let K=T.message;if(K?.reasoning_content&&K?.content)console.log(`[Thinking] ${K.reasoning_content}
200
230
 
201
- ${K.content}`);else if(K?.content)console.log(K.content);else if(K?.reasoning_content)console.log(`[Thinking] ${K.reasoning_content}`)}}}});var Z5=j({name:"asr",description:"cmd.asr.desc",usage:"mimo asr <audio-file> [flags]",options:[{flag:"--language <lang>",description:"flag.asr.language"},{flag:"--stream",description:"flag.asr.stream"},{flag:"--file <path>",description:"flag.asr.file"}],examples:["mimo asr recording.wav","mimo asr audio.mp3 --language zh","mimo asr --file recording.wav --language en"],async run($,Y){let Z=Y,w=G$($),W=Y._positional?.[0]??Z.file;if(!W)throw new L(V("asr.noFile"),E.USAGE,"Usage: mimo asr <audio-file> [flags]");await O3(W,10);let G=await s1(W),Q=Z.language??"auto",T={model:"mimo-v2.5-asr",messages:[{role:"user",content:[{type:"input_audio",input_audio:{data:G}}]}],stream:Z.stream??!1,asr_options:{language:Q}};if($.dryRun){console.log(JSON.stringify({request:{...T,messages:[{role:"user",content:"[audio data]"}]}},null,2));return}if(Z.stream){let K=await w.chatCompletionStream(T);try{for await(let U of K)for(let M of U.choices){let q=n$(M.delta);if(q?.content)process.stdout.write(q.content)}}catch(U){throw new L(V("asr.streamFailed")+(U instanceof Error?U.message:String(U)),E.NETWORK,V("asr.checkHint"))}finally{a$(K)}process.stdout.write(`
202
- `)}else{let K;try{K=await w.chatCompletion(T)}catch(U){throw new L(V("asr.requestFailed")+(U instanceof Error?U.message:String(U)),E.NETWORK,V("asr.checkHint"))}for(let U of K.choices){let M=U.message?.content;if(M)console.log(typeof M==="string"?M:JSON.stringify(M))}}}});import{writeFileSync as _Z,mkdirSync as AZ,existsSync as fZ}from"node:fs";import{dirname as jZ,resolve as bZ}from"node:path";function o1($){let Y=q9();return{start(){Y.start($)},stop(Z){Y.stop(Z??"",0)},update(Z){Y.message(Z)}}}var w5=["mimo_default","冰糖","茉莉","苏打","白桦","Mia","Chloe","Milo","Dean"];function _2($,Y){let Z=new Date().toISOString().slice(0,19).replace(/[T:]/g,"-");return`${$}_${Z}.${Y}`}function A2($,Y){let Z=bZ(Y),w=jZ(Z);if(!fZ(w))AZ(w,{recursive:!0});let X=Buffer.from($,"base64");return _Z(Z,X),Z}var R4=j({name:"tts synthesize",description:"cmd.ttsSynth.desc",apiDocs:"/docs/api-reference/tts",usage:"mimo tts synthesize --text <text> [flags]",options:[{flag:"-t, --text <text>",description:"flag.tts.text",required:!0},{flag:"--voice <id>",description:"flag.tts.voice",default:"mimo_default"},{flag:"--style <desc>",description:"flag.tts.style"},{flag:"--format <fmt>",description:"flag.tts.format",default:"wav"},{flag:"-o, --out <path>",description:"flag.tts.out"}],examples:['mimo tts synthesize --text "你好,世界!"','mimo tts synthesize -t "Hello world" --voice Mia --format mp3','mimo tts synthesize -t "温柔地说" --style "温柔、缓慢" --voice 茉莉'],async run($,Y){let Z=Y,w=Z.text;if(!w)throw new L(V("tts.noText"),E.USAGE,'mimo tts synthesize --text "你好,世界!"');if(w.trim().length===0)throw new L(V("tts.emptyText"),E.USAGE,"Provide non-empty text to synthesize.");let X=5000;if(w.length>X)throw new L(V("tts.textTooLong",{len:String(w.length),max:String(X)}),E.USAGE,V("tts.textTooLongHint"));let W=Z.voice??"mimo_default";if(!w5.includes(W))throw new L(V("tts.invalidVoice")+'"'+W+'". '+w5.join(", "),E.USAGE);let G=Z.format??"wav",Q=Z.out??_2("tts_output",G),z=[];if(Z.style)z.push({role:"user",content:Z.style}),z.push({role:"assistant",content:w});else z.push({role:"assistant",content:w});let H={model:"mimo-v2.5-tts",messages:z,stream:!1,audio:{format:G,voice:W}};if(U1($,H))return;let T=o1(V("spinner.synthesizing"));T.start();try{let M=(await G$($).chatCompletion(H)).choices?.[0]?.message?.audio;if(!M?.data)throw new L(V("tts.noAudioData"),E.GENERAL);let q=A2(M.data,Q);T.stop("");let P=X$($.output);if(!$.quiet)console.log(W$({output:q,voice:W,format:G},P));else console.log(q)}catch(K){throw T.stop(""),K}}});var G5=j({name:"tts clone",description:"cmd.ttsClone.desc",apiDocs:"/docs/api-reference/tts-voiceclone",usage:"mimo tts clone --sample <audio> --text <text> [flags]",options:[{flag:"--sample <path>",description:"flag.tts.sample",required:!0},{flag:"-t, --text <text>",description:"flag.tts.text",required:!0},{flag:"--format <fmt>",description:"flag.tts.format",default:"wav"},{flag:"-o, --out <path>",description:"flag.tts.out"}],examples:['mimo tts clone --sample voice.mp3 --text "你好,世界!"','mimo tts clone --sample my_voice.wav -t "Hello world" --format mp3'],async run($,Y){let Z=Y,w=Z.sample,X=Z.text;if(!w)throw new L(V("tts.noSample"),E.USAGE,'mimo tts clone --sample voice.mp3 --text "你好,世界!"');if(!X)throw new L(V("tts.noText"),E.USAGE,'mimo tts clone --sample voice.mp3 --text "你好,世界!"');await O3(w,10);let W=Z.format??"wav",G=Z.out??_2("clone_output",W),Q=o1(V("spinner.readingSample"));Q.start();try{let z=await s1(w);Q.update(V("spinner.cloning"));let T={model:"mimo-v2.5-tts-voiceclone",messages:[{role:"user",content:""},{role:"assistant",content:X}],stream:!1,audio:{format:W,voice:z}};if(U1($,T)){Q.stop("");return}let M=(await G$($).chatCompletion(T)).choices?.[0]?.message?.audio;if(!M?.data)throw new L(V("tts.noAudioData"),E.GENERAL);let q=A2(M.data,G);Q.stop("");let P=X$($.output);if(!$.quiet)console.log(W$({output:q,format:W},P));else console.log(q)}catch(z){throw Q.stop(""),z}}});var X5=j({name:"tts design",description:"cmd.ttsDesign.desc",apiDocs:"/docs/api-reference/tts-voicedesign",usage:"mimo tts design --prompt <description> [flags]",options:[{flag:"-p, --prompt <desc>",description:"flag.ttsDesign.prompt",required:!0},{flag:"-t, --text <text>",description:"flag.ttsDesign.text"},{flag:"--optimize-text",description:"flag.ttsDesign.optimizeText"},{flag:"--format <fmt>",description:"flag.tts.format",default:"wav"},{flag:"-o, --out <path>",description:"flag.tts.out"}],examples:['mimo tts design --prompt "温柔的女声,语速较慢" --text "你好,世界!"','mimo tts design -p "低沉男声,播音腔" --optimize-text','mimo tts design --prompt "活泼的少女音" -t "今天天气真好" --format mp3'],async run($,Y){let Z=Y,w=Z.prompt;if(!w)throw new L(V("tts.noPrompt"),E.USAGE,'mimo tts design --prompt "温柔的女声" --text "你好"');let X=Z.text,W=Z.optimizeText??!1;if(!X&&!W)throw new L(V("tts.noTextOrOptimize"),E.USAGE,'mimo tts design --prompt "温柔的女声" --text "你好" 或 --optimize-text');let G=Z.format??"wav",Q=Z.out??_2("design_output",G),z=[{role:"user",content:w}];if(X)z.push({role:"assistant",content:X});let H={format:G};if(W&&!X)H.optimize_text_preview=!0;let T={model:"mimo-v2.5-tts-voicedesign",messages:z,stream:!1,audio:H};if(U1($,T))return;let K=o1(V("spinner.designing"));K.start();try{let q=(await G$($).chatCompletion(T)).choices?.[0]?.message?.audio;if(!q?.data)throw new L(V("tts.noAudioData"),E.GENERAL);let P=A2(q.data,Q);K.stop("");let A=X$($.output);if(!$.quiet)console.log(W$({output:P,format:G},A));else console.log(P)}catch(U){throw K.stop(""),U}}});var W5=[{name:"MiMo默认",voiceId:"mimo_default",language:"中/英",gender:"-"},{name:"冰糖",voiceId:"冰糖",language:"中文",gender:"女"},{name:"茉莉",voiceId:"茉莉",language:"中文",gender:"女"},{name:"苏打",voiceId:"苏打",language:"中文",gender:"男"},{name:"白桦",voiceId:"白桦",language:"中文",gender:"男"},{name:"Mia",voiceId:"Mia",language:"英文",gender:"女"},{name:"Chloe",voiceId:"Chloe",language:"英文",gender:"女"},{name:"Milo",voiceId:"Milo",language:"英文",gender:"男"},{name:"Dean",voiceId:"Dean",language:"英文",gender:"男"}],J5=j({name:"tts voices",description:"cmd.ttsVoices.desc",usage:"mimo tts voices",options:[],examples:["mimo tts voices","mimo tts voices --output json"],async run($,Y){let Z=X$($.output);if(Z==="json"){console.log(W$(W5,Z));return}let w=["name","voiceId","language","gender"],X=W5.map((W)=>[W.name,W.voiceId,W.language,W.gender]);console.log(k3(w,X))}});h.register("chat",p6);h.register("repl",i6);h.register("vision",Y5);h.register("asr",Z5);h.register("tts synthesize",R4);h.register("tts generate",R4);h.register("tts clone",G5);h.register("tts design",X5);h.register("tts voices",J5);h.register("auth login",k9);h.register("auth status",C9);h.register("auth logout",S9);h.register("config show",R9);h.register("config set",_9);h.register("update",A9);h.register("help",f9);h.register("language",j9);var vZ=[["auth","login"],["auth","status"],["auth","logout"],["config","show"],["config","set"],["update"],["help"],["language"]];process.on("SIGINT",()=>{process.stderr.write(V("main.interrupted")+`
203
- `),process.exit(130)});process.stdout.on("error",($)=>{if($.code==="EPIPE")process.exit(0);else throw $});process.on("uncaughtException",($)=>{x$($)});process.on("unhandledRejection",($)=>{x$($)});async function yZ(){let $;try{$=process.argv.slice(2)}catch(Q){process.stderr.write(V("main.fatalArgv")),process.exit(1)}if($.includes("--version")||$.includes("-v"))console.log(`mimo ${q1}`),process.exit(0);let Y=I4($,T1);if($.includes("--help")||$.includes("-h")){let Q=y2({});j2(Q.language),h.printHelp(Y),process.exit(0)}if(Y.length===0){let Q=y2({});if(j2(Q.language),h.printHelp([]),!(Q.apiKey||Q.fileApiKey||process.env.MIMO_API_KEY))process.stderr.write(V("main.notLoggedIn")+`
204
- `),process.stderr.write(V("main.loginHint1")+`
205
- `),process.stderr.write(V("main.loginHint2")+`
231
+ ${K.content}`);else if(K?.content)console.log(K.content);else if(K?.reasoning_content)console.log(`[Thinking] ${K.reasoning_content}`)}}}});var X5=f({name:"asr",description:"cmd.asr.desc",usage:"mimo asr <audio-file> [flags]",options:[{flag:"--language <lang>",description:"flag.asr.language"},{flag:"--stream",description:"flag.asr.stream"},{flag:"--file <path>",description:"flag.asr.file"}],examples:["mimo asr recording.wav","mimo asr audio.mp3 --language zh","mimo asr --file recording.wav --language en"],async run($,Y){let Z=Y,w=G$($),W=Y._positional?.[0]??Z.file;if(!W)throw new L(z("asr.noFile"),E.USAGE,"Usage: mimo asr <audio-file> [flags]");await E3(W,10);let G=await s1(W),Q=Z.language??"auto",T={model:"mimo-v2.5-asr",messages:[{role:"user",content:[{type:"input_audio",input_audio:{data:G}}]}],stream:Z.stream??!1,asr_options:{language:Q}};if($.dryRun){console.log(JSON.stringify({request:{...T,messages:[{role:"user",content:"[audio data]"}]}},null,2));return}if(Z.stream){let K=await w.chatCompletionStream(T);try{for await(let U of K)for(let M of U.choices){let q=n$(M.delta);if(q?.content)process.stdout.write(q.content)}}catch(U){throw new L(z("asr.streamFailed")+(U instanceof Error?U.message:String(U)),E.NETWORK,z("asr.checkHint"))}finally{a$(K)}process.stdout.write(`
232
+ `)}else{let K;try{K=await w.chatCompletion(T)}catch(U){throw new L(z("asr.requestFailed")+(U instanceof Error?U.message:String(U)),E.NETWORK,z("asr.checkHint"))}for(let U of K.choices){let M=U.message?.content;if(M)console.log(typeof M==="string"?M:JSON.stringify(M))}}}});import{writeFileSync as gZ,mkdirSync as mZ,existsSync as cZ}from"node:fs";import{dirname as dZ,resolve as uZ}from"node:path";function o1($){let Y=E9();return{start(){Y.start($)},stop(Z){Y.stop(Z??"",0)},update(Z){Y.message(Z)}}}var W5=["mimo_default","冰糖","茉莉","苏打","白桦","Mia","Chloe","Milo","Dean"];function _2($,Y){let Z=new Date().toISOString().slice(0,19).replace(/[T:]/g,"-");return`${$}_${Z}.${Y}`}function A2($,Y){let Z=uZ(Y),w=dZ(Z);if(!cZ(w))mZ(w,{recursive:!0});let X=Buffer.from($,"base64");return gZ(Z,X),Z}var _4=f({name:"tts synthesize",description:"cmd.ttsSynth.desc",apiDocs:"/docs/api-reference/tts",usage:"mimo tts synthesize --text <text> [flags]",options:[{flag:"-t, --text <text>",description:"flag.tts.text",required:!0},{flag:"--voice <id>",description:"flag.tts.voice",default:"mimo_default"},{flag:"--style <desc>",description:"flag.tts.style"},{flag:"--format <fmt>",description:"flag.tts.format",default:"wav"},{flag:"-o, --out <path>",description:"flag.tts.out"}],examples:['mimo tts synthesize --text "你好,世界!"','mimo tts synthesize -t "Hello world" --voice Mia --format mp3','mimo tts synthesize -t "温柔地说" --style "温柔、缓慢" --voice 茉莉'],async run($,Y){let Z=Y,w=Z.text;if(!w)throw new L(z("tts.noText"),E.USAGE,'mimo tts synthesize --text "你好,世界!"');if(w.trim().length===0)throw new L(z("tts.emptyText"),E.USAGE,"Provide non-empty text to synthesize.");let X=5000;if(w.length>X)throw new L(z("tts.textTooLong",{len:String(w.length),max:String(X)}),E.USAGE,z("tts.textTooLongHint"));let W=Z.voice??"mimo_default";if(!W5.includes(W))throw new L(z("tts.invalidVoice")+'"'+W+'". '+W5.join(", "),E.USAGE);let G=Z.format??"wav",Q=Z.out??_2("tts_output",G),V=[];if(Z.style)V.push({role:"user",content:Z.style}),V.push({role:"assistant",content:w});else V.push({role:"assistant",content:w});let H={model:"mimo-v2.5-tts",messages:V,stream:!1,audio:{format:G,voice:W}};if(U1($,H))return;let T=o1(z("spinner.synthesizing"));T.start();try{let M=(await G$($).chatCompletion(H)).choices?.[0]?.message?.audio;if(!M?.data)throw new L(z("tts.noAudioData"),E.GENERAL);let q=A2(M.data,Q);T.stop("");let P=X$($.output);if(!$.quiet)console.log(W$({output:q,voice:W,format:G},P));else console.log(q)}catch(K){throw T.stop(""),K}}});var J5=f({name:"tts clone",description:"cmd.ttsClone.desc",apiDocs:"/docs/api-reference/tts-voiceclone",usage:"mimo tts clone --sample <audio> --text <text> [flags]",options:[{flag:"--sample <path>",description:"flag.tts.sample",required:!0},{flag:"-t, --text <text>",description:"flag.tts.text",required:!0},{flag:"--format <fmt>",description:"flag.tts.format",default:"wav"},{flag:"-o, --out <path>",description:"flag.tts.out"}],examples:['mimo tts clone --sample voice.mp3 --text "你好,世界!"','mimo tts clone --sample my_voice.wav -t "Hello world" --format mp3'],async run($,Y){let Z=Y,w=Z.sample,X=Z.text;if(!w)throw new L(z("tts.noSample"),E.USAGE,'mimo tts clone --sample voice.mp3 --text "你好,世界!"');if(!X)throw new L(z("tts.noText"),E.USAGE,'mimo tts clone --sample voice.mp3 --text "你好,世界!"');await E3(w,10);let W=Z.format??"wav",G=Z.out??_2("clone_output",W),Q=o1(z("spinner.readingSample"));Q.start();try{let V=await s1(w);Q.update(z("spinner.cloning"));let T={model:"mimo-v2.5-tts-voiceclone",messages:[{role:"user",content:""},{role:"assistant",content:X}],stream:!1,audio:{format:W,voice:V}};if(U1($,T)){Q.stop("");return}let M=(await G$($).chatCompletion(T)).choices?.[0]?.message?.audio;if(!M?.data)throw new L(z("tts.noAudioData"),E.GENERAL);let q=A2(M.data,G);Q.stop("");let P=X$($.output);if(!$.quiet)console.log(W$({output:q,format:W},P));else console.log(q)}catch(V){throw Q.stop(""),V}}});var Q5=f({name:"tts design",description:"cmd.ttsDesign.desc",apiDocs:"/docs/api-reference/tts-voicedesign",usage:"mimo tts design --prompt <description> [flags]",options:[{flag:"-p, --prompt <desc>",description:"flag.ttsDesign.prompt",required:!0},{flag:"-t, --text <text>",description:"flag.ttsDesign.text"},{flag:"--optimize-text",description:"flag.ttsDesign.optimizeText"},{flag:"--format <fmt>",description:"flag.tts.format",default:"wav"},{flag:"-o, --out <path>",description:"flag.tts.out"}],examples:['mimo tts design --prompt "温柔的女声,语速较慢" --text "你好,世界!"','mimo tts design -p "低沉男声,播音腔" --optimize-text','mimo tts design --prompt "活泼的少女音" -t "今天天气真好" --format mp3'],async run($,Y){let Z=Y,w=Z.prompt;if(!w)throw new L(z("tts.noPrompt"),E.USAGE,'mimo tts design --prompt "温柔的女声" --text "你好"');let X=Z.text,W=Z.optimizeText??!1;if(!X&&!W)throw new L(z("tts.noTextOrOptimize"),E.USAGE,'mimo tts design --prompt "温柔的女声" --text "你好" 或 --optimize-text');let G=Z.format??"wav",Q=Z.out??_2("design_output",G),V=[{role:"user",content:w}];if(X)V.push({role:"assistant",content:X});let H={format:G};if(W&&!X)H.optimize_text_preview=!0;let T={model:"mimo-v2.5-tts-voicedesign",messages:V,stream:!1,audio:H};if(U1($,T))return;let K=o1(z("spinner.designing"));K.start();try{let q=(await G$($).chatCompletion(T)).choices?.[0]?.message?.audio;if(!q?.data)throw new L(z("tts.noAudioData"),E.GENERAL);let P=A2(q.data,Q);K.stop("");let A=X$($.output);if(!$.quiet)console.log(W$({output:P,format:G},A));else console.log(P)}catch(U){throw K.stop(""),U}}});var z5=[{name:"MiMo默认",voiceId:"mimo_default",language:"中/英",gender:"-"},{name:"冰糖",voiceId:"冰糖",language:"中文",gender:"女"},{name:"茉莉",voiceId:"茉莉",language:"中文",gender:"女"},{name:"苏打",voiceId:"苏打",language:"中文",gender:"男"},{name:"白桦",voiceId:"白桦",language:"中文",gender:"男"},{name:"Mia",voiceId:"Mia",language:"英文",gender:"女"},{name:"Chloe",voiceId:"Chloe",language:"英文",gender:"女"},{name:"Milo",voiceId:"Milo",language:"英文",gender:"男"},{name:"Dean",voiceId:"Dean",language:"英文",gender:"男"}],N5=f({name:"tts voices",description:"cmd.ttsVoices.desc",usage:"mimo tts voices",options:[],examples:["mimo tts voices","mimo tts voices --output json"],async run($,Y){let Z=X$($.output);if(Z==="json"){console.log(W$(z5,Z));return}let w=["name","voiceId","language","gender"],X=z5.map((W)=>[W.name,W.voiceId,W.language,W.gender]);console.log(C3(w,X))}});D.register("chat",a6);D.register("repl",t6);D.register("vision",G5);D.register("asr",X5);D.register("tts synthesize",_4);D.register("tts generate",_4);D.register("tts clone",J5);D.register("tts design",Q5);D.register("tts voices",N5);D.register("auth login",S9);D.register("auth status",R9);D.register("auth logout",P9);D.register("config show",_9);D.register("config set",f9);D.register("update",j9);D.register("help",b9);D.register("language",v9);D.register("uninstall",y9);var lZ=[["auth","login"],["auth","status"],["auth","logout"],["config","show"],["config","set"],["update"],["help"],["language"],["uninstall"]];process.on("SIGINT",()=>{process.stderr.write(z("main.interrupted")+`
233
+ `),process.exit(130)});process.stdout.on("error",($)=>{if($.code==="EPIPE")process.exit(0);else throw $});process.on("uncaughtException",($)=>{x$($)});process.on("unhandledRejection",($)=>{x$($)});async function pZ(){let $;try{$=process.argv.slice(2)}catch(Q){process.stderr.write(z("main.fatalArgv")),process.exit(1)}if($.includes("--version")||$.includes("-v"))console.log(`mimo ${q1}`),process.exit(0);let Y=h4($,T1);if($.includes("--help")||$.includes("-h")){let Q=y2({});j2(Q.language),D.printHelp(Y),process.exit(0)}if(Y.length===0){let Q=y2({});if(j2(Q.language),D.printHelp([]),!(Q.apiKey||Q.fileApiKey||Q.fileSkApiKey||process.env.MIMO_API_KEY))process.stderr.write(z("main.notLoggedIn")+`
234
+ `),process.stderr.write(z("main.loginHint1")+`
235
+ `),process.stderr.write(z("main.loginHint2")+`
206
236
 
207
- `);process.exit(0)}let{command:Z,extra:w}=h.resolve(Y),X=D4($,[...T1,...Z.options??[]]);if(w.length>0)X._positional=w;let W;try{W=y2(X)}catch(Q){x$(Q),process.exit(1)}if(j2(W.language),!vZ.some((Q)=>Q.every((z,H)=>Y[H]===z)))await E9(W);await Z.execute(W,X)}if(j4.main==j4.module)yZ().catch(x$);export{yZ as main};
237
+ `);process.exit(0)}let{command:Z,extra:w}=D.resolve(Y),X=g4($,[...T1,...Z.options??[]]);if(w.length>0)X._positional=w;let W;try{W=y2(X)}catch(Q){x$(Q),process.exit(1)}if(j2(W.language),!lZ.some((Q)=>Q.every((V,H)=>Y[H]===V)))await F9(W);await Z.execute(W,X)}if(v4.main==v4.module)pZ().catch(x$);export{pZ as main};
208
238
 
209
- //# debugId=1094ACFFDD3F860D64756E2164756E21
239
+ //# debugId=65B734CA6FF42AD564756E2164756E21
210
240
  //# sourceMappingURL=mimo.mjs.map