@humain/terminal 0.0.7 → 0.0.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/CHANGELOG.md +10 -0
- package/README.md +7 -6
- package/dist/bundle/chunks/chunk-74NVHVNZ.js +16 -0
- package/dist/bundle/chunks/{chunk-HNVPY4LZ.js → chunk-MMFBCF6F.js} +93 -102
- package/dist/bundle/chunks/{chunk-M2GYSCCG.js → chunk-PSKDLDLZ.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-XT7NQJ2E.js → google-generative-ai-FF7M7XHT.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-IDQ6Z53W.js → google-vertex-YMUBFRBA.js} +1 -1
- package/dist/bundle/chunks/https-proxy-agent-562J2I52.js +2 -0
- package/dist/bundle/chunks/{mistral-conversations-HHDZ4FHR.js → mistral-conversations-O4M7IQML.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-6QBYTBXY.js → openai-completions-L4AHDQ5D.js} +1 -1
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/startup-ui.d.ts.map +1 -1
- package/dist/cli/startup-ui.js +2 -1
- package/dist/cli/startup-ui.js.map +1 -1
- package/dist/core/agent-session.d.ts +12 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +77 -9
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +4 -3
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +5 -0
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +19 -5
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +5 -0
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +44 -1
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +18 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +4 -2
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +8 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +17 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/extensions/llama/client.d.ts +6 -0
- package/dist/extensions/llama/client.d.ts.map +1 -1
- package/dist/extensions/llama/client.js +7 -0
- package/dist/extensions/llama/client.js.map +1 -1
- package/dist/extensions/llama/provider.d.ts +3 -1
- package/dist/extensions/llama/provider.d.ts.map +1 -1
- package/dist/extensions/llama/provider.js +27 -6
- package/dist/extensions/llama/provider.js.map +1 -1
- package/dist/humain/mcp-adapter/vendor/package.json +2 -2
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +2 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +2 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +10 -0
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +4 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +48 -24
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +7 -0
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +7 -0
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +3 -0
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +12 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +6 -4
- package/dist/utils/shell.js.map +1 -1
- package/docs/compaction.md +2 -0
- package/docs/custom-provider.md +7 -7
- package/docs/environment-variables.md +4 -1
- package/docs/extensions.md +18 -0
- package/docs/keybindings.md +1 -1
- package/docs/quickstart.md +1 -1
- package/docs/rpc.md +23 -0
- package/docs/settings.md +12 -4
- package/docs/terminal-setup.md +12 -0
- package/docs/usage.md +4 -3
- package/examples/extensions/custom-provider-anthropic/package-lock.json +6 -6
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +23 -23
- package/package.json +7 -7
- package/dist/bundle/chunks/chunk-3D3G2X5U.js +0 -6
- package/dist/bundle/chunks/dist-7DSXV2TY.js +0 -9
|
@@ -4,7 +4,7 @@ import{retryProviderRequest}from"./chunk-XNGRGP62.js";import{getJsonSchemaToolPa
|
|
|
4
4
|
Content-Type: ${partContentType}\r
|
|
5
5
|
\r
|
|
6
6
|
`,typeof currentPart.content=="string"?yield currentPart.content:yield*currentPart.content,yield`\r
|
|
7
|
-
`}yield finale}static#proxyAgent;static#fetch;static async#getProxyAgent(){return this.#proxyAgent||=(await import("./dist-7DSXV2TY.js")).HttpsProxyAgent,this.#proxyAgent}static async#getFetch(){let hasWindow=typeof window<"u"&&!!window;return this.#fetch||=hasWindow?window.fetch:(await import("./src-QKGKDFSU.js")).default,this.#fetch}static mergeHeaders(base,...append){base=base instanceof Headers?base:new Headers(base);for(let headers of append)(headers instanceof Headers?headers:new Headers(headers)).forEach((value,key)=>{key==="set-cookie"?base.append(key,value):base.set(key,value)});return base}};exports.Gaxios=Gaxios;_a2=Gaxios}});var require_src=__commonJS({"node_modules/gaxios/build/cjs/src/index.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p)&&__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});exports.instance=exports.Gaxios=exports.GaxiosError=void 0;exports.request=request;var gaxios_js_1=require_gaxios();Object.defineProperty(exports,"Gaxios",{enumerable:!0,get:function(){return gaxios_js_1.Gaxios}});var common_js_1=require_common();Object.defineProperty(exports,"GaxiosError",{enumerable:!0,get:function(){return common_js_1.GaxiosError}});__exportStar(require_interceptor(),exports);exports.instance=new gaxios_js_1.Gaxios;async function request(opts){return exports.instance.request(opts)}}});var require_bignumber=__commonJS({"node_modules/bignumber.js/bignumber.js"(exports,module){(function(globalObject){"use strict";var BigNumber,isNumeric=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,mathceil=Math.ceil,mathfloor=Math.floor,bignumberError="[BigNumber Error] ",tooManyDigits=bignumberError+"Number primitive has more than 15 significant digits: ",BASE=1e14,LOG_BASE=14,MAX_SAFE_INTEGER=9007199254740991,POWS_TEN=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],SQRT_BASE=1e7,MAX=1e9;function clone(configObject){var div,convertBase,parseNumeric,P=BigNumber2.prototype={constructor:BigNumber2,toString:null,valueOf:null},ONE=new BigNumber2(1),DECIMAL_PLACES=20,ROUNDING_MODE=4,TO_EXP_NEG=-7,TO_EXP_POS=21,MIN_EXP=-1e7,MAX_EXP=1e7,CRYPTO=!1,MODULO_MODE=1,POW_PRECISION=0,FORMAT={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},ALPHABET="0123456789abcdefghijklmnopqrstuvwxyz",alphabetHasNormalDecimalDigits=!0;function BigNumber2(v,b){var alphabet,c,caseChanged,e,i,isNum,len,str,x=this;if(!(x instanceof BigNumber2))return new BigNumber2(v,b);if(b==null){if(v&&v._isBigNumber===!0){x.s=v.s,!v.c||v.e>MAX_EXP?x.c=x.e=null:v.e<MIN_EXP?x.c=[x.e=0]:(x.e=v.e,x.c=v.c.slice());return}if((isNum=typeof v=="number")&&v*0==0){if(x.s=1/v<0?(v=-v,-1):1,v===~~v){for(e=0,i=v;i>=10;i/=10,e++);e>MAX_EXP?x.c=x.e=null:(x.e=e,x.c=[v]);return}str=String(v)}else{if(!isNumeric.test(str=String(v)))return parseNumeric(x,str,isNum);x.s=str.charCodeAt(0)==45?(str=str.slice(1),-1):1}(e=str.indexOf("."))>-1&&(str=str.replace(".","")),(i=str.search(/e/i))>0?(e<0&&(e=i),e+=+str.slice(i+1),str=str.substring(0,i)):e<0&&(e=str.length)}else{if(intCheck(b,2,ALPHABET.length,"Base"),b==10&&alphabetHasNormalDecimalDigits)return x=new BigNumber2(v),round(x,DECIMAL_PLACES+x.e+1,ROUNDING_MODE);if(str=String(v),isNum=typeof v=="number"){if(v*0!=0)return parseNumeric(x,str,isNum,b);if(x.s=1/v<0?(str=str.slice(1),-1):1,BigNumber2.DEBUG&&str.replace(/^0\.0*|\./,"").length>15)throw Error(tooManyDigits+v)}else x.s=str.charCodeAt(0)===45?(str=str.slice(1),-1):1;for(alphabet=ALPHABET.slice(0,b),e=i=0,len=str.length;i<len;i++)if(alphabet.indexOf(c=str.charAt(i))<0){if(c=="."){if(i>e){e=len;continue}}else if(!caseChanged&&(str==str.toUpperCase()&&(str=str.toLowerCase())||str==str.toLowerCase()&&(str=str.toUpperCase()))){caseChanged=!0,i=-1,e=0;continue}return parseNumeric(x,String(v),isNum,b)}isNum=!1,str=convertBase(str,b,10,x.s),(e=str.indexOf("."))>-1?str=str.replace(".",""):e=str.length}for(i=0;str.charCodeAt(i)===48;i++);for(len=str.length;str.charCodeAt(--len)===48;);if(str=str.slice(i,++len)){if(len-=i,isNum&&BigNumber2.DEBUG&&len>15&&(v>MAX_SAFE_INTEGER||v!==mathfloor(v)))throw Error(tooManyDigits+x.s*v);if((e=e-i-1)>MAX_EXP)x.c=x.e=null;else if(e<MIN_EXP)x.c=[x.e=0];else{if(x.e=e,x.c=[],i=(e+1)%LOG_BASE,e<0&&(i+=LOG_BASE),i<len){for(i&&x.c.push(+str.slice(0,i)),len-=LOG_BASE;i<len;)x.c.push(+str.slice(i,i+=LOG_BASE));i=LOG_BASE-(str=str.slice(i)).length}else i-=len;for(;i--;str+="0");x.c.push(+str)}}else x.c=[x.e=0]}BigNumber2.clone=clone,BigNumber2.ROUND_UP=0,BigNumber2.ROUND_DOWN=1,BigNumber2.ROUND_CEIL=2,BigNumber2.ROUND_FLOOR=3,BigNumber2.ROUND_HALF_UP=4,BigNumber2.ROUND_HALF_DOWN=5,BigNumber2.ROUND_HALF_EVEN=6,BigNumber2.ROUND_HALF_CEIL=7,BigNumber2.ROUND_HALF_FLOOR=8,BigNumber2.EUCLID=9,BigNumber2.config=BigNumber2.set=function(obj){var p,v;if(obj!=null)if(typeof obj=="object"){if(obj.hasOwnProperty(p="DECIMAL_PLACES")&&(v=obj[p],intCheck(v,0,MAX,p),DECIMAL_PLACES=v),obj.hasOwnProperty(p="ROUNDING_MODE")&&(v=obj[p],intCheck(v,0,8,p),ROUNDING_MODE=v),obj.hasOwnProperty(p="EXPONENTIAL_AT")&&(v=obj[p],v&&v.pop?(intCheck(v[0],-MAX,0,p),intCheck(v[1],0,MAX,p),TO_EXP_NEG=v[0],TO_EXP_POS=v[1]):(intCheck(v,-MAX,MAX,p),TO_EXP_NEG=-(TO_EXP_POS=v<0?-v:v))),obj.hasOwnProperty(p="RANGE"))if(v=obj[p],v&&v.pop)intCheck(v[0],-MAX,-1,p),intCheck(v[1],1,MAX,p),MIN_EXP=v[0],MAX_EXP=v[1];else if(intCheck(v,-MAX,MAX,p),v)MIN_EXP=-(MAX_EXP=v<0?-v:v);else throw Error(bignumberError+p+" cannot be zero: "+v);if(obj.hasOwnProperty(p="CRYPTO"))if(v=obj[p],v===!!v)if(v)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))CRYPTO=v;else throw CRYPTO=!v,Error(bignumberError+"crypto unavailable");else CRYPTO=v;else throw Error(bignumberError+p+" not true or false: "+v);if(obj.hasOwnProperty(p="MODULO_MODE")&&(v=obj[p],intCheck(v,0,9,p),MODULO_MODE=v),obj.hasOwnProperty(p="POW_PRECISION")&&(v=obj[p],intCheck(v,0,MAX,p),POW_PRECISION=v),obj.hasOwnProperty(p="FORMAT"))if(v=obj[p],typeof v=="object")FORMAT=v;else throw Error(bignumberError+p+" not an object: "+v);if(obj.hasOwnProperty(p="ALPHABET"))if(v=obj[p],typeof v=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(v))alphabetHasNormalDecimalDigits=v.slice(0,10)=="0123456789",ALPHABET=v;else throw Error(bignumberError+p+" invalid: "+v)}else throw Error(bignumberError+"Object expected: "+obj);return{DECIMAL_PLACES,ROUNDING_MODE,EXPONENTIAL_AT:[TO_EXP_NEG,TO_EXP_POS],RANGE:[MIN_EXP,MAX_EXP],CRYPTO,MODULO_MODE,POW_PRECISION,FORMAT,ALPHABET}},BigNumber2.isBigNumber=function(v){if(!v||v._isBigNumber!==!0)return!1;if(!BigNumber2.DEBUG)return!0;var i,n,c=v.c,e=v.e,s=v.s;out:if({}.toString.call(c)=="[object Array]"){if((s===1||s===-1)&&e>=-MAX&&e<=MAX&&e===mathfloor(e)){if(c[0]===0){if(e===0&&c.length===1)return!0;break out}if(i=(e+1)%LOG_BASE,i<1&&(i+=LOG_BASE),String(c[0]).length==i){for(i=0;i<c.length;i++)if(n=c[i],n<0||n>=BASE||n!==mathfloor(n))break out;if(n!==0)return!0}}}else if(c===null&&e===null&&(s===null||s===1||s===-1))return!0;throw Error(bignumberError+"Invalid BigNumber: "+v)},BigNumber2.maximum=BigNumber2.max=function(){return maxOrMin(arguments,-1)},BigNumber2.minimum=BigNumber2.min=function(){return maxOrMin(arguments,1)},BigNumber2.random=(function(){var pow2_53=9007199254740992,random53bitInt=Math.random()*pow2_53&2097151?function(){return mathfloor(Math.random()*pow2_53)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(dp){var a,b,e,k,v,i=0,c=[],rand=new BigNumber2(ONE);if(dp==null?dp=DECIMAL_PLACES:intCheck(dp,0,MAX),k=mathceil(dp/LOG_BASE),CRYPTO)if(crypto.getRandomValues){for(a=crypto.getRandomValues(new Uint32Array(k*=2));i<k;)v=a[i]*131072+(a[i+1]>>>11),v>=9e15?(b=crypto.getRandomValues(new Uint32Array(2)),a[i]=b[0],a[i+1]=b[1]):(c.push(v%1e14),i+=2);i=k/2}else if(crypto.randomBytes){for(a=crypto.randomBytes(k*=7);i<k;)v=(a[i]&31)*281474976710656+a[i+1]*1099511627776+a[i+2]*4294967296+a[i+3]*16777216+(a[i+4]<<16)+(a[i+5]<<8)+a[i+6],v>=9e15?crypto.randomBytes(7).copy(a,i):(c.push(v%1e14),i+=7);i=k/7}else throw CRYPTO=!1,Error(bignumberError+"crypto unavailable");if(!CRYPTO)for(;i<k;)v=random53bitInt(),v<9e15&&(c[i++]=v%1e14);for(k=c[--i],dp%=LOG_BASE,k&&dp&&(v=POWS_TEN[LOG_BASE-dp],c[i]=mathfloor(k/v)*v);c[i]===0;c.pop(),i--);if(i<0)c=[e=0];else{for(e=-1;c[0]===0;c.splice(0,1),e-=LOG_BASE);for(i=1,v=c[0];v>=10;v/=10,i++);i<LOG_BASE&&(e-=LOG_BASE-i)}return rand.e=e,rand.c=c,rand}})(),BigNumber2.sum=function(){for(var i=1,args=arguments,sum=new BigNumber2(args[0]);i<args.length;)sum=sum.plus(args[i++]);return sum},convertBase=(function(){var decimal="0123456789";function toBaseOut(str,baseIn,baseOut,alphabet){for(var j,arr=[0],arrL,i=0,len=str.length;i<len;){for(arrL=arr.length;arrL--;arr[arrL]*=baseIn);for(arr[0]+=alphabet.indexOf(str.charAt(i++)),j=0;j<arr.length;j++)arr[j]>baseOut-1&&(arr[j+1]==null&&(arr[j+1]=0),arr[j+1]+=arr[j]/baseOut|0,arr[j]%=baseOut)}return arr.reverse()}return function(str,baseIn,baseOut,sign,callerIsToString){var alphabet,d,e,k,r,x,xc,y,i=str.indexOf("."),dp=DECIMAL_PLACES,rm=ROUNDING_MODE;for(i>=0&&(k=POW_PRECISION,POW_PRECISION=0,str=str.replace(".",""),y=new BigNumber2(baseIn),x=y.pow(str.length-i),POW_PRECISION=k,y.c=toBaseOut(toFixedPoint(coeffToString(x.c),x.e,"0"),10,baseOut,decimal),y.e=y.c.length),xc=toBaseOut(str,baseIn,baseOut,callerIsToString?(alphabet=ALPHABET,decimal):(alphabet=decimal,ALPHABET)),e=k=xc.length;xc[--k]==0;xc.pop());if(!xc[0])return alphabet.charAt(0);if(i<0?--e:(x.c=xc,x.e=e,x.s=sign,x=div(x,y,dp,rm,baseOut),xc=x.c,r=x.r,e=x.e),d=e+dp+1,i=xc[d],k=baseOut/2,r=r||d<0||xc[d+1]!=null,r=rm<4?(i!=null||r)&&(rm==0||rm==(x.s<0?3:2)):i>k||i==k&&(rm==4||r||rm==6&&xc[d-1]&1||rm==(x.s<0?8:7)),d<1||!xc[0])str=r?toFixedPoint(alphabet.charAt(1),-dp,alphabet.charAt(0)):alphabet.charAt(0);else{if(xc.length=d,r)for(--baseOut;++xc[--d]>baseOut;)xc[d]=0,d||(++e,xc=[1].concat(xc));for(k=xc.length;!xc[--k];);for(i=0,str="";i<=k;str+=alphabet.charAt(xc[i++]));str=toFixedPoint(str,e,alphabet.charAt(0))}return str}})(),div=(function(){function multiply(x,k,base){var m,temp,xlo,xhi,carry=0,i=x.length,klo=k%SQRT_BASE,khi=k/SQRT_BASE|0;for(x=x.slice();i--;)xlo=x[i]%SQRT_BASE,xhi=x[i]/SQRT_BASE|0,m=khi*xlo+xhi*klo,temp=klo*xlo+m%SQRT_BASE*SQRT_BASE+carry,carry=(temp/base|0)+(m/SQRT_BASE|0)+khi*xhi,x[i]=temp%base;return carry&&(x=[carry].concat(x)),x}function compare2(a,b,aL,bL){var i,cmp;if(aL!=bL)cmp=aL>bL?1:-1;else for(i=cmp=0;i<aL;i++)if(a[i]!=b[i]){cmp=a[i]>b[i]?1:-1;break}return cmp}function subtract(a,b,aL,base){for(var i=0;aL--;)a[aL]-=i,i=a[aL]<b[aL]?1:0,a[aL]=i*base+a[aL]-b[aL];for(;!a[0]&&a.length>1;a.splice(0,1));}return function(x,y,dp,rm,base){var cmp,e,i,more,n,prod,prodL,q,qc,rem,remL,rem0,xi,xL,yc0,yL,yz,s=x.s==y.s?1:-1,xc=x.c,yc=y.c;if(!xc||!xc[0]||!yc||!yc[0])return new BigNumber2(!x.s||!y.s||(xc?yc&&xc[0]==yc[0]:!yc)?NaN:xc&&xc[0]==0||!yc?s*0:s/0);for(q=new BigNumber2(s),qc=q.c=[],e=x.e-y.e,s=dp+e+1,base||(base=BASE,e=bitFloor(x.e/LOG_BASE)-bitFloor(y.e/LOG_BASE),s=s/LOG_BASE|0),i=0;yc[i]==(xc[i]||0);i++);if(yc[i]>(xc[i]||0)&&e--,s<0)qc.push(1),more=!0;else{for(xL=xc.length,yL=yc.length,i=0,s+=2,n=mathfloor(base/(yc[0]+1)),n>1&&(yc=multiply(yc,n,base),xc=multiply(xc,n,base),yL=yc.length,xL=xc.length),xi=yL,rem=xc.slice(0,yL),remL=rem.length;remL<yL;rem[remL++]=0);yz=yc.slice(),yz=[0].concat(yz),yc0=yc[0],yc[1]>=base/2&&yc0++;do{if(n=0,cmp=compare2(yc,rem,yL,remL),cmp<0){if(rem0=rem[0],yL!=remL&&(rem0=rem0*base+(rem[1]||0)),n=mathfloor(rem0/yc0),n>1)for(n>=base&&(n=base-1),prod=multiply(yc,n,base),prodL=prod.length,remL=rem.length;compare2(prod,rem,prodL,remL)==1;)n--,subtract(prod,yL<prodL?yz:yc,prodL,base),prodL=prod.length,cmp=1;else n==0&&(cmp=n=1),prod=yc.slice(),prodL=prod.length;if(prodL<remL&&(prod=[0].concat(prod)),subtract(rem,prod,remL,base),remL=rem.length,cmp==-1)for(;compare2(yc,rem,yL,remL)<1;)n++,subtract(rem,yL<remL?yz:yc,remL,base),remL=rem.length}else cmp===0&&(n++,rem=[0]);qc[i++]=n,rem[0]?rem[remL++]=xc[xi]||0:(rem=[xc[xi]],remL=1)}while((xi++<xL||rem[0]!=null)&&s--);more=rem[0]!=null,qc[0]||qc.splice(0,1)}if(base==BASE){for(i=1,s=qc[0];s>=10;s/=10,i++);round(q,dp+(q.e=i+e*LOG_BASE-1)+1,rm,more)}else q.e=e,q.r=+more;return q}})();function format(n,i,rm,id){var c0,e,ne,len,str;if(rm==null?rm=ROUNDING_MODE:intCheck(rm,0,8),!n.c)return n.toString();if(c0=n.c[0],ne=n.e,i==null)str=coeffToString(n.c),str=id==1||id==2&&(ne<=TO_EXP_NEG||ne>=TO_EXP_POS)?toExponential(str,ne):toFixedPoint(str,ne,"0");else if(n=round(new BigNumber2(n),i,rm),e=n.e,str=coeffToString(n.c),len=str.length,id==1||id==2&&(i<=e||e<=TO_EXP_NEG)){for(;len<i;str+="0",len++);str=toExponential(str,e)}else if(i-=ne+(id===2&&e>ne),str=toFixedPoint(str,e,"0"),e+1>len){if(--i>0)for(str+=".";i--;str+="0");}else if(i+=e-len,i>0)for(e+1==len&&(str+=".");i--;str+="0");return n.s<0&&c0?"-"+str:str}function maxOrMin(args,n){for(var k,y,i=1,x=new BigNumber2(args[0]);i<args.length;i++)y=new BigNumber2(args[i]),(!y.s||(k=compare(x,y))===n||k===0&&x.s===n)&&(x=y);return x}function normalise(n,c,e){for(var i=1,j=c.length;!c[--j];c.pop());for(j=c[0];j>=10;j/=10,i++);return(e=i+e*LOG_BASE-1)>MAX_EXP?n.c=n.e=null:e<MIN_EXP?n.c=[n.e=0]:(n.e=e,n.c=c),n}parseNumeric=(function(){var basePrefix=/^(-?)0([xbo])(?=\w[\w.]*$)/i,dotAfter=/^([^.]+)\.$/,dotBefore=/^\.([^.]+)$/,isInfinityOrNaN=/^-?(Infinity|NaN)$/,whitespaceOrPlus=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(x,str,isNum,b){var base,s=isNum?str:str.replace(whitespaceOrPlus,"");if(isInfinityOrNaN.test(s))x.s=isNaN(s)?null:s<0?-1:1;else{if(!isNum&&(s=s.replace(basePrefix,function(m,p1,p2){return base=(p2=p2.toLowerCase())=="x"?16:p2=="b"?2:8,!b||b==base?p1:m}),b&&(base=b,s=s.replace(dotAfter,"$1").replace(dotBefore,"0.$1")),str!=s))return new BigNumber2(s,base);if(BigNumber2.DEBUG)throw Error(bignumberError+"Not a"+(b?" base "+b:"")+" number: "+str);x.s=null}x.c=x.e=null}})();function round(x,sd,rm,r){var d,i,j,k,n,ni,rd,xc=x.c,pows10=POWS_TEN;if(xc){out:{for(d=1,k=xc[0];k>=10;k/=10,d++);if(i=sd-d,i<0)i+=LOG_BASE,j=sd,n=xc[ni=0],rd=mathfloor(n/pows10[d-j-1]%10);else if(ni=mathceil((i+1)/LOG_BASE),ni>=xc.length)if(r){for(;xc.length<=ni;xc.push(0));n=rd=0,d=1,i%=LOG_BASE,j=i-LOG_BASE+1}else break out;else{for(n=k=xc[ni],d=1;k>=10;k/=10,d++);i%=LOG_BASE,j=i-LOG_BASE+d,rd=j<0?0:mathfloor(n/pows10[d-j-1]%10)}if(r=r||sd<0||xc[ni+1]!=null||(j<0?n:n%pows10[d-j-1]),r=rm<4?(rd||r)&&(rm==0||rm==(x.s<0?3:2)):rd>5||rd==5&&(rm==4||r||rm==6&&(i>0?j>0?n/pows10[d-j]:0:xc[ni-1])%10&1||rm==(x.s<0?8:7)),sd<1||!xc[0])return xc.length=0,r?(sd-=x.e+1,xc[0]=pows10[(LOG_BASE-sd%LOG_BASE)%LOG_BASE],x.e=-sd||0):xc[0]=x.e=0,x;if(i==0?(xc.length=ni,k=1,ni--):(xc.length=ni+1,k=pows10[LOG_BASE-i],xc[ni]=j>0?mathfloor(n/pows10[d-j]%pows10[j])*k:0),r)for(;;)if(ni==0){for(i=1,j=xc[0];j>=10;j/=10,i++);for(j=xc[0]+=k,k=1;j>=10;j/=10,k++);i!=k&&(x.e++,xc[0]==BASE&&(xc[0]=1));break}else{if(xc[ni]+=k,xc[ni]!=BASE)break;xc[ni--]=0,k=1}for(i=xc.length;xc[--i]===0;xc.pop());}x.e>MAX_EXP?x.c=x.e=null:x.e<MIN_EXP&&(x.c=[x.e=0])}return x}function valueOf(n){var str,e=n.e;return e===null?n.toString():(str=coeffToString(n.c),str=e<=TO_EXP_NEG||e>=TO_EXP_POS?toExponential(str,e):toFixedPoint(str,e,"0"),n.s<0?"-"+str:str)}return P.absoluteValue=P.abs=function(){var x=new BigNumber2(this);return x.s<0&&(x.s=1),x},P.comparedTo=function(y,b){return compare(this,new BigNumber2(y,b))},P.decimalPlaces=P.dp=function(dp,rm){var c,n,v,x=this;if(dp!=null)return intCheck(dp,0,MAX),rm==null?rm=ROUNDING_MODE:intCheck(rm,0,8),round(new BigNumber2(x),dp+x.e+1,rm);if(!(c=x.c))return null;if(n=((v=c.length-1)-bitFloor(this.e/LOG_BASE))*LOG_BASE,v=c[v])for(;v%10==0;v/=10,n--);return n<0&&(n=0),n},P.dividedBy=P.div=function(y,b){return div(this,new BigNumber2(y,b),DECIMAL_PLACES,ROUNDING_MODE)},P.dividedToIntegerBy=P.idiv=function(y,b){return div(this,new BigNumber2(y,b),0,1)},P.exponentiatedBy=P.pow=function(n,m){var half,isModExp,i,k,more,nIsBig,nIsNeg,nIsOdd,y,x=this;if(n=new BigNumber2(n),n.c&&!n.isInteger())throw Error(bignumberError+"Exponent not an integer: "+valueOf(n));if(m!=null&&(m=new BigNumber2(m)),nIsBig=n.e>14,!x.c||!x.c[0]||x.c[0]==1&&!x.e&&x.c.length==1||!n.c||!n.c[0])return y=new BigNumber2(Math.pow(+valueOf(x),nIsBig?n.s*(2-isOdd(n)):+valueOf(n))),m?y.mod(m):y;if(nIsNeg=n.s<0,m){if(m.c?!m.c[0]:!m.s)return new BigNumber2(NaN);isModExp=!nIsNeg&&x.isInteger()&&m.isInteger(),isModExp&&(x=x.mod(m))}else{if(n.e>9&&(x.e>0||x.e<-1||(x.e==0?x.c[0]>1||nIsBig&&x.c[1]>=24e7:x.c[0]<8e13||nIsBig&&x.c[0]<=9999975e7)))return k=x.s<0&&isOdd(n)?-0:0,x.e>-1&&(k=1/k),new BigNumber2(nIsNeg?1/k:k);POW_PRECISION&&(k=mathceil(POW_PRECISION/LOG_BASE+2))}for(nIsBig?(half=new BigNumber2(.5),nIsNeg&&(n.s=1),nIsOdd=isOdd(n)):(i=Math.abs(+valueOf(n)),nIsOdd=i%2),y=new BigNumber2(ONE);;){if(nIsOdd){if(y=y.times(x),!y.c)break;k?y.c.length>k&&(y.c.length=k):isModExp&&(y=y.mod(m))}if(i){if(i=mathfloor(i/2),i===0)break;nIsOdd=i%2}else if(n=n.times(half),round(n,n.e+1,1),n.e>14)nIsOdd=isOdd(n);else{if(i=+valueOf(n),i===0)break;nIsOdd=i%2}x=x.times(x),k?x.c&&x.c.length>k&&(x.c.length=k):isModExp&&(x=x.mod(m))}return isModExp?y:(nIsNeg&&(y=ONE.div(y)),m?y.mod(m):k?round(y,POW_PRECISION,ROUNDING_MODE,more):y)},P.integerValue=function(rm){var n=new BigNumber2(this);return rm==null?rm=ROUNDING_MODE:intCheck(rm,0,8),round(n,n.e+1,rm)},P.isEqualTo=P.eq=function(y,b){return compare(this,new BigNumber2(y,b))===0},P.isFinite=function(){return!!this.c},P.isGreaterThan=P.gt=function(y,b){return compare(this,new BigNumber2(y,b))>0},P.isGreaterThanOrEqualTo=P.gte=function(y,b){return(b=compare(this,new BigNumber2(y,b)))===1||b===0},P.isInteger=function(){return!!this.c&&bitFloor(this.e/LOG_BASE)>this.c.length-2},P.isLessThan=P.lt=function(y,b){return compare(this,new BigNumber2(y,b))<0},P.isLessThanOrEqualTo=P.lte=function(y,b){return(b=compare(this,new BigNumber2(y,b)))===-1||b===0},P.isNaN=function(){return!this.s},P.isNegative=function(){return this.s<0},P.isPositive=function(){return this.s>0},P.isZero=function(){return!!this.c&&this.c[0]==0},P.minus=function(y,b){var i,j,t,xLTy,x=this,a=x.s;if(y=new BigNumber2(y,b),b=y.s,!a||!b)return new BigNumber2(NaN);if(a!=b)return y.s=-b,x.plus(y);var xe=x.e/LOG_BASE,ye=y.e/LOG_BASE,xc=x.c,yc=y.c;if(!xe||!ye){if(!xc||!yc)return xc?(y.s=-b,y):new BigNumber2(yc?x:NaN);if(!xc[0]||!yc[0])return yc[0]?(y.s=-b,y):new BigNumber2(xc[0]?x:ROUNDING_MODE==3?-0:0)}if(xe=bitFloor(xe),ye=bitFloor(ye),xc=xc.slice(),a=xe-ye){for((xLTy=a<0)?(a=-a,t=xc):(ye=xe,t=yc),t.reverse(),b=a;b--;t.push(0));t.reverse()}else for(j=(xLTy=(a=xc.length)<(b=yc.length))?a:b,a=b=0;b<j;b++)if(xc[b]!=yc[b]){xLTy=xc[b]<yc[b];break}if(xLTy&&(t=xc,xc=yc,yc=t,y.s=-y.s),b=(j=yc.length)-(i=xc.length),b>0)for(;b--;xc[i++]=0);for(b=BASE-1;j>a;){if(xc[--j]<yc[j]){for(i=j;i&&!xc[--i];xc[i]=b);--xc[i],xc[j]+=BASE}xc[j]-=yc[j]}for(;xc[0]==0;xc.splice(0,1),--ye);return xc[0]?normalise(y,xc,ye):(y.s=ROUNDING_MODE==3?-1:1,y.c=[y.e=0],y)},P.modulo=P.mod=function(y,b){var q,s,x=this;return y=new BigNumber2(y,b),!x.c||!y.s||y.c&&!y.c[0]?new BigNumber2(NaN):!y.c||x.c&&!x.c[0]?new BigNumber2(x):(MODULO_MODE==9?(s=y.s,y.s=1,q=div(x,y,0,3),y.s=s,q.s*=s):q=div(x,y,0,MODULO_MODE),y=x.minus(q.times(y)),!y.c[0]&&MODULO_MODE==1&&(y.s=x.s),y)},P.multipliedBy=P.times=function(y,b){var c,e,i,j,k,m,xcL,xlo,xhi,ycL,ylo,yhi,zc,base,sqrtBase,x=this,xc=x.c,yc=(y=new BigNumber2(y,b)).c;if(!xc||!yc||!xc[0]||!yc[0])return!x.s||!y.s||xc&&!xc[0]&&!yc||yc&&!yc[0]&&!xc?y.c=y.e=y.s=null:(y.s*=x.s,!xc||!yc?y.c=y.e=null:(y.c=[0],y.e=0)),y;for(e=bitFloor(x.e/LOG_BASE)+bitFloor(y.e/LOG_BASE),y.s*=x.s,xcL=xc.length,ycL=yc.length,xcL<ycL&&(zc=xc,xc=yc,yc=zc,i=xcL,xcL=ycL,ycL=i),i=xcL+ycL,zc=[];i--;zc.push(0));for(base=BASE,sqrtBase=SQRT_BASE,i=ycL;--i>=0;){for(c=0,ylo=yc[i]%sqrtBase,yhi=yc[i]/sqrtBase|0,k=xcL,j=i+k;j>i;)xlo=xc[--k]%sqrtBase,xhi=xc[k]/sqrtBase|0,m=yhi*xlo+xhi*ylo,xlo=ylo*xlo+m%sqrtBase*sqrtBase+zc[j]+c,c=(xlo/base|0)+(m/sqrtBase|0)+yhi*xhi,zc[j--]=xlo%base;zc[j]=c}return c?++e:zc.splice(0,1),normalise(y,zc,e)},P.negated=function(){var x=new BigNumber2(this);return x.s=-x.s||null,x},P.plus=function(y,b){var t,x=this,a=x.s;if(y=new BigNumber2(y,b),b=y.s,!a||!b)return new BigNumber2(NaN);if(a!=b)return y.s=-b,x.minus(y);var xe=x.e/LOG_BASE,ye=y.e/LOG_BASE,xc=x.c,yc=y.c;if(!xe||!ye){if(!xc||!yc)return new BigNumber2(a/0);if(!xc[0]||!yc[0])return yc[0]?y:new BigNumber2(xc[0]?x:a*0)}if(xe=bitFloor(xe),ye=bitFloor(ye),xc=xc.slice(),a=xe-ye){for(a>0?(ye=xe,t=yc):(a=-a,t=xc),t.reverse();a--;t.push(0));t.reverse()}for(a=xc.length,b=yc.length,a-b<0&&(t=yc,yc=xc,xc=t,b=a),a=0;b;)a=(xc[--b]=xc[b]+yc[b]+a)/BASE|0,xc[b]=BASE===xc[b]?0:xc[b]%BASE;return a&&(xc=[a].concat(xc),++ye),normalise(y,xc,ye)},P.precision=P.sd=function(sd,rm){var c,n,v,x=this;if(sd!=null&&sd!==!!sd)return intCheck(sd,1,MAX),rm==null?rm=ROUNDING_MODE:intCheck(rm,0,8),round(new BigNumber2(x),sd,rm);if(!(c=x.c))return null;if(v=c.length-1,n=v*LOG_BASE+1,v=c[v]){for(;v%10==0;v/=10,n--);for(v=c[0];v>=10;v/=10,n++);}return sd&&x.e+1>n&&(n=x.e+1),n},P.shiftedBy=function(k){return intCheck(k,-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER),this.times("1e"+k)},P.squareRoot=P.sqrt=function(){var m,n,r,rep,t,x=this,c=x.c,s=x.s,e=x.e,dp=DECIMAL_PLACES+4,half=new BigNumber2("0.5");if(s!==1||!c||!c[0])return new BigNumber2(!s||s<0&&(!c||c[0])?NaN:c?x:1/0);if(s=Math.sqrt(+valueOf(x)),s==0||s==1/0?(n=coeffToString(c),(n.length+e)%2==0&&(n+="0"),s=Math.sqrt(+n),e=bitFloor((e+1)/2)-(e<0||e%2),s==1/0?n="5e"+e:(n=s.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new BigNumber2(n)):r=new BigNumber2(s+""),r.c[0]){for(e=r.e,s=e+dp,s<3&&(s=0);;)if(t=r,r=half.times(t.plus(div(x,t,dp,1))),coeffToString(t.c).slice(0,s)===(n=coeffToString(r.c)).slice(0,s))if(r.e<e&&--s,n=n.slice(s-3,s+1),n=="9999"||!rep&&n=="4999"){if(!rep&&(round(t,t.e+DECIMAL_PLACES+2,0),t.times(t).eq(x))){r=t;break}dp+=4,s+=4,rep=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(round(r,r.e+DECIMAL_PLACES+2,1),m=!r.times(r).eq(x));break}}return round(r,r.e+DECIMAL_PLACES+1,ROUNDING_MODE,m)},P.toExponential=function(dp,rm){return dp!=null&&(intCheck(dp,0,MAX),dp++),format(this,dp,rm,1)},P.toFixed=function(dp,rm){return dp!=null&&(intCheck(dp,0,MAX),dp=dp+this.e+1),format(this,dp,rm)},P.toFormat=function(dp,rm,format2){var str,x=this;if(format2==null)dp!=null&&rm&&typeof rm=="object"?(format2=rm,rm=null):dp&&typeof dp=="object"?(format2=dp,dp=rm=null):format2=FORMAT;else if(typeof format2!="object")throw Error(bignumberError+"Argument not an object: "+format2);if(str=x.toFixed(dp,rm),x.c){var i,arr=str.split("."),g1=+format2.groupSize,g2=+format2.secondaryGroupSize,groupSeparator=format2.groupSeparator||"",intPart=arr[0],fractionPart=arr[1],isNeg=x.s<0,intDigits=isNeg?intPart.slice(1):intPart,len=intDigits.length;if(g2&&(i=g1,g1=g2,g2=i,len-=i),g1>0&&len>0){for(i=len%g1||g1,intPart=intDigits.substr(0,i);i<len;i+=g1)intPart+=groupSeparator+intDigits.substr(i,g1);g2>0&&(intPart+=groupSeparator+intDigits.slice(i)),isNeg&&(intPart="-"+intPart)}str=fractionPart?intPart+(format2.decimalSeparator||"")+((g2=+format2.fractionGroupSize)?fractionPart.replace(new RegExp("\\d{"+g2+"}\\B","g"),"$&"+(format2.fractionGroupSeparator||"")):fractionPart):intPart}return(format2.prefix||"")+str+(format2.suffix||"")},P.toFraction=function(md){var d,d0,d1,d2,e,exp,n,n0,n1,q,r,s,x=this,xc=x.c;if(md!=null&&(n=new BigNumber2(md),!n.isInteger()&&(n.c||n.s!==1)||n.lt(ONE)))throw Error(bignumberError+"Argument "+(n.isInteger()?"out of range: ":"not an integer: ")+valueOf(n));if(!xc)return new BigNumber2(x);for(d=new BigNumber2(ONE),n1=d0=new BigNumber2(ONE),d1=n0=new BigNumber2(ONE),s=coeffToString(xc),e=d.e=s.length-x.e-1,d.c[0]=POWS_TEN[(exp=e%LOG_BASE)<0?LOG_BASE+exp:exp],md=!md||n.comparedTo(d)>0?e>0?d:n1:n,exp=MAX_EXP,MAX_EXP=1/0,n=new BigNumber2(s),n0.c[0]=0;q=div(n,d,0,1),d2=d0.plus(q.times(d1)),d2.comparedTo(md)!=1;)d0=d1,d1=d2,n1=n0.plus(q.times(d2=n1)),n0=d2,d=n.minus(q.times(d2=d)),n=d2;return d2=div(md.minus(d0),d1,0,1),n0=n0.plus(d2.times(n1)),d0=d0.plus(d2.times(d1)),n0.s=n1.s=x.s,e=e*2,r=div(n1,d1,e,ROUNDING_MODE).minus(x).abs().comparedTo(div(n0,d0,e,ROUNDING_MODE).minus(x).abs())<1?[n1,d1]:[n0,d0],MAX_EXP=exp,r},P.toNumber=function(){return+valueOf(this)},P.toPrecision=function(sd,rm){return sd!=null&&intCheck(sd,1,MAX),format(this,sd,rm,2)},P.toString=function(b){var str,n=this,s=n.s,e=n.e;return e===null?s?(str="Infinity",s<0&&(str="-"+str)):str="NaN":(b==null?str=e<=TO_EXP_NEG||e>=TO_EXP_POS?toExponential(coeffToString(n.c),e):toFixedPoint(coeffToString(n.c),e,"0"):b===10&&alphabetHasNormalDecimalDigits?(n=round(new BigNumber2(n),DECIMAL_PLACES+e+1,ROUNDING_MODE),str=toFixedPoint(coeffToString(n.c),n.e,"0")):(intCheck(b,2,ALPHABET.length,"Base"),str=convertBase(toFixedPoint(coeffToString(n.c),e,"0"),10,b,s,!0)),s<0&&n.c[0]&&(str="-"+str)),str},P.valueOf=P.toJSON=function(){return valueOf(this)},P._isBigNumber=!0,configObject!=null&&BigNumber2.set(configObject),BigNumber2}function bitFloor(n){var i=n|0;return n>0||n===i?i:i-1}function coeffToString(a){for(var s,z,i=1,j=a.length,r=a[0]+"";i<j;){for(s=a[i++]+"",z=LOG_BASE-s.length;z--;s="0"+s);r+=s}for(j=r.length;r.charCodeAt(--j)===48;);return r.slice(0,j+1||1)}function compare(x,y){var a,b,xc=x.c,yc=y.c,i=x.s,j=y.s,k=x.e,l=y.e;if(!i||!j)return null;if(a=xc&&!xc[0],b=yc&&!yc[0],a||b)return a?b?0:-j:i;if(i!=j)return i;if(a=i<0,b=k==l,!xc||!yc)return b?0:!xc^a?1:-1;if(!b)return k>l^a?1:-1;for(j=(k=xc.length)<(l=yc.length)?k:l,i=0;i<j;i++)if(xc[i]!=yc[i])return xc[i]>yc[i]^a?1:-1;return k==l?0:k>l^a?1:-1}function intCheck(n,min,max,name){if(n<min||n>max||n!==mathfloor(n))throw Error(bignumberError+(name||"Argument")+(typeof n=="number"?n<min||n>max?" out of range: ":" not an integer: ":" not a primitive number: ")+String(n))}function isOdd(n){var k=n.c.length-1;return bitFloor(n.e/LOG_BASE)==k&&n.c[k]%2!=0}function toExponential(str,e){return(str.length>1?str.charAt(0)+"."+str.slice(1):str)+(e<0?"e":"e+")+e}function toFixedPoint(str,e,z){var len,zs;if(e<0){for(zs=z+".";++e;zs+=z);str=zs+str}else if(len=str.length,++e>len){for(zs=z,e-=len;--e;zs+=z);str+=zs}else e<len&&(str=str.slice(0,e)+"."+str.slice(e));return str}BigNumber=clone(),BigNumber.default=BigNumber.BigNumber=BigNumber,typeof define=="function"&&define.amd?define(function(){return BigNumber}):typeof module<"u"&&module.exports?module.exports=BigNumber:(globalObject||(globalObject=typeof self<"u"&&self?self:window),globalObject.BigNumber=BigNumber)})(exports)}});var require_stringify=__commonJS({"node_modules/json-bigint/lib/stringify.js"(exports,module){var BigNumber=require_bignumber(),JSON2=module.exports;(function(){"use strict";function f(n){return n<10?"0"+n:n}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;function quote(string){return escapable.lastIndex=0,escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c=="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key],isBigNumber=value!=null&&(value instanceof BigNumber||BigNumber.isBigNumber(value));switch(value&&typeof value=="object"&&typeof value.toJSON=="function"&&(value=value.toJSON(key)),typeof rep=="function"&&(value=rep.call(holder,key,value)),typeof value){case"string":return isBigNumber?value:quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":case"bigint":return String(value);case"object":if(!value)return"null";if(gap+=indent,partial=[],Object.prototype.toString.apply(value)==="[object Array]"){for(length=value.length,i=0;i<length;i+=1)partial[i]=str(i,value)||"null";return v=partial.length===0?"[]":gap?`[
|
|
7
|
+
`}yield finale}static#proxyAgent;static#fetch;static async#getProxyAgent(){return this.#proxyAgent||=(await import("./https-proxy-agent-562J2I52.js")).HttpsProxyAgent,this.#proxyAgent}static async#getFetch(){let hasWindow=typeof window<"u"&&!!window;return this.#fetch||=hasWindow?window.fetch:(await import("./src-QKGKDFSU.js")).default,this.#fetch}static mergeHeaders(base,...append){base=base instanceof Headers?base:new Headers(base);for(let headers of append)(headers instanceof Headers?headers:new Headers(headers)).forEach((value,key)=>{key==="set-cookie"?base.append(key,value):base.set(key,value)});return base}};exports.Gaxios=Gaxios;_a2=Gaxios}});var require_src=__commonJS({"node_modules/gaxios/build/cjs/src/index.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p)&&__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});exports.instance=exports.Gaxios=exports.GaxiosError=void 0;exports.request=request;var gaxios_js_1=require_gaxios();Object.defineProperty(exports,"Gaxios",{enumerable:!0,get:function(){return gaxios_js_1.Gaxios}});var common_js_1=require_common();Object.defineProperty(exports,"GaxiosError",{enumerable:!0,get:function(){return common_js_1.GaxiosError}});__exportStar(require_interceptor(),exports);exports.instance=new gaxios_js_1.Gaxios;async function request(opts){return exports.instance.request(opts)}}});var require_bignumber=__commonJS({"node_modules/bignumber.js/bignumber.js"(exports,module){(function(globalObject){"use strict";var BigNumber,isNumeric=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,mathceil=Math.ceil,mathfloor=Math.floor,bignumberError="[BigNumber Error] ",tooManyDigits=bignumberError+"Number primitive has more than 15 significant digits: ",BASE=1e14,LOG_BASE=14,MAX_SAFE_INTEGER=9007199254740991,POWS_TEN=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],SQRT_BASE=1e7,MAX=1e9;function clone(configObject){var div,convertBase,parseNumeric,P=BigNumber2.prototype={constructor:BigNumber2,toString:null,valueOf:null},ONE=new BigNumber2(1),DECIMAL_PLACES=20,ROUNDING_MODE=4,TO_EXP_NEG=-7,TO_EXP_POS=21,MIN_EXP=-1e7,MAX_EXP=1e7,CRYPTO=!1,MODULO_MODE=1,POW_PRECISION=0,FORMAT={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},ALPHABET="0123456789abcdefghijklmnopqrstuvwxyz",alphabetHasNormalDecimalDigits=!0;function BigNumber2(v,b){var alphabet,c,caseChanged,e,i,isNum,len,str,x=this;if(!(x instanceof BigNumber2))return new BigNumber2(v,b);if(b==null){if(v&&v._isBigNumber===!0){x.s=v.s,!v.c||v.e>MAX_EXP?x.c=x.e=null:v.e<MIN_EXP?x.c=[x.e=0]:(x.e=v.e,x.c=v.c.slice());return}if((isNum=typeof v=="number")&&v*0==0){if(x.s=1/v<0?(v=-v,-1):1,v===~~v){for(e=0,i=v;i>=10;i/=10,e++);e>MAX_EXP?x.c=x.e=null:(x.e=e,x.c=[v]);return}str=String(v)}else{if(!isNumeric.test(str=String(v)))return parseNumeric(x,str,isNum);x.s=str.charCodeAt(0)==45?(str=str.slice(1),-1):1}(e=str.indexOf("."))>-1&&(str=str.replace(".","")),(i=str.search(/e/i))>0?(e<0&&(e=i),e+=+str.slice(i+1),str=str.substring(0,i)):e<0&&(e=str.length)}else{if(intCheck(b,2,ALPHABET.length,"Base"),b==10&&alphabetHasNormalDecimalDigits)return x=new BigNumber2(v),round(x,DECIMAL_PLACES+x.e+1,ROUNDING_MODE);if(str=String(v),isNum=typeof v=="number"){if(v*0!=0)return parseNumeric(x,str,isNum,b);if(x.s=1/v<0?(str=str.slice(1),-1):1,BigNumber2.DEBUG&&str.replace(/^0\.0*|\./,"").length>15)throw Error(tooManyDigits+v)}else x.s=str.charCodeAt(0)===45?(str=str.slice(1),-1):1;for(alphabet=ALPHABET.slice(0,b),e=i=0,len=str.length;i<len;i++)if(alphabet.indexOf(c=str.charAt(i))<0){if(c=="."){if(i>e){e=len;continue}}else if(!caseChanged&&(str==str.toUpperCase()&&(str=str.toLowerCase())||str==str.toLowerCase()&&(str=str.toUpperCase()))){caseChanged=!0,i=-1,e=0;continue}return parseNumeric(x,String(v),isNum,b)}isNum=!1,str=convertBase(str,b,10,x.s),(e=str.indexOf("."))>-1?str=str.replace(".",""):e=str.length}for(i=0;str.charCodeAt(i)===48;i++);for(len=str.length;str.charCodeAt(--len)===48;);if(str=str.slice(i,++len)){if(len-=i,isNum&&BigNumber2.DEBUG&&len>15&&(v>MAX_SAFE_INTEGER||v!==mathfloor(v)))throw Error(tooManyDigits+x.s*v);if((e=e-i-1)>MAX_EXP)x.c=x.e=null;else if(e<MIN_EXP)x.c=[x.e=0];else{if(x.e=e,x.c=[],i=(e+1)%LOG_BASE,e<0&&(i+=LOG_BASE),i<len){for(i&&x.c.push(+str.slice(0,i)),len-=LOG_BASE;i<len;)x.c.push(+str.slice(i,i+=LOG_BASE));i=LOG_BASE-(str=str.slice(i)).length}else i-=len;for(;i--;str+="0");x.c.push(+str)}}else x.c=[x.e=0]}BigNumber2.clone=clone,BigNumber2.ROUND_UP=0,BigNumber2.ROUND_DOWN=1,BigNumber2.ROUND_CEIL=2,BigNumber2.ROUND_FLOOR=3,BigNumber2.ROUND_HALF_UP=4,BigNumber2.ROUND_HALF_DOWN=5,BigNumber2.ROUND_HALF_EVEN=6,BigNumber2.ROUND_HALF_CEIL=7,BigNumber2.ROUND_HALF_FLOOR=8,BigNumber2.EUCLID=9,BigNumber2.config=BigNumber2.set=function(obj){var p,v;if(obj!=null)if(typeof obj=="object"){if(obj.hasOwnProperty(p="DECIMAL_PLACES")&&(v=obj[p],intCheck(v,0,MAX,p),DECIMAL_PLACES=v),obj.hasOwnProperty(p="ROUNDING_MODE")&&(v=obj[p],intCheck(v,0,8,p),ROUNDING_MODE=v),obj.hasOwnProperty(p="EXPONENTIAL_AT")&&(v=obj[p],v&&v.pop?(intCheck(v[0],-MAX,0,p),intCheck(v[1],0,MAX,p),TO_EXP_NEG=v[0],TO_EXP_POS=v[1]):(intCheck(v,-MAX,MAX,p),TO_EXP_NEG=-(TO_EXP_POS=v<0?-v:v))),obj.hasOwnProperty(p="RANGE"))if(v=obj[p],v&&v.pop)intCheck(v[0],-MAX,-1,p),intCheck(v[1],1,MAX,p),MIN_EXP=v[0],MAX_EXP=v[1];else if(intCheck(v,-MAX,MAX,p),v)MIN_EXP=-(MAX_EXP=v<0?-v:v);else throw Error(bignumberError+p+" cannot be zero: "+v);if(obj.hasOwnProperty(p="CRYPTO"))if(v=obj[p],v===!!v)if(v)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))CRYPTO=v;else throw CRYPTO=!v,Error(bignumberError+"crypto unavailable");else CRYPTO=v;else throw Error(bignumberError+p+" not true or false: "+v);if(obj.hasOwnProperty(p="MODULO_MODE")&&(v=obj[p],intCheck(v,0,9,p),MODULO_MODE=v),obj.hasOwnProperty(p="POW_PRECISION")&&(v=obj[p],intCheck(v,0,MAX,p),POW_PRECISION=v),obj.hasOwnProperty(p="FORMAT"))if(v=obj[p],typeof v=="object")FORMAT=v;else throw Error(bignumberError+p+" not an object: "+v);if(obj.hasOwnProperty(p="ALPHABET"))if(v=obj[p],typeof v=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(v))alphabetHasNormalDecimalDigits=v.slice(0,10)=="0123456789",ALPHABET=v;else throw Error(bignumberError+p+" invalid: "+v)}else throw Error(bignumberError+"Object expected: "+obj);return{DECIMAL_PLACES,ROUNDING_MODE,EXPONENTIAL_AT:[TO_EXP_NEG,TO_EXP_POS],RANGE:[MIN_EXP,MAX_EXP],CRYPTO,MODULO_MODE,POW_PRECISION,FORMAT,ALPHABET}},BigNumber2.isBigNumber=function(v){if(!v||v._isBigNumber!==!0)return!1;if(!BigNumber2.DEBUG)return!0;var i,n,c=v.c,e=v.e,s=v.s;out:if({}.toString.call(c)=="[object Array]"){if((s===1||s===-1)&&e>=-MAX&&e<=MAX&&e===mathfloor(e)){if(c[0]===0){if(e===0&&c.length===1)return!0;break out}if(i=(e+1)%LOG_BASE,i<1&&(i+=LOG_BASE),String(c[0]).length==i){for(i=0;i<c.length;i++)if(n=c[i],n<0||n>=BASE||n!==mathfloor(n))break out;if(n!==0)return!0}}}else if(c===null&&e===null&&(s===null||s===1||s===-1))return!0;throw Error(bignumberError+"Invalid BigNumber: "+v)},BigNumber2.maximum=BigNumber2.max=function(){return maxOrMin(arguments,-1)},BigNumber2.minimum=BigNumber2.min=function(){return maxOrMin(arguments,1)},BigNumber2.random=(function(){var pow2_53=9007199254740992,random53bitInt=Math.random()*pow2_53&2097151?function(){return mathfloor(Math.random()*pow2_53)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(dp){var a,b,e,k,v,i=0,c=[],rand=new BigNumber2(ONE);if(dp==null?dp=DECIMAL_PLACES:intCheck(dp,0,MAX),k=mathceil(dp/LOG_BASE),CRYPTO)if(crypto.getRandomValues){for(a=crypto.getRandomValues(new Uint32Array(k*=2));i<k;)v=a[i]*131072+(a[i+1]>>>11),v>=9e15?(b=crypto.getRandomValues(new Uint32Array(2)),a[i]=b[0],a[i+1]=b[1]):(c.push(v%1e14),i+=2);i=k/2}else if(crypto.randomBytes){for(a=crypto.randomBytes(k*=7);i<k;)v=(a[i]&31)*281474976710656+a[i+1]*1099511627776+a[i+2]*4294967296+a[i+3]*16777216+(a[i+4]<<16)+(a[i+5]<<8)+a[i+6],v>=9e15?crypto.randomBytes(7).copy(a,i):(c.push(v%1e14),i+=7);i=k/7}else throw CRYPTO=!1,Error(bignumberError+"crypto unavailable");if(!CRYPTO)for(;i<k;)v=random53bitInt(),v<9e15&&(c[i++]=v%1e14);for(k=c[--i],dp%=LOG_BASE,k&&dp&&(v=POWS_TEN[LOG_BASE-dp],c[i]=mathfloor(k/v)*v);c[i]===0;c.pop(),i--);if(i<0)c=[e=0];else{for(e=-1;c[0]===0;c.splice(0,1),e-=LOG_BASE);for(i=1,v=c[0];v>=10;v/=10,i++);i<LOG_BASE&&(e-=LOG_BASE-i)}return rand.e=e,rand.c=c,rand}})(),BigNumber2.sum=function(){for(var i=1,args=arguments,sum=new BigNumber2(args[0]);i<args.length;)sum=sum.plus(args[i++]);return sum},convertBase=(function(){var decimal="0123456789";function toBaseOut(str,baseIn,baseOut,alphabet){for(var j,arr=[0],arrL,i=0,len=str.length;i<len;){for(arrL=arr.length;arrL--;arr[arrL]*=baseIn);for(arr[0]+=alphabet.indexOf(str.charAt(i++)),j=0;j<arr.length;j++)arr[j]>baseOut-1&&(arr[j+1]==null&&(arr[j+1]=0),arr[j+1]+=arr[j]/baseOut|0,arr[j]%=baseOut)}return arr.reverse()}return function(str,baseIn,baseOut,sign,callerIsToString){var alphabet,d,e,k,r,x,xc,y,i=str.indexOf("."),dp=DECIMAL_PLACES,rm=ROUNDING_MODE;for(i>=0&&(k=POW_PRECISION,POW_PRECISION=0,str=str.replace(".",""),y=new BigNumber2(baseIn),x=y.pow(str.length-i),POW_PRECISION=k,y.c=toBaseOut(toFixedPoint(coeffToString(x.c),x.e,"0"),10,baseOut,decimal),y.e=y.c.length),xc=toBaseOut(str,baseIn,baseOut,callerIsToString?(alphabet=ALPHABET,decimal):(alphabet=decimal,ALPHABET)),e=k=xc.length;xc[--k]==0;xc.pop());if(!xc[0])return alphabet.charAt(0);if(i<0?--e:(x.c=xc,x.e=e,x.s=sign,x=div(x,y,dp,rm,baseOut),xc=x.c,r=x.r,e=x.e),d=e+dp+1,i=xc[d],k=baseOut/2,r=r||d<0||xc[d+1]!=null,r=rm<4?(i!=null||r)&&(rm==0||rm==(x.s<0?3:2)):i>k||i==k&&(rm==4||r||rm==6&&xc[d-1]&1||rm==(x.s<0?8:7)),d<1||!xc[0])str=r?toFixedPoint(alphabet.charAt(1),-dp,alphabet.charAt(0)):alphabet.charAt(0);else{if(xc.length=d,r)for(--baseOut;++xc[--d]>baseOut;)xc[d]=0,d||(++e,xc=[1].concat(xc));for(k=xc.length;!xc[--k];);for(i=0,str="";i<=k;str+=alphabet.charAt(xc[i++]));str=toFixedPoint(str,e,alphabet.charAt(0))}return str}})(),div=(function(){function multiply(x,k,base){var m,temp,xlo,xhi,carry=0,i=x.length,klo=k%SQRT_BASE,khi=k/SQRT_BASE|0;for(x=x.slice();i--;)xlo=x[i]%SQRT_BASE,xhi=x[i]/SQRT_BASE|0,m=khi*xlo+xhi*klo,temp=klo*xlo+m%SQRT_BASE*SQRT_BASE+carry,carry=(temp/base|0)+(m/SQRT_BASE|0)+khi*xhi,x[i]=temp%base;return carry&&(x=[carry].concat(x)),x}function compare2(a,b,aL,bL){var i,cmp;if(aL!=bL)cmp=aL>bL?1:-1;else for(i=cmp=0;i<aL;i++)if(a[i]!=b[i]){cmp=a[i]>b[i]?1:-1;break}return cmp}function subtract(a,b,aL,base){for(var i=0;aL--;)a[aL]-=i,i=a[aL]<b[aL]?1:0,a[aL]=i*base+a[aL]-b[aL];for(;!a[0]&&a.length>1;a.splice(0,1));}return function(x,y,dp,rm,base){var cmp,e,i,more,n,prod,prodL,q,qc,rem,remL,rem0,xi,xL,yc0,yL,yz,s=x.s==y.s?1:-1,xc=x.c,yc=y.c;if(!xc||!xc[0]||!yc||!yc[0])return new BigNumber2(!x.s||!y.s||(xc?yc&&xc[0]==yc[0]:!yc)?NaN:xc&&xc[0]==0||!yc?s*0:s/0);for(q=new BigNumber2(s),qc=q.c=[],e=x.e-y.e,s=dp+e+1,base||(base=BASE,e=bitFloor(x.e/LOG_BASE)-bitFloor(y.e/LOG_BASE),s=s/LOG_BASE|0),i=0;yc[i]==(xc[i]||0);i++);if(yc[i]>(xc[i]||0)&&e--,s<0)qc.push(1),more=!0;else{for(xL=xc.length,yL=yc.length,i=0,s+=2,n=mathfloor(base/(yc[0]+1)),n>1&&(yc=multiply(yc,n,base),xc=multiply(xc,n,base),yL=yc.length,xL=xc.length),xi=yL,rem=xc.slice(0,yL),remL=rem.length;remL<yL;rem[remL++]=0);yz=yc.slice(),yz=[0].concat(yz),yc0=yc[0],yc[1]>=base/2&&yc0++;do{if(n=0,cmp=compare2(yc,rem,yL,remL),cmp<0){if(rem0=rem[0],yL!=remL&&(rem0=rem0*base+(rem[1]||0)),n=mathfloor(rem0/yc0),n>1)for(n>=base&&(n=base-1),prod=multiply(yc,n,base),prodL=prod.length,remL=rem.length;compare2(prod,rem,prodL,remL)==1;)n--,subtract(prod,yL<prodL?yz:yc,prodL,base),prodL=prod.length,cmp=1;else n==0&&(cmp=n=1),prod=yc.slice(),prodL=prod.length;if(prodL<remL&&(prod=[0].concat(prod)),subtract(rem,prod,remL,base),remL=rem.length,cmp==-1)for(;compare2(yc,rem,yL,remL)<1;)n++,subtract(rem,yL<remL?yz:yc,remL,base),remL=rem.length}else cmp===0&&(n++,rem=[0]);qc[i++]=n,rem[0]?rem[remL++]=xc[xi]||0:(rem=[xc[xi]],remL=1)}while((xi++<xL||rem[0]!=null)&&s--);more=rem[0]!=null,qc[0]||qc.splice(0,1)}if(base==BASE){for(i=1,s=qc[0];s>=10;s/=10,i++);round(q,dp+(q.e=i+e*LOG_BASE-1)+1,rm,more)}else q.e=e,q.r=+more;return q}})();function format(n,i,rm,id){var c0,e,ne,len,str;if(rm==null?rm=ROUNDING_MODE:intCheck(rm,0,8),!n.c)return n.toString();if(c0=n.c[0],ne=n.e,i==null)str=coeffToString(n.c),str=id==1||id==2&&(ne<=TO_EXP_NEG||ne>=TO_EXP_POS)?toExponential(str,ne):toFixedPoint(str,ne,"0");else if(n=round(new BigNumber2(n),i,rm),e=n.e,str=coeffToString(n.c),len=str.length,id==1||id==2&&(i<=e||e<=TO_EXP_NEG)){for(;len<i;str+="0",len++);str=toExponential(str,e)}else if(i-=ne+(id===2&&e>ne),str=toFixedPoint(str,e,"0"),e+1>len){if(--i>0)for(str+=".";i--;str+="0");}else if(i+=e-len,i>0)for(e+1==len&&(str+=".");i--;str+="0");return n.s<0&&c0?"-"+str:str}function maxOrMin(args,n){for(var k,y,i=1,x=new BigNumber2(args[0]);i<args.length;i++)y=new BigNumber2(args[i]),(!y.s||(k=compare(x,y))===n||k===0&&x.s===n)&&(x=y);return x}function normalise(n,c,e){for(var i=1,j=c.length;!c[--j];c.pop());for(j=c[0];j>=10;j/=10,i++);return(e=i+e*LOG_BASE-1)>MAX_EXP?n.c=n.e=null:e<MIN_EXP?n.c=[n.e=0]:(n.e=e,n.c=c),n}parseNumeric=(function(){var basePrefix=/^(-?)0([xbo])(?=\w[\w.]*$)/i,dotAfter=/^([^.]+)\.$/,dotBefore=/^\.([^.]+)$/,isInfinityOrNaN=/^-?(Infinity|NaN)$/,whitespaceOrPlus=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(x,str,isNum,b){var base,s=isNum?str:str.replace(whitespaceOrPlus,"");if(isInfinityOrNaN.test(s))x.s=isNaN(s)?null:s<0?-1:1;else{if(!isNum&&(s=s.replace(basePrefix,function(m,p1,p2){return base=(p2=p2.toLowerCase())=="x"?16:p2=="b"?2:8,!b||b==base?p1:m}),b&&(base=b,s=s.replace(dotAfter,"$1").replace(dotBefore,"0.$1")),str!=s))return new BigNumber2(s,base);if(BigNumber2.DEBUG)throw Error(bignumberError+"Not a"+(b?" base "+b:"")+" number: "+str);x.s=null}x.c=x.e=null}})();function round(x,sd,rm,r){var d,i,j,k,n,ni,rd,xc=x.c,pows10=POWS_TEN;if(xc){out:{for(d=1,k=xc[0];k>=10;k/=10,d++);if(i=sd-d,i<0)i+=LOG_BASE,j=sd,n=xc[ni=0],rd=mathfloor(n/pows10[d-j-1]%10);else if(ni=mathceil((i+1)/LOG_BASE),ni>=xc.length)if(r){for(;xc.length<=ni;xc.push(0));n=rd=0,d=1,i%=LOG_BASE,j=i-LOG_BASE+1}else break out;else{for(n=k=xc[ni],d=1;k>=10;k/=10,d++);i%=LOG_BASE,j=i-LOG_BASE+d,rd=j<0?0:mathfloor(n/pows10[d-j-1]%10)}if(r=r||sd<0||xc[ni+1]!=null||(j<0?n:n%pows10[d-j-1]),r=rm<4?(rd||r)&&(rm==0||rm==(x.s<0?3:2)):rd>5||rd==5&&(rm==4||r||rm==6&&(i>0?j>0?n/pows10[d-j]:0:xc[ni-1])%10&1||rm==(x.s<0?8:7)),sd<1||!xc[0])return xc.length=0,r?(sd-=x.e+1,xc[0]=pows10[(LOG_BASE-sd%LOG_BASE)%LOG_BASE],x.e=-sd||0):xc[0]=x.e=0,x;if(i==0?(xc.length=ni,k=1,ni--):(xc.length=ni+1,k=pows10[LOG_BASE-i],xc[ni]=j>0?mathfloor(n/pows10[d-j]%pows10[j])*k:0),r)for(;;)if(ni==0){for(i=1,j=xc[0];j>=10;j/=10,i++);for(j=xc[0]+=k,k=1;j>=10;j/=10,k++);i!=k&&(x.e++,xc[0]==BASE&&(xc[0]=1));break}else{if(xc[ni]+=k,xc[ni]!=BASE)break;xc[ni--]=0,k=1}for(i=xc.length;xc[--i]===0;xc.pop());}x.e>MAX_EXP?x.c=x.e=null:x.e<MIN_EXP&&(x.c=[x.e=0])}return x}function valueOf(n){var str,e=n.e;return e===null?n.toString():(str=coeffToString(n.c),str=e<=TO_EXP_NEG||e>=TO_EXP_POS?toExponential(str,e):toFixedPoint(str,e,"0"),n.s<0?"-"+str:str)}return P.absoluteValue=P.abs=function(){var x=new BigNumber2(this);return x.s<0&&(x.s=1),x},P.comparedTo=function(y,b){return compare(this,new BigNumber2(y,b))},P.decimalPlaces=P.dp=function(dp,rm){var c,n,v,x=this;if(dp!=null)return intCheck(dp,0,MAX),rm==null?rm=ROUNDING_MODE:intCheck(rm,0,8),round(new BigNumber2(x),dp+x.e+1,rm);if(!(c=x.c))return null;if(n=((v=c.length-1)-bitFloor(this.e/LOG_BASE))*LOG_BASE,v=c[v])for(;v%10==0;v/=10,n--);return n<0&&(n=0),n},P.dividedBy=P.div=function(y,b){return div(this,new BigNumber2(y,b),DECIMAL_PLACES,ROUNDING_MODE)},P.dividedToIntegerBy=P.idiv=function(y,b){return div(this,new BigNumber2(y,b),0,1)},P.exponentiatedBy=P.pow=function(n,m){var half,isModExp,i,k,more,nIsBig,nIsNeg,nIsOdd,y,x=this;if(n=new BigNumber2(n),n.c&&!n.isInteger())throw Error(bignumberError+"Exponent not an integer: "+valueOf(n));if(m!=null&&(m=new BigNumber2(m)),nIsBig=n.e>14,!x.c||!x.c[0]||x.c[0]==1&&!x.e&&x.c.length==1||!n.c||!n.c[0])return y=new BigNumber2(Math.pow(+valueOf(x),nIsBig?n.s*(2-isOdd(n)):+valueOf(n))),m?y.mod(m):y;if(nIsNeg=n.s<0,m){if(m.c?!m.c[0]:!m.s)return new BigNumber2(NaN);isModExp=!nIsNeg&&x.isInteger()&&m.isInteger(),isModExp&&(x=x.mod(m))}else{if(n.e>9&&(x.e>0||x.e<-1||(x.e==0?x.c[0]>1||nIsBig&&x.c[1]>=24e7:x.c[0]<8e13||nIsBig&&x.c[0]<=9999975e7)))return k=x.s<0&&isOdd(n)?-0:0,x.e>-1&&(k=1/k),new BigNumber2(nIsNeg?1/k:k);POW_PRECISION&&(k=mathceil(POW_PRECISION/LOG_BASE+2))}for(nIsBig?(half=new BigNumber2(.5),nIsNeg&&(n.s=1),nIsOdd=isOdd(n)):(i=Math.abs(+valueOf(n)),nIsOdd=i%2),y=new BigNumber2(ONE);;){if(nIsOdd){if(y=y.times(x),!y.c)break;k?y.c.length>k&&(y.c.length=k):isModExp&&(y=y.mod(m))}if(i){if(i=mathfloor(i/2),i===0)break;nIsOdd=i%2}else if(n=n.times(half),round(n,n.e+1,1),n.e>14)nIsOdd=isOdd(n);else{if(i=+valueOf(n),i===0)break;nIsOdd=i%2}x=x.times(x),k?x.c&&x.c.length>k&&(x.c.length=k):isModExp&&(x=x.mod(m))}return isModExp?y:(nIsNeg&&(y=ONE.div(y)),m?y.mod(m):k?round(y,POW_PRECISION,ROUNDING_MODE,more):y)},P.integerValue=function(rm){var n=new BigNumber2(this);return rm==null?rm=ROUNDING_MODE:intCheck(rm,0,8),round(n,n.e+1,rm)},P.isEqualTo=P.eq=function(y,b){return compare(this,new BigNumber2(y,b))===0},P.isFinite=function(){return!!this.c},P.isGreaterThan=P.gt=function(y,b){return compare(this,new BigNumber2(y,b))>0},P.isGreaterThanOrEqualTo=P.gte=function(y,b){return(b=compare(this,new BigNumber2(y,b)))===1||b===0},P.isInteger=function(){return!!this.c&&bitFloor(this.e/LOG_BASE)>this.c.length-2},P.isLessThan=P.lt=function(y,b){return compare(this,new BigNumber2(y,b))<0},P.isLessThanOrEqualTo=P.lte=function(y,b){return(b=compare(this,new BigNumber2(y,b)))===-1||b===0},P.isNaN=function(){return!this.s},P.isNegative=function(){return this.s<0},P.isPositive=function(){return this.s>0},P.isZero=function(){return!!this.c&&this.c[0]==0},P.minus=function(y,b){var i,j,t,xLTy,x=this,a=x.s;if(y=new BigNumber2(y,b),b=y.s,!a||!b)return new BigNumber2(NaN);if(a!=b)return y.s=-b,x.plus(y);var xe=x.e/LOG_BASE,ye=y.e/LOG_BASE,xc=x.c,yc=y.c;if(!xe||!ye){if(!xc||!yc)return xc?(y.s=-b,y):new BigNumber2(yc?x:NaN);if(!xc[0]||!yc[0])return yc[0]?(y.s=-b,y):new BigNumber2(xc[0]?x:ROUNDING_MODE==3?-0:0)}if(xe=bitFloor(xe),ye=bitFloor(ye),xc=xc.slice(),a=xe-ye){for((xLTy=a<0)?(a=-a,t=xc):(ye=xe,t=yc),t.reverse(),b=a;b--;t.push(0));t.reverse()}else for(j=(xLTy=(a=xc.length)<(b=yc.length))?a:b,a=b=0;b<j;b++)if(xc[b]!=yc[b]){xLTy=xc[b]<yc[b];break}if(xLTy&&(t=xc,xc=yc,yc=t,y.s=-y.s),b=(j=yc.length)-(i=xc.length),b>0)for(;b--;xc[i++]=0);for(b=BASE-1;j>a;){if(xc[--j]<yc[j]){for(i=j;i&&!xc[--i];xc[i]=b);--xc[i],xc[j]+=BASE}xc[j]-=yc[j]}for(;xc[0]==0;xc.splice(0,1),--ye);return xc[0]?normalise(y,xc,ye):(y.s=ROUNDING_MODE==3?-1:1,y.c=[y.e=0],y)},P.modulo=P.mod=function(y,b){var q,s,x=this;return y=new BigNumber2(y,b),!x.c||!y.s||y.c&&!y.c[0]?new BigNumber2(NaN):!y.c||x.c&&!x.c[0]?new BigNumber2(x):(MODULO_MODE==9?(s=y.s,y.s=1,q=div(x,y,0,3),y.s=s,q.s*=s):q=div(x,y,0,MODULO_MODE),y=x.minus(q.times(y)),!y.c[0]&&MODULO_MODE==1&&(y.s=x.s),y)},P.multipliedBy=P.times=function(y,b){var c,e,i,j,k,m,xcL,xlo,xhi,ycL,ylo,yhi,zc,base,sqrtBase,x=this,xc=x.c,yc=(y=new BigNumber2(y,b)).c;if(!xc||!yc||!xc[0]||!yc[0])return!x.s||!y.s||xc&&!xc[0]&&!yc||yc&&!yc[0]&&!xc?y.c=y.e=y.s=null:(y.s*=x.s,!xc||!yc?y.c=y.e=null:(y.c=[0],y.e=0)),y;for(e=bitFloor(x.e/LOG_BASE)+bitFloor(y.e/LOG_BASE),y.s*=x.s,xcL=xc.length,ycL=yc.length,xcL<ycL&&(zc=xc,xc=yc,yc=zc,i=xcL,xcL=ycL,ycL=i),i=xcL+ycL,zc=[];i--;zc.push(0));for(base=BASE,sqrtBase=SQRT_BASE,i=ycL;--i>=0;){for(c=0,ylo=yc[i]%sqrtBase,yhi=yc[i]/sqrtBase|0,k=xcL,j=i+k;j>i;)xlo=xc[--k]%sqrtBase,xhi=xc[k]/sqrtBase|0,m=yhi*xlo+xhi*ylo,xlo=ylo*xlo+m%sqrtBase*sqrtBase+zc[j]+c,c=(xlo/base|0)+(m/sqrtBase|0)+yhi*xhi,zc[j--]=xlo%base;zc[j]=c}return c?++e:zc.splice(0,1),normalise(y,zc,e)},P.negated=function(){var x=new BigNumber2(this);return x.s=-x.s||null,x},P.plus=function(y,b){var t,x=this,a=x.s;if(y=new BigNumber2(y,b),b=y.s,!a||!b)return new BigNumber2(NaN);if(a!=b)return y.s=-b,x.minus(y);var xe=x.e/LOG_BASE,ye=y.e/LOG_BASE,xc=x.c,yc=y.c;if(!xe||!ye){if(!xc||!yc)return new BigNumber2(a/0);if(!xc[0]||!yc[0])return yc[0]?y:new BigNumber2(xc[0]?x:a*0)}if(xe=bitFloor(xe),ye=bitFloor(ye),xc=xc.slice(),a=xe-ye){for(a>0?(ye=xe,t=yc):(a=-a,t=xc),t.reverse();a--;t.push(0));t.reverse()}for(a=xc.length,b=yc.length,a-b<0&&(t=yc,yc=xc,xc=t,b=a),a=0;b;)a=(xc[--b]=xc[b]+yc[b]+a)/BASE|0,xc[b]=BASE===xc[b]?0:xc[b]%BASE;return a&&(xc=[a].concat(xc),++ye),normalise(y,xc,ye)},P.precision=P.sd=function(sd,rm){var c,n,v,x=this;if(sd!=null&&sd!==!!sd)return intCheck(sd,1,MAX),rm==null?rm=ROUNDING_MODE:intCheck(rm,0,8),round(new BigNumber2(x),sd,rm);if(!(c=x.c))return null;if(v=c.length-1,n=v*LOG_BASE+1,v=c[v]){for(;v%10==0;v/=10,n--);for(v=c[0];v>=10;v/=10,n++);}return sd&&x.e+1>n&&(n=x.e+1),n},P.shiftedBy=function(k){return intCheck(k,-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER),this.times("1e"+k)},P.squareRoot=P.sqrt=function(){var m,n,r,rep,t,x=this,c=x.c,s=x.s,e=x.e,dp=DECIMAL_PLACES+4,half=new BigNumber2("0.5");if(s!==1||!c||!c[0])return new BigNumber2(!s||s<0&&(!c||c[0])?NaN:c?x:1/0);if(s=Math.sqrt(+valueOf(x)),s==0||s==1/0?(n=coeffToString(c),(n.length+e)%2==0&&(n+="0"),s=Math.sqrt(+n),e=bitFloor((e+1)/2)-(e<0||e%2),s==1/0?n="5e"+e:(n=s.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new BigNumber2(n)):r=new BigNumber2(s+""),r.c[0]){for(e=r.e,s=e+dp,s<3&&(s=0);;)if(t=r,r=half.times(t.plus(div(x,t,dp,1))),coeffToString(t.c).slice(0,s)===(n=coeffToString(r.c)).slice(0,s))if(r.e<e&&--s,n=n.slice(s-3,s+1),n=="9999"||!rep&&n=="4999"){if(!rep&&(round(t,t.e+DECIMAL_PLACES+2,0),t.times(t).eq(x))){r=t;break}dp+=4,s+=4,rep=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(round(r,r.e+DECIMAL_PLACES+2,1),m=!r.times(r).eq(x));break}}return round(r,r.e+DECIMAL_PLACES+1,ROUNDING_MODE,m)},P.toExponential=function(dp,rm){return dp!=null&&(intCheck(dp,0,MAX),dp++),format(this,dp,rm,1)},P.toFixed=function(dp,rm){return dp!=null&&(intCheck(dp,0,MAX),dp=dp+this.e+1),format(this,dp,rm)},P.toFormat=function(dp,rm,format2){var str,x=this;if(format2==null)dp!=null&&rm&&typeof rm=="object"?(format2=rm,rm=null):dp&&typeof dp=="object"?(format2=dp,dp=rm=null):format2=FORMAT;else if(typeof format2!="object")throw Error(bignumberError+"Argument not an object: "+format2);if(str=x.toFixed(dp,rm),x.c){var i,arr=str.split("."),g1=+format2.groupSize,g2=+format2.secondaryGroupSize,groupSeparator=format2.groupSeparator||"",intPart=arr[0],fractionPart=arr[1],isNeg=x.s<0,intDigits=isNeg?intPart.slice(1):intPart,len=intDigits.length;if(g2&&(i=g1,g1=g2,g2=i,len-=i),g1>0&&len>0){for(i=len%g1||g1,intPart=intDigits.substr(0,i);i<len;i+=g1)intPart+=groupSeparator+intDigits.substr(i,g1);g2>0&&(intPart+=groupSeparator+intDigits.slice(i)),isNeg&&(intPart="-"+intPart)}str=fractionPart?intPart+(format2.decimalSeparator||"")+((g2=+format2.fractionGroupSize)?fractionPart.replace(new RegExp("\\d{"+g2+"}\\B","g"),"$&"+(format2.fractionGroupSeparator||"")):fractionPart):intPart}return(format2.prefix||"")+str+(format2.suffix||"")},P.toFraction=function(md){var d,d0,d1,d2,e,exp,n,n0,n1,q,r,s,x=this,xc=x.c;if(md!=null&&(n=new BigNumber2(md),!n.isInteger()&&(n.c||n.s!==1)||n.lt(ONE)))throw Error(bignumberError+"Argument "+(n.isInteger()?"out of range: ":"not an integer: ")+valueOf(n));if(!xc)return new BigNumber2(x);for(d=new BigNumber2(ONE),n1=d0=new BigNumber2(ONE),d1=n0=new BigNumber2(ONE),s=coeffToString(xc),e=d.e=s.length-x.e-1,d.c[0]=POWS_TEN[(exp=e%LOG_BASE)<0?LOG_BASE+exp:exp],md=!md||n.comparedTo(d)>0?e>0?d:n1:n,exp=MAX_EXP,MAX_EXP=1/0,n=new BigNumber2(s),n0.c[0]=0;q=div(n,d,0,1),d2=d0.plus(q.times(d1)),d2.comparedTo(md)!=1;)d0=d1,d1=d2,n1=n0.plus(q.times(d2=n1)),n0=d2,d=n.minus(q.times(d2=d)),n=d2;return d2=div(md.minus(d0),d1,0,1),n0=n0.plus(d2.times(n1)),d0=d0.plus(d2.times(d1)),n0.s=n1.s=x.s,e=e*2,r=div(n1,d1,e,ROUNDING_MODE).minus(x).abs().comparedTo(div(n0,d0,e,ROUNDING_MODE).minus(x).abs())<1?[n1,d1]:[n0,d0],MAX_EXP=exp,r},P.toNumber=function(){return+valueOf(this)},P.toPrecision=function(sd,rm){return sd!=null&&intCheck(sd,1,MAX),format(this,sd,rm,2)},P.toString=function(b){var str,n=this,s=n.s,e=n.e;return e===null?s?(str="Infinity",s<0&&(str="-"+str)):str="NaN":(b==null?str=e<=TO_EXP_NEG||e>=TO_EXP_POS?toExponential(coeffToString(n.c),e):toFixedPoint(coeffToString(n.c),e,"0"):b===10&&alphabetHasNormalDecimalDigits?(n=round(new BigNumber2(n),DECIMAL_PLACES+e+1,ROUNDING_MODE),str=toFixedPoint(coeffToString(n.c),n.e,"0")):(intCheck(b,2,ALPHABET.length,"Base"),str=convertBase(toFixedPoint(coeffToString(n.c),e,"0"),10,b,s,!0)),s<0&&n.c[0]&&(str="-"+str)),str},P.valueOf=P.toJSON=function(){return valueOf(this)},P._isBigNumber=!0,configObject!=null&&BigNumber2.set(configObject),BigNumber2}function bitFloor(n){var i=n|0;return n>0||n===i?i:i-1}function coeffToString(a){for(var s,z,i=1,j=a.length,r=a[0]+"";i<j;){for(s=a[i++]+"",z=LOG_BASE-s.length;z--;s="0"+s);r+=s}for(j=r.length;r.charCodeAt(--j)===48;);return r.slice(0,j+1||1)}function compare(x,y){var a,b,xc=x.c,yc=y.c,i=x.s,j=y.s,k=x.e,l=y.e;if(!i||!j)return null;if(a=xc&&!xc[0],b=yc&&!yc[0],a||b)return a?b?0:-j:i;if(i!=j)return i;if(a=i<0,b=k==l,!xc||!yc)return b?0:!xc^a?1:-1;if(!b)return k>l^a?1:-1;for(j=(k=xc.length)<(l=yc.length)?k:l,i=0;i<j;i++)if(xc[i]!=yc[i])return xc[i]>yc[i]^a?1:-1;return k==l?0:k>l^a?1:-1}function intCheck(n,min,max,name){if(n<min||n>max||n!==mathfloor(n))throw Error(bignumberError+(name||"Argument")+(typeof n=="number"?n<min||n>max?" out of range: ":" not an integer: ":" not a primitive number: ")+String(n))}function isOdd(n){var k=n.c.length-1;return bitFloor(n.e/LOG_BASE)==k&&n.c[k]%2!=0}function toExponential(str,e){return(str.length>1?str.charAt(0)+"."+str.slice(1):str)+(e<0?"e":"e+")+e}function toFixedPoint(str,e,z){var len,zs;if(e<0){for(zs=z+".";++e;zs+=z);str=zs+str}else if(len=str.length,++e>len){for(zs=z,e-=len;--e;zs+=z);str+=zs}else e<len&&(str=str.slice(0,e)+"."+str.slice(e));return str}BigNumber=clone(),BigNumber.default=BigNumber.BigNumber=BigNumber,typeof define=="function"&&define.amd?define(function(){return BigNumber}):typeof module<"u"&&module.exports?module.exports=BigNumber:(globalObject||(globalObject=typeof self<"u"&&self?self:window),globalObject.BigNumber=BigNumber)})(exports)}});var require_stringify=__commonJS({"node_modules/json-bigint/lib/stringify.js"(exports,module){var BigNumber=require_bignumber(),JSON2=module.exports;(function(){"use strict";function f(n){return n<10?"0"+n:n}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;function quote(string){return escapable.lastIndex=0,escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c=="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key],isBigNumber=value!=null&&(value instanceof BigNumber||BigNumber.isBigNumber(value));switch(value&&typeof value=="object"&&typeof value.toJSON=="function"&&(value=value.toJSON(key)),typeof rep=="function"&&(value=rep.call(holder,key,value)),typeof value){case"string":return isBigNumber?value:quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":case"bigint":return String(value);case"object":if(!value)return"null";if(gap+=indent,partial=[],Object.prototype.toString.apply(value)==="[object Array]"){for(length=value.length,i=0;i<length;i+=1)partial[i]=str(i,value)||"null";return v=partial.length===0?"[]":gap?`[
|
|
8
8
|
`+gap+partial.join(`,
|
|
9
9
|
`+gap)+`
|
|
10
10
|
`+mind+"]":"["+partial.join(",")+"]",gap=mind,v}if(rep&&typeof rep=="object")for(length=rep.length,i=0;i<length;i+=1)typeof rep[i]=="string"&&(k=rep[i],v=str(k,value),v&&partial.push(quote(k)+(gap?": ":":")+v));else Object.keys(value).forEach(function(k2){var v2=str(k2,value);v2&&partial.push(quote(k2)+(gap?": ":":")+v2)});return v=partial.length===0?"{}":gap?`{
|
package/dist/bundle/chunks/{google-generative-ai-XT7NQJ2E.js → google-generative-ai-FF7M7XHT.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{GoogleGenAI,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling}from"./chunk-
|
|
2
|
+
import{GoogleGenAI,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling}from"./chunk-PSKDLDLZ.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-XNGRGP62.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-TXBQIIIO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-6R7UI4IY.js";import{calculateCost,clampThinkingLevel}from"./chunk-WJZ4KLGL.js";import{AssistantMessageEventStream}from"./chunk-72KO4OMP.js";import"./chunk-JXWJOIH4.js";var toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:"google-generative-ai",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options?.headers),params=buildParams(model,context,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning),resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning),googleModel=model;return isGemini3ProModel(googleModel)||isGemini3FlashModel(googleModel)||isGemma4Model(googleModel)?stream(model,context,{...base,thinking:{enabled:!0,level:getThinkingLevel(resolvedLevel,googleModel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(googleModel,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,apiKey,optionsHeaders){let httpOptions={};model.baseUrl&&(httpOptions.baseUrl=model.baseUrl,httpOptions.apiVersion="");let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),new GoogleGenAI({apiKey,httpOptions:Object.keys(httpOptions).length>0?httpOptions:void 0})}function buildParams(model,context,options={}){let contents=convertMessages(model,context),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=context.tools?.length?resolveGoogleFunctionCallingMode(context.tools,options.toolChoice,supportsStrictMode):void 0,config={...Object.keys(generationConfig).length>0&&generationConfig,...context.systemPrompt&&{systemInstruction:sanitizeSurrogates(context.systemPrompt)},...context.tools&&context.tools.length>0&&{tools:convertTools(context.tools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=options.thinking.level:options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function isGemma4Model(model){return/gemma-?4/.test(model.id.toLowerCase())}function isGemini3ProModel(model){return/gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase())}function isGemini3FlashModel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"}function getDisabledThinkingConfig(model){return isGemini3ProModel(model)?{thinkingLevel:"LOW"}:isGemini3FlashModel(model)?{thinkingLevel:"MINIMAL"}:isGemma4Model(model)?{thinkingLevel:"MINIMAL"}:{thinkingBudget:0}}function getThinkingLevel(effort,model){if(isGemini3ProModel(model))switch(effort){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}if(isGemma4Model(model))switch(effort){case"minimal":case"low":return"MINIMAL";case"medium":case"high":return"HIGH"}switch(effort){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{GoogleGenAI,ResourceScope,ThinkingLevel,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling}from"./chunk-M2GYSCCG.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-XNGRGP62.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-TXBQIIIO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-6R7UI4IY.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{calculateCost,clampThinkingLevel}from"./chunk-WJZ4KLGL.js";import{AssistantMessageEventStream}from"./chunk-72KO4OMP.js";import"./chunk-JXWJOIH4.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",THINKING_LEVEL_MAP={THINKING_LEVEL_UNSPECIFIED:ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ThinkingLevel.MINIMAL,LOW:ThinkingLevel.LOW,MEDIUM:ThinkingLevel.MEDIUM,HIGH:ThinkingLevel.HIGH},toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:"google-vertex",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let apiKey=resolveApiKey(options),client=apiKey?createClientWithApiKey(model,apiKey,options?.headers):createClient(model,resolveProject(options),resolveLocation(options),options?.headers,options?.env),params=buildParams(model,context,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning),resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning),geminiModel=model;return isGemini3ProModel(geminiModel)||isGemini3FlashModel(geminiModel)?stream(model,context,{...base,thinking:{enabled:!0,level:getGemini3ThinkingLevel(resolvedLevel,geminiModel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(geminiModel,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,project,location,optionsHeaders,env){let googleAuthOptions=buildGoogleAuthOptions(env);return new GoogleGenAI({vertexai:!0,project,location,apiVersion:API_VERSION,...googleAuthOptions?{googleAuthOptions}:{},httpOptions:buildHttpOptions(model,optionsHeaders)})}function createClientWithApiKey(model,apiKey,optionsHeaders){return new GoogleGenAI({vertexai:!0,apiKey,apiVersion:API_VERSION,httpOptions:buildHttpOptions(model,optionsHeaders)})}function buildHttpOptions(model,optionsHeaders){let httpOptions={},baseUrl=resolveCustomBaseUrl(model.baseUrl);baseUrl&&(httpOptions.baseUrl=baseUrl,httpOptions.baseUrlResourceScope=ResourceScope.COLLECTION,baseUrlIncludesApiVersion(baseUrl)&&(httpOptions.apiVersion=""));let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),Object.keys(httpOptions).length>0?httpOptions:void 0}function resolveCustomBaseUrl(baseUrl){let trimmed=baseUrl.trim();if(!(!trimmed||trimmed.includes("{location}")))return trimmed}function baseUrlIncludesApiVersion(baseUrl){try{return new URL(baseUrl).pathname.split("/").some(part=>/^v\d+(?:beta\d*)?$/.test(part))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl)}}function buildGoogleAuthOptions(env){let keyFilename=getProviderEnvValue("GOOGLE_APPLICATION_CREDENTIALS",env);return keyFilename?{keyFilename}:void 0}function resolveApiKey(options){let apiKey=options?.apiKey?.trim();if(!(!apiKey||apiKey===GCP_VERTEX_CREDENTIALS_MARKER||isPlaceholderApiKey(apiKey)))return apiKey}function isPlaceholderApiKey(apiKey){return/^<[^>]+>$/.test(apiKey)}function resolveProject(options){let project=options?.project||getProviderEnvValue("GOOGLE_CLOUD_PROJECT",options?.env)||getProviderEnvValue("GCLOUD_PROJECT",options?.env);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return project}function resolveLocation(options){let location=options?.location||getProviderEnvValue("GOOGLE_CLOUD_LOCATION",options?.env);if(!location)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return location}function buildParams(model,context,options={}){let contents=convertMessages(model,context),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=context.tools?.length?resolveGoogleFunctionCallingMode(context.tools,options.toolChoice,supportsStrictMode):void 0,config={...Object.keys(generationConfig).length>0&&generationConfig,...context.systemPrompt&&{systemInstruction:sanitizeSurrogates(context.systemPrompt)},...context.tools&&context.tools.length>0&&{tools:convertTools(context.tools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=THINKING_LEVEL_MAP[options.thinking.level]:options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function isGemini3ProModel(model){return/gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase())}function isGemini3FlashModel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"}function getDisabledThinkingConfig(model){let geminiModel=model;return isGemini3ProModel(geminiModel)?{thinkingLevel:ThinkingLevel.LOW}:isGemini3FlashModel(geminiModel)?{thinkingLevel:ThinkingLevel.MINIMAL}:{thinkingBudget:0}}function getGemini3ThinkingLevel(effort,model){if(isGemini3ProModel(model))switch(effort){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(effort){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
|
2
|
+
import{GoogleGenAI,ResourceScope,ThinkingLevel,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling}from"./chunk-PSKDLDLZ.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-XNGRGP62.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-TXBQIIIO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-6R7UI4IY.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{calculateCost,clampThinkingLevel}from"./chunk-WJZ4KLGL.js";import{AssistantMessageEventStream}from"./chunk-72KO4OMP.js";import"./chunk-JXWJOIH4.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",THINKING_LEVEL_MAP={THINKING_LEVEL_UNSPECIFIED:ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ThinkingLevel.MINIMAL,LOW:ThinkingLevel.LOW,MEDIUM:ThinkingLevel.MEDIUM,HIGH:ThinkingLevel.HIGH},toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:"google-vertex",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let apiKey=resolveApiKey(options),client=apiKey?createClientWithApiKey(model,apiKey,options?.headers):createClient(model,resolveProject(options),resolveLocation(options),options?.headers,options?.env),params=buildParams(model,context,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning),resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning),geminiModel=model;return isGemini3ProModel(geminiModel)||isGemini3FlashModel(geminiModel)?stream(model,context,{...base,thinking:{enabled:!0,level:getGemini3ThinkingLevel(resolvedLevel,geminiModel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(geminiModel,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,project,location,optionsHeaders,env){let googleAuthOptions=buildGoogleAuthOptions(env);return new GoogleGenAI({vertexai:!0,project,location,apiVersion:API_VERSION,...googleAuthOptions?{googleAuthOptions}:{},httpOptions:buildHttpOptions(model,optionsHeaders)})}function createClientWithApiKey(model,apiKey,optionsHeaders){return new GoogleGenAI({vertexai:!0,apiKey,apiVersion:API_VERSION,httpOptions:buildHttpOptions(model,optionsHeaders)})}function buildHttpOptions(model,optionsHeaders){let httpOptions={},baseUrl=resolveCustomBaseUrl(model.baseUrl);baseUrl&&(httpOptions.baseUrl=baseUrl,httpOptions.baseUrlResourceScope=ResourceScope.COLLECTION,baseUrlIncludesApiVersion(baseUrl)&&(httpOptions.apiVersion=""));let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),Object.keys(httpOptions).length>0?httpOptions:void 0}function resolveCustomBaseUrl(baseUrl){let trimmed=baseUrl.trim();if(!(!trimmed||trimmed.includes("{location}")))return trimmed}function baseUrlIncludesApiVersion(baseUrl){try{return new URL(baseUrl).pathname.split("/").some(part=>/^v\d+(?:beta\d*)?$/.test(part))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl)}}function buildGoogleAuthOptions(env){let keyFilename=getProviderEnvValue("GOOGLE_APPLICATION_CREDENTIALS",env);return keyFilename?{keyFilename}:void 0}function resolveApiKey(options){let apiKey=options?.apiKey?.trim();if(!(!apiKey||apiKey===GCP_VERTEX_CREDENTIALS_MARKER||isPlaceholderApiKey(apiKey)))return apiKey}function isPlaceholderApiKey(apiKey){return/^<[^>]+>$/.test(apiKey)}function resolveProject(options){let project=options?.project||getProviderEnvValue("GOOGLE_CLOUD_PROJECT",options?.env)||getProviderEnvValue("GCLOUD_PROJECT",options?.env);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return project}function resolveLocation(options){let location=options?.location||getProviderEnvValue("GOOGLE_CLOUD_LOCATION",options?.env);if(!location)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return location}function buildParams(model,context,options={}){let contents=convertMessages(model,context),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=context.tools?.length?resolveGoogleFunctionCallingMode(context.tools,options.toolChoice,supportsStrictMode):void 0,config={...Object.keys(generationConfig).length>0&&generationConfig,...context.systemPrompt&&{systemInstruction:sanitizeSurrogates(context.systemPrompt)},...context.tools&&context.tools.length>0&&{tools:convertTools(context.tools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=THINKING_LEVEL_MAP[options.thinking.level]:options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function isGemini3ProModel(model){return/gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase())}function isGemini3FlashModel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"}function getDisabledThinkingConfig(model){let geminiModel=model;return isGemini3ProModel(geminiModel)?{thinkingLevel:ThinkingLevel.LOW}:isGemini3FlashModel(geminiModel)?{thinkingLevel:ThinkingLevel.MINIMAL}:{thinkingBudget:0}}function getGemini3ThinkingLevel(effort,model){if(isGemini3ProModel(model))switch(effort){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(effort){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{HttpsProxyAgent,init_dist3 as init_dist}from"./chunk-74NVHVNZ.js";import{__esm}from"./chunk-JXWJOIH4.js";var init_https_proxy_agent=__esm({"https-proxy-agent-named-export:https-proxy-agent"(){init_dist()}});init_https_proxy_agent();export{HttpsProxyAgent};
|
package/dist/bundle/chunks/{mistral-conversations-HHDZ4FHR.js → mistral-conversations-O4M7IQML.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
2
|
import{shortHash}from"./chunk-PJACZCIR.js";import{buildBaseOptions,getJsonSchemaToolParameters,getPiUserAgent,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-TXBQIIIO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-6R7UI4IY.js";import{parseStreamingJson}from"./chunk-D7XAASZM.js";import{calculateCost,clampThinkingLevel}from"./chunk-WJZ4KLGL.js";import{AssistantMessageEventStream}from"./chunk-72KO4OMP.js";import"./chunk-JXWJOIH4.js";var MISTRAL_TOOL_CALL_ID_LENGTH=9,MAX_MISTRAL_ERROR_BODY_CHARS=4e3,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output=createOutput(model);try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let normalizeMistralToolCallId=createMistralToolCallIdNormalizer(),transformedMessages=transformMessages(context.messages,model,id=>normalizeMistralToolCallId(id)),payload=buildChatPayload(model,context,transformedMessages,options),nextPayload=await options?.onPayload?.(payload,model);nextPayload!==void 0&&(payload=nextPayload);let mistralStream=await requestMistralStream(model,payload,apiKey,options);if(stream2.push({type:"start",partial:output}),await consumeChatStream(model,output,stream2,mistralStream),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Mistral stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialArgs;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatMistralError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0,reasoning=clampedReasoning==="off"?void 0:clampedReasoning,shouldUseReasoning=model.reasoning&&reasoning!==void 0;return stream(model,context,{...base,promptMode:shouldUseReasoning&&usesPromptModeReasoning(model)?"reasoning":void 0,reasoningEffort:shouldUseReasoning&&usesReasoningEffort(model)?mapReasoningEffort(model,reasoning):void 0})};function createOutput(model){return{role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()}}function createMistralToolCallIdNormalizer(){let idMap=new Map,reverseMap=new Map;return id=>{let existing=idMap.get(id);if(existing)return existing;let attempt=0;for(;;){let candidate=deriveMistralToolCallId(id,attempt),owner=reverseMap.get(candidate);if(!owner||owner===id)return idMap.set(id,candidate),reverseMap.set(candidate,id),candidate;attempt++}}}function deriveMistralToolCallId(id,attempt){let normalized=id.replace(/[^a-zA-Z0-9]/g,"");if(attempt===0&&normalized.length===MISTRAL_TOOL_CALL_ID_LENGTH)return normalized;let seedBase=normalized||id,seed=attempt===0?seedBase:`${seedBase}:${attempt}`;return shortHash(seed).replace(/[^a-zA-Z0-9]/g,"").slice(0,MISTRAL_TOOL_CALL_ID_LENGTH)}function formatMistralError(error){if(error instanceof Error){let httpError=error,statusCode=typeof httpError.statusCode=="number"?httpError.statusCode:void 0,bodyText=typeof httpError.body=="string"?httpError.body.trim():void 0;return statusCode!==void 0&&bodyText?`Mistral API error (${statusCode}): ${truncateErrorText(bodyText,MAX_MISTRAL_ERROR_BODY_CHARS)}`:statusCode!==void 0?`Mistral API error (${statusCode}): ${error.message}`:error.message}return safeJsonStringify(error)}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}async function requestMistralStream(model,payload,apiKey,options){let baseUrl=new URL(model.baseUrl);baseUrl.pathname=`${baseUrl.pathname.replace(/\/+$/u,"")}/`;let url=new URL("v1/chat/completions",baseUrl),headers=buildMistralHeaders(model,apiKey,options),timeoutSignal=AbortSignal.timeout(options?.timeoutMs??6e4),signal=options?.signal?AbortSignal.any([options.signal,timeoutSignal]):timeoutSignal,response=await(options?.fetch??globalThis.fetch)(url,{method:"POST",headers,body:JSON.stringify(toMistralWirePayload(payload)),signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),!response.ok){let body=await response.text();throw new MistralHttpError(response.status,body,response.statusText)}if(!response.body)throw new Error("Mistral response has no body");return readMistralEvents(response.body,signal)}var MistralHttpError=class extends Error{constructor(statusCode,body,statusText){super(statusText||`Request failed with status ${statusCode}`),this.name="MistralHttpError",this.statusCode=statusCode,this.body=body}};function buildMistralHeaders(model,apiKey,options){let headers=new Headers({"User-Agent":getPiUserAgent(),accept:"text/event-stream",authorization:`Bearer ${apiKey}`,"content-type":"application/json"});applyMistralHeaderOverrides(headers,model.headers),applyMistralHeaderOverrides(headers,options?.headers);let hasExplicitAffinity=hasMistralHeaderOverride(model.headers,"x-affinity")||hasMistralHeaderOverride(options?.headers,"x-affinity");return shouldUsePromptCaching(options)&&!hasExplicitAffinity&&headers.set("x-affinity",options.sessionId),headers}function applyMistralHeaderOverrides(headers,overrides){if(overrides)for(let[name,value]of Object.entries(overrides))value===null?headers.delete(name):headers.set(name,value)}function hasMistralHeaderOverride(overrides,target){return!!overrides&&Object.keys(overrides).some(name=>name.toLowerCase()===target)}function toMistralWirePayload(payload){let wirePayload={...payload};for(let[source,target]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])remapMistralProperty(wirePayload,source,target);wirePayload.messages=payload.messages.map(message=>toMistralWireMessage(message));let responseFormat=wirePayload.response_format;if(isMistralRecord(responseFormat)){let wireResponseFormat={...responseFormat};remapMistralProperty(wireResponseFormat,"jsonSchema","json_schema");let jsonSchema=wireResponseFormat.json_schema;if(isMistralRecord(jsonSchema)){let wireJsonSchema={...jsonSchema};remapMistralProperty(wireJsonSchema,"schemaDefinition","schema"),wireResponseFormat.json_schema=wireJsonSchema}wirePayload.response_format=wireResponseFormat}return wirePayload}function toMistralWireMessage(message){let wireMessage={...message};return remapMistralProperty(wireMessage,"toolCalls","tool_calls"),remapMistralProperty(wireMessage,"toolCallId","tool_call_id"),Array.isArray(message.content)&&(wireMessage.content=message.content.map(chunk=>toMistralWireContentChunk(chunk))),wireMessage}function toMistralWireContentChunk(chunk){let wireChunk={...chunk};for(let[source,target]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])remapMistralProperty(wireChunk,source,target);return wireChunk}function remapMistralProperty(record,source,target){source in record&&(record[target]=record[source],delete record[source])}function isMistralRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var MISTRAL_STREAM_DONE=Symbol("mistral-stream-done");async function*readMistralEvents(body,signal){let reader=body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal.aborted)throw signal.reason;let{done,value}=await reader.read();if(signal.aborted)throw signal.reason;buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});let boundary=findMistralEventBoundary(buffer);for(;boundary;){let event=parseMistralEvent(buffer.slice(0,boundary.index));if(buffer=buffer.slice(boundary.index+boundary.length),event===MISTRAL_STREAM_DONE)return;event&&(yield event),boundary=findMistralEventBoundary(buffer)}if(done)break}if(buffer.trim()){let event=parseMistralEvent(buffer);event!==MISTRAL_STREAM_DONE&&event&&(yield event)}}finally{signal.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function findMistralEventBoundary(buffer){let match=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(buffer);return match?.index===void 0?void 0:{index:match.index,length:match[0].length}}function parseMistralEvent(raw){let data=raw.split(/\r\n|\r|\n/u).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join(`
|
|
3
|
-
`).trim();if(!data)return;if(data==="[DONE]")return MISTRAL_STREAM_DONE;let parsed=JSON.parse(data);if(!isMistralRecord(parsed)||!Array.isArray(parsed.choices))throw new Error("Invalid Mistral streaming event");return{data:parsed}}function buildChatPayload(model,context,messages,options){let payload={model:model.id,stream:!0,messages:toChatMessages(messages,model.input.includes("image"))};return context.tools?.length&&(payload.tools=toFunctionTools(context.tools)),options?.temperature!==void 0&&(payload.temperature=options.temperature),options?.maxTokens!==void 0&&(payload.maxTokens=options.maxTokens),options?.toolChoice&&(payload.toolChoice=mapToolChoice(options.toolChoice)),options?.promptMode&&(payload.promptMode=options.promptMode),options?.reasoningEffort&&(payload.reasoningEffort=options.reasoningEffort),shouldUsePromptCaching(options)&&(payload.promptCacheKey=options.sessionId),context.systemPrompt&&payload.messages.unshift({role:"system",content:sanitizeSurrogates(context.systemPrompt)}),payload}function shouldUsePromptCaching(options){return options?.cacheRetention!=="none"&&!!options?.sessionId}function getMistralCachedPromptTokens(usage,promptTokens){let rawUsage=usage,rawCachedTokens=rawUsage.promptTokensDetails?.cachedTokens??rawUsage.prompt_tokens_details?.cached_tokens??rawUsage.promptTokenDetails?.cachedTokens??rawUsage.prompt_token_details?.cached_tokens??rawUsage.numCachedTokens??rawUsage.num_cached_tokens??0,cachedTokens=typeof rawCachedTokens=="number"&&Number.isFinite(rawCachedTokens)?rawCachedTokens:0;return Math.min(promptTokens,Math.max(0,cachedTokens))}async function consumeChatStream(model,output,stream2,mistralStream){let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1,toolBlocksByKey=new Map,finishCurrentBlock=block=>{if(block){if(block.type==="text"){stream2.push({type:"text_end",contentIndex:blockIndex(),content:block.text,partial:output});return}block.type==="thinking"&&stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:block.thinking,partial:output})}};for await(let event of mistralStream){let chunk=event.data;if(output.responseId||=chunk.id,chunk.usage){let promptTokens=chunk.usage.prompt_tokens||0,cachedPromptTokens=getMistralCachedPromptTokens(chunk.usage,promptTokens);output.usage.input=Math.max(0,promptTokens-cachedPromptTokens),output.usage.output=chunk.usage.completion_tokens||0,output.usage.cacheRead=cachedPromptTokens,output.usage.cacheWrite=0,output.usage.totalTokens=chunk.usage.total_tokens||output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,calculateCost(model,output.usage)}let choice=chunk.choices[0];if(!choice)continue;if(choice.finish_reason){output.rawStopReason=choice.finish_reason;let stopReasonResult=mapChatStopReason(choice.finish_reason);output.stopReason=stopReasonResult.stopReason,stopReasonResult.errorMessage&&(output.errorMessage=stopReasonResult.errorMessage)}let delta=choice.delta;if(delta.content!==null&&delta.content!==void 0){let contentItems=typeof delta.content=="string"?[delta.content]:delta.content;for(let item of contentItems){if(typeof item=="string"){let textDelta=sanitizeSurrogates(item);currentBlock?.type!=="text"&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output});continue}if(item.type==="thinking"){let deltaText=(item.thinking??[]).map(part=>part.text??"").filter(text=>text.length>0).join(""),thinkingDelta=sanitizeSurrogates(deltaText);if(!thinkingDelta)continue;currentBlock?.type!=="thinking"&&(finishCurrentBlock(currentBlock),currentBlock={type:"thinking",thinking:""},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})),currentBlock.thinking+=thinkingDelta,stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:thinkingDelta,partial:output});continue}if(item.type==="text"){let textDelta=sanitizeSurrogates(item.text??"");currentBlock?.type!=="text"&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output})}}}let toolCalls=delta.tool_calls||[];for(let toolCall of toolCalls){currentBlock&&(finishCurrentBlock(currentBlock),currentBlock=null);let callId=toolCall.id&&toolCall.id!=="null"?toolCall.id:deriveMistralToolCallId(`toolcall:${toolCall.index??0}`,0),key
|
|
3
|
+
`).trim();if(!data)return;if(data==="[DONE]")return MISTRAL_STREAM_DONE;let parsed=JSON.parse(data);if(!isMistralRecord(parsed)||!Array.isArray(parsed.choices))throw new Error("Invalid Mistral streaming event");return{data:parsed}}function buildChatPayload(model,context,messages,options){let payload={model:model.id,stream:!0,messages:toChatMessages(messages,model.input.includes("image"))};return context.tools?.length&&(payload.tools=toFunctionTools(context.tools)),options?.temperature!==void 0&&(payload.temperature=options.temperature),options?.maxTokens!==void 0&&(payload.maxTokens=options.maxTokens),options?.toolChoice&&(payload.toolChoice=mapToolChoice(options.toolChoice)),options?.promptMode&&(payload.promptMode=options.promptMode),options?.reasoningEffort&&(payload.reasoningEffort=options.reasoningEffort),shouldUsePromptCaching(options)&&(payload.promptCacheKey=options.sessionId),context.systemPrompt&&payload.messages.unshift({role:"system",content:sanitizeSurrogates(context.systemPrompt)}),payload}function shouldUsePromptCaching(options){return options?.cacheRetention!=="none"&&!!options?.sessionId}function getMistralCachedPromptTokens(usage,promptTokens){let rawUsage=usage,rawCachedTokens=rawUsage.promptTokensDetails?.cachedTokens??rawUsage.prompt_tokens_details?.cached_tokens??rawUsage.promptTokenDetails?.cachedTokens??rawUsage.prompt_token_details?.cached_tokens??rawUsage.numCachedTokens??rawUsage.num_cached_tokens??0,cachedTokens=typeof rawCachedTokens=="number"&&Number.isFinite(rawCachedTokens)?rawCachedTokens:0;return Math.min(promptTokens,Math.max(0,cachedTokens))}async function consumeChatStream(model,output,stream2,mistralStream){let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1,toolBlocksByKey=new Map,finishCurrentBlock=block=>{if(block){if(block.type==="text"){stream2.push({type:"text_end",contentIndex:blockIndex(),content:block.text,partial:output});return}block.type==="thinking"&&stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:block.thinking,partial:output})}};for await(let event of mistralStream){let chunk=event.data;if(output.responseId||=chunk.id,chunk.usage){let promptTokens=chunk.usage.prompt_tokens||0,cachedPromptTokens=getMistralCachedPromptTokens(chunk.usage,promptTokens);output.usage.input=Math.max(0,promptTokens-cachedPromptTokens),output.usage.output=chunk.usage.completion_tokens||0,output.usage.cacheRead=cachedPromptTokens,output.usage.cacheWrite=0,output.usage.totalTokens=chunk.usage.total_tokens||output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,calculateCost(model,output.usage)}let choice=chunk.choices[0];if(!choice)continue;if(choice.finish_reason){output.rawStopReason=choice.finish_reason;let stopReasonResult=mapChatStopReason(choice.finish_reason);output.stopReason=stopReasonResult.stopReason,stopReasonResult.errorMessage&&(output.errorMessage=stopReasonResult.errorMessage)}let delta=choice.delta;if(delta.content!==null&&delta.content!==void 0){let contentItems=typeof delta.content=="string"?[delta.content]:delta.content;for(let item of contentItems){if(typeof item=="string"){let textDelta=sanitizeSurrogates(item);currentBlock?.type!=="text"&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output});continue}if(item.type==="thinking"){let deltaText=(item.thinking??[]).map(part=>part.text??"").filter(text=>text.length>0).join(""),thinkingDelta=sanitizeSurrogates(deltaText);if(!thinkingDelta)continue;currentBlock?.type!=="thinking"&&(finishCurrentBlock(currentBlock),currentBlock={type:"thinking",thinking:""},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})),currentBlock.thinking+=thinkingDelta,stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:thinkingDelta,partial:output});continue}if(item.type==="text"){let textDelta=sanitizeSurrogates(item.text??"");currentBlock?.type!=="text"&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output})}}}let toolCalls=delta.tool_calls||[];for(let toolCall of toolCalls){currentBlock&&(finishCurrentBlock(currentBlock),currentBlock=null);let callId=toolCall.id&&toolCall.id!=="null"?toolCall.id:deriveMistralToolCallId(`toolcall:${toolCall.index??0}`,0),key=toolCall.index??callId,existingIndex=toolBlocksByKey.get(key),block;if(existingIndex!==void 0){let existing=output.content[existingIndex];existing?.type==="toolCall"&&(block=existing)}block||(block={type:"toolCall",id:callId,name:toolCall.function.name,arguments:{},partialArgs:""},output.content.push(block),toolBlocksByKey.set(key,output.content.length-1),stream2.push({type:"toolcall_start",contentIndex:output.content.length-1,partial:output}));let argsDelta=typeof toolCall.function.arguments=="string"?toolCall.function.arguments:JSON.stringify(toolCall.function.arguments||{});block.partialArgs=(block.partialArgs||"")+argsDelta,block.arguments=parseStreamingJson(block.partialArgs),stream2.push({type:"toolcall_delta",contentIndex:toolBlocksByKey.get(key),delta:argsDelta,partial:output})}}finishCurrentBlock(currentBlock);for(let index of toolBlocksByKey.values()){let block=output.content[index];if(block.type!=="toolCall")continue;let toolBlock=block;toolBlock.arguments=parseStreamingJson(toolBlock.partialArgs),delete toolBlock.partialArgs,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:toolBlock,partial:output})}}function toFunctionTools(tools){return tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,!0);return{type:"function",function:{name:tool.name,description:tool.description,parameters:stripSymbolKeys(getJsonSchemaToolParameters(tool,strict)),strict:strict??!1}}})}function stripSymbolKeys(value){if(Array.isArray(value))return value.map(item=>stripSymbolKeys(item));if(value&&typeof value=="object"){let result={};for(let[key,entry]of Object.entries(value))result[key]=stripSymbolKeys(entry);return result}return value}function toChatMessages(messages,supportsImages){let result=[];for(let msg of messages){if(msg.role==="user"){if(typeof msg.content=="string"){result.push({role:"user",content:sanitizeSurrogates(msg.content)});continue}let hadImages=msg.content.some(item=>item.type==="image"),content=msg.content.filter(item=>item.type==="text"||supportsImages).map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",imageUrl:`data:${item.mimeType};base64,${item.data}`});if(content.length>0){result.push({role:"user",content});continue}hadImages&&!supportsImages&&result.push({role:"user",content:"(image omitted: model does not support images)"});continue}if(msg.role==="assistant"){let contentParts=[],toolCalls=[];for(let block of msg.content){if(block.type==="text"){block.text.trim().length>0&&contentParts.push({type:"text",text:sanitizeSurrogates(block.text)});continue}if(block.type==="thinking"){block.thinking.trim().length>0&&contentParts.push({type:"thinking",thinking:[{type:"text",text:sanitizeSurrogates(block.thinking)}]});continue}toolCalls.push({id:block.id,type:"function",function:{name:block.name,arguments:JSON.stringify(block.arguments||{})},index:0})}let assistantMessage={role:"assistant",prefix:!1};contentParts.length>0&&(assistantMessage.content=contentParts),toolCalls.length>0&&(assistantMessage.toolCalls=toolCalls),(contentParts.length>0||toolCalls.length>0)&&result.push(assistantMessage);continue}let toolContent=[],textResult=msg.content.filter(part=>part.type==="text").map(part=>part.type==="text"?sanitizeSurrogates(part.text):"").join(`
|
|
4
4
|
`),hasImages=msg.content.some(part=>part.type==="image"),toolText=buildToolResultText(textResult,hasImages,supportsImages,msg.isError);toolContent.push({type:"text",text:toolText});for(let part of msg.content)supportsImages&&part.type==="image"&&toolContent.push({type:"image_url",imageUrl:`data:${part.mimeType};base64,${part.data}`});result.push({role:"tool",toolCallId:msg.toolCallId,name:msg.toolName,content:toolContent})}return result}function buildToolResultText(text,hasImages,supportsImages,isError){let trimmed=text.trim(),errorPrefix=isError?"[tool error] ":"";return trimmed.length>0?`${errorPrefix}${trimmed}${hasImages&&!supportsImages?`
|
|
5
5
|
[tool image omitted: model does not support images]`:""}`:hasImages?supportsImages?isError?"[tool error] (see attached image)":"(see attached image)":isError?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)":isError?"[tool error] (no tool output)":"(no tool output)"}function usesReasoningEffort(model){return model.id==="mistral-small-2603"||model.id==="mistral-small-latest"||model.id==="mistral-medium-3.5"}function usesPromptModeReasoning(model){return model.reasoning&&!usesReasoningEffort(model)}function mapReasoningEffort(model,level){return model.thinkingLevelMap?.[level]??"high"}function mapToolChoice(choice){if(choice)return choice==="auto"||choice==="none"||choice==="any"||choice==="required"?choice:{type:"function",function:{name:choice.function.name}}}function mapChatStopReason(reason){if(reason===null)return{stopReason:"stop"};switch(reason){case"stop":return{stopReason:"stop"};case"length":case"model_length":return{stopReason:"length"};case"tool_calls":return{stopReason:"toolUse"};case"error":return{stopReason:"error",errorMessage:"Provider stopped with: error"};default:return{stopReason:"error",errorMessage:`Provider stopped with: ${reason}`}}}export{stream,streamSimple};
|
package/dist/bundle/chunks/{openai-completions-6QBYTBXY.js → openai-completions-L4AHDQ5D.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{OpenAI}from"./chunk-3VI4HD7D.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import{shortHash}from"./chunk-PJACZCIR.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PGXDEOVV.js";import{retryProviderRequest}from"./chunk-XNGRGP62.js";import{appendGrammarToolInputJsonDelta,buildBaseOptions,clampThinkingBudgetToAnswerRoom,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,getPiUserAgent,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,thinkingBudgetForLevel,transformMessages}from"./chunk-TXBQIIIO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-6R7UI4IY.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{parseStreamingJson}from"./chunk-D7XAASZM.js";import{calculateCost,clampThinkingLevel}from"./chunk-WJZ4KLGL.js";import{AssistantMessageEventStream}from"./chunk-72KO4OMP.js";import"./chunk-JXWJOIH4.js";function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function getClientApiKey(provider,apiKey,headers){if(apiKey)return apiKey;if(hasHeader(headers,"authorization")||hasHeader(headers,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${provider}`)}function hasToolHistory(messages){for(let msg of messages)if(msg.role==="toolResult"||msg.role==="assistant"&&msg.content.some(block=>block.type==="toolCall"))return!0;return!1}function getDeferredToolNames(messages){let names=new Set;for(let message of messages)if(message.role==="toolResult")for(let name of message.addedToolNames??[])names.add(name);return names}function getToolsByName(tools,names){if(!tools)return[];let toolsByName=new Map(tools.map(tool=>[tool.name,tool]));return Array.from(names).map(name=>toolsByName.get(name)).filter(tool=>tool!==void 0)}function isTextContentBlock(block){return block.type==="text"}function isThinkingContentBlock(block){return block.type==="thinking"}function isToolCallBlock(block){return block.type==="toolCall"}function isImageContentBlock(block){return block.type==="image"}function isReasoningDetailObject(detail){return typeof detail=="object"&&detail!==null&&!Array.isArray(detail)}function hasValidCommonReasoningDetailFields(candidate){return(candidate.id===void 0||candidate.id===null||typeof candidate.id=="string")&&(candidate.format===void 0||typeof candidate.format=="string")&&(candidate.index===void 0||typeof candidate.index=="number")}function isOpenAIReasoningDetail(detail){if(!isReasoningDetailObject(detail)||!hasValidCommonReasoningDetailFields(detail))return!1;switch(detail.type){case"reasoning.summary":return typeof detail.summary=="string";case"reasoning.encrypted":return typeof detail.data=="string";case"reasoning.text":return typeof detail.text=="string"&&(detail.signature===void 0||detail.signature===null||typeof detail.signature=="string");default:return!1}}function parseOpenAIReasoningDetails(signature){if(signature)try{let parsed=JSON.parse(signature);return Array.isArray(parsed)&&parsed.length>0&&parsed.every(isOpenAIReasoningDetail)?parsed:void 0}catch{return}}function parseLegacyEncryptedReasoningDetail(signature){if(signature)try{let parsed=JSON.parse(signature);return isOpenAIReasoningDetail(parsed)&&parsed.type==="reasoning.encrypted"&&typeof parsed.id=="string"&&parsed.id.length>0&&parsed.data.length>0?parsed:void 0}catch{return}}var OPENAI_COMPLETIONS_REASONING_FIELDS=["reasoning","reasoning_content","reasoning_text"];function isOpenAICompletionsReasoningField(field){return OPENAI_COMPLETIONS_REASONING_FIELDS.includes(field)}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("HUMAIN_TERMINAL_CACHE_RETENTION",env)==="long"||getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let apiKey=getClientApiKey(model.provider,options?.apiKey,options?.headers),compat=getCompat(model),grammarToolInputProperties=createGrammarToolInputProperties(context.tools,compat.supportsOpenAIGrammarTools),cacheRetention=resolveCacheRetention(options?.cacheRetention,options?.env),cacheSessionId=cacheRetention==="none"?void 0:options?.sessionId,client=createClient(model,context,apiKey,options?.headers,options?.fetch,cacheSessionId,compat),params=buildParams(model,context,options,compat,cacheRetention,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.chat.completions.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output});let textBlock=null,thinkingBlock=null,hasFinishReason=!1,toolCallBlocksByIndex=new Map,toolCallBlocksById=new Map,blocks=output.content,getContentIndex=block=>blocks.indexOf(block),getCustomToolCallInput=block=>{let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""},appendCustomToolCallInput=(block,nextInput,close)=>{let customInput=block.customInput;if(!customInput)return;let delta=appendGrammarToolInputJsonDelta(customInput.jsonBuffer,customInput.property,nextInput,close);return block.arguments={[customInput.property]:nextInput},delta},finishBlock=block=>{let contentIndex=getContentIndex(block);if(contentIndex!==-1){if(block.type==="text")stream2.push({type:"text_end",contentIndex,content:block.text,partial:output});else if(block.type==="thinking")stream2.push({type:"thinking_end",contentIndex,content:block.thinking,partial:output});else if(block.type==="toolCall"){if(block.customInput){let delta=appendCustomToolCallInput(block,getCustomToolCallInput(block),!0);delta!==void 0&&stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}else block.arguments=parseStreamingJson(block.partialArgs);delete block.partialArgs,delete block.customInput,delete block.streamIndex,stream2.push({type:"toolcall_end",contentIndex,toolCall:block,partial:output})}}},ensureTextBlock=()=>(textBlock||(textBlock={type:"text",text:""},blocks.push(textBlock),stream2.push({type:"text_start",contentIndex:getContentIndex(textBlock),partial:output})),textBlock),ensureThinkingBlock=thinkingSignature=>(thinkingBlock||(thinkingBlock={type:"thinking",thinking:"",thinkingSignature},blocks.push(thinkingBlock),stream2.push({type:"thinking_start",contentIndex:getContentIndex(thinkingBlock),partial:output})),thinkingBlock),ensureToolCallBlock=toolCall=>{let streamIndex=typeof toolCall.index=="number"?toolCall.index:void 0,name=toolCall.function?.name??toolCall.custom?.name??"",block=streamIndex!==void 0?toolCallBlocksByIndex.get(streamIndex):void 0;if(!block&&toolCall.id&&(block=toolCallBlocksById.get(toolCall.id)),!block){let customInputProperty=toolCall.custom&&!toolCall.function?grammarToolInputProperties.get(name)??"input":void 0,hasCustomInput=customInputProperty!==void 0;block={type:"toolCall",id:toolCall.id||"",name,arguments:hasCustomInput?{[customInputProperty]:""}:{},partialArgs:hasCustomInput?void 0:"",customInput:hasCustomInput?{property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex},streamIndex!==void 0&&toolCallBlocksByIndex.set(streamIndex,block),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),blocks.push(block),stream2.push({type:"toolcall_start",contentIndex:getContentIndex(block),partial:output})}if(streamIndex!==void 0&&block.streamIndex===void 0&&(block.streamIndex=streamIndex,toolCallBlocksByIndex.set(streamIndex,block)),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),!block.name&&name&&(block.name=name),toolCall.custom&&!toolCall.function&&!block.customInput){let customInputProperty=grammarToolInputProperties.get(block.name)??"input";block.arguments={[customInputProperty]:""},block.customInput={property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}},delete block.partialArgs}return block};for await(let chunk of openaiStream){if(!chunk||typeof chunk!="object")continue;output.responseId||=chunk.id,typeof chunk.model=="string"&&chunk.model.length>0&&chunk.model!==model.id&&(output.responseModel||=chunk.model),chunk.usage&&(output.usage=parseChunkUsage(chunk.usage,model));let choice=Array.isArray(chunk.choices)?chunk.choices[0]:void 0;if(choice){if(!chunk.usage&&choice.usage&&(output.usage=parseChunkUsage(choice.usage,model)),choice.finish_reason){output.rawStopReason=choice.finish_reason;let finishReasonResult=mapStopReason(choice.finish_reason);output.stopReason=finishReasonResult.stopReason,finishReasonResult.errorMessage&&(output.errorMessage=finishReasonResult.errorMessage),hasFinishReason=!0}if(choice.delta){if(choice.delta.content!==null&&choice.delta.content!==void 0&&choice.delta.content.length>0){let block=ensureTextBlock();block.text+=choice.delta.content,stream2.push({type:"text_delta",contentIndex:getContentIndex(block),delta:choice.delta.content,partial:output})}let reasoningFields=["reasoning_content","reasoning","reasoning_text"],deltaFields=choice.delta,foundReasoningField=null;for(let field of reasoningFields){let value=deltaFields[field];if(typeof value=="string"&&value.length>0){foundReasoningField=field;break}}if(foundReasoningField){let delta=deltaFields[foundReasoningField];if(typeof delta=="string"&&delta.length>0){let thinkingSignature=model.provider==="opencode-go"&&foundReasoningField==="reasoning"?"reasoning_content":foundReasoningField,block=ensureThinkingBlock(thinkingSignature);block.thinking+=delta,stream2.push({type:"thinking_delta",contentIndex:getContentIndex(block),delta,partial:output})}}if(choice?.delta?.tool_calls)for(let toolCall of choice.delta.tool_calls){let block=ensureToolCallBlock(toolCall);!block.id&&toolCall.id&&(block.id=toolCall.id,toolCallBlocksById.set(toolCall.id,block));let name=toolCall.function?.name??toolCall.custom?.name;!block.name&&name&&(block.name=name);let delta="";if(toolCall.function?.arguments)delta=toolCall.function.arguments,block.partialArgs=(block.partialArgs??"")+toolCall.function.arguments,block.arguments=parseStreamingJson(block.partialArgs);else if(toolCall.custom?.input){let nextInput=getCustomToolCallInput(block)+toolCall.custom.input;delta=appendCustomToolCallInput(block,nextInput,!1)??""}stream2.push({type:"toolcall_delta",contentIndex:getContentIndex(block),delta,partial:output})}let reasoningDetails=choice.delta.reasoning_details;if(Array.isArray(reasoningDetails))for(let detail of reasoningDetails){if(!isOpenAIReasoningDetail(detail))continue;let block=ensureThinkingBlock(""),preservedDetails=parseOpenAIReasoningDetails(block.thinkingSignature)??[];preservedDetails.push(detail),block.thinkingSignature=JSON.stringify(preservedDetails)}}}}for(let block of blocks)finishBlock(block);if(options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="aborted")throw new Error("Request was aborted");if(!hasFinishReason&&!compat.supportsFinishReason&&(output.stopReason=output.content.some(block=>block.type==="toolCall")?"toolUse":"stop"),output.stopReason==="error")throw new Error(output.errorMessage||"Provider returned an error stop reason");if(compat.supportsFinishReason&&!hasFinishReason||output.stopReason==="pending")throw new Error("Stream ended without finish_reason");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.index,delete block.partialArgs,delete block.customInput,delete block.streamIndex;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error));let rawMetadata=error?.error?.metadata?.raw;rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
|
|
2
|
+
import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{OpenAI}from"./chunk-3VI4HD7D.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import{shortHash}from"./chunk-PJACZCIR.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PGXDEOVV.js";import{retryProviderRequest}from"./chunk-XNGRGP62.js";import{appendGrammarToolInputJsonDelta,buildBaseOptions,clampThinkingBudgetToAnswerRoom,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,getPiUserAgent,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,thinkingBudgetForLevel,transformMessages}from"./chunk-TXBQIIIO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-6R7UI4IY.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{parseStreamingJson}from"./chunk-D7XAASZM.js";import{calculateCost,clampThinkingLevel}from"./chunk-WJZ4KLGL.js";import{AssistantMessageEventStream}from"./chunk-72KO4OMP.js";import"./chunk-JXWJOIH4.js";function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function getClientApiKey(provider,apiKey,headers){if(apiKey)return apiKey;if(hasHeader(headers,"authorization")||hasHeader(headers,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${provider}`)}function hasToolHistory(messages){for(let msg of messages)if(msg.role==="toolResult"||msg.role==="assistant"&&msg.content.some(block=>block.type==="toolCall"))return!0;return!1}function getDeferredToolNames(messages){let names=new Set;for(let message of messages)if(message.role==="toolResult")for(let name of message.addedToolNames??[])names.add(name);return names}function getToolsByName(tools,names){if(!tools)return[];let toolsByName=new Map(tools.map(tool=>[tool.name,tool]));return Array.from(names).map(name=>toolsByName.get(name)).filter(tool=>tool!==void 0)}function isTextContentBlock(block){return block.type==="text"}function isThinkingContentBlock(block){return block.type==="thinking"}function isToolCallBlock(block){return block.type==="toolCall"}function isImageContentBlock(block){return block.type==="image"}function isReasoningDetailObject(detail){return typeof detail=="object"&&detail!==null&&!Array.isArray(detail)}function hasValidCommonReasoningDetailFields(candidate){return(candidate.id===void 0||candidate.id===null||typeof candidate.id=="string")&&(candidate.format===void 0||typeof candidate.format=="string")&&(candidate.index===void 0||typeof candidate.index=="number")}function isOpenAIReasoningDetail(detail){if(!isReasoningDetailObject(detail)||!hasValidCommonReasoningDetailFields(detail))return!1;switch(detail.type){case"reasoning.summary":return typeof detail.summary=="string";case"reasoning.encrypted":return typeof detail.data=="string";case"reasoning.text":return typeof detail.text=="string"&&(detail.signature===void 0||detail.signature===null||typeof detail.signature=="string");default:return!1}}function parseOpenAIReasoningDetails(signature){if(signature)try{let parsed=JSON.parse(signature);return Array.isArray(parsed)&&parsed.length>0&&parsed.every(isOpenAIReasoningDetail)?parsed:void 0}catch{return}}function parseLegacyEncryptedReasoningDetail(signature){if(signature)try{let parsed=JSON.parse(signature);return isOpenAIReasoningDetail(parsed)&&parsed.type==="reasoning.encrypted"&&typeof parsed.id=="string"&&parsed.id.length>0&&parsed.data.length>0?parsed:void 0}catch{return}}function fillMissingCommonReasoningDetailFields(target,source){target.id??=source.id,target.format||=source.format,target.index??=source.index}function appendOpenAIReasoningDetail(details,detail){let lastDetail=details[details.length-1];if(detail.type==="reasoning.text"&&lastDetail?.type==="reasoning.text"){lastDetail.text+=detail.text,lastDetail.signature||=detail.signature,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}if(detail.type==="reasoning.summary"&&lastDetail?.type==="reasoning.summary"){lastDetail.summary+=detail.summary,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}details.push({...detail})}var OPENAI_COMPLETIONS_REASONING_FIELDS=["reasoning","reasoning_content","reasoning_text"];function isOpenAICompletionsReasoningField(field){return OPENAI_COMPLETIONS_REASONING_FIELDS.includes(field)}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("HUMAIN_TERMINAL_CACHE_RETENTION",env)==="long"||getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()},streamedReasoningDetails,applyStreamedReasoningDetails=block=>{streamedReasoningDetails!==void 0&&(block.thinkingSignature=JSON.stringify(streamedReasoningDetails))};try{let apiKey=getClientApiKey(model.provider,options?.apiKey,options?.headers),compat=getCompat(model),grammarToolInputProperties=createGrammarToolInputProperties(context.tools,compat.supportsOpenAIGrammarTools),cacheRetention=resolveCacheRetention(options?.cacheRetention,options?.env),cacheSessionId=cacheRetention==="none"?void 0:options?.sessionId,client=createClient(model,context,apiKey,options?.headers,options?.fetch,cacheSessionId,compat),params=buildParams(model,context,options,compat,cacheRetention,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.chat.completions.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output});let textBlock=null,thinkingBlock=null,hasFinishReason=!1,toolCallBlocksByIndex=new Map,toolCallBlocksById=new Map,blocks=output.content,getContentIndex=block=>blocks.indexOf(block),getCustomToolCallInput=block=>{let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""},appendCustomToolCallInput=(block,nextInput,close)=>{let customInput=block.customInput;if(!customInput)return;let delta=appendGrammarToolInputJsonDelta(customInput.jsonBuffer,customInput.property,nextInput,close);return block.arguments={[customInput.property]:nextInput},delta},finishBlock=block=>{let contentIndex=getContentIndex(block);if(contentIndex!==-1){if(block.type==="text")stream2.push({type:"text_end",contentIndex,content:block.text,partial:output});else if(block.type==="thinking")applyStreamedReasoningDetails(block),stream2.push({type:"thinking_end",contentIndex,content:block.thinking,partial:output});else if(block.type==="toolCall"){if(block.customInput){let delta=appendCustomToolCallInput(block,getCustomToolCallInput(block),!0);delta!==void 0&&stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}else block.arguments=parseStreamingJson(block.partialArgs);delete block.partialArgs,delete block.customInput,delete block.streamIndex,stream2.push({type:"toolcall_end",contentIndex,toolCall:block,partial:output})}}},ensureTextBlock=()=>(textBlock||(textBlock={type:"text",text:""},blocks.push(textBlock),stream2.push({type:"text_start",contentIndex:getContentIndex(textBlock),partial:output})),textBlock),ensureThinkingBlock=thinkingSignature=>(thinkingBlock||(thinkingBlock={type:"thinking",thinking:"",thinkingSignature},blocks.push(thinkingBlock),stream2.push({type:"thinking_start",contentIndex:getContentIndex(thinkingBlock),partial:output})),thinkingBlock),ensureToolCallBlock=toolCall=>{let streamIndex=typeof toolCall.index=="number"?toolCall.index:void 0,name=toolCall.function?.name??toolCall.custom?.name??"",block=streamIndex!==void 0?toolCallBlocksByIndex.get(streamIndex):void 0;if(!block&&toolCall.id&&(block=toolCallBlocksById.get(toolCall.id)),!block){let customInputProperty=toolCall.custom&&!toolCall.function?grammarToolInputProperties.get(name)??"input":void 0,hasCustomInput=customInputProperty!==void 0;block={type:"toolCall",id:toolCall.id||"",name,arguments:hasCustomInput?{[customInputProperty]:""}:{},partialArgs:hasCustomInput?void 0:"",customInput:hasCustomInput?{property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex},streamIndex!==void 0&&toolCallBlocksByIndex.set(streamIndex,block),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),blocks.push(block),stream2.push({type:"toolcall_start",contentIndex:getContentIndex(block),partial:output})}if(streamIndex!==void 0&&block.streamIndex===void 0&&(block.streamIndex=streamIndex,toolCallBlocksByIndex.set(streamIndex,block)),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),!block.name&&name&&(block.name=name),toolCall.custom&&!toolCall.function&&!block.customInput){let customInputProperty=grammarToolInputProperties.get(block.name)??"input";block.arguments={[customInputProperty]:""},block.customInput={property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}},delete block.partialArgs}return block};for await(let chunk of openaiStream){if(!chunk||typeof chunk!="object")continue;output.responseId||=chunk.id,typeof chunk.model=="string"&&chunk.model.length>0&&chunk.model!==model.id&&(output.responseModel||=chunk.model),chunk.usage&&(output.usage=parseChunkUsage(chunk.usage,model));let choice=Array.isArray(chunk.choices)?chunk.choices[0]:void 0;if(choice){if(!chunk.usage&&choice.usage&&(output.usage=parseChunkUsage(choice.usage,model)),choice.finish_reason){output.rawStopReason=choice.finish_reason;let finishReasonResult=mapStopReason(choice.finish_reason);output.stopReason=finishReasonResult.stopReason,finishReasonResult.errorMessage&&(output.errorMessage=finishReasonResult.errorMessage),hasFinishReason=!0}if(choice.delta){if(choice.delta.content!==null&&choice.delta.content!==void 0&&choice.delta.content.length>0){let block=ensureTextBlock();block.text+=choice.delta.content,stream2.push({type:"text_delta",contentIndex:getContentIndex(block),delta:choice.delta.content,partial:output})}let reasoningFields=["reasoning_content","reasoning","reasoning_text"],deltaFields=choice.delta,foundReasoningField=null;for(let field of reasoningFields){let value=deltaFields[field];if(typeof value=="string"&&value.length>0){foundReasoningField=field;break}}if(foundReasoningField){let delta=deltaFields[foundReasoningField];if(typeof delta=="string"&&delta.length>0){let thinkingSignature=model.provider==="opencode-go"&&foundReasoningField==="reasoning"?"reasoning_content":foundReasoningField,block=ensureThinkingBlock(thinkingSignature);block.thinking+=delta,stream2.push({type:"thinking_delta",contentIndex:getContentIndex(block),delta,partial:output})}}if(choice?.delta?.tool_calls)for(let toolCall of choice.delta.tool_calls){let block=ensureToolCallBlock(toolCall);!block.id&&toolCall.id&&(block.id=toolCall.id,toolCallBlocksById.set(toolCall.id,block));let name=toolCall.function?.name??toolCall.custom?.name;!block.name&&name&&(block.name=name);let delta="";if(toolCall.function?.arguments)delta=toolCall.function.arguments,block.partialArgs=(block.partialArgs??"")+toolCall.function.arguments,block.arguments=parseStreamingJson(block.partialArgs);else if(toolCall.custom?.input){let nextInput=getCustomToolCallInput(block)+toolCall.custom.input;delta=appendCustomToolCallInput(block,nextInput,!1)??""}stream2.push({type:"toolcall_delta",contentIndex:getContentIndex(block),delta,partial:output})}let reasoningDetails=choice.delta.reasoning_details;if(Array.isArray(reasoningDetails))for(let detail of reasoningDetails)isOpenAIReasoningDetail(detail)&&(ensureThinkingBlock(""),streamedReasoningDetails??=[],appendOpenAIReasoningDetail(streamedReasoningDetails,detail))}}}for(let block of blocks)finishBlock(block);if(options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="aborted")throw new Error("Request was aborted");if(!hasFinishReason&&!compat.supportsFinishReason&&(output.stopReason=output.content.some(block=>block.type==="toolCall")?"toolUse":"stop"),output.stopReason==="error")throw new Error(output.errorMessage||"Provider returned an error stop reason");if(compat.supportsFinishReason&&!hasFinishReason||output.stopReason==="pending")throw new Error("Stream ended without finish_reason");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)block.type==="thinking"&&applyStreamedReasoningDetails(block),delete block.index,delete block.partialArgs,delete block.customInput,delete block.streamIndex;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error));let rawMetadata=error?.error?.metadata?.raw;rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
|
|
3
3
|
${rawMetadata}`),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{getClientApiKey(model.provider,options?.apiKey,options?.headers);let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning,thinkingBudgets:options?.thinkingBudgets})};function createClient(model,context,apiKey,optionsHeaders,fetch,sessionId,compat=getCompat(model)){let headers={"User-Agent":getPiUserAgent(),...model.headers};if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(context.messages),copilotHeaders=buildCopilotDynamicHeaders({messages:context.messages,hasImages});Object.assign(headers,copilotHeaders)}return sessionId&&compat.sendSessionAffinityHeaders&&(compat.sessionAffinityFormat==="openrouter"?headers["x-session-id"]=sessionId:(compat.sessionAffinityFormat==="openai"&&(headers.session_id=sessionId),headers["x-client-request-id"]=sessionId,headers["x-session-affinity"]=sessionId)),optionsHeaders&&Object.assign(headers,optionsHeaders),new OpenAI({apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:headers})}function buildParams(model,context,options,compat=getCompat(model),cacheRetention=resolveCacheRetention(options?.cacheRetention,options?.env),grammarToolInputProperties=createGrammarToolInputProperties(context.tools,compat.supportsOpenAIGrammarTools)){let messages=convertMessages(model,context,compat,{grammarToolInputProperties}),cacheControl=getCompatCacheControl(compat,cacheRetention),params={model:model.id,messages,stream:!0,prompt_cache_key:model.baseUrl.includes("api.openai.com")&&cacheRetention!=="none"||cacheRetention==="long"&&compat.supportsLongCacheRetention?clampOpenAIPromptCacheKey(options?.sessionId):void 0,prompt_cache_retention:cacheRetention==="long"&&compat.supportsLongCacheRetention?"24h":void 0};compat.supportsUsageInStreaming!==!1&&(params.stream_options={include_usage:!0}),compat.supportsStore&&(params.store=!1),options?.maxTokens&&(compat.maxTokensField==="max_tokens"?params.max_tokens=options.maxTokens:params.max_completion_tokens=options.maxTokens),options?.temperature!==void 0&&(params.temperature=options.temperature);let deferredToolNames=compat.deferredToolsMode==="kimi"?getDeferredToolNames(context.messages):new Set,activeTools=context.tools?.filter(tool=>!deferredToolNames.has(tool.name));activeTools&&activeTools.length>0?(params.tools=convertTools(activeTools,compat),compat.zaiToolStream&&(params.tool_stream=!0)):hasToolHistory(context.messages)&&(params.tools=[]),cacheControl&&applyAnthropicCacheControl(messages,params.tools,cacheControl),options?.toolChoice&&(params.tool_choice=options.toolChoice);let thinkingTokenBudgetField=resolveThinkingTokenBudgetField(compat),thinkingBudget=resolveClampedThinkingBudget(model,options,params);if(compat.thinkingFormat==="zai"&&model.reasoning){let zaiParams=params;if(zaiParams.thinking=options?.reasoningEffort?{type:"enabled",clear_thinking:!1}:{type:"disabled"},options?.reasoningEffort&&compat.supportsReasoningEffort){let mappedEffort=model.thinkingLevelMap?.[options.reasoningEffort],effort=mappedEffort===void 0?options.reasoningEffort:mappedEffort;typeof effort=="string"&&(zaiParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="qwen"&&model.reasoning){if(params.enable_thinking=!!options?.reasoningEffort,options?.reasoningEffort&&compat.supportsReasoningEffort){let effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort;typeof effort=="string"&&(params.reasoning_effort=effort)}}else if(compat.thinkingFormat==="qwen-chat-template"&&model.reasoning)params.chat_template_kwargs={enable_thinking:!!options?.reasoningEffort,preserve_thinking:!0};else if(compat.thinkingFormat==="chat-template"&&model.reasoning){let chatTemplateKwargs=buildChatTemplateValues(model,options,compat.chatTemplateKwargs,thinkingBudget);chatTemplateKwargs&&(params.chat_template_kwargs=chatTemplateKwargs)}else if(compat.thinkingFormat==="baseten"&&model.reasoning){let basetenParams=params,chatTemplateArgs=buildChatTemplateValues(model,options,compat.chatTemplateArgs,thinkingBudget);if(chatTemplateArgs&&(basetenParams.chat_template_args=chatTemplateArgs),compat.supportsReasoningEffort){let requestedEffort=options?.reasoningEffort,mappedEffort=requestedEffort?model.thinkingLevelMap?.[requestedEffort]:model.thinkingLevelMap?.off,effort=mappedEffort===void 0?requestedEffort:mappedEffort;typeof effort=="string"&&(basetenParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="deepseek"&&model.reasoning)options?.reasoningEffort?params.thinking={type:"enabled"}:model.thinkingLevelMap?.off!==null&&(params.thinking={type:"disabled"}),options?.reasoningEffort&&compat.supportsReasoningEffort&&(params.reasoning_effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort);else if(compat.thinkingFormat==="openrouter"&&model.reasoning){let openRouterParams=params;options?.reasoningEffort?openRouterParams.reasoning={effort:model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort}:model.thinkingLevelMap?.off!==null&&(openRouterParams.reasoning={effort:model.thinkingLevelMap?.off??"none"})}else if(compat.thinkingFormat==="ant-ling"&&model.reasoning&&options?.reasoningEffort){let effort=model.thinkingLevelMap?.[options.reasoningEffort];typeof effort=="string"&&(params.reasoning={effort})}else if(compat.thinkingFormat==="together"&&model.reasoning){let togetherParams=params;togetherParams.reasoning={enabled:!!options?.reasoningEffort},options?.reasoningEffort&&compat.supportsReasoningEffort&&(togetherParams.reasoning_effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort)}else if(compat.thinkingFormat==="string-thinking"&&model.reasoning){let stringThinkingParams=params;options?.reasoningEffort?stringThinkingParams.thinking=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort:model.thinkingLevelMap?.off!==null&&(stringThinkingParams.thinking=model.thinkingLevelMap?.off??"none")}else if(options?.reasoningEffort&&model.reasoning&&compat.supportsReasoningEffort)params.reasoning_effort=model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort;else if(!options?.reasoningEffort&&model.reasoning&&compat.supportsReasoningEffort){let offValue=model.thinkingLevelMap?.off;typeof offValue=="string"&&(params.reasoning_effort=offValue)}if(thinkingTokenBudgetField&&thinkingBudget!==void 0&&Object.assign(params,{[thinkingTokenBudgetField]:thinkingBudget}),model.compat?.openRouterRouting&&(params.provider=model.compat.openRouterRouting),model.compat?.vercelGatewayRouting){let routing=model.compat.vercelGatewayRouting;if(routing.only||routing.order){let gatewayOptions={};routing.only&&(gatewayOptions.only=routing.only),routing.order&&(gatewayOptions.order=routing.order),params.providerOptions={gateway:gatewayOptions}}}return options?.samplingParams&&Object.assign(params,options.samplingParams),params}function resolveThinkingTokenBudgetField(compat){if(compat.thinkingTokenBudgetField)return compat.thinkingTokenBudgetField;if(compat.supportsThinkingTokenBudget)return"thinking_token_budget"}function resolveClampedThinkingBudget(model,options,params){if(!options?.reasoningEffort||!model.reasoning)return;let ceiling=params.max_tokens??params.max_completion_tokens??model.maxTokens,budget=clampThinkingBudgetToAnswerRoom(thinkingBudgetForLevel(options.reasoningEffort,options.thinkingBudgets),ceiling);return budget>0?budget:void 0}function buildChatTemplateValues(model,options,values,thinkingBudget){let resolvedValues={};for(let[key,value]of Object.entries(values)){let resolved=resolveChatTemplateKwargValue(model,options,value,thinkingBudget);resolved!==void 0&&(resolvedValues[key]=resolved)}return Object.keys(resolvedValues).length>0?resolvedValues:void 0}function resolveChatTemplateKwargValue(model,options,value,thinkingBudget){if(typeof value!="object"||value===null)return value;let reasoningEffort=options?.reasoningEffort;if(!reasoningEffort&&value.omitWhenOff)return;if(value.$var==="thinking.enabled")return!!reasoningEffort;if(value.$var==="thinking.budget")return thinkingBudget;let mappedValue=reasoningEffort?model.thinkingLevelMap?.[reasoningEffort]:model.thinkingLevelMap?.off;return mappedValue===void 0?reasoningEffort:typeof mappedValue=="string"?mappedValue:void 0}function getCompatCacheControl(compat,cacheRetention){if(compat.cacheControlFormat!=="anthropic"||cacheRetention==="none")return;let ttl=cacheRetention==="long"&&compat.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...ttl?{ttl}:{}}}function applyAnthropicCacheControl(messages,tools,cacheControl){addCacheControlToSystemPrompt(messages,cacheControl),addCacheControlToLastTool(tools,cacheControl),addCacheControlToLastConversationMessage(messages,cacheControl)}function addCacheControlToSystemPrompt(messages,cacheControl){for(let message of messages)if(message.role==="system"||message.role==="developer"){addCacheControlToInstructionMessage(message,cacheControl);return}}function addCacheControlToLastConversationMessage(messages,cacheControl){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if((message.role==="user"||message.role==="assistant"||message.role==="tool")&&addCacheControlToMessage(message,cacheControl))return}}function addCacheControlToLastTool(tools,cacheControl){if(!tools||tools.length===0)return;let lastTool=tools[tools.length-1];lastTool.cache_control=cacheControl}function addCacheControlToInstructionMessage(message,cacheControl){return addCacheControlToTextContent(message,cacheControl)}function addCacheControlToMessage(message,cacheControl){return message.role==="user"||message.role==="assistant"||message.role==="tool"?addCacheControlToTextContent(message,cacheControl):!1}function addCacheControlToTextContent(message,cacheControl){let content=message.content;if(typeof content=="string")return content.length===0?!1:(message.content=[{type:"text",text:content,cache_control:cacheControl}],!0);if(!Array.isArray(content))return!1;for(let i=content.length-1;i>=0;i--){let part=content[i];if(part?.type==="text"){let textPart=part;return textPart.cache_control=cacheControl,!0}}return!1}function convertMessages(model,context,compat,options){let params=[],normalizeToolCallId=id=>{if(id.includes("|")){let separatorIndex=id.indexOf("|"),callId=id.slice(0,separatorIndex).replace(/[^a-zA-Z0-9_-]/g,"_"),itemId=id.slice(separatorIndex+1).replace(/[^a-zA-Z0-9_-]/g,"_"),combinedId=itemId.length>0?`${callId}_${itemId}`:callId;if(combinedId.length<=40)return combinedId;let hash=shortHash(id).slice(0,8);return`${callId.slice(0,Math.max(1,40-hash.length-1))}_${hash}`}return model.provider==="openai"&&id.length>40?id.slice(0,40):id},transformedMessages=transformMessages(context.messages,model,id=>normalizeToolCallId(id));if(context.systemPrompt){let role=model.reasoning&&compat.supportsDeveloperRole?"developer":"system";params.push({role,content:sanitizeSurrogates(context.systemPrompt)})}let lastRole=null;for(let i=0;i<transformedMessages.length;i++){let msg=transformedMessages[i];if(compat.requiresAssistantAfterToolResult&&lastRole==="toolResult"&&msg.role==="user"&¶ms.push({role:"assistant",content:"I have processed the tool results."}),msg.role==="user")if(typeof msg.content=="string")params.push({role:"user",content:sanitizeSurrogates(msg.content)});else{let content=msg.content.map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",image_url:{url:`data:${item.mimeType};base64,${item.data}`}});if(content.length===0)continue;params.push({role:"user",content})}else if(msg.role==="assistant"){let assistantMsg={role:"assistant",content:compat.requiresAssistantAfterToolResult?"":null},assistantTextParts=msg.content.filter(isTextContentBlock).filter(block=>block.text.trim().length>0).map(block=>({type:"text",text:sanitizeSurrogates(block.text)})),assistantText=assistantTextParts.map(part=>part.text).join(""),thinkingBlocks=msg.content.filter(isThinkingContentBlock),toolCalls=msg.content.filter(isToolCallBlock),signedReasoningDetails=thinkingBlocks.map(block=>parseOpenAIReasoningDetails(block.thinkingSignature)).find(details=>details!==void 0),legacyReasoningDetails=toolCalls.map(toolCall=>parseLegacyEncryptedReasoningDetail(toolCall.thoughtSignature)).filter(detail=>detail!==void 0),preservedReasoningDetails=signedReasoningDetails??(legacyReasoningDetails.length>0?legacyReasoningDetails:void 0),nonEmptyThinkingBlocks=thinkingBlocks.filter(block=>block.thinking.trim().length>0);if(nonEmptyThinkingBlocks.length>0){if(compat.requiresThinkingAsText){let thinkingText=nonEmptyThinkingBlocks.map(block=>sanitizeSurrogates(block.thinking)).join(`
|
|
4
4
|
|
|
5
5
|
`);assistantMsg.content=[{type:"text",text:thinkingText},...assistantTextParts]}else if(assistantText.length>0&&(assistantMsg.content=assistantText),!preservedReasoningDetails){let signature=nonEmptyThinkingBlocks[0].thinkingSignature;model.provider==="opencode-go"&&signature==="reasoning"&&(signature="reasoning_content"),signature&&isOpenAICompletionsReasoningField(signature)&&(assistantMsg[signature]=nonEmptyThinkingBlocks.map(block=>block.thinking).join(`
|
package/dist/bundle/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
3
|
-
import{configureHttpDispatcher,main}from"./chunks/chunk-
|
|
3
|
+
import{configureHttpDispatcher,main}from"./chunks/chunk-MMFBCF6F.js";import{APP_NAME,ENV_PREFIX}from"./chunks/chunk-ARF4OE6X.js";import"./chunks/chunk-MA4UUCYX.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-SGTGQNNP.js";import"./chunks/chunk-ECWELYBH.js";import"./chunks/chunk-74NVHVNZ.js";import"./chunks/chunk-CBHC6EL7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-D7XAASZM.js";import"./chunks/chunk-WJZ4KLGL.js";import"./chunks/chunk-72KO4OMP.js";import"./chunks/chunk-JXWJOIH4.js";process.title=APP_NAME;process.env[`${ENV_PREFIX}_CODING_AGENT`]="true";process.emitWarning=(()=>{});configureHttpDispatcher();main(process.argv.slice(2));
|
package/dist/bundle/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{AgentExecInputError,AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,buildContextEntries,buildSessionContext,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createPiAgentExecutionHost,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,defineTool,discoverAndLoadExtensions,estimateTokens,executeHumainAgentRequest,findCutPoint,findTurnStartIndex,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPowerShellConfig,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resolveCliModel,resolveModelScopeWithDiagnostics,runAgentExecMode,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-
|
|
2
|
+
import{AgentExecInputError,AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,buildContextEntries,buildSessionContext,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createPiAgentExecutionHost,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,executeHumainAgentRequest,findCutPoint,findTurnStartIndex,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPowerShellConfig,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resolveCliModel,resolveModelScopeWithDiagnostics,runAgentExecMode,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-MMFBCF6F.js";import{CONFIG_DIR_NAME,UPSTREAM_PI_VERSION,VERSION,formatDimensionNote,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath,resizeImage}from"./chunks/chunk-ARF4OE6X.js";import"./chunks/chunk-MA4UUCYX.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-SGTGQNNP.js";import"./chunks/chunk-ECWELYBH.js";import"./chunks/chunk-74NVHVNZ.js";import"./chunks/chunk-CBHC6EL7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-D7XAASZM.js";import"./chunks/chunk-WJZ4KLGL.js";import"./chunks/chunk-72KO4OMP.js";import"./chunks/chunk-JXWJOIH4.js";export{AgentExecInputError,AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UPSTREAM_PI_VERSION,UserMessageComponent,UserMessageSelectorComponent,VERSION,buildContextEntries,buildSessionContext,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createPiAgentExecutionHost,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,executeHumainAgentRequest,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runAgentExecMode,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
|
package/dist/bundle/rpc-entry.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
3
|
-
import{configureHttpDispatcher,main}from"./chunks/chunk-
|
|
3
|
+
import{configureHttpDispatcher,main}from"./chunks/chunk-MMFBCF6F.js";import{APP_NAME}from"./chunks/chunk-ARF4OE6X.js";import"./chunks/chunk-MA4UUCYX.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-SGTGQNNP.js";import"./chunks/chunk-ECWELYBH.js";import"./chunks/chunk-74NVHVNZ.js";import"./chunks/chunk-CBHC6EL7.js";import"./chunks/chunk-7DDKXS2Q.js";import"./chunks/chunk-D7XAASZM.js";import"./chunks/chunk-WJZ4KLGL.js";import"./chunks/chunk-72KO4OMP.js";import"./chunks/chunk-JXWJOIH4.js";process.title=`${APP_NAME}-rpc`;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT="pi";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"startup-ui.d.ts","sourceRoot":"","sources":["../../src/cli/startup-ui.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"startup-ui.d.ts","sourceRoot":"","sources":["../../src/cli/startup-ui.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,KAAK,GAAG,EAER,MAAM,wBAAwB,CAAC;AAchC,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAuB9D,UAAU,oBAAoB;IAC7B,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,EAAE,MAAM,CAAC;CACtB;AA2CD,wBAAsB,gBAAgB,CAAC,eAAe,EAAE,eAAe,GAAG,OAAO,CAAC,GAAG,CAAC,CASrF;AAED,wBAAgB,eAAe,CAAC,EAAE,EAAE,GAAG,EAAE,eAAe,EAAE,eAAe,GAAG,IAAI,CAG/E;AAkBD;;;;;GAKG;AACH,wBAAgB,sCAAsC,CAAC,QAAQ,EAAE,oBAAoB,GAAG,OAAO,CAE9F;AAED,wBAAgB,uBAAuB,CAAC,YAAY,GAAE,MAA0B,GAAG,OAAO,CAczF;AAED,wBAAsB,mBAAmB,CAAC,CAAC,EAC1C,eAAe,EAAE,eAAe,EAChC,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,KAAK,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,CAAC,GACzC,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAyBxB;AAED,8DAA8D;AAC9D,wBAAsB,kBAAkB,CAAC,eAAe,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAuCxF;AAED,wBAAsB,gBAAgB,CACrC,eAAe,EAAE,eAAe,EAChC,KAAK,EAAE,MAAM,EACb,WAAW,CAAC,EAAE,MAAM,GAClB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA4B7B"}
|
package/dist/cli/startup-ui.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ProcessTerminal, setKeybindings, TuiMainScreen } from "@earendil-works/pi-tui";
|
|
1
|
+
import { ProcessTerminal, setCapabilityOverrides, setKeybindings, TuiMainScreen, } from "@earendil-works/pi-tui";
|
|
2
2
|
import { existsSync } from "fs";
|
|
3
3
|
import { APP_NAME, CONFIG_DIR_NAME, ENV_AGENT_DIR, FIRST_TIME_SETUP_ENABLED, getAgentDir, getSettingsPath, PACKAGE_NAME, } from "../config.js";
|
|
4
4
|
import { areExperimentalFeaturesEnabled } from "../core/experimental.js";
|
|
@@ -52,6 +52,7 @@ async function loadStartupThemes(settingsManager) {
|
|
|
52
52
|
return loadThemes(resolvedPaths.themes);
|
|
53
53
|
}
|
|
54
54
|
export async function createStartupTui(settingsManager) {
|
|
55
|
+
setCapabilityOverrides(settingsManager.getTerminalCapabilityOverrides());
|
|
55
56
|
setRegisteredThemes(await loadStartupThemes(settingsManager));
|
|
56
57
|
const terminalTheme = detectTerminalBackgroundFromEnv().theme;
|
|
57
58
|
initTheme(resolveThemeSetting(settingsManager.getThemeSetting(), terminalTheme) ?? terminalTheme);
|